Skip to content

Commit

Permalink
Fix unintialized memory access
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Aug 26, 2020
1 parent b6284a8 commit dacc4ac
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
11 changes: 10 additions & 1 deletion bl.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit dacc4ac

Please sign in to comment.