Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7369d77

Browse files
Eusgorjuanarbol
authored andcommitted
http2: avoid uaf while receiving and sending rst_stream
Mark the session as receiving around nghttp2_session_mem_recv() and defer RST_STREAM handling while receive is in progress. This prevents closing a stream while nghttp2 still processes it and avoids heap-use-after-free in nghttp2_session_mem_recv2(). Fixes: #64113 Signed-off-by: Evgeniy Gorbanev <gorbanev.es@gmail.com> PR-URL: #64166 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Tim Perry <pimterry@gmail.com> Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com> Signed-off-by: Juan JosΓ© Arboleda <soyjuanarbol@gmail.com>
1 parent 7ffe4be commit 7369d77

2 files changed

Lines changed: 120 additions & 6 deletions

File tree

β€Žsrc/node_http2.ccβ€Ž

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,21 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
820820
return;
821821
set_closing();
822822

823+
// Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks.
824+
// ConsumeHTTP2Data() finishes the close once mem_recv returns.
825+
if (is_receiving()) {
826+
set_close_pending();
827+
pending_close_code_ = code;
828+
pending_close_socket_closed_ = socket_closed;
829+
return;
830+
}
831+
832+
FinishClose(code, socket_closed);
833+
}
834+
835+
voidHttp2Session::FinishClose(uint32_t code, bool socket_closed) {
836+
CHECK(is_closing());
837+
823838
// Stop reading on the i/o stream
824839
if (stream_ != nullptr) {
825840
set_reading_stopped();
@@ -869,6 +884,12 @@ void Http2Session::Close(uint32_t code, bool socket_closed) {
869884
EmitStatistics();
870885
}
871886

887+
voidHttp2Session::MaybeFinishPendingClose() {
888+
if (!is_close_pending() || is_destroyed()) return;
889+
set_close_pending(false);
890+
FinishClose(pending_close_code_, pending_close_socket_closed_);
891+
}
892+
872893
// Locates an existing known stream by ID. nghttp2 has a similar method
873894
// but this is faster and does not fail if the stream is not found.
874895
BaseObjectPtr<Http2Stream> Http2Session::FindStream(int32_t id) {
@@ -963,11 +984,13 @@ void Http2Session::ConsumeHTTP2Data() {
963984
nghttp2_session_want_read(session_.get()));
964985
set_receive_paused(false);
965986
custom_recv_error_code_ = nullptr;
987+
set_receiving();
966988
ssize_t ret =
967989
nghttp2_session_mem_recv(session_.get(),
968990
reinterpret_cast<uint8_t*>(stream_buf_.base) +
969991
stream_buf_offset_,
970992
read_len);
993+
set_receiving(false);
971994
CHECK_NE(ret, NGHTTP2_ERR_NOMEM);
972995
CHECK_IMPLIES(custom_recv_error_code_ != nullptr, ret < 0);
973996

@@ -981,6 +1004,10 @@ void Http2Session::ConsumeHTTP2Data() {
9811004
// Even if all bytes were received, a paused stream may delay the
9821005
// nghttp2_on_frame_recv_callback which may have an END_STREAM flag.
9831006
stream_buf_offset_ += ret;
1007+
// Still complete a Close() deferred during mem_recv; do not fall through
1008+
// to SendPendingData() here (paused receives historically skip that flush
1009+
// because a write may already be in progress).
1010+
MaybeFinishPendingClose();
9841011
goto done;
9851012
}
9861013

@@ -991,12 +1018,23 @@ void Http2Session::ConsumeHTTP2Data() {
9911018
stream_buf_allocation_.reset();
9921019
stream_buf_ = uv_buf_init(nullptr, 0);
9931020

1021+
// Finish a Close() deferred during mem_recv before flushing, so GOAWAY is
1022+
// not written after pending RST_STREAM frames.
1023+
MaybeFinishPendingClose();
1024+
1025+
done:
1026+
// Finish a Close() deferred above before flushing, so GOAWAY is not written
1027+
// after pending RST_STREAM frames.
1028+
if (is_close_pending() && !is_destroyed()) {
1029+
set_close_pending(false);
1030+
FinishClose(pending_close_code_, pending_close_socket_closed_);
1031+
}
1032+
9941033
// Send any data that was queued up while processing the received data.
9951034
if (ret >= 0 && !is_destroyed()) {
9961035
SendPendingData();
9971036
}
9981037

999-
done:
10001038
if (ret < 0) [[unlikely]] {
10011039
Isolate* isolate = env()->isolate();
10021040
Debug(this,
@@ -1410,6 +1448,9 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14101448
len -= avail;
14111449
stream->EmitRead(avail, buf);
14121450

1451+
// JS may have destroyed the stream from inside onread; stop delivering.
1452+
if (stream->is_destroyed()) break;
1453+
14131454
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14141455
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14151456
// more data is being requested.
@@ -1967,6 +2008,12 @@ uint8_t Http2Session::SendPendingData() {
19672008
// SendPendingData should not be called recursively.
19682009
if (is_sending())
19692010
return1;
2011+
2012+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2013+
// incoming data. Sending may close the stream and free nghttp2 state
2014+
// that is still in use by `nghttp2_session_mem_recv()`.
2015+
if (is_receiving()) return1;
2016+
19702017
// This is cleared by ClearOutgoing().
19712018
set_sending();
19722019

@@ -2376,10 +2423,48 @@ void Http2Stream::Destroy() {
23762423
// Do nothing if this stream instance is already destroyed
23772424
if (is_destroyed())
23782425
return;
2379-
if (session_->has_pending_rststream(id_))
2380-
FlushRstStream();
2426+
2427+
// Session may already be gone if destroy was deferred across a session
2428+
// teardown.
2429+
if (!session_) {
2430+
set_destroyed();
2431+
Detach();
2432+
return;
2433+
}
2434+
2435+
// Mark destroyed immediately so OnDataChunkReceived stops EmitRead into an
2436+
// already-destroyed JS stream (which would treat the byte count as errno).
23812437
set_destroyed();
23822438

2439+
// While mem_recv is active, do not FlushRstStream or RemoveStream yet:
2440+
// - FlushRstStream would close the nghttp2 stream before queued response
2441+
// DATA can be mem_send'd after receive returns.
2442+
// - RemoveStream would make OnSendData/Provider::OnRead fail to FindStream.
2443+
// Pending RSTs stay in pending_rst_streams_ and are flushed from
2444+
// ClearOutgoing after the post-receive SendPendingData.
2445+
if (session_->is_receiving()) {
2446+
BaseObjectPtr<Http2Stream> strong_ref{this};
2447+
env()->SetImmediate(
2448+
[this, strong_ref](Environment*) { CompleteDestroyCleanup(); });
2449+
return;
2450+
}
2451+
2452+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2453+
2454+
CompleteDestroyCleanup();
2455+
}
2456+
2457+
voidHttp2Stream::CompleteDestroyCleanup() {
2458+
if (!session_) {
2459+
Detach();
2460+
return;
2461+
}
2462+
2463+
// Destroy() always set_destroyed() before scheduling or calling this.
2464+
CHECK(is_destroyed());
2465+
2466+
if (session_->has_pending_rststream(id_)) FlushRstStream();
2467+
23832468
Debug(this, "destroying stream");
23842469

23852470
// Wait until the start of the next loop to delete because there
@@ -2416,7 +2501,6 @@ void Http2Stream::Destroy() {
24162501
EmitStatistics();
24172502
}
24182503

2419-
24202504
// Initiates a response on the Http2Stream using data provided via the
24212505
// StreamBase Streams API.
24222506
intHttp2Stream::SubmitResponse(const Http2Headers& headers, int options) {
@@ -2525,6 +2609,18 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25252609
return code == NGHTTP2_CANCEL;
25262610
};
25272611

2612+
// Do not call `nghttp2_session_mem_send()` while nghttp2 is processing
2613+
// incoming data. Sending may close the stream and free nghttp2 state
2614+
// that is still in use by `nghttp2_session_mem_recv()`.
2615+
if (session_->is_receiving() && available_outbound_length_ == 0) {
2616+
if (is_stream_cancel(code)) {
2617+
session_->AddPendingRstStream(id_);
2618+
return;
2619+
}
2620+
FlushRstStream();
2621+
return;
2622+
}
2623+
25282624
// If RST_STREAM frame is received with error code NGHTTP2_CANCEL,
25292625
// add it to the pending list and don't force purge the data. It is
25302626
// to avoids the double free error due to unwanted behavior of nghttp2.
@@ -2560,8 +2656,8 @@ void Http2Stream::SubmitRstStream(const uint32_t code) {
25602656
}
25612657

25622658
voidHttp2Stream::FlushRstStream() {
2563-
if (is_destroyed())
2564-
return;
2659+
if (!session_) return;
2660+
session_->RemovePendingRstStream(id_);
25652661
Http2Scope h2scope(this);
25662662
CHECK_EQ(nghttp2_submit_rst_stream(
25672663
session_->session(),

β€Žsrc/node_http2.hβ€Ž

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ constexpr int kSessionStateSending = 0x10;
7676
constexprintkSessionStateWriteInProgress = 0x20;
7777
constexprintkSessionStateReadingStopped = 0x40;
7878
constexprintkSessionStateReceivePaused = 0x80;
79+
constexprintkSessionStateReceiving = 0x100;
80+
constexprintkSessionStateClosePending = 0x200;
7981

8082
// The Padding Strategy determines the method by which extra padding is
8183
// selected for HEADERS and DATA frames. These are configurable via the
@@ -326,6 +328,10 @@ class Http2Stream : public AsyncWrap,
326328
// Destroy this stream instance and free all held memory.
327329
voidDestroy();
328330

331+
// Completes Destroy() after set_destroyed(); may run deferred until after
332+
// nghttp2_session_mem_recv() returns.
333+
voidCompleteDestroyCleanup();
334+
329335
boolis_destroyed() const {
330336
return flags_ & kStreamStateDestroyed;
331337
}
@@ -654,6 +660,8 @@ class Http2Session : public AsyncWrap,
654660
IS_FLAG(write_in_progress, kSessionStateWriteInProgress)
655661
IS_FLAG(reading_stopped, kSessionStateReadingStopped)
656662
IS_FLAG(receive_paused, kSessionStateReceivePaused)
663+
IS_FLAG(receiving, kSessionStateReceiving)
664+
IS_FLAG(close_pending, kSessionStateClosePending)
657665

658666
#undef IS_FLAG
659667

@@ -699,6 +707,10 @@ class Http2Session : public AsyncWrap,
699707
stream_id);
700708
}
701709

710+
voidRemovePendingRstStream(int32_t stream_id) {
711+
std::erase(pending_rst_streams_, stream_id);
712+
}
713+
702714
// Handle reads/writes from the underlying network transport.
703715
uv_buf_tOnStreamAlloc(size_t suggested_size) override;
704716
voidOnStreamRead(ssize_t nread, constuv_buf_t& buf) override;
@@ -948,6 +960,10 @@ class Http2Session : public AsyncWrap,
948960
std::vector<uint8_t> outgoing_storage_;
949961
size_t outgoing_length_ = 0;
950962
std::vector<int32_t> pending_rst_streams_;
963+
// Saved arguments for Close() deferred while nghttp2_session_mem_recv()
964+
// callbacks are active.
965+
uint32_t pending_close_code_ = NGHTTP2_NO_ERROR;
966+
bool pending_close_socket_closed_ = false;
951967
// Count streams that have been rejected while being opened. Exceeding a fixed
952968
// limit will result in the session being destroyed, as an indication of a
953969
// misbehaving peer. This counter is reset once new streams are being
@@ -962,6 +978,8 @@ class Http2Session : public AsyncWrap,
962978

963979
voidCopyDataIntoOutgoing(constuint8_t* src, size_t src_length);
964980
voidClearOutgoing(int status);
981+
voidFinishClose(uint32_t code, bool socket_closed);
982+
voidMaybeFinishPendingClose();
965983

966984
voidMaybeNotifyGracefulCloseComplete();
967985

0 commit comments

Comments
Β (0)