From 214812804e38807c65a8d98f8f14026cb7b683a1 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 30 Jun 2016 11:51:17 +0200 Subject: [PATCH] src: guard against overflow in ParseArrayIndex() ParseArrayIndex() would wrap around large (>=2^32) index values on platforms where sizeof(int64_t) > sizeof(size_t). Ensure that the return value fits in a size_t. PR-URL: https://github.com/nodejs/node/pull/7497 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- src/node_buffer.cc | 5 +++++ test/parallel/test-buffer-alloc.js | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 011f67fa799913..3f295da89356ab 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -185,6 +185,11 @@ inline MUST_USE_RESULT bool ParseArrayIndex(Local arg, if (tmp_i < 0) return false; + // Check that the result fits in a size_t. + const uint64_t kSizeMax = static_cast(static_cast(-1)); + if (static_cast(tmp_i) > kSizeMax) + return false; + *ret = static_cast(tmp_i); return true; } diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index a90625e163c5cc..1d51c78f5c0a95 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1444,6 +1444,13 @@ assert.equal(Buffer.prototype.offset, undefined); assert.equal(SlowBuffer.prototype.parent, undefined); assert.equal(SlowBuffer.prototype.offset, undefined); +// ParseArrayIndex() should reject values that don't fit in a 32 bits size_t. +assert.throws(() => { + const a = Buffer(1).fill(0); + const b = Buffer(1).fill(0); + a.copy(b, 0, 0x100000000, 0x100000001); +}), /out of range index/; + // Unpooled buffer (replaces SlowBuffer) const ubuf = Buffer.allocUnsafeSlow(10); assert(ubuf);