Skip to content

Commit

Permalink
buffer: zero-fill uninitialized bytes in .concat()
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
ChALkeR authored and rvagg committed Sep 27, 2016
1 parent 3ff82de commit 93b10fb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
8 changes: 8 additions & 0 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,14 @@ Buffer.concat = function(list, length) {
pos += buf.length;
}

// Note: `length` is always equal to `buffer.length` at this point
if (pos < length) {
// Zero-fill the remaining bytes if the specified `length` was more than
// the actual total length, i.e. if we have some remaining allocated bytes
// there were not initialized.
buffer.fill(0, pos, length);
}

return buffer;
};

Expand Down
24 changes: 23 additions & 1 deletion test/parallel/test-buffer-concat.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict';
require('../common');
var common = require('../common');
var assert = require('assert');

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

const random10 = common.hasCrypto
? require('crypto').randomBytes(10)
: Buffer.alloc(10, 1);
const empty = Buffer.alloc(0);

assert.notDeepStrictEqual(random10, empty);
assert.notDeepStrictEqual(random10, Buffer.alloc(10));

assert.deepStrictEqual(Buffer.concat([], 100), empty);
assert.deepStrictEqual(Buffer.concat([random10], 0), empty);
assert.deepStrictEqual(Buffer.concat([random10], 10), random10);
assert.deepStrictEqual(Buffer.concat([random10, random10], 10), random10);
assert.deepStrictEqual(Buffer.concat([empty, random10]), random10);
assert.deepStrictEqual(Buffer.concat([random10, empty, empty]), random10);

// The tail should be zero-filled
assert.deepStrictEqual(Buffer.concat([empty], 100), Buffer.alloc(100));
assert.deepStrictEqual(Buffer.concat([empty], 4096), Buffer.alloc(4096));
assert.deepStrictEqual(
Buffer.concat([random10], 40),
Buffer.concat([random10, Buffer.alloc(30)]));

console.log('ok');

0 comments on commit 93b10fb

Please sign in to comment.