Skip to content

Commit dacc4ac

Browse files
committed
Fix unintialized memory access
1 parent b6284a8 commit dacc4ac

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
@@ -186,18 +186,22 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
186186

187187
if (bytes > l) {
188188
this._bufs[i].copy(dst, bufoff, start)
189+
bufoff += l
189190
} else {
190191
this._bufs[i].copy(dst, bufoff, start, start + bytes)
192+
bufoff += l
191193
break
192194
}
193195

194-
bufoff += l
195196
bytes -= l
196197

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

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

@@ -233,6 +237,11 @@ BufferList.prototype.toString = function toString (encoding, start, end) {
233237
}
234238

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