From: Alexander Borisov Date: Tue, 6 Oct 2020 17:24:21 +0000 (+0300) Subject: Fixed heap-use-after-free in JSON.stringify(). X-Git-Url: http://www.kaiwu.me/postgresql/commit/?a=commitdiff_plain;h=63aa001ebd7a386939851cf8b2c0332d718f5c23;p=njs.git Fixed heap-use-after-free in JSON.stringify(). njs_json_stringify_iterator() assumed, while stringifying flat arrays, that a flat array will always remain flat. This is not the case for flat arrays with values with custom getters which may modify the enclosing array upon invocation. This closes #322 issue on GitHub. --- diff --git a/src/njs_json.c b/src/njs_json.c index 6bbf13b1..2a2e4dd8 100644 --- a/src/njs_json.c +++ b/src/njs_json.c @@ -1296,7 +1296,18 @@ njs_json_stringify_iterator(njs_vm_t *vm, njs_json_stringify_t *stringify, njs_json_stringify_indent(stringify, &chain, 0); } - stringify->retval = njs_array_start(&state->value)[state->index++]; + if (njs_is_fast_array(&state->value)) { + value = njs_array_start(&state->value); + stringify->retval = value[state->index++]; + + } else { + ret = njs_value_property_i64(vm, &state->value, state->index++, + &stringify->retval); + if (njs_slow_path(ret == NJS_ERROR)) { + return ret; + } + } + value = &stringify->retval; ret = njs_json_stringify_to_json(stringify, state, NULL, value); diff --git a/src/test/njs_unit_test.c b/src/test/njs_unit_test.c index 64c993cf..3cdcf173 100644 --- a/src/test/njs_unit_test.c +++ b/src/test/njs_unit_test.c @@ -16848,6 +16848,13 @@ static njs_unit_test_t njs_test[] = { njs_str("var a = {}; a.a = a; JSON.stringify(a)"), njs_str("TypeError: Nested too deep or a cyclic structure") }, + { njs_str("var array = [1,2,3];" + "array[1] = {get value() {" + " Object.defineProperty(array, '2', {get: () => 10}) }" + "};" + "JSON.stringify(array)"), + njs_str("[1,{},10]") }, + /* njs.dump(). */ { njs_str("njs.dump({a:1, b:[1,,2,{c:new Boolean(1)}]})"),