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: nodejs#32770
Fixes: nodejs#32753
Fixes: nodejs#32747
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Yongsheng Zhang <[email protected]>
  • Loading branch information
Flarna authored and targos committed Apr 25, 2020
1 parent 8db5201 commit 121b024
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 121b024

Please sign in to comment.