From dacc4ac7d5fcd6201bcf26fbd886951be9537466 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Wed, 26 Aug 2020 10:06:00 +0200 Subject: [PATCH] Fix unintialized memory access --- bl.js | 11 ++++++++++- test/test.js | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/bl.js b/bl.js index af49483..52c3740 100644 --- a/bl.js +++ b/bl.js @@ -186,18 +186,22 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { if (bytes > l) { this._bufs[i].copy(dst, bufoff, start) + bufoff += l } else { this._bufs[i].copy(dst, bufoff, start, start + bytes) + bufoff += l break } - bufoff += l bytes -= l if (start) start = 0 } + // safeguard so that we don't return uninitialized memory + if (dst.length > bufoff) return dst.slice(0, bufoff) + return dst } @@ -233,6 +237,11 @@ BufferList.prototype.toString = function toString (encoding, start, end) { } BufferList.prototype.consume = function consume (bytes) { + // first, normalize the argument, in accordance with how Buffer does it + bytes = Math.trunc(bytes) + // do nothing if not a positive number + if (Number.isNaN(bytes) || bytes <= 0) return this + while (this._bufs.length) { if (bytes >= this._bufs[0].length) { bytes -= this._bufs[0].length diff --git a/test/test.js b/test/test.js index 475cda8..42fcad4 100644 --- a/test/test.js +++ b/test/test.js @@ -431,6 +431,22 @@ tape('test toString encoding', function (t) { t.end() }) +tape('uninitialized memory', function (t) { + const secret = crypto.randomBytes(256) + for (let i = 0; i < 1e6; i++) { + const clone = Buffer.from(secret) + const bl = new BufferList() + bl.append(Buffer.from('a')) + bl.consume(-1024) + const buf = bl.slice(1) + if (buf.indexOf(clone) !== -1) { + t.fail(`Match (at ${i})`) + break + } + } + t.end() +}) + !process.browser && tape('test stream', function (t) { var random = crypto.randomBytes(65534) , rndhash = hash(random, 'md5')