Skip to content

Commit 93b10fb

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#65 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Rod Vagg <rod@vagg.org>
1 parent 3ff82de commit 93b10fb

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/buffer.js

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

294+
// Note: `length` is always equal to `buffer.length` at this point
295+
if (pos < length) {
296+
// Zero-fill the remaining bytes if the specified `length` was more than
297+
// the actual total length, i.e. if we have some remaining allocated bytes
298+
// there were not initialized.
299+
buffer.fill(0, pos, length);
300+
}
301+
294302
return buffer;
295303
};
296304

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+
var common = require('../common');
33
var assert = require('assert');
44

55
var zero = [];
@@ -24,4 +24,26 @@ assert.throws(function() {
2424
Buffer.concat([42]);
2525
}, TypeError);
2626

27+
const random10 = common.hasCrypto
28+
? require('crypto').randomBytes(10)
29+
: Buffer.alloc(10, 1);
30+
const empty = Buffer.alloc(0);
31+
32+
assert.notDeepStrictEqual(random10, empty);
33+
assert.notDeepStrictEqual(random10, Buffer.alloc(10));
34+
35+
assert.deepStrictEqual(Buffer.concat([], 100), empty);
36+
assert.deepStrictEqual(Buffer.concat([random10], 0), empty);
37+
assert.deepStrictEqual(Buffer.concat([random10], 10), random10);
38+
assert.deepStrictEqual(Buffer.concat([random10, random10], 10), random10);
39+
assert.deepStrictEqual(Buffer.concat([empty, random10]), random10);
40+
assert.deepStrictEqual(Buffer.concat([random10, empty, empty]), random10);
41+
42+
// The tail should be zero-filled
43+
assert.deepStrictEqual(Buffer.concat([empty], 100), Buffer.alloc(100));
44+
assert.deepStrictEqual(Buffer.concat([empty], 4096), Buffer.alloc(4096));
45+
assert.deepStrictEqual(
46+
Buffer.concat([random10], 40),
47+
Buffer.concat([random10, Buffer.alloc(30)]));
48+
2749
console.log('ok');

0 commit comments

Comments
 (0)