Skip to content

Commit d3e240e

Browse files
committed
Fix unintialized memory access
1 parent 1c590ad commit d3e240e

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

BufferList.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -134,19 +134,23 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
134134

135135
if (bytes > l) {
136136
this._bufs[i].copy(dst, bufoff, start)
137+
bufoff += l
137138
} else {
138139
this._bufs[i].copy(dst, bufoff, start, start + bytes)
140+
bufoff += l
139141
break
140142
}
141143

142-
bufoff += l
143144
bytes -= l
144145

145146
if (start) {
146147
start = 0
147148
}
148149
}
149150

151+
// safeguard so that we don't return uninitialized memory
152+
if (dst.length > bufoff) return dst.slice(0, bufoff)
153+
150154
return dst
151155
}
152156

@@ -188,6 +192,11 @@ BufferList.prototype.toString = function toString (encoding, start, end) {
188192
}
189193

190194
BufferList.prototype.consume = function consume (bytes) {
195+
// first, normalize the argument, in accordance with how Buffer does it
196+
bytes = Math.trunc(bytes)
197+
// do nothing if not a positive number
198+
if (Number.isNaN(bytes) || bytes <= 0) return this
199+
191200
while (this._bufs.length) {
192201
if (bytes >= this._bufs[0].length) {
193202
bytes -= this._bufs[0].length

test/test.js

+16
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,22 @@ tape('test toString encoding', function (t) {
463463
t.end()
464464
})
465465

466+
tape('uninitialized memory', function (t) {
467+
const secret = crypto.randomBytes(256)
468+
for (let i = 0; i < 1e6; i++) {
469+
const clone = Buffer.from(secret)
470+
const bl = new BufferList()
471+
bl.append(Buffer.from('a'))
472+
bl.consume(-1024)
473+
const buf = bl.slice(1)
474+
if (buf.indexOf(clone) !== -1) {
475+
t.fail(`Match (at ${i})`)
476+
break
477+
}
478+
}
479+
t.end()
480+
})
481+
466482
!process.browser && tape('test stream', function (t) {
467483
const random = crypto.randomBytes(65534)
468484

0 commit comments

Comments
 (0)