Skip to content

Commit 55a6515

Browse files
mcollinaaduh95
authored andcommitted
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: #67542 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it>
1 parent 265bbc1 commit 55a6515

4 files changed

Lines changed: 102 additions & 2 deletions

File tree

‎lib/internal/stream_base_commons.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
const {
44
Array,
5+
ArrayBufferPrototypeGetDetached,
56
Symbol,
67
} = primordials;
78

@@ -188,6 +189,15 @@ function onStreamRead(arrayBuffer) {
188189
if (isUint8Array(nextBuf))
189190
stream[kBuffer] = ret = nextBuf;
190191
}
192+
// If the buffer that will be reused for the next read was detached during
193+
// the callback (e.g. by transferring a view into a byte `ReadableStream`),
194+
// it can no longer be safely written to. Stop reading instead of handing
195+
// the stale address back to the native read path.
196+
const reusableBuf = stream[kBuffer];
197+
if (isUint8Array(reusableBuf) &&
198+
ArrayBufferPrototypeGetDetached(reusableBuf.buffer)) {
199+
result = false;
200+
}
191201
} else {
192202
const offset = streamBaseState[kArrayBufferOffset];
193203
const buf = new FastBuffer(arrayBuffer, offset, nread);

‎src/stream_base.cc‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,9 @@ int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) {
164164
CHECK(Buffer::HasInstance(args[0]));
165165

166166
uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0]));
167-
PushStreamListener(new CustomBufferJSListener(buf));
167+
Local<ArrayBuffer> array_buffer = args[0].As<v8::ArrayBufferView>()->Buffer();
168+
PushStreamListener(
169+
new CustomBufferJSListener(array_buffer->GetBackingStore(), buf));
168170
return 0;
169171
}
170172

@@ -825,8 +827,11 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
825827
StreamBase::SKIP_NREAD_CHECKS);
826828
Local<Value> next_buf_v;
827829
if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
830+
Local<ArrayBuffer> array_buffer =
831+
next_buf_v.As<v8::ArrayBufferView>()->Buffer();
828832
buffer_.base = Buffer::Data(next_buf_v);
829833
buffer_.len = Buffer::Length(next_buf_v);
834+
backing_store_ = array_buffer->GetBackingStore();
830835
}
831836
}
832837

‎src/stream_base.h‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,17 @@ class CustomBufferJSListener : public ReportWritesToJSStreamListener {
211211
void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override;
212212
void OnStreamDestroy() override { delete this; }
213213

214-
explicit CustomBufferJSListener(uv_buf_t buffer) : buffer_(buffer) {}
214+
explicit CustomBufferJSListener(
215+
std::shared_ptr<v8::BackingStore> backing_store, uv_buf_t buffer)
216+
: backing_store_(std::move(backing_store)), buffer_(buffer) {}
215217

216218
private:
219+
// Retain the backing store for the lifetime of the listener. The raw address
220+
// in `buffer_` is derived from it, so retaining the backing store guarantees
221+
// the address does not dangle even if application code later transfers (and
222+
// thereby detaches) the buffer, e.g. by enqueuing a view into a byte
223+
// `ReadableStream`.
224+
std::shared_ptr<v8::BackingStore> backing_store_;
217225
uv_buf_t buffer_;
218226
};
219227

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const net = require('net');
5+
const assert = require('assert');
6+
7+
// Regression test.
8+
//
9+
// When an `onread` callback transfers a view of the reusable buffer into a byte
10+
// `ReadableStream`, the transfer detaches the buffer's backing store. The socket
11+
// must not keep writing subsequent peer data into the detached backing store,
12+
// otherwise it corrupts the chunk the application has retained.
13+
14+
let controller;
15+
const stream = new ReadableStream({
16+
type: 'bytes',
17+
start(c) {
18+
controller = c;
19+
},
20+
});
21+
const reader = stream.getReader();
22+
23+
const server = net.createServer(common.mustCall((socket) => {
24+
socket.setNoDelay(true);
25+
socket.write('first');
26+
// Send more data shortly after the client transfers the first chunk.
27+
const timer = setTimeout(() => {
28+
socket.write('Z'.repeat(1024));
29+
}, 50);
30+
socket.on('close', () => clearTimeout(timer));
31+
socket.on('error', common.mustNotCall());
32+
}));
33+
34+
server.listen(0, common.mustCall(() => {
35+
const port = server.address().port;
36+
37+
let transferred = false;
38+
39+
const client = net.createConnection({
40+
host: '127.0.0.1',
41+
port,
42+
onread: {
43+
buffer: Buffer.alloc(4096),
44+
callback(nread, buf) {
45+
// Enqueueing a view transfers (and thereby detaches) the underlying
46+
// ArrayBuffer. An affected binary then keeps writing later peer data
47+
// over this chunk's memory.
48+
if (transferred) return;
49+
transferred = true;
50+
const view = new Uint8Array(buf.buffer, buf.byteOffset, nread);
51+
controller.enqueue(view);
52+
},
53+
},
54+
});
55+
56+
client.on('error', common.mustNotCall());
57+
58+
(async () => {
59+
const { value: chunk, done } = await reader.read();
60+
assert.strictEqual(done, false);
61+
62+
// The first peer write ("first", 5 bytes) is delivered intact.
63+
assert.strictEqual(chunk[0], 0x66); // 'f'
64+
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
65+
66+
// Give the second peer write time to reach the client. Reading has stopped,
67+
// so the retained chunk must not be overwritten.
68+
await new Promise((resolve) => setTimeout(resolve, 200));
69+
70+
assert.strictEqual(chunk[0], 0x66,
71+
`retained chunk was corrupted: 0x${chunk[0].toString(16)}`);
72+
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
73+
74+
client.end();
75+
server.close();
76+
})().then(common.mustCall());
77+
}));

0 commit comments

Comments
 (0)