Skip to content
Crypto Disclosed report Advanced CVE-2020-8172

Node.js: TLS session reuse can lead to hostname verification bypass

Node.js TLS session reuse could store sessions from servers with invalid certificates or wrong hostnames, because the 'session' event fires regardless of hostname verification. An attacker could then reuse such a session to bypass hostname verification on later connections, enabling a man-in-the-middle attack.

fwilhelm Follow

Originally disclosed on HackerOne

  • Triaged in 19 hours
  • Fixed in 3 months
  • Paid in 4 months
  • Disclosed after 3 months

The Node.js TLS library supports client side reuse of TLS sessions when multiple connections to the same server are opened.

Code that wants to use this feature can listen for the 'session' event (https://nodejs.org/api/tls.html#tls_event_session) on a tls.TLSSocket to get notified of newly created TLS sessions. The documentation for this event explicitly mentions that the passed sessions "can be used immediately or later".

The problem with this design is that 'session' events are triggered even if verification of the server certificate hostname in onConnectSecure fails. (https://github.com/nodejs/node/blob/b1d4c13430c92e94920f0c8c9ba1295c075c9e89/lib/_tls_wrap.js#L1502):

onConnectSecure is triggered by the OpenSSL info callback (with the flag SSL_CB_HANDSHAKE_DONE) after a TLS handshake. The 'session' event is triggered by OpenSSLs get_session_cb, which can happen before the info callback in TLS 1.2 and after in TLS 1.3 and which is triggered regardless of the result of onConnectSecure.

This means that sessions where the server presented an invalid certificate, or one with a wrong hostname, will trigger the session event and can end up being reused or stored in a cache.

That behavior is insecure, because resumed sessions will not be subjected to another hostname verification check as long as they are CA signed:

// Verify that server's identity matches it's certificate's names // Unless server has resumed our existing session if (!verifyError && !this.isSessionReused()) { const hostname = options.servername || options.host || (options.socket && options.socket._host) || 'localhost'; const cert = this.getPeerCertificate(true); verifyError = options.checkServerIdentity(hostname, cert); }

In practice, this means that the immediate reuse described in the API documentation is always insecure and that session caches are at risk of storing insecure sessions. The most important implementation of a session cache is in the https library (https://github.com/nodejs/node/blob/b1d4c13430c92e94920f0c8c9ba1295c075c9e89/lib/https.js#L130): New sessions are stored in the cache when the ‘session’ event is triggered and are evicted once a tls socket is closed with an error.

if (options._agentKey) { // Cache new session for reuse socket.on('session', (session) => { this._cacheSession(options._agentKey, session); });

// Evict session on error
socket.once('close', (err) => {
  if (err)
    this._evictSession(options._agentKey);
});

}

This opens a small race window where an invalid session can be used by other HTTPs requests to the same host. The attached proof-of-concept wins the race reliably against a local server using a setImmediate() callback, but there are probably other ways this could be exploited in real world applications. I also did not fully investigate if there is a way to trigger the socket ‘close’ event with no error which would skip the session eviction and turn this into a 100% reliable bypass.

The POC requires a target server with a valid CA signed certificate (for an arbitrary hostname) and support for TLS resumption. I’ve attached a minimal golang https server that worked for me.

[fwilhelm@fwilhelm node]$ ../node/node-v13.9.0-linux-x64/bin/node poc.js [!] First request failed:Host: nodejs.org. is not in the cert's altnames: DNS:loca.host [x] Starting second request [x] Dumping globalAgent._sessionCache.map: { 'nodejs.org:8444:::::::::::::::::TLSv1_2_method:': <Buffer 30 82 06 2f 02 01 01 02 02 03 04 04 02 13 01 04 20 cd b7 17 84 ac 9f 31 6f 1c cc 73 de 31 05 eb dc 60 62 df c7 c5 d5 8c b4 75 cc a7 28 1f d9 c0 22 04 ... 1537 more bytes> } [!] Bypassed hostname verification. Server response: 200 { date: 'Thu, 05 Mar 2020 17:08:24 GMT', 'content-length': '29', 'content-type': 'text/plain; charset=utf-8', connection: 'close' }

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

Impact

MitM of TLS connections

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

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

Context

Node.js ships a TLS library that supports client side reuse of TLS sessions when several connections are opened to the same server. Applications that want this feature listen for the 'session' event on a tls.TLSSocket to be notified of newly created TLS sessions. The documentation for that event states that the passed sessions "can be used immediately or later".

The most important consumer of this mechanism is the https library, which keeps a session cache on the agent so that later requests to the same host can resume an earlier session instead of performing a full handshake.

The report concerns the interaction between that session handling and hostname verification of the server certificate. The affected asset is the Node.js repository itself.

Setup

The proof of concept was run with a Node.js build from the node-v13.9.0-linux-x64 distribution, invoked from a shell prompt as shown in the exploitation section. It requires a target server that presents a valid CA signed certificate for an arbitrary hostname and that supports TLS resumption. The researcher attached a minimal Go HTTPS server that worked for the test. No other accounts, roles or tooling are described.

Finding it

The researcher observed that 'session' events are triggered even when verification of the server certificate hostname in onConnectSecure fails. The relevant code is in lib/_tls_wrap.js:

JavaScript
// Verify that server's identity matches it's certificate's names
// Unless server has resumed our existing session
if (!verifyError && !this.isSessionReused()) {
    const hostname = options.servername ||
                   options.host ||
                   (options.socket && options.socket._host) ||
                   'localhost';
    const cert = this.getPeerCertificate(true);
    verifyError = options.checkServerIdentity(hostname, cert);
}

The ordering explains why this matters. onConnectSecure is triggered by the OpenSSL info callback with the flag SSL_CB_HANDSHAKE_DONE after a TLS handshake. The 'session' event is triggered by OpenSSL's get_session_cb, which can happen before the info callback in TLS 1.2 and after it in TLS 1.3, and which fires regardless of the result of onConnectSecure.

As a result, sessions where the server presented an invalid certificate, or one with a wrong hostname, still trigger the session event and can end up being reused or stored in a cache.

Exploitation

The bypass rests on the fact that resumed sessions are not subjected to another hostname verification check as long as they are CA signed. The code above only calls checkServerIdentity when !this.isSessionReused(), so a resumed session skips the hostname comparison entirely.

In the https library, new sessions are stored in the cache when the 'session' event is triggered and are evicted once a TLS socket is closed with an error:

JavaScript
 if (options._agentKey) {
    // Cache new session for reuse
    socket.on('session', (session) => {
      this._cacheSession(options._agentKey, session);
    });

    // Evict session on error
    socket.once('close', (err) => {
      if (err)
        this._evictSession(options._agentKey);
    });
  }

This opens a small race window in which an invalid session can be used by other HTTPS requests to the same host. The proof of concept wins the race reliably against a local server using a setImmediate() callback. The researcher notes that there are probably other ways this could be exploited in real world applications, and that he did not fully investigate whether the socket 'close' event can be triggered with no error, which would skip the session eviction and turn this into a 100% reliable bypass.

Step 1: run the proof of concept against the test server

The PoC is executed with the Node.js binary from the downloaded distribution:

Bash
[fwilhelm@fwilhelm node]$ ../node/node-v13.9.0-linux-x64/bin/node poc.js

Step 2: observe the first request failing hostname verification

The first request is rejected because the certificate presented by the server does not cover the requested hostname:

Text
[!] First request failed:Host: nodejs.org. is not in the cert's altnames: DNS:loca.host

The certificate presented by the server covers loca.host, not nodejs.org. The connection fails the identity check, yet the session has already been captured by the 'session' event.

Step 3: start the second request and inspect the session cache

The second request is started, and the global agent's session cache is dumped:

Text
[x] Starting second request
[x] Dumping globalAgent._sessionCache.map:
{
  'nodejs.org:8444:::::::::::::::::TLSv1_2_method:': <Buffer 30 82 06 2f 02 01 01 02 02 03 04 04 02 13 01 04 20 cd b7 17 84 ac 9f 31 6f 1c cc 73 de 31 05 eb dc 60 62 df c7 c5 d5 8c b4 75 cc a7 28 1f d9 c0 22 04 ... 1537 more bytes>
}

The cache key contains the host and port (nodejs.org:8444) followed by TLS parameters, and the value is the serialised session. The session from the failed connection is present in the cache, which is the precondition for the bypass.

Step 4: observe the bypassed verification and the server response

The second request resumes the cached session. Because the session is reused, the hostname check is skipped, and the request succeeds against a server whose certificate does not match the hostname:

Text
[!] Bypassed hostname verification. Server response: 200
{
  date: 'Thu, 05 Mar 2020 17:08:24 GMT',
  'content-length': '29',
  'content-type': 'text/plain; charset=utf-8',
  connection: 'close'
}

The response headers show a normal HTTP 200 from the server, delivered over a connection whose peer identity was never verified against the requested hostname.

Root cause

The 'session' event is emitted from OpenSSL's get_session_cb independently of the outcome of onConnectSecure. In TLS 1.2 the callback can fire before the info callback that runs the verification, and in TLS 1.3 after it, but in neither case is the event gated on the verification result. Sessions from connections that failed certificate or hostname validation therefore reach application code and caches.

The second half of the problem is in the verification logic itself: checkServerIdentity is only invoked when the session is not reused. A resumed session is trusted on the basis that it is CA signed, so the hostname is never compared again. Combined with the https agent caching sessions on the 'session' event and evicting them only when the socket closes with an error, an invalid session can be picked up by another request to the same host during the window before eviction. The race is small but, as the PoC shows, winnable.

Impact

A man-in-the-middle of TLS connections. The report describes a man-in-the-middle of TLS connections. The PoC shows that a session from a connection that failed hostname verification can be cached and then resumed by a second request to the same host. The report describes the immediate reuse promised by the API documentation as always insecure, and session caches as at risk of storing insecure sessions. The practical exploitation shown is a race against a local server; the researcher states that other exploitation routes in real world applications probably exist but were not investigated, and that a fully reliable bypass via a 'close' event without an error was not confirmed.

Fix

The report does not describe a fix or a change that was made in response. The behaviour it identifies is that the 'session' event is emitted regardless of the verification result, and that hostname verification is skipped for resumed sessions; addressing it means not exposing or caching sessions from connections that failed verification, and not treating session resumption as a substitute for checking the peer identity.

Variants to test

  1. Other TLS clients with session caches. Look for clients that store sessions on a callback fired before identity verification completes. A positive result is a cached session entry for a host whose certificate did not match, followed by a successful resumed request.
  2. TLS 1.3 versus TLS 1.2 ordering. Test both protocol versions, since the session callback fires before the info callback in TLS 1.2 and after it in TLS 1.3. A positive result is a session captured in either ordering despite a failed hostname check.
  3. Eviction paths. Try to make the socket close without an error after an invalid session is cached. A positive result is a session that survives in the cache and is reused by later requests.
  4. Race timing. Replace the setImmediate() scheduling used in the PoC with other concurrency patterns in the target application. A positive result is a second request that resumes the invalid session before eviction.
  5. Custom checkServerIdentity implementations. Applications that supply their own identity check are equally affected if resumption skips it. A positive result is a resumed connection to a host whose certificate the custom check would have rejected.

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

What happened, in plain words

Node.js is a program that lets developers run JavaScript outside a web browser, typically on a server. It comes with a built-in library for TLS, the technology that puts the padlock in your browser and encrypts traffic between a client and a server. That library has a feature called session reuse: when a program opens several connections to the same server, it can save the details of the first secure conversation and reuse them later instead of doing the whole setup again. It is a bit like keeping your passport stamp from a previous trip so you do not have to queue at the border again.

A program that wants this feature listens for an event called 'session'. An event is simply a signal that the library sends when something happens, and listening for it means telling the library "call this piece of my code when that signal fires". The Node.js documentation says the session handed to you this way "can be used immediately or later".

The problem is that this signal fires even when the client has just discovered that the server's certificate does not belong to the hostname it asked for. A certificate is the digital ID card a server shows to prove who it is, and the hostname check is comparing the name on that ID card with the name you typed. If they do not match, the connection should be refused. But the session from that refused connection still gets saved, and later requests can reuse it. When a session is reused, Node.js skips the hostname check, so the second request goes through to a server that was never properly identified. That is the man-in-the-middle risk the report describes: a session from a connection that failed the hostname check can be reused without that check.

The researcher, fwilhelm, reported this to the Node.js project, and it was disclosed on 3 June 2020. The affected code is the Node.js repository itself.

The pieces involved

Before the details, a few terms that come up constantly.

  • TLS is the encryption layer behind HTTPS. It does two jobs: it scrambles the traffic so nobody in the middle can read it, and it checks that the server really is who it claims to be.
  • A TLS handshake is the opening conversation where client and server agree on encryption keys and exchange certificates. It is the most expensive part of a connection, which is why reuse exists.
  • A TLS session is the saved result of a handshake. Reusing it means the next connection can skip most of the work.
  • A certificate authority (CA) is an organisation that signs certificates. If a certificate is CA signed, the client can trust that the certificate really belongs to whoever requested it, but it still has to check that the name on it matches the server it is talking to.
  • Hostname verification is that name check. It is the step that stops an attacker with a genuine certificate for attacker.example from impersonating yourbank.example.
  • An API is the set of functions and events a library offers to programmers. The Node.js TLS API is what applications call to open secure connections.
  • A cache is a temporary store of things you expect to need again. Here it holds saved sessions so later requests can reuse them.
  • A race window is a short period during which two things happen in an order that can be exploited. If the bad thing happens before the good thing cleans it up, the attacker wins.

The setup

The proof of concept was run with a Node.js build from the node-v13.9.0-linux-x64 distribution, started from a shell prompt. It needs a target server that presents a valid CA signed certificate for some arbitrary hostname and that supports TLS resumption. The researcher attached a minimal Go HTTPS server that worked for the test. Nothing else is described: no accounts, no special roles, no other tools.

Finding the flaw

The researcher noticed that the 'session' event fires even when the hostname check in a function called onConnectSecure fails. The relevant code lives in lib/_tls_wrap.js:

JavaScript
// Verify that server's identity matches it's certificate's names
// Unless server has resumed our existing session
if (!verifyError && !this.isSessionReused()) {
    const hostname = options.servername ||
                   options.host ||
                   (options.socket && options.socket._host) ||
                   'localhost';
    const cert = this.getPeerCertificate(true);
    verifyError = options.checkServerIdentity(hostname, cert);
}

Line by line:

  1. The comment says the code is about to check that the server's identity matches the names on its certificate, but only if the server has not resumed an existing session.
  2. if (!verifyError && !this.isSessionReused()) is the gate. The check only runs when there is no earlier error and when the session is not being reused. If the session is reused, everything inside the block is skipped.
  3. const hostname = options.servername || options.host || (options.socket && options.socket._host) || 'localhost'; works out which hostname to compare against, trying several places the name might be stored and falling back to localhost.
  4. const cert = this.getPeerCertificate(true); fetches the certificate the server presented.
  5. verifyError = options.checkServerIdentity(hostname, cert); runs the actual comparison and stores any error.

The ordering is what makes this dangerous. onConnectSecure is triggered by a callback from OpenSSL, the library Node.js uses for TLS, with the flag SSL_CB_HANDSHAKE_DONE, meaning the handshake has finished. The 'session' event is triggered by a different OpenSSL callback, get_session_cb. In TLS 1.2 that second callback can fire before the first one; in TLS 1.3 it fires after. In neither case does it wait for the result of onConnectSecure.

So a session where the server presented an invalid certificate, or one with the wrong hostname, still triggers the session event and can be reused or stored in a cache.

How the bypass works

The bypass depends on one fact: a resumed session is not checked against the hostname again, as long as it is CA signed. Look back at the code above: checkServerIdentity is only called when !this.isSessionReused(). A resumed session skips the comparison entirely.

In the https library, the part of Node.js that makes web requests, new sessions are stored in a cache when the 'session' event fires, and removed once a TLS socket closes with an error:

JavaScript
 if (options._agentKey) {
    // Cache new session for reuse
    socket.on('session', (session) => {
      this._cacheSession(options._agentKey, session);
    });

    // Evict session on error
    socket.once('close', (err) => {
      if (err)
        this._evictSession(options._agentKey);
    });
  }

Line by line:

  1. if (options._agentKey) { only does this when there is an agent key, the identifier used to group connections to the same host.
  2. socket.on('session', (session) => { listens for the session event on the socket.
  3. this._cacheSession(options._agentKey, session); saves the session in the cache under that key.
  4. socket.once('close', (err) => { listens for the socket closing, once.
  5. if (err) checks whether the close came with an error.
  6. this._evictSession(options._agentKey); removes the session from the cache if it did.

Because the session is cached on the event and only removed when the socket closes with an error, there is a small race window in which an invalid session can be used by other HTTPS requests to the same host. The proof of concept wins that race reliably against a local server using a setImmediate() callback, which schedules work to run as soon as possible. The researcher notes there are probably other ways to exploit this in real applications, and that he did not fully investigate whether the socket 'close' event can be triggered without an error, which would skip the eviction and make the bypass 100% reliable.

Step 1: run the proof of concept against the test server

The PoC is started with the Node.js binary from the downloaded distribution:

Bash
[fwilhelm@fwilhelm node]$ ../node/node-v13.9.0-linux-x64/bin/node poc.js

This runs the script poc.js with that particular Node.js build. The prompt shows the researcher's shell and directory, and the path points at the unpacked distribution.

Step 2: watch the first request fail the hostname check

The first request is rejected because the certificate the server presented does not cover the requested hostname:

Text
[!] First request failed:Host: nodejs.org. is not in the cert's altnames: DNS:loca.host

The certificate covers loca.host, not nodejs.org. The identity check fails, yet the session has already been captured by the 'session' event. This is the heart of the bug: the failure does not stop the session from being saved.

Step 3: start the second request and look at the cache

The second request is started and the global agent's session cache is printed:

Text
[x] Starting second request
[x] Dumping globalAgent._sessionCache.map:
{
  'nodejs.org:8444:::::::::::::::::TLSv1_2_method:': <Buffer 30 82 06 2f 02 01 01 02 02 03 04 04 02 13 01 04 20 cd b7 17 84 ac 9f 31 6f 1c cc 73 de 31 05 eb dc 60 62 df c7 c5 d5 8c b4 75 cc a7 28 1f d9 c0 22 04 ... 1537 more bytes>
}

The key contains the host and port (nodejs.org:8444) followed by TLS parameters, and the value is the serialised session. The session from the failed connection is sitting in the cache. That is the precondition for the bypass: the bad session is available for the next request to pick up.

Step 4: see the verification bypassed and the server answer

The second request resumes the cached session. Because the session is reused, the hostname check is skipped, and the request succeeds against a server whose certificate does not match the hostname:

Text
[!] Bypassed hostname verification. Server response: 200
{
  date: 'Thu, 05 Mar 2020 17:08:24 GMT',
  'content-length': '29',
  'content-type': 'text/plain; charset=utf-8',
  connection: 'close'
}

The headers show a normal HTTP 200 response, delivered over a connection whose peer was never verified against the requested hostname. The response shows the second request succeeded despite the hostname mismatch.

Root cause

The 'session' event is emitted from OpenSSL's get_session_cb independently of what onConnectSecure decides. In TLS 1.2 the callback can fire before the verification callback, in TLS 1.3 after it, but in neither case is the event gated on the result. Sessions from connections that failed certificate or hostname validation therefore reach application code and caches.

The second half of the problem is in the verification logic itself: checkServerIdentity is only called when the session is not reused. A resumed session is trusted because it is CA signed, so the hostname is never compared again. Combined with the https agent caching sessions on the 'session' event and removing them only when the socket closes with an error, an invalid session can be picked up by another request to the same host during the window before removal. The race is small, but as the PoC shows, it can be won.

Impact

A man-in-the-middle of TLS connections. An attacker who can present a CA signed certificate for an arbitrary hostname, and whose server supports TLS resumption, can get a session into the client's cache despite failing hostname verification, and have later requests to the intended host resume that session without a hostname check. The report describes the immediate reuse promised by the API documentation as always insecure, and session caches as at risk of storing insecure sessions. The practical exploitation shown is a race against a local server; the researcher states that other routes in real applications probably exist but were not investigated, and that a fully reliable bypass via a 'close' event without an error was not confirmed.

Fix

The report does not describe a fix or a change made in response. The behaviour it identifies is that the 'session' event is emitted regardless of the verification result, and that hostname verification is skipped for resumed sessions. Addressing it means not exposing or caching sessions from connections that failed verification, and not treating session resumption as a substitute for checking the peer's identity.

Variants to test

  1. Other TLS clients with session caches. Look for clients that store sessions on a callback fired before identity verification completes. A positive result is a cached session entry for a host whose certificate did not match, followed by a successful resumed request.
  2. TLS 1.3 versus TLS 1.2 ordering. Test both protocol versions, since the session callback fires before the info callback in TLS 1.2 and after it in TLS 1.3. A positive result is a session captured in either ordering despite a failed hostname check.
  3. Eviction paths. Try to make the socket close without an error after an invalid session is cached. A positive result is a session that survives in the cache and is reused by later requests.
  4. Race timing. Replace the setImmediate() scheduling used in the PoC with other concurrency patterns in the target application. A positive result is a second request that resumes the invalid session before eviction.
  5. Custom checkServerIdentity implementations. Applications that supply their own identity check are equally affected if resumption skips it. A positive result is a resumed connection to a host whose certificate the custom check would have rejected.

Glossary

  • API: the set of functions and events a library offers to programmers.
  • Cache: a temporary store of things expected to be needed again.
  • Certificate: a server's digital ID card, signed by a certificate authority, containing the names it is allowed to serve.
  • Certificate authority (CA): an organisation that signs certificates so clients can trust them.
  • Event: a signal a library sends when something happens; code can listen for it and react.
  • Handshake: the opening conversation of a TLS connection where keys are agreed and certificates exchanged.
  • Hostname verification: checking that the name on a server's certificate matches the hostname the client asked for.
  • HTTPS: HTTP carried over TLS, giving encryption and server identity checks.
  • Man-in-the-middle: an attacker positioned between client and server, able to intercept or alter traffic.
  • Node.js: a runtime that lets JavaScript run outside a browser, commonly on servers.
  • OpenSSL: the library Node.js uses to implement TLS.
  • Proof of concept (PoC): a small program that demonstrates a vulnerability in practice.
  • Race window: a short period in which the order of two events can be exploited.
  • Session: the saved result of a TLS handshake, reusable for later connections.
  • Session reuse (resumption): opening a new connection by reusing a saved session instead of doing a full handshake.
  • Socket: one end of a network connection in a program.
  • TLS: the encryption layer behind HTTPS, providing confidentiality and server identity checks.

More by fwilhelm

View all

1 more disclosed report, best first.

More from Node.js

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cryptographic weaknesses

The lesson behind this report.

Encryption, signatures, randomness or certificate checks that do not protect what they claim to.