stream: stop reusing a detached onread buffer

CustomBufferJSListener keeps only the raw address (uv_buf_t) of the
user-supplied onread buffer, without retaining the backing store. If
application code transfers (and thereby detaches) that buffer during the
onread callback, for example by enqueuing a view into a byte
ReadableStream, the backing store is moved away from under the listener
and the raw address is left dangling. Reading subsequent peer data into
that address then corrupts memory the application owns, and if the
backing store is later released, it becomes a use-after-free.

Retain the backing store in CustomBufferJSListener so the raw address
never dangles, and stop reading when the onread callback detaches the
buffer so the stale address is not handed back to libuv.

Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/67542
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
This commit is contained in:
Matteo Collina authored and Antoine du Hamel committed 2026-11-23 12:34:21 +01:00
1 parent 265bbc1b9c
commit 55a6515165
4 files changed
+102 -2

No files matched your search

+10
View File
@@ -2,6 +2,7 @@
const {
Array,
ArrayBufferPrototypeGetDetached,
Symbol,
} = primordials;
@@ -188,6 +189,15 @@ function onStreamRead(arrayBuffer) {
if (isUint8Array(nextBuf))
stream[kBuffer] = ret = nextBuf;
}
// If the buffer that will be reused for the next read was detached during
// the callback (e.g. by transferring a view into a byte `ReadableStream`),
// it can no longer be safely written to. Stop reading instead of handing
// the stale address back to the native read path.
const reusableBuf = stream[kBuffer];
if (isUint8Array(reusableBuf) &&
ArrayBufferPrototypeGetDetached(reusableBuf.buffer)) {
result = false;
}
} else {
const offset = streamBaseState[kArrayBufferOffset];
const buf = new FastBuffer(arrayBuffer, offset, nread);
+6 -1
View File
@@ -164,7 +164,9 @@ int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(Buffer::HasInstance(args[0]));
uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0]));
PushStreamListener(new CustomBufferJSListener(buf));
Local<ArrayBuffer> array_buffer = args[0].As<v8::ArrayBufferView>()->Buffer();
PushStreamListener(
new CustomBufferJSListener(array_buffer->GetBackingStore(), buf));
return 0;
}
@@ -825,8 +827,11 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
StreamBase::SKIP_NREAD_CHECKS);
Local<Value> next_buf_v;
if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
Local<ArrayBuffer> array_buffer =
next_buf_v.As<v8::ArrayBufferView>()->Buffer();
buffer_.base = Buffer::Data(next_buf_v);
buffer_.len = Buffer::Length(next_buf_v);
backing_store_ = array_buffer->GetBackingStore();
}
}
+9 -1
View File
@@ -211,9 +211,17 @@ class CustomBufferJSListener : public ReportWritesToJSStreamListener {
void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
void OnStreamDestroy() override { delete this; }
explicit CustomBufferJSListener(uv_buf_t buffer) : buffer_(buffer) {}
explicit CustomBufferJSListener(
std::shared_ptr<v8::BackingStore> backing_store, uv_buf_t buffer)
: backing_store_(std::move(backing_store)), buffer_(buffer) {}
private:
// Retain the backing store for the lifetime of the listener. The raw address
// in `buffer_` is derived from it, so retaining the backing store guarantees
// the address does not dangle even if application code later transfers (and
// thereby detaches) the buffer, e.g. by enqueuing a view into a byte
// `ReadableStream`.
std::shared_ptr<v8::BackingStore> backing_store_;
uv_buf_t buffer_;
};
@@ -0,0 +1,77 @@
'use strict';
const common = require('../common');
const net = require('net');
const assert = require('assert');
// Regression test.
//
// When an `onread` callback transfers a view of the reusable buffer into a byte
// `ReadableStream`, the transfer detaches the buffer's backing store. The socket
// must not keep writing subsequent peer data into the detached backing store,
// otherwise it corrupts the chunk the application has retained.
let controller;
const stream = new ReadableStream({
type: 'bytes',
start(c) {
controller = c;
},
});
const reader = stream.getReader();
const server = net.createServer(common.mustCall((socket) => {
socket.setNoDelay(true);
socket.write('first');
// Send more data shortly after the client transfers the first chunk.
const timer = setTimeout(() => {
socket.write('Z'.repeat(1024));
}, 50);
socket.on('close', () => clearTimeout(timer));
socket.on('error', common.mustNotCall());
}));
server.listen(0, common.mustCall(() => {
const port = server.address().port;
let transferred = false;
const client = net.createConnection({
host: '127.0.0.1',
port,
onread: {
buffer: Buffer.alloc(4096),
callback(nread, buf) {
// Enqueueing a view transfers (and thereby detaches) the underlying
// ArrayBuffer. An affected binary then keeps writing later peer data
// over this chunk's memory.
if (transferred) return;
transferred = true;
const view = new Uint8Array(buf.buffer, buf.byteOffset, nread);
controller.enqueue(view);
},
},
});
client.on('error', common.mustNotCall());
(async () => {
const { value: chunk, done } = await reader.read();
assert.strictEqual(done, false);
// The first peer write ("first", 5 bytes) is delivered intact.
assert.strictEqual(chunk[0], 0x66); // 'f'
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
// Give the second peer write time to reach the client. Reading has stopped,
// so the retained chunk must not be overwritten.
await new Promise((resolve) => setTimeout(resolve, 200));
assert.strictEqual(chunk[0], 0x66,
`retained chunk was corrupted: 0x${chunk[0].toString(16)}`);
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
client.end();
server.close();
})().then(common.mustCall());
}));