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 <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
This commit is contained in:
Gerhard Stoebich 2020-04-10 20:25:48 +02:00 committed by Ruben Bridgewater
parent 1436f5359c
commit a1178b6c5b
2 changed files with 19 additions and 1 deletions

View File

@ -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.

View File

@ -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'
});
}