Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina
, '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

Drop the hand-rolled TLS client hello parser - #64827

Closed
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser
Closed

Drop the hand-rolled TLS client hello parser#64827
pimterry wants to merge 2 commits into
nodejs:mainfrom
pimterry:drop-client-parser

Conversation

@pimterry

Copy link
Copy Markdown
Member

Our TLS code currently contains a custom parser for TLS client hellos hand-rolled in C++. This is complicated and a bit scary (which is why we have a separate fuzzer for it) and does extra work anytime it's used: OpenSSL already parses the hello, and this duplicates it, and adds checks throughout various other methods to support that. It's only required for a niche legacy feature (TLS session ids) that isn't even supported in TLS 1.3, but it makes up just under 10% of our TLS implementation (and ~15% of the TLS C++).

This parser exists because 'resumeSession' needs to support async lookups for session ids, on top of OpenSSL's SSL_CTX_sess_set_get_cb which is sync-only. We handled that by parsing out the session id ourselves, in advance, and passing through to OpenSSL when we were ready to answer synchronously.

Nowadays though (since OpenSSL 1.1.1) both OpenSSL & BoringSSL have an early ClientHello callback with suspend/resume support to handle this properly. This custom parser is redundant, and can be replaced by standard APIs in both backends.

We've previously talked about dropping this, over literally more than a decade, e.g. #1464 stopping using the parser to power SNI & OCSP, #1462 discussed dropping session ids completely to help us kill it, and #5774 trying to deprecate it away.

Nowadays it's much easier and we don't need any breaking changes at all. This PR deletes lots of code and switches to the modern mechanisms for this (separate impls for BoringSSL & OpenSSL). It drops the client hello parser & all related infrastructure, while preserving all the functionality. We could aim to drop session ids later anyway as a breaking change, but this makes them very cheap to keep in the meantime.

In addition, one of the new tests here covers a bug that this fixes en route: the hello parser silently dropped session events on fragmented hellos, which we now handle correctly instead for free. That fix should be the only externally visible change.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/crypto
  • @nodejs/gyp
  • @nodejs/net

@nodejs-github-botnodejs-github-bot added c++ Issues and PRs that require attention from people who are familiar with C++. lib / src Issues and PRs involving general changes in the lib/ or src/ directories. needs-ci PRs that need a full CI run. labels Jul 29, 2026

@mcollinamcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry
pimterryforce-pushed the drop-client-parser branch from 00c4a38 to 5875e8eCompareJuly 29, 2026 18:38
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

CI: https://ci.nodejs.org/job/node-test-pull-request/75299/

@codecov

codecovBot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04348% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (41525ab) to head (a2cfcc4).
⚠️ Report is 116 commits behind head on main.

Files with missing linesPatch %Lines
src/crypto/crypto_tls.cc87.95%2 Missing and 8 partials ⚠️
src/crypto/crypto_tls.h50.00%0 Missing and 1 partial ⚠️
Additional details and impacted files
@@ Coverage Diff @@## main #64827 +/- ##
==========================================
+ Coverage 90.16% 90.30% +0.14% 
==========================================
Files 746 759 +13 Lines 242660 247376 +4716 Branches 45720 46651 +931 ==========================================
+ Hits 218793 223392 +4599 - Misses 15360 15458 +98 - Partials 8507 8526 +19 
Files with missing linesCoverage Δ
lib/internal/tls/wrap.js95.15% <100.00%> (+0.04%)⬆️
src/crypto/crypto_context.cc72.34% <100.00%> (+0.06%)⬆️
src/crypto/crypto_context.h100.00% <ø> (ø)
src/crypto/crypto_tls.h82.35% <50.00%> (-4.32%)⬇️
src/crypto/crypto_tls.cc78.72% <87.95%> (+0.42%)⬆️

... and 125 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pimterry

Copy link
Copy Markdown
MemberAuthor

Had to force push to fix docs linting, but this is otherwise green and good to go. Can I get a quick re-review @nodejs/crypto or @mcollina to land this?

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

reviewing...

@panva

panva commented Aug 3, 2026

Copy link
Copy Markdown
Member

@pimterry worth looking into?

