From 3492a0eb1ea3f8c4610a6ea8fbd8580620e0e152 Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Tue, 8 Mar 2022 22:06:11 +0530 Subject: [PATCH] string_decoder: fix crash when calling __proto__.write() This makes the function throw an exception from JS instead of crashing. Fixes: https://github.com/nodejs/node/issues/41949 Signed-off-by: Darshan Sen PR-URL: https://github.com/nodejs/node/pull/42062 Reviewed-By: James M Snell Reviewed-By: Mestery --- lib/string_decoder.js | 4 ++++ test/parallel/test-string-decoder.js | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 7447bb3f4699b1..9eae594aaa27ea 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -43,6 +43,7 @@ const { const internalUtil = require('internal/util'); const { ERR_INVALID_ARG_TYPE, + ERR_INVALID_THIS, ERR_UNKNOWN_ENCODING } = require('internal/errors').codes; const isEncoding = Buffer[internalUtil.kIsEncodingSymbol]; @@ -101,6 +102,9 @@ StringDecoder.prototype.write = function write(buf) { throw new ERR_INVALID_ARG_TYPE('buf', ['Buffer', 'TypedArray', 'DataView'], buf); + if (!this[kNativeDecoder]) { + throw new ERR_INVALID_THIS('StringDecoder'); + } return decode(this[kNativeDecoder], buf); }; diff --git a/test/parallel/test-string-decoder.js b/test/parallel/test-string-decoder.js index be876f46e5af02..02f0a3a718bdec 100644 --- a/test/parallel/test-string-decoder.js +++ b/test/parallel/test-string-decoder.js @@ -210,6 +210,13 @@ if (common.enoughTestMem) { ); } +assert.throws( + () => new StringDecoder('utf8').__proto__.write(Buffer.from('abc')), // eslint-disable-line no-proto + { + code: 'ERR_INVALID_THIS', + } +); + // Test verifies that StringDecoder will correctly decode the given input // buffer with the given encoding to the expected output. It will attempt all // possible ways to write() the input buffer, see writeSequences(). The