Skip to content

Commit

Permalink
buffer: add type check in bidirectionalIndexOf
Browse files Browse the repository at this point in the history
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: #32770
Fixes: #32753
Fixes: #32747
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
  • Loading branch information
Flarna authored and targos committed Apr 28, 2020
1 parent dec8a21 commit 02f99d2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ const {
hideStackFrames
} = require('internal/errors');
const {
validateBuffer,
validateInt32,
validateString
} = require('internal/validators');
Expand Down Expand Up @@ -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;
Expand All @@ -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.

Expand Down
15 changes: 15 additions & 0 deletions test/parallel/test-buffer-indexof.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
});
}

0 comments on commit 02f99d2

Please sign in to comment.