From 02f99d289da1e76a2d8681c3627bb5e3f254cd8f Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Fri, 10 Apr 2020 20:25:48 +0200 Subject: [PATCH] buffer: add type check in bidirectionalIndexOf Add a type check in bidirectionalIndexOf to avoid using something else as Buffer. This may happen if e.g. lastIndexOf is called with invalid this. PR-URL: https://github.com/nodejs/node/pull/32770 Fixes: https://github.com/nodejs/node/issues/32753 Fixes: https://github.com/nodejs/node/issues/32747 Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater Reviewed-By: Yongsheng Zhang --- lib/buffer.js | 5 ++++- test/parallel/test-buffer-indexof.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index cc4ee31dd581be..874227f0d44051 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -97,6 +97,7 @@ const { hideStackFrames } = require('internal/errors'); const { + validateBuffer, validateInt32, validateString } = require('internal/validators'); @@ -902,6 +903,8 @@ Buffer.prototype.compare = function compare(target, // - encoding - an optional encoding, relevant if val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + validateBuffer(buffer); + if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = undefined; @@ -914,7 +917,7 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { byteOffset = +byteOffset; // If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer. if (NumberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length; + byteOffset = dir ? 0 : (buffer.length || buffer.byteLength); } dir = !!dir; // Cast to bool. diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index d789c9b46cf868..b17520366e506a 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -606,3 +606,18 @@ assert.strictEqual(reallyLong.lastIndexOf(pattern), 0); assert.strictEqual(haystack.indexOf(needle), 2); assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3); } + +// Avoid abort because of invalid usage +// see https://github.com/nodejs/node/issues/32753 +{ + assert.throws(() => { + const buffer = require('buffer'); + new buffer.Buffer.prototype.lastIndexOf(1, 'str'); + }, { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + message: 'The "buffer" argument must be an instance of Buffer, ' + + 'TypedArray, or DataView. ' + + 'Received an instance of lastIndexOf' + }); +}