Skip to content

Commit 495d688

Browse files
ChALkeRrvagg
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: nodejs-private/node-private#64 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
1 parent c34e58e commit 495d688

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

lib/buffer.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,14 @@ Buffer.concat = function(list, length) {
338338
pos += buf.length;
339339
}
340340

341+
// Note: `length` is always equal to `buffer.length` at this point
342+
if (pos < length) {
343+
// Zero-fill the remaining bytes if the specified `length` was more than
344+
// the actual total length, i.e. if we have some remaining allocated bytes
345+
// there were not initialized.
346+
buffer.fill(0, pos, length);
347+
}
348+
341349
return buffer;
342350
};
343351

test/parallel/test-buffer-concat.js

Lines changed: 23 additions & 1 deletion
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)