Skip to content

Commit aa34465

Browse files
committed
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: #32770 Fixes: #32753 Fixes: #32747 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Yongsheng Zhang <[email protected]>
1 parent 1211b9a commit aa34465

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/buffer.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ const {
9797
hideStackFrames
9898
} = require('internal/errors');
9999
const {
100+
validateBuffer,
100101
validateInt32,
101102
validateString
102103
} = require('internal/validators');
@@ -902,6 +903,8 @@ Buffer.prototype.compare = function compare(target,
902903
// - encoding - an optional encoding, relevant if val is a string
903904
// - dir - true for indexOf, false for lastIndexOf
904905
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
906+
validateBuffer(buffer);
907+
905908
if (typeof byteOffset === 'string') {
906909
encoding = byteOffset;
907910
byteOffset = undefined;
@@ -914,7 +917,7 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
914917
byteOffset = +byteOffset;
915918
// If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer.
916919
if (NumberIsNaN(byteOffset)) {
917-
byteOffset = dir ? 0 : buffer.length;
920+
byteOffset = dir ? 0 : (buffer.length || buffer.byteLength);
918921
}
919922
dir = !!dir; // Cast to bool.
920923

test/parallel/test-buffer-indexof.js

+15
Original file line numberDiff line numberDiff line change
@@ -606,3 +606,18 @@ assert.strictEqual(reallyLong.lastIndexOf(pattern), 0);
606606
assert.strictEqual(haystack.indexOf(needle), 2);
607607
assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3);
608608
}
609+
610+
// Avoid abort because of invalid usage
611+
// see https://github.com./nodejs/node/issues/32753
612+
{
613+
assert.throws(() => {
614+
const buffer = require('buffer');
615+
new buffer.Buffer.prototype.lastIndexOf(1, 'str');
616+
}, {
617+
code: 'ERR_INVALID_ARG_TYPE',
618+
name: 'TypeError',
619+
message: 'The "buffer" argument must be an instance of Buffer, ' +
620+
'TypedArray, or DataView. ' +
621+
'Received an instance of lastIndexOf'
622+
});
623+
}

0 commit comments

Comments
 (0)