]> git.kaiwu.me - njs.git/commitdiff
Fixed Buffer allocation length checks
authorDmitry Volyntsev <xeioex@nginx.com>
Sat, 23 May 2026 01:18:39 +0000 (18:18 -0700)
committerDmitry Volyntsev <xeioexception@gmail.com>
Tue, 26 May 2026 21:45:24 +0000 (14:45 -0700)
On 32-bit platforms, where size_t is 32 bits, callers passing
int64_t lengths >= 2^32 to njs_buffer_alloc() had the value
silently truncated before reaching the UINT32_MAX check in
njs_array_buffer_alloc(), so Buffer.from({length: 0x100000000})
returned a zero-sized buffer instead of raising a RangeError.

Widened the size parameter to uint64_t so the value reaches
njs_typed_array_alloc() intact and the "invalid index" range
error fires consistently on 32-bit and 64-bit builds.

Buffer.concat() is protected by the same change: it likewise
reads an int64_t length from JS and forwards it to
njs_buffer_alloc() without an upper bound check of its own.

src/njs_buffer.c
test/buffer.t.js

index 622d906823d8ab642923f10149da688814fc8083..886a865736d0d7053971f60be17da9fe45fdedd3 100644 (file)
@@ -191,7 +191,7 @@ njs_buffer_set(njs_vm_t *vm, njs_value_t *value, const u_char *start,
 
 
 static njs_typed_array_t *
-njs_buffer_alloc(njs_vm_t *vm, size_t size, njs_bool_t zeroing)
+njs_buffer_alloc(njs_vm_t *vm, uint64_t size, njs_bool_t zeroing)
 {
     njs_value_t        value;
     njs_typed_array_t  *array;
index c10b0180942787b042cba87813e285b8fa00c7d2..f4841b052429b1c52cb896d59d211c39edd0f47a 100644 (file)
@@ -354,6 +354,8 @@ let from_tsuite = {
         { args: [{length:3, 0:0x62, 1:0x75, 2:0x66}], expected: 'buf' },
         { args: [[-1, 1, 255, 22323, -Infinity, Infinity, NaN]], fmt: "hex", expected: 'ff01ff33000000' },
         { args: [{length:5, 0:'A'.charCodeAt(0), 2:'X', 3:NaN, 4:0xfd}], fmt: "hex", expected: '41000000fd' },
+        { args: [{length: 0x100000000}], exception: 'RangeError: invalid index' },
+        { args: [{length: 0x100000001}], exception: 'RangeError: invalid index' },
         { args: [[1, 2, 0.23, '5', 'A']], fmt: "hex", expected: '0102000500' },
         { args: [new Uint8Array([0xff, 0xde, 0xba])], fmt: "hex", expected: 'ffdeba' },