crypto: use internal random buffer bounds

Read buffer lengths and element sizes from internal slots in
randomFillSync() and randomFill(). Shadowed properties can otherwise
skip filling, change the selected range, or fail a native bounds check.

Use the intrinsic byte length for the getRandomValues() quota check and
keep its delegation to randomFillSync().

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
Assisted-by: Codex
PR-URL: https://github.com/nodejs/node/pull/66237
Backport-PR-URL: https://github.com/nodejs/node/pull/66970
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-11-11 17:28:10 +01:00
1 parent 1a2b5cc6ff
commit f393f8be84
3 files changed
+201 -11

No files matched your search

+50 -11
View File
@@ -10,6 +10,7 @@ const {
BigInt,
BigIntPrototypeToString,
DataView,
DataViewPrototypeGetByteLength,
DataViewPrototypeGetUint8,
DateNow,
FunctionPrototypeBind,
@@ -22,6 +23,10 @@ const {
StringPrototypePadStart,
TypedArrayPrototypeFill,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetByteLength,
TypedArrayPrototypeGetLength,
TypedArrayPrototypeGetSymbolToStringTag,
Uint8Array,
} = primordials;
const {
@@ -59,6 +64,8 @@ const {
const {
isArrayBufferView,
isAnyArrayBuffer,
isDataView,
isSharedArrayBuffer,
isTypedArray,
isFloat16Array,
isFloat32Array,
@@ -78,6 +85,35 @@ const {
const kMaxInt32 = 2 ** 31 - 1;
const kMaxPossibleLength = MathMin(kMaxLength, kMaxInt32);
function getByteLength(buf) {
if (isArrayBufferView(buf)) {
return isDataView(buf) ?
DataViewPrototypeGetByteLength(buf) : TypedArrayPrototypeGetByteLength(buf);
}
if (isSharedArrayBuffer(buf))
return TypedArrayPrototypeGetByteLength(new Uint8Array(buf));
return ArrayBufferPrototypeGetByteLength(buf);
}
function getElementSize(buf) {
switch (TypedArrayPrototypeGetSymbolToStringTag(buf)) {
case 'Int16Array':
case 'Uint16Array':
case 'Float16Array':
return 2;
case 'Int32Array':
case 'Uint32Array':
case 'Float32Array':
return 4;
case 'Float64Array':
case 'BigInt64Array':
case 'BigUint64Array':
return 8;
default:
return 1;
}
}
function assertOffset(offset, elementSize, length) {
validateNumber(offset, 'offset');
offset *= elementSize;
@@ -134,14 +170,15 @@ function randomFillSync(buf, offset = 0, size) {
buf);
}
const elementSize = buf.BYTES_PER_ELEMENT || 1;
const elementSize = getElementSize(buf);
const byteLength = getByteLength(buf);
offset = assertOffset(offset, elementSize, buf.byteLength);
offset = assertOffset(offset, elementSize, byteLength);
if (size === undefined) {
size = buf.byteLength - offset;
size = byteLength - offset;
} else {
size = assertSize(size, elementSize, offset, buf.byteLength);
size = assertSize(size, elementSize, offset, byteLength);
}
if (size === 0)
@@ -168,26 +205,27 @@ function randomFill(buf, offset, size, callback) {
buf);
}
const elementSize = buf.BYTES_PER_ELEMENT || 1;
const elementSize = getElementSize(buf);
if (typeof offset === 'function') {
callback = offset;
offset = 0;
// Size is a length here, assertSize() call turns it into a number of bytes
size = buf.length;
size = isTypedArray(buf) ? TypedArrayPrototypeGetLength(buf) : undefined;
} else if (typeof size === 'function') {
callback = size;
size = (buf.length ?? buf.byteLength) - offset;
size = (isTypedArray(buf) ? TypedArrayPrototypeGetLength(buf) : getByteLength(buf)) - offset;
} else {
validateFunction(callback, 'callback');
}
offset = assertOffset(offset, elementSize, buf.byteLength);
const byteLength = getByteLength(buf);
offset = assertOffset(offset, elementSize, byteLength);
if (size === undefined) {
size = buf.byteLength - offset;
size = byteLength - offset;
} else {
size = assertSize(size, elementSize, offset, buf.byteLength);
size = assertSize(size, elementSize, offset, byteLength);
}
if (size === 0) {
@@ -337,7 +375,8 @@ function getRandomValues(data) {
'The data argument must be an integer-type TypedArray',
'TypeMismatchError');
}
if (data.byteLength > 65536) {
const byteLength = TypedArrayPrototypeGetByteLength(data);
if (byteLength > 65536) {
throw lazyDOMException(
'The requested length exceeds 65,536 bytes',
'QuotaExceededError');
@@ -0,0 +1,120 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const { randomFill, randomFillSync } = require('crypto');
const typedArrays = [
Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
Int32Array, Uint32Array, Float32Array, Float64Array,
BigInt64Array, BigUint64Array,
];
if (globalThis.Float16Array !== undefined)
typedArrays.push(globalThis.Float16Array);
const factories = [];
for (const Backing of [ArrayBuffer, SharedArrayBuffer]) {
for (const Type of [...typedArrays, Buffer, DataView]) {
const elementSize = Type.BYTES_PER_ELEMENT || 1;
factories.push({
name: `${Type.name} on ${Backing.name}`,
elementSize,
make(length = 64) {
const backing = new Backing(length + 64);
const input = Type === Buffer ? Buffer.from(backing, 32, length) :
new Type(backing, 32, length / elementSize);
return { input, backing, bytes: new Uint8Array(backing), start: 32, length };
},
});
}
factories.push({
name: Backing.name,
elementSize: 1,
make(length = 64) {
const input = new Backing(length);
return { input, backing: input, bytes: new Uint8Array(input), start: 0, length };
},
});
}
function shadowMetadata(target, mode) {
const values = {
byteLength: mode === 'zero' ? 0 : 4096,
length: mode === 'zero' ? 0 : 4096,
BYTES_PER_ELEMENT: mode === 'zero' ? 0 : 4096,
buffer: new ArrayBuffer(0),
byteOffset: mode === 'zero' ? 0 : 4096,
[Symbol.toStringTag]: 'NotAnArrayBufferView',
};
for (const key of Reflect.ownKeys(values)) {
Object.defineProperty(target, key, mode === 'getters' ?
{ get: common.mustNotCall(`Unexpected ${String(key)} getter`) } :
{ value: values[key] });
}
}
function checkFilled({ input, bytes, start }, result, offset, size, label) {
assert.strictEqual(result, input, label);
assert(bytes.subarray(0, start + offset).every((byte) => byte === 0), label);
assert(bytes.subarray(start + offset + size).every((byte) => byte === 0), label);
// Every nonempty test range contains at least 32 random bytes. Detect a
// no-op without assuming that any particular generated byte is nonzero.
if (size !== 0)
assert(bytes.subarray(start + offset, start + offset + size).some((byte) => byte !== 0), label);
}
for (const factory of factories) {
const { elementSize } = factory;
const ranges = [
{ args: [], offset: 0, size: 64 },
{ args: [16 / elementSize], offset: 16, size: 48 },
{ args: [16 / elementSize, 32 / elementSize], offset: 16, size: 32 },
{ args: [16 / elementSize, undefined], offset: 16, size: 48 },
{ args: [64 / elementSize], offset: 64, size: 0 },
];
for (const mode of ['getters', 'zero', 'inflated']) {
for (const { args, offset, size } of ranges) {
for (const async of [false, true]) {
const value = factory.make();
shadowMetadata(value.input, mode);
if (value.backing !== value.input)
shadowMetadata(value.backing, mode);
const label = `${factory.name}, ${mode}, ${async ? 'async' : 'sync'}, ${args}`;
if (async) {
assert.strictEqual(randomFill(value.input, ...args, common.mustSucceed((result) => {
checkFilled(value, result, offset, size, label);
})), undefined);
} else {
checkFilled(value, randomFillSync(value.input, ...args), offset, size, label);
}
}
}
}
// Inflated public bounds must not let an invalid range reach the native job.
// Keep the real element width here so each range exceeds the actual buffer.
const units = 64 / elementSize;
for (const args of [[units + 1], [0, units + 1], [units, 1]]) {
const { input } = factory.make();
Object.defineProperties(input, {
byteLength: { value: 4096 },
length: { value: 4096 },
});
assert.throws(() => randomFillSync(input, ...args), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => randomFill(input, ...args, common.mustNotCall()), {
code: 'ERR_OUT_OF_RANGE',
});
}
for (const args of [[], [0], [0, 0], [0, undefined]]) {
const value = factory.make(0);
shadowMetadata(value.input, 'inflated');
checkFilled(value, randomFillSync(value.input, ...args), 0, 0, factory.name);
assert.strictEqual(randomFill(value.input, ...args, common.mustSucceed((result) => {
checkFilled(value, result, 0, 0, factory.name);
})), undefined);
}
}
@@ -0,0 +1,31 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const webcrypto = globalThis.crypto;
for (const Type of [Uint8Array, Uint16Array, Uint32Array, BigUint64Array]) {
const storage = new Uint8Array(128);
const view = new Type(storage.buffer, 32, 32 / Type.BYTES_PER_ELEMENT);
for (const name of ['buffer', 'byteOffset', 'byteLength', 'BYTES_PER_ELEMENT']) {
Object.defineProperty(view, name, { get: common.mustNotCall() });
Object.defineProperty(storage.buffer, name, { get: common.mustNotCall() });
}
assert.strictEqual(webcrypto.getRandomValues(view), view);
assert(storage.subarray(32, 64).some((byte) => byte !== 0));
assert(storage.subarray(0, 32).every((byte) => byte === 0));
assert(storage.subarray(64).every((byte) => byte === 0));
}
const oversized = new Uint8Array(65537);
Object.defineProperty(oversized, 'byteLength', { value: 0 });
assert.throws(() => webcrypto.getRandomValues(oversized), {
name: 'QuotaExceededError',
});
const empty = new Uint8Array(0);
Object.defineProperty(empty, 'byteLength', { value: 65537 });
assert.strictEqual(webcrypto.getRandomValues(empty), empty);