Diff
diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc
index 9981704fb34..fe11a049b9c 100644
--- a/src/crypto/crypto_tls.cc+++ b/src/crypto/crypto_tls.cc@@ -218,32 +218,18 @@ int SSLCertCallback(SSL* s, void* arg) {
// handshake will continue after certcb is done.
return -1;
- Environment* env = w->env();- HandleScope handle_scope(env->isolate());- Context::Scope context_scope(env->context());
w->set_cert_cb_running();
- Local<Object> info = Object::New(env->isolate());+ // The view points into SSL-owned memory, so copy it before deferring.+ std::string servername;+ if (auto name = SSLPointer::GetServerName(s)) servername = *name;- auto servername = SSLPointer::GetServerName(s);- Local<String> servername_str =- !servername.has_value()- ? String::Empty(env->isolate())- : OneByteString(env->isolate(), servername.value());-- Local<Value> ocsp = Boolean::New(- env->isolate(), SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);+ w->ScheduleCertCb(std::move(servername),+ SSL_get_tlsext_status_type(s) == TLSEXT_STATUSTYPE_ocsp);- if (info->Set(env->context(), env->servername_string(), servername_str)- .IsNothing() ||- info->Set(env->context(), env->ocsp_request_string(), ocsp).IsNothing()) {- return 1;- }-- Local<Value> argv[] = { info };- w->MakeCallback(env->oncertcb_string(), arraysize(argv), argv);-- return w->is_cert_cb_running() ? -1 : 1;+ // Suspend handshake with SSL_ERROR_WANT_X509_LOOKUP, and handshake will+ // continue after certcb is done.+ return -1;
}
int SelectALPNCallback(
@@ -519,9 +505,7 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
env->tls_ticket_string(),
Boolean::New(env->isolate(), has_ticket))
.IsNothing()) {
- // Continue the handshake unresumed rather than leaving it suspended.- hello_answered_ = true;- Cycle();+ // An exception is pending, so don't re-enter SSL or JS to resume.
return;
}
@@ -529,6 +513,41 @@ void TLSWrap::EmitClientHello(const std::vector<unsigned char>& session_id,
MakeCallback(env->onclienthello_string(), arraysize(argv), argv);
}
+// As with the ClientHello, JS must not run on the library's stack: 'oncertcb'+// handlers synchronously call back into the handle to resume the handshake.+void TLSWrap::ScheduleCertCb(std::string servername, bool ocsp) {+ Debug(this, "Scheduling oncertcb");+ BaseObjectPtr<TLSWrap> strong_ref{this};+ env()->SetImmediate([this,+ strong_ref,+ servername = std::move(servername),+ ocsp](Environment* env) {+ if (ssl_) EmitCertCb(servername, ocsp);+ });+}++void TLSWrap::EmitCertCb(const std::string& servername, bool ocsp) {+ Debug(this, "Emitting oncertcb");+ Environment* env = this->env();+ HandleScope handle_scope(env->isolate());+ Context::Scope context_scope(env->context());++ Local<Object> info = Object::New(env->isolate());+ if (info->Set(env->context(),+ env->servername_string(),+ OneByteString(env->isolate(), servername))+ .IsNothing() ||+ info->Set(env->context(),+ env->ocsp_request_string(),+ Boolean::New(env->isolate(), ocsp))+ .IsNothing()) {+ return;+ }++ Local<Value> argv[] = {info};+ MakeCallback(env->oncertcb_string(), arraysize(argv), argv);+}+
void TLSWrap::InitSSL() {
// Initialize SSL – OpenSSL takes ownership of these.
enc_in_ = NodeBIO::New(env()).release();
diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h
index 61f773b9c60..a5ded339291 100644
--- a/src/crypto/crypto_tls.h+++ b/src/crypto/crypto_tls.h@@ -115,6 +115,9 @@ class TLSWrap : public AsyncWrap,
size_t session_id_len,
bool has_ticket);
+ // Schedules 'oncertcb'. The handshake stays suspended until certCbDone().+ void ScheduleCertCb(std::string servername, bool ocsp);+
// Implement MemoryRetainer:
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(TLSWrap)
@@ -149,6 +152,7 @@ class TLSWrap : public AsyncWrap,
void WaitForCertCb(CertCb cb, void* arg);
void EmitClientHello(const std::vector<unsigned char>& session_id,
bool has_ticket);
+ void EmitCertCb(const std::string& servername, bool ocsp);
TLSWrap(Environment* env,
v8::Local<v8::Object> obj,
diff --git a/staged.diff b/staged.diff
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/test/parallel/test-tls-certcb-sync-write.js b/test/parallel/test-tls-certcb-sync-write.js
new file mode 100644
index 00000000000..caf591d669f
--- /dev/null+++ b/test/parallel/test-tls-certcb-sync-write.js@@ -0,0 +1,49 @@+'use strict';++// Writing to a server TLSSocket synchronously from inside an SNICallback,+// while the handshake is still waiting on the certificate callback, must not+// break the connection; the data must be delivered once the handshake ends.++const common = require('../common');++if (!common.hasCrypto)+ common.skip('missing crypto');++const assert = require('assert');+const fixtures = require('../common/fixtures');+const net = require('net');+const tls = require('tls');++const secureContext = tls.createSecureContext({+ key: fixtures.readKey('rsa_private.pem'),+ cert: fixtures.readKey('rsa_cert.crt'),+});++let serverSocket;+const server = net.createServer(common.mustCall((raw) => {+ serverSocket = new tls.TLSSocket(raw, {+ isServer: true,+ secureContext,+ SNICallback: common.mustCall((servername, callback) => {+ assert.strictEqual(servername, 'localhost');+ serverSocket.write('from-mid-handshake');+ callback(null, null);+ }),+ });+ serverSocket.on('error', common.mustNotCall());+}));++server.listen(0, common.mustCall(() => {+ const client = tls.connect({+ port: server.address().port,+ servername: 'localhost',+ rejectUnauthorized: false,+ }, common.mustCall(() => {+ client.on('data', common.mustCall((data) => {+ assert.strictEqual(data.toString(), 'from-mid-handshake');+ client.end();+ server.close();+ }));+ }));+ client.on('error', common.mustNotCall());+}));

@pimterry

Copy link
Copy Markdown
MemberAuthor

Oh good find @panva! Yes, the existing SNI/OCSP callbacks have the same reentrancy issues today as the resumeSession callback is now handling here, well spotted. I've pulled in your changes to fix them as well 👍.

@panvapanva added the commit-queue-rebase PRs the Commit Queue should land as multiple self-contained commits. label Aug 3, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
@pimterry

Copy link
Copy Markdown
MemberAuthor

Gah, missed the CPP autoformat, now fixed.

@panvapanva added author ready PRs with CI started, the required approvals, and no outstanding review comments. request-ci Add this label to start a Jenkins CI on a PR. labels Aug 3, 2026
@github-actionsgithub-actionsBot removed the request-ci Add this label to start a Jenkins CI on a PR. label Aug 3, 2026
@nodejs-github-bot

This comment was marked as outdated.

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@pimterrypimterry added the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-botnodejs-github-bot removed the commit-queue PRs queued for automated landing through the Commit Queue. label Aug 4, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Landed in 72768c7...d18457b

nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
nodejs-github-bot pushed a commit that referenced this pull request Aug 4, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
This existed for 'resumeSession', which needed to do an async lookup
though SSL_CTX_sess_set_get_cb is sync-only. Nowadays both OpenSSL &
BoringSSL have an early ClientHello callback for suspend/resume to
handle this properly, so it was redundant, in addition to being
complicated and generally a bit fragile & scary.
This PR switches to use the modern OpenSSL/BoringSSL mechanisms for this
and drops the client hello parser & related infrastructure completely.
In addition, there's a new test here, covering a fixed bug: the hello
parser silently dropped fragmented hellos, which we now do handle
correctly.
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
aduh95 pushed a commit that referenced this pull request Aug 13, 2026
Both events (backed by oncertcb) could potentially write to the socket
synchronously, re-entering SSL mid-handshake and breaking the
connection, so we defer them just like the new 'resumeSession'
behaviour.
Also fixes a small bug in the error path of EmitClientHello, which now
bails out more aggressively instead of resuming handshakes in a V8
teardown scenario.
Co-authored-by: Filip Skokan <panva.ip@gmail.com>
Signed-off-by: Tim Perry <pimterry@gmail.com>
PR-URL: #64827
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author readyPRs with CI started, the required approvals, and no outstanding review comments.c++Issues and PRs that require attention from people who are familiar with C++.commit-queue-rebasePRs the Commit Queue should land as multiple self-contained commits.lib / srcIssues and PRs involving general changes in the lib/ or src/ directories.needs-ciPRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants

@pimterry@nodejs-github-bot@panva@mcollina