From 3651f012f2f36578ab8e939967af1b1591fec33e Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 18 Oct 2016 09:34:28 -0400 Subject: [PATCH] buffer: convert range to numbers before validation Prior to this commit, a carefully crafted object with a Symbol.toPrimitive could bypass range validation. This commit converts the range values to numbers before performing any validation. --- lib/buffer.js | 5 ++++- test/parallel/test-buffer-fill.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index 7b3342229cc108..d4e38da703237d 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -703,6 +703,9 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) { val = val & 255; } + start = +start; + end = end === undefined ? this.length : +end; + // Invalid ranges are not set to a default, so can range check early. if (start < 0 || end > this.length) throw new RangeError('Out of range index'); @@ -711,7 +714,7 @@ Buffer.prototype.fill = function fill(val, start, end, encoding) { return this; start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + end = end >>> 0; binding.fill(this, val, start, end, encoding); diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index e5581b2d83d041..f9a773fbce13ab 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -314,3 +314,24 @@ Buffer.alloc(8, ''); buf.fill('է'); assert.strictEqual(buf.toString(), 'էէէէէ'); } + +{ + const buff = Buffer.alloc(1); + const start = { + ctr: 0, + [Symbol.toPrimitive](hint) { + if (this.ctr <= 0) { + this.ctr++; + return 0; + } else { + return -1; + } + } + }; + + assert.deepStrictEqual(buff.fill(0xff, start, 1), + Buffer.from([0xff])); + assert.throws(() => { + buff.fill(0xee, start, 1); + }, /RangeError: Out of range index/); +}