Skip to content

Commit 88af668

Browse files
committed
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>
1 parent 24f2323 commit 88af668

4 files changed

Lines changed: 107 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
@@ -163,7 +163,9 @@ int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) {
163163
CHECK(Buffer::HasInstance(args[0]));
164164

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

@@ -795,8 +797,11 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) {
795797
StreamBase::SKIP_NREAD_CHECKS);
796798
Local<Value> next_buf_v;
797799
if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) {
800+
Local<ArrayBuffer> array_buffer =
801+
next_buf_v.As<v8::ArrayBufferView>()->Buffer();
798802
buffer_.base = Buffer::Data(next_buf_v);
799803
buffer_.len = Buffer::Length(next_buf_v);
804+
backing_store_ = array_buffer->GetBackingStore();
800805
}
801806
}
802807

‎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: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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 has transferred the first chunk.
27+
const timer = setTimeout(() => {
28+
socket.write('Z'.repeat(1024));
29+
}, 50);
30+
socket.on('close', () => clearTimeout(timer));
31+
// If the protocol stack tears the connection down while data is still
32+
// buffered on the client side, the peer may surface ECONNRESET. Tolerate it.
33+
socket.on('error', (err) => assert.strictEqual(err.code, 'ECONNRESET'));
34+
}));
35+
36+
server.listen(0, common.mustCall(() => {
37+
const port = server.address().port;
38+
39+
let transferred = false;
40+
41+
const client = net.createConnection({
42+
host: '127.0.0.1',
43+
port,
44+
onread: {
45+
buffer: Buffer.alloc(4096),
46+
callback(nread, buf) {
47+
// Enqueueing a view transfers (and thereby detaches) the underlying
48+
// ArrayBuffer. On an affected binary a subsequent peer write would
49+
// overwrite this chunk's memory.
50+
if (transferred) return;
51+
transferred = true;
52+
const view = new Uint8Array(buf.buffer, buf.byteOffset, nread);
53+
controller.enqueue(view);
54+
},
55+
},
56+
});
57+
58+
// Once the reusable buffer is detached the socket stops reading. Tearing the
59+
// connection down afterwards may surface ECONNRESET; it is not the condition
60+
// under test.
61+
client.on('error', (err) => assert.strictEqual(err.code, 'ECONNRESET'));
62+
63+
(async () => {
64+
const { value: chunk, done } = await reader.read();
65+
assert.strictEqual(done, false);
66+
67+
// The first peer write ("first", 5 bytes) is delivered intact.
68+
assert.strictEqual(chunk[0], 0x66); // 'f'
69+
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
70+
71+
// Give the second peer write time to reach the client. Reading has stopped,
72+
// so the retained chunk must not be corrupted.
73+
await new Promise((resolve) => setTimeout(resolve, 200));
74+
75+
assert.strictEqual(chunk[0], 0x66,
76+
`retained chunk was corrupted: 0x${chunk[0].toString(16)}`);
77+
assert.strictEqual(Buffer.from(chunk).toString(), 'first');
78+
79+
client.end();
80+
server.close();
81+
})().then(common.mustCall());
82+
}));

0 commit comments

Comments
 (0)