Skip to content

Commit 8fb8c46

Browse files
ChALkeRevanlucas
authored andcommitted
buffer: zero-fill uninitialized bytes in .concat()
This makes sure that no uninitialized bytes are leaked when the specified `totalLength` input value is greater than the actual total length of the specified buffers array, e.g. in Buffer.concat([Buffer.alloc(0)], 100). PR-URL: https://github.com/nodejs/node-private/pull/64 Reviewed-By: Rod Vagg <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 743f0c9 commit 8fb8c46

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/buffer.js

+8
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,14 @@ Buffer.concat = function(list, length) {
311311
pos += buf.length;
312312
}
313313

314+
// Note: `length` is always equal to `buffer.length` at this point
315+
if (pos < length) {
316+
// Zero-fill the remaining bytes if the specified `length` was more than
317+
// the actual total length, i.e. if we have some remaining allocated bytes
318+
// there were not initialized.
319+
buffer.fill(0, pos, length);
320+
}
321+
314322
return buffer;
315323
};
316324

test/parallel/test-buffer-concat.js

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
'use strict';
2-
require('../common');
2+
const common = require('../common');
33
const assert = require('assert');
44

55
const zero = [];
@@ -38,3 +38,25 @@ function assertWrongList(value) {
3838
err.message === '"list" argument must be an Array of Buffers';
3939
});
4040
}
41+
42+
const random10 = common.hasCrypto
43+
? require('crypto').randomBytes(10)
44+
: Buffer.alloc(10, 1);
45+
const empty = Buffer.alloc(0);
46+
47+
assert.notDeepStrictEqual(random10, empty);
48+
assert.notDeepStrictEqual(random10, Buffer.alloc(10));
49+
50+
assert.deepStrictEqual(Buffer.concat([], 100), empty);
51+
assert.deepStrictEqual(Buffer.concat([random10], 0), empty);
52+
assert.deepStrictEqual(Buffer.concat([random10], 10), random10);
53+
assert.deepStrictEqual(Buffer.concat([random10, random10], 10), random10);
54+
assert.deepStrictEqual(Buffer.concat([empty, random10]), random10);
55+
assert.deepStrictEqual(Buffer.concat([random10, empty, empty]), random10);
56+
57+
// The tail should be zero-filled
58+
assert.deepStrictEqual(Buffer.concat([empty], 100), Buffer.alloc(100));
59+
assert.deepStrictEqual(Buffer.concat([empty], 4096), Buffer.alloc(4096));
60+
assert.deepStrictEqual(
61+
Buffer.concat([random10], 40),
62+
Buffer.concat([random10, Buffer.alloc(30)]));

0 commit comments

Comments
 (0)