Skip to content

Commit 8a8c13c

Browse files
committed
Fix unintialized memory access
1 parent ecc0cc5 commit 8a8c13c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

bl.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -185,18 +185,22 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
185185

186186
if (bytes > l) {
187187
this._bufs[i].copy(dst, bufoff, start)
188+
bufoff += l
188189
} else {
189190
this._bufs[i].copy(dst, bufoff, start, start + bytes)
191+
bufoff += l
190192
break
191193
}
192194

193-
bufoff += l
194195
bytes -= l
195196

196197
if (start)
197198
start = 0
198199
}
199200

201+
// safeguard so that we don't return uninitialized memory
202+
if (dst.length > bufoff) return dst.slice(0, bufoff)
203+
200204
return dst
201205
}
202206

@@ -232,6 +236,11 @@ BufferList.prototype.toString = function toString (encoding, start, end) {
232236
}
233237

234238
BufferList.prototype.consume = function consume (bytes) {
239+
// first, normalize the argument, in accordance with how Buffer does it
240+
bytes = Math.trunc(bytes)
241+
// do nothing if not a positive number
242+
if (Number.isNaN(bytes) || bytes <= 0) return this
243+
235244
while (this._bufs.length) {
236245
if (bytes >= this._bufs[0].length) {
237246
bytes -= this._bufs[0].length

test/test.js

+16
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,22 @@ tape('test toString encoding', function (t) {
431431
t.end()
432432
})
433433

434+
tape('uninitialized memory', function (t) {
435+
const secret = crypto.randomBytes(256)
436+
for (let i = 0; i < 1e6; i++) {
437+
const clone = Buffer.from(secret)
438+
const bl = new BufferList()
439+
bl.append(Buffer.from('a'))
440+
bl.consume(-1024)
441+
const buf = bl.slice(1)
442+
if (buf.indexOf(clone) !== -1) {
443+
t.fail(`Match (at ${i})`)
444+
break
445+
}
446+
}
447+
t.end()
448+
})
449+
434450
!process.browser && tape('test stream', function (t) {
435451
var random = crypto.randomBytes(65534)
436452
, rndhash = hash(random, 'md5')

0 commit comments

Comments
 (0)