Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/jsc/array_buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,21 @@ impl MarkedArrayBuffer {
})
}

/// The caller's live `ArrayBuffer` for in-place writes. When this is an
/// owned snapshot of a resizable input (see `StringOrBuffer::array_buffer_into`),
/// `self.buffer.ptr` points at a private copy, so re-read from `value`.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[inline]
pub fn live_array_buffer(&self, global: &JSGlobalObject) -> ArrayBuffer {
if self.owns_buffer && self.buffer.value != JSValue::ZERO {
return self
.buffer
.value
.as_array_buffer(global)
.unwrap_or_default();
}
self.buffer
}

pub fn from_bytes(bytes: &mut [u8], typed_array_type: JSType) -> MarkedArrayBuffer {
MarkedArrayBuffer {
buffer: ArrayBuffer::from_bytes(bytes, typed_array_type),
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/api/MarkdownObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ impl PinnedView {
let Some(b) = buffer.buffer() else {
return Ok(None);
};
if b.owns_buffer {
return Ok(None);
}
match b.buffer.value.as_pinned_arraybuffer(global) {
Some(pinned) => Ok(Some(Self(pinned))),
None => Err(global.throw_out_of_memory()),
Expand Down
10 changes: 5 additions & 5 deletions src/runtime/crypto/CryptoHasher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ impl CryptoHasher {

if let Some(string_or_buffer) = output {
if let StringOrBuffer::Buffer(buffer) = &string_or_buffer {
let ab = buffer.buffer;
let ab = buffer.live_array_buffer(global);
return Self::hash_to_bytes(global, &mut evp, input, Some(ab));
}
// `inline else => |*str|` — every non-buffer arm yields a string-like
Expand Down Expand Up @@ -687,7 +687,7 @@ impl CryptoHasher {
) -> JsResult<JSValue> {
if let Some(string_or_buffer) = output {
if let StringOrBuffer::Buffer(buffer) = &string_or_buffer {
let ab = buffer.buffer;
let ab = buffer.live_array_buffer(global);
return this.digest_to_bytes(global, Some(ab));
}
// `defer str.deinit()` — handled by Drop.
Expand Down Expand Up @@ -927,7 +927,7 @@ impl CryptoHasherZig {
) -> JsResult<JSValue> {
if let Some(string_or_buffer) = output {
if let StringOrBuffer::Buffer(buffer) = &string_or_buffer {
let ab = buffer.buffer;
let ab = buffer.live_array_buffer(global);
return Self::hash_by_name_inner_to_bytes::<A>(global, input, Some(ab));
}
let Some(encoding) = Encoding::from(string_or_buffer.slice()) else {
Expand Down Expand Up @@ -1374,7 +1374,7 @@ impl<H: StaticHasher> StaticCryptoHasher<H> {

if let Some(string_or_buffer) = output {
if let StringOrBuffer::Buffer(buffer) = &string_or_buffer {
let ab = buffer.buffer;
let ab = buffer.live_array_buffer(global);
return Self::hash_to_bytes(global, input, Some(ab));
}
let Some(encoding) = Encoding::from(string_or_buffer.slice()) else {
Expand Down Expand Up @@ -1464,7 +1464,7 @@ impl<H: StaticHasher> StaticCryptoHasher<H> {
}
if let Some(string_or_buffer) = output {
if let StringOrBuffer::Buffer(buffer) = &string_or_buffer {
let ab = buffer.buffer;
let ab = buffer.live_array_buffer(global);
return this.digest_to_bytes(global, Some(ab));
}
let Some(encoding) = Encoding::from(string_or_buffer.slice()) else {
Expand Down
4 changes: 3 additions & 1 deletion src/runtime/node/node_fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3891,7 +3891,9 @@ pub mod args {
}
}
}
if arguments.will_be_async && matches!(args.buffer, StringOrBuffer::Buffer(_)) {
if arguments.will_be_async
&& matches!(&args.buffer, StringOrBuffer::Buffer(b) if !b.owns_buffer)
{
if let Some(pinned) = bv.as_pinned_arraybuffer(ctx) {
args.buffer = StringOrBuffer::Buffer(Buffer {
buffer: pinned,
Expand Down
73 changes: 49 additions & 24 deletions src/runtime/node/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@
Self::EncodedSlice(_encoded) => {
// ZigStringSlice has Drop; cleanup is implicit.
}
Self::Buffer(_) => {}
Self::Buffer(buffer) => {
buffer.destroy();
}

Check warning on line 279 in src/runtime/node/types.rs

View check run for this annotation

Claude / Claude Code Review

Stale comments claim StringOrBuffer::Drop is a no-op for Buffer

Now that `Drop for StringOrBuffer` calls `buffer.destroy()`, the comments at `src/runtime/webcore/Blob.rs:4037` and `src/runtime/webcore/fetch.rs:1822` ("StringOrBuffer::Drop is a no-op for Buffer; release the readFile allocation explicitly") are false, and the explicit `buf.destroy()` calls that follow are redundant. No runtime effect — `destroy()` is idempotent — but the comments will actively mislead the next reader about Drop semantics; consider deleting both the comments and the now-dead ex
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
Expand Down Expand Up @@ -356,7 +358,9 @@
if buffer.buffer.value != JSValue::ZERO {
return Ok(buffer.buffer.value);
}
Ok(buffer.to_node_buffer(ctx))
let js = buffer.to_node_buffer(ctx);
buffer.owns_buffer = false;
Ok(js)
}
}
}
Expand All @@ -371,6 +375,47 @@
}
}

/// Core of the `ArrayBuffer`/view arm of `from_js_*`. `pin()` guards
/// `transfer()` but not `ArrayBuffer.prototype.resize()`: a shrink
/// mprotects trimmed pages `PROT_NONE` while a borrowed slice still spans
/// them, so a later argument's getter/`toString` (sync) or the JS thread
/// (async) can SIGSEGV the reader. Snapshot resizable non-shared inputs
/// into an owned `Buffer` so variant dispatch (CryptoHasher output,
/// `fs.write`) stays intact; growable `SharedArrayBuffer` only grows
/// in-place so the captured extent remains readable.
#[inline]
fn array_buffer_into(out: &mut Self, global: &JSGlobalObject, value: JSValue, is_async: bool) {
let ab = value.as_array_buffer(global).unwrap_or_default();
let buffer = if ab.resizable && !ab.shared {
let bytes = ab.byte_slice();
let mut owned = if bytes.is_empty() {
Buffer::EMPTY
} else {
global.vm().report_extra_memory(bytes.len());
bun_core::handle_oom(Buffer::from_string(bytes))
};
owned.buffer.value = value;
owned.buffer.typed_array_type = ab.typed_array_type;
owned
} else if is_async {
Buffer::from_js_pinned(global, value).unwrap_or(Buffer {
buffer: ab,
owns_buffer: false,
pinned: false,
})
} else {
Buffer {
buffer: ab,
owns_buffer: false,
pinned: false,
}
};
if is_async {
buffer.buffer.value.protect();
}
*out = Self::Buffer(buffer);
}

/// Out-param core of [`from_js_maybe_async`]. Writes the decoded payload
/// directly into `*out` and returns
/// `Ok(true)` on success, `Ok(false)` if `value` is not a string/buffer
Expand Down Expand Up @@ -437,18 +482,7 @@
| JSType::BigInt64Array
| JSType::BigUint64Array
| JSType::DataView => {
let buffer = if is_async {
Buffer::from_js_pinned(global, value)
.unwrap_or_else(|| Buffer::from_array_buffer(global, value))
} else {
Buffer::from_array_buffer(global, value)
};

if is_async {
buffer.buffer.value.protect();
}

*out = Self::Buffer(buffer);
Self::array_buffer_into(out, global, value, is_async);
Ok(true)
}
_ => Ok(false),
Expand Down Expand Up @@ -508,16 +542,7 @@
allow_string_object: bool,
) -> JsResult<bool> {
if value.is_cell() && value.js_type().is_array_buffer_like() {
let buffer = if is_async {
Buffer::from_js_pinned(global, value)
.unwrap_or_else(|| Buffer::from_array_buffer(global, value))
} else {
Buffer::from_array_buffer(global, value)
};
if is_async {
buffer.buffer.value.protect();
}
*out = Self::Buffer(buffer);
Self::array_buffer_into(out, global, value, is_async);
return Ok(true);
}

Expand Down
85 changes: 85 additions & 0 deletions test/js/node/crypto/scrypt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,88 @@ test("scrypt async does not leak callback/buffers when output allocation fails",

expect(exitCode).toBe(0);
});

// `StringOrBuffer::from_js` borrowed the password/salt view, then a later
// argument's getter ran `ArrayBuffer.prototype.resize(0)`, which mprotects
// the trimmed pages PROT_NONE while the borrowed slice still spans them;
// reading it SIGSEGVs. `pin()` only guards `transfer()`, so resizable
// non-shared inputs are now snapshotted at capture time.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
test("scrypt reads resizable ArrayBuffer inputs at capture time even if a later arg resizes them", async () => {
const script = `
const crypto = require("node:crypto");
const SIZE = 1 << 16;
const fixed = b => Buffer.alloc(SIZE, b);
const resizable = b => new Uint8Array(new ArrayBuffer(SIZE, { maxByteLength: SIZE })).fill(b);

const fullPw = crypto.scryptSync(fixed(0x41), fixed(0x42).subarray(0, 16), 16, { N: 1024 }).toString("hex");
const fullSalt = crypto.scryptSync(fixed(0x41).subarray(0, 16), fixed(0x42), 16, { N: 1024 }).toString("hex");

const out = {};

// sync: options.N getter resizes the captured password to 0.
{
const pw = resizable(0x41);
out.syncPw = crypto.scryptSync(pw, fixed(0x42).subarray(0, 16), 16, {
get N() { pw.buffer.resize(0); return 1024; },
}).toString("hex") === fullPw;
}
// sync: options.N getter resizes the captured salt to 0.
{
const salt = resizable(0x42);
out.syncSalt = crypto.scryptSync(fixed(0x41).subarray(0, 16), salt, 16, {
get N() { salt.buffer.resize(0); return 1024; },
}).toString("hex") === fullSalt;
}
// async: JS thread resizes the password after the job is queued.
{
const pw = resizable(0x41);
const p = new Promise((res, rej) =>
crypto.scrypt(pw, fixed(0x42).subarray(0, 16), 16, { N: 1024 }, (e, k) => e ? rej(e) : res(k)));
pw.buffer.resize(0);
out.asyncPw = (await p).toString("hex") === fullPw;
}
// zero-length resizable input stays zero-length.
{
const pw = new Uint8Array(new ArrayBuffer(0, { maxByteLength: SIZE }));
out.syncEmpty = crypto.scryptSync(pw, fixed(0x42).subarray(0, 16), 16, { N: 1024 }).toString("hex")
=== crypto.scryptSync(Buffer.alloc(0), fixed(0x42).subarray(0, 16), 16, { N: 1024 }).toString("hex");
}
// growable SharedArrayBuffer is not snapshotted (grow-only, reading the
// captured extent stays valid) but still derives the same key.
{
const pw = new Uint8Array(new SharedArrayBuffer(SIZE, { maxByteLength: 2 * SIZE })).fill(0x41);
out.sab = crypto.scryptSync(pw, fixed(0x42).subarray(0, 16), 16, { N: 1024 }).toString("hex") === fullPw;
}

// regression guard: passing a resizable output buffer to Bun.SHA256.hash
// still writes into the caller's buffer, not a private copy.
{
const dst = new Uint8Array(new ArrayBuffer(32, { maxByteLength: 64 }));
const ret = Bun.SHA256.hash(fixed(0x41).subarray(0, 5), dst);
const want = Bun.SHA256.hash(fixed(0x41).subarray(0, 5));
out.hashOutput = ret === dst && Buffer.from(dst).equals(Buffer.from(want));
}

console.log(JSON.stringify(out));
`;

await using proc = Bun.spawn({
cmd: [bunExe(), "-e", script],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stderr).toBe("");
expect(JSON.parse(stdout.trim())).toEqual({
syncPw: true,
syncSalt: true,
asyncPw: true,
syncEmpty: true,
sab: true,
hashOutput: true,
});
expect(exitCode).toBe(0);
});
Loading