Commit 7dcb25a528c for nodejs
commit 7dcb25a528cf28e60d03c00167a34a86767e7a14
Author: James M Snell <jasnell@gmail.com>
Date: Fri Nov 27 22:28:59 2026 +0000
net: support DTLS 1.3
Add minVersion and maxVersion. DTLS 1.2 stays the default.
DTLSv1_listen() cannot negotiate DTLS 1.3, so when it is enabled the
server validates addresses with a pending handshake per peer and only
announces the session once the cookie verifies.
Add session.onsessionticket, since DTLS 1.3 tickets arrive after the
handshake.
Assisted-by: Claude Opus 5.5
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67837
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
diff --git a/doc/api/dtls.md b/doc/api/dtls.md
index 44e090dc5bf..7b92bfebfef 100644
--- a/doc/api/dtls.md
+++ b/doc/api/dtls.md
@@ -57,8 +57,10 @@ DTLS is designed for UDP transport and differs from TLS in several key ways:
DTLS preserves datagram semantics.
* One socket, many peers: A single UDP socket can serve multiple DTLS
sessions. The `DTLSEndpoint` manages this multiplexing.
-* Cookie exchange: DTLS servers use a stateless cookie mechanism
- (HelloVerifyRequest) to prevent denial-of-service amplification attacks.
+* Cookie exchange: DTLS servers validate a new peer's address with a cookie
+ (HelloVerifyRequest in DTLS 1.2, HelloRetryRequest in DTLS 1.3) before
+ committing to a handshake, to prevent denial-of-service amplification
+ attacks.
* Retransmission: DTLS handles handshake retransmission internally since
UDP does not guarantee delivery.
@@ -66,6 +68,10 @@ DTLS is designed for UDP transport and differs from TLS in several key ways:
<!-- YAML
added: v26.9.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/00000
+ description: Added the `minVersion` and `maxVersion` options.
-->
* `callback` {Function} Called for each new DTLS session accepted by the
@@ -89,6 +95,11 @@ added: v26.9.0
* `host` {string} Address to bind to. **Default:** `'0.0.0.0'`.
* `ca` {string|Buffer|string\[]|Buffer\[]} CA certificates in PEM format.
* `ciphers` {string} OpenSSL cipher list string.
+ * `minVersion` {string} The oldest protocol version to accept, `'DTLSv1.2'`
+ or `'DTLSv1.3'`. **Default:** `'DTLSv1.2'`. See [Protocol versions][].
+ * `maxVersion` {string} The newest protocol version to offer, `'DTLSv1.2'`
+ or `'DTLSv1.3'`. **Default:** `'DTLSv1.2'`, or `minVersion` if that is
+ newer.
* `alpn` {string\[]|Buffer} ALPN protocol names. Each name must be between
1 and 255 bytes. A `Buffer` must already be in ALPN wire format: one
length byte followed by that many bytes, repeated.
@@ -168,6 +179,10 @@ console.log('DTLS server listening on', endpoint.address);
<!-- YAML
added: v26.9.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/00000
+ description: Added the `minVersion` and `maxVersion` options.
-->
* `host` {string} Remote host to connect to, as an IPv4 or IPv6 literal.
@@ -209,6 +224,11 @@ added: v26.9.0
1 and 255 bytes. A `Buffer` must already be in ALPN wire format: one
length byte followed by that many bytes, repeated.
* `srtp` {string} SRTP protection profile names.
+ * `minVersion` {string} The oldest protocol version to accept, `'DTLSv1.2'`
+ or `'DTLSv1.3'`. **Default:** `'DTLSv1.2'`. See [Protocol versions][].
+ * `maxVersion` {string} The newest protocol version to offer, `'DTLSv1.2'`
+ or `'DTLSv1.3'`. **Default:** `'DTLSv1.2'`, or `minVersion` if that is
+ newer.
* `mtu` {number} Maximum size in bytes of a DTLS datagram. **Default:**
`1200`.
* `handshakeTimeout` {number} Milliseconds a handshake may take before it is
@@ -239,6 +259,10 @@ session.onmessage = (data) => {
<!-- YAML
added: v26.10.0
+changes:
+ - version: REPLACEME
+ pr-url: https://github.com/nodejs/node/pull/00000
+ description: Added the `minVersion` and `maxVersion` options.
-->
* `options` {Object}
@@ -250,6 +274,10 @@ added: v26.10.0
* `ecdhCurve` {string} Named curve or curve list for ECDH.
* `isServer` {boolean} Build a context for a server. **Default:** `false`.
* `key` {string|Buffer} Private key in PEM format.
+ * `maxVersion` {string} Newest protocol version to offer. See
+ [Protocol versions][].
+ * `minVersion` {string} Oldest protocol version to accept. See
+ [Protocol versions][].
* `passphrase` {string} Passphrase for `key`, if it is encrypted.
* `rejectUnauthorized` {boolean} Verification behaviour, as for
[`dtls.listen()`][] and [`dtls.connect()`][].
@@ -315,6 +343,43 @@ const s2 = connect('192.0.2.2', 5684, {
});
```
+## Protocol versions
+
+DTLS 1.2 ([RFC 6347][]) and DTLS 1.3 ([RFC 9147][]) are supported. DTLS 1.0 is
+not: it is deprecated by [RFC 8996][] and has no AEAD cipher suites. Each side
+offers the range from `minVersion` to `maxVersion`, and the newest version both
+allow is negotiated; with none in common the handshake fails with a
+`protocol_version` alert. Only DTLS 1.2 is enabled by default.
+
+```mjs
+import { connect, listen } from 'node:dtls';
+
+const endpoint = listen(onsession, {
+ cert, key, port: 5684, maxVersion: 'DTLSv1.3',
+});
+
+const session = connect('192.0.2.1', 5684, { ca, maxVersion: 'DTLSv1.3' });
+const { protocol } = await session.opened; // 'DTLSv1.3'
+```
+
+What changes under DTLS 1.3:
+
+* A server validates the peer's address with a cookie in a
+ HelloRetryRequest rather than a HelloVerifyRequest; see
+ [Denial of service][].
+* The server issues resumption tickets after the handshake rather than during
+ it, so [`session.session`][] is `undefined` when `session.opened` settles.
+ Use [`session.onsessionticket`][]; see [Session resumption][].
+* A server rejects a client certificate after the client has finished its
+ side of the handshake, so the client's `session.opened` can resolve and the
+ session then fail with a `certificate_required` or similar alert.
+* A wrong pre-shared key is rejected at once with a `decrypt_error` alert,
+ rather than stalling; see [Pre-shared keys][].
+* [`session.send()`][] accepts at most 16383 bytes, and
+ [`session.exportKeyingMaterial()`][] at most 255 hash lengths.
+* The `ciphers` option applies to DTLS 1.2 cipher suites only. DTLS 1.3 uses
+ OpenSSL's default TLS 1.3 suites.
+
## Server Name Indication
An endpoint can serve more than one identity by giving `listen()` an `sni`
@@ -407,6 +472,18 @@ failure.
## Denial of service
+A server does not commit to a handshake, or announce a session, until the peer
+has returned a cookie from the address it claims to be sending from. With only
+DTLS 1.2 enabled this is stateless: nothing is kept for a peer until its
+cookie comes back. With DTLS 1.3 enabled the server keeps a small pending
+handshake for each new peer while the exchange completes, because a DTLS 1.3
+ClientHello often spans several datagrams and the second ClientHello cannot be
+verified without it. Pending handshakes are not visible to JavaScript and do
+not count against `maxSessions`; at most 1024 are kept, the oldest giving way
+to a new one, and each expires after 10 seconds. Nothing is sent to a peer
+that has not completed the exchange except replies to datagrams it sent, each
+smaller than what it answers.
+
Cookie exchange proves a peer can receive at its claimed address, but it does
not limit how many sessions that peer may then establish, and each session
holds a TLS state machine, two buffers and a timer. `maxSessions` bounds the
@@ -443,9 +520,9 @@ the handshake completes; it is not an idle timeout.
A handshake can stall without either peer being at fault or aware.
DTLS discards records it cannot authenticate rather than answering them
-(RFC 6347 section 4.1.2.1), so a mismatched pre-shared key or a cipher list
-with nothing in common produces silence rather than an alert. This timeout is
-what ends those.
+(RFC 6347 section 4.1.2.1), so under DTLS 1.2 a mismatched pre-shared key or a
+cipher list with nothing in common produces silence rather than an alert. This
+timeout is what ends those.
## Pre-shared keys
@@ -483,7 +560,10 @@ listen(onsession, {
```
The callback runs during the handshake and must return synchronously, so it
-cannot consult a database. Where both are given, the map is checked first and
+cannot consult a database. Under DTLS 1.3 a server's callback is called for
+each ClientHello, so usually twice per handshake, and the first call comes
+before the client has completed the cookie exchange. It has to give the same
+answer both times. Where both are given, the map is checked first and
the callback is only reached when the map has no answer -- a configuration
using only the map never runs JavaScript inside the handshake.
@@ -519,6 +599,10 @@ listen(onsession, { port: 5684, psk, ciphers: 'PSK-AES128-CCM8@SECLEVEL=0' });
### Failure modes
+Under DTLS 1.3 a wrong key fails the handshake straight away with a
+`decrypt_error` alert, because the client proves it holds the key in its
+ClientHello. What follows describes DTLS 1.2.
+
A wrong key does not produce an error. The identity only names the key, so the
handshake proceeds and the two sides derive different secrets; the first
record that fails authentication is then discarded rather than answered, since
@@ -560,6 +644,19 @@ await second.opened;
console.log(second.reused); // True.
```
+Under DTLS 1.3 the server sends its tickets once the handshake has completed,
+so there is nothing to resume with when `opened` settles. Set
+[`session.onsessionticket`][], which is called with each ticket as it arrives
+under either version:
+
+```mjs
+const first = connect('192.0.2.1', 5684, {
+ ca, servername: 'device.example', maxVersion: 'DTLSv1.3',
+});
+first.onsessionticket = (ticket) => saveForLater(ticket);
+await first.opened;
+```
+
A session that the server will not accept -- expired, or issued by a different
endpoint -- is not an error. The handshake simply proceeds in full, and
[`session.reused`][] is `false`.
@@ -832,8 +929,9 @@ Represents a DTLS association with a single remote peer.
### `session.send(data)`
* `data` {string|Buffer|TypedArray|DataView} The data to send. At most 16384
- bytes. A view sends the bytes it covers, so an offset or a subarray is sent
- as given rather than as the whole buffer behind it.
+ bytes, or 16383 under DTLS 1.3. A view sends the bytes it covers, so an
+ offset or a subarray is sent as given rather than as the whole buffer behind
+ it.
* Returns: {number} The number of bytes written to the DTLS layer.
Send application data to the peer. The data is encrypted by DTLS before
@@ -843,7 +941,10 @@ being sent over UDP. Can only be called after the handshake completes
DTLS carries application data in a single record per datagram and does not
fragment it, so `data` must fit in one record. Sending more throws
`ERR_OUT_OF_RANGE`. This limit is independent of the `mtu` option: a record
-larger than the path MTU is still sent, and is fragmented by IP.
+larger than the path MTU is still sent, and is fragmented by IP. The DTLS 1.3
+limit is a byte lower than the protocol allows because OpenSSL misjudges the
+size of a full-length DTLS 1.3 record on receipt and ends the association
+with a `record_overflow` alert.
Throws `ERR_INVALID_STATE` if the handshake has not completed, or if the
session is closed or destroyed.
@@ -951,7 +1052,8 @@ added: v26.10.0
-->
* Returns: {Buffer|undefined} An opaque session for resuming this connection
- later, or `undefined` on a server session or before the handshake completes.
+ later, or `undefined` on a server session, before the handshake completes,
+ or under DTLS 1.3 before the server's first ticket has arrived.
Pass it as the `session` option to a later [`dtls.connect()`][]. It is bound to
the host this connection authenticated against and is refused elsewhere; see
@@ -1058,6 +1160,10 @@ bound is not imposed by [RFC 5705][]; it exists so that a caller cannot request
an arbitrarily large allocation, and is far above what any defined exporter
needs (DTLS-SRTP uses 60 bytes).
+Under DTLS 1.3 the exporter is HKDF based and cannot produce more than 255
+times the cipher suite's hash length: 8160 bytes with a SHA-256 suite, 12240
+with SHA-384. A larger `length` throws `ERR_OUT_OF_RANGE`.
+
### Callback properties
#### `session.onmessage`
@@ -1088,6 +1194,21 @@ Set to receive handshake completion notifications.
Set to receive TLS key log lines (for debugging with Wireshark).
+#### `session.onsessionticket`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* {Function}
+ * `ticket` {Buffer} The same value [`session.session`][] returns.
+
+Set on a client session to be told each time it has a session that a later
+connection can resume. Under DTLS 1.2 that is once, as the handshake
+completes. Under DTLS 1.3 it is once for each ticket the server sends after
+the handshake, which by default is two. Set it before awaiting
+`session.opened`. Never called on a server session.
+
### `session[Symbol.asyncDispose]()`
Equivalent to calling `session.close()`.
@@ -1247,8 +1368,12 @@ The minimum allowed MTU is 256 bytes. The maximum is 65535.
[Handshake timeout]: #handshake-timeout
[Permission Model]: permissions.md#permission-model
[Pre-shared keys]: #pre-shared-keys
+[Protocol versions]: #protocol-versions
[RFC 5705]: https://www.rfc-editor.org/rfc/rfc5705
+[RFC 6347]: https://www.rfc-editor.org/rfc/rfc6347
[RFC 7301]: https://www.rfc-editor.org/rfc/rfc7301
+[RFC 8996]: https://www.rfc-editor.org/rfc/rfc8996
+[RFC 9147]: https://www.rfc-editor.org/rfc/rfc9147
[Server Name Indication]: #server-name-indication
[Session resumption]: #session-resumption
[`DTLSEndpoint`]: #class-dtlsendpoint
@@ -1262,6 +1387,8 @@ The minimum allowed MTU is 256 bytes. The maximum is 65535.
[`session.authorizationError`]: #sessionauthorizationerror
[`session.authorized`]: #sessionauthorized
[`session.destroy()`]: #sessiondestroyerror
+[`session.exportKeyingMaterial()`]: #sessionexportkeyingmateriallength-label-context
+[`session.onsessionticket`]: #sessiononsessionticket
[`session.peerX509Certificate`]: #sessionpeerx509certificate
[`session.reused`]: #sessionreused
[`session.send()`]: #sessionsenddata
diff --git a/lib/internal/dtls/dtls.js b/lib/internal/dtls/dtls.js
index 1b1a0e27b2b..0239ec118eb 100644
--- a/lib/internal/dtls/dtls.js
+++ b/lib/internal/dtls/dtls.js
@@ -7,8 +7,10 @@
const {
ArrayFrom,
ArrayIsArray,
+ ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
FunctionPrototypeBind,
+ MathMax,
ObjectKeys,
PromisePrototypeThen,
PromiseWithResolvers,
@@ -44,6 +46,7 @@ const {
validateObject,
validateString,
validateInteger,
+ validateOneOf,
validateUint32,
} = require('internal/validators');
@@ -90,6 +93,7 @@ const {
kSessionError,
kSessionClose,
kSessionKeylog,
+ kSessionTicket,
} = require('internal/dtls/symbols');
const {
@@ -98,6 +102,8 @@ const {
SSL_VERIFY_NONE_VALUE,
SSL_VERIFY_PEER_VALUE,
SSL_VERIFY_FAIL_IF_NO_PEER_CERT_VALUE,
+ DTLS1_2_VERSION_VALUE,
+ DTLS1_3_VERSION_VALUE,
} = internalBinding('dtls');
const kEmptyObject = { __proto__: null };
@@ -172,6 +178,7 @@ class DTLSSession {
#onerror;
#onhandshake;
#onkeylog;
+ #onsessionticket;
#ownsEndpoint = false;
constructor(privateSymbol, handle, endpoint, verifyHost) {
@@ -249,6 +256,17 @@ class DTLSSession {
get onkeylog() { return this.#onkeylog; }
+ set onsessionticket(fn) {
+ if (fn !== undefined && fn !== null) {
+ validateFunction(fn, 'onsessionticket');
+ this.#onsessionticket = FunctionPrototypeBind(fn, this);
+ } else {
+ this.#onsessionticket = undefined;
+ }
+ }
+
+ get onsessionticket() { return this.#onsessionticket; }
+
// --- Send data ---
send(data) {
@@ -516,6 +534,14 @@ class DTLSSession {
}
}
+ [kSessionTicket]() {
+ // Only a client has anything to carry to its next connection; session
+ // returns undefined on a server.
+ if (this.#onsessionticket === undefined) return;
+ const ticket = this.session;
+ if (ticket !== undefined) this.#onsessionticket(ticket);
+ }
+
async [SymbolAsyncDispose]() {
await this.close();
}
@@ -614,6 +640,9 @@ class DTLSEndpoint {
onSessionKeylog: function(line) {
this[kOwner]?.[kSessionKeylog](line);
},
+ onSessionTicket: function() {
+ this[kOwner]?.[kSessionTicket]();
+ },
});
}
@@ -820,6 +849,8 @@ function createContext(options = kEmptyObject) {
const context = new DTLSContext_(isServer);
+ applyProtocolVersions(context, options.minVersion, options.maxVersion);
+
// Pre-shared keys (RFC 4279).
if (options.psk !== undefined) {
applyPSK(context, options.psk, isServer, options.pskIdentityHint);
@@ -1011,6 +1042,38 @@ function createContext(options = kEmptyObject) {
return context;
}
+// Protocol versions by name, in the order they were published, which is the
+// order minVersion and maxVersion compare in. DTLS 1.0 is not offered: it is
+// deprecated by RFC 8996 and has no AEAD cipher suites.
+const kProtocolVersions = ['DTLSv1.2', 'DTLSv1.3'];
+const kProtocolVersionValues = [DTLS1_2_VERSION_VALUE, DTLS1_3_VERSION_VALUE];
+const kDefaultMinVersion = 'DTLSv1.2';
+const kDefaultMaxVersion = 'DTLSv1.2';
+
+function applyProtocolVersions(context, minVersion, maxVersion) {
+ if (minVersion === undefined) minVersion = kDefaultMinVersion;
+ validateOneOf(minVersion, 'options.minVersion', kProtocolVersions);
+ const min = ArrayPrototypeIndexOf(kProtocolVersions, minVersion);
+ let max;
+ if (maxVersion === undefined) {
+ // A floor above the default ceiling raises the ceiling with it: asking
+ // for at least DTLS 1.3 is not a request for a range that is empty.
+ max = MathMax(min, ArrayPrototypeIndexOf(kProtocolVersions,
+ kDefaultMaxVersion));
+ maxVersion = kProtocolVersions[max];
+ } else {
+ validateOneOf(maxVersion, 'options.maxVersion', kProtocolVersions);
+ max = ArrayPrototypeIndexOf(kProtocolVersions, maxVersion);
+ }
+ if (min > max) {
+ throw new ERR_INVALID_ARG_VALUE(
+ 'options.minVersion', minVersion,
+ `must not be newer than options.maxVersion ('${maxVersion}')`);
+ }
+ context.setProtocolVersions(kProtocolVersionValues[min],
+ kProtocolVersionValues[max]);
+}
+
// Cipher list used when psk is given and ciphers is not.
//
// DEFAULT has to come first: OpenSSL only honours it as the opening
@@ -1158,9 +1221,9 @@ const kServerOnlyContextOptions = [
];
const kContextOptions = [
- 'alpn', 'ca', 'cert', 'ciphers', 'ecdhCurve', 'key', 'passphrase',
- 'psk', 'pskIdentityHint', 'rejectUnauthorized', 'requestCert',
- 'sessionIdContext', 'sni', 'srtp', 'ticketKeys',
+ 'alpn', 'ca', 'cert', 'ciphers', 'ecdhCurve', 'key', 'maxVersion',
+ 'minVersion', 'passphrase', 'psk', 'pskIdentityHint', 'rejectUnauthorized',
+ 'requestCert', 'sessionIdContext', 'sni', 'srtp', 'ticketKeys',
];
/**
diff --git a/lib/internal/dtls/symbols.js b/lib/internal/dtls/symbols.js
index 2ac4be8a82a..6594107bb2a 100644
--- a/lib/internal/dtls/symbols.js
+++ b/lib/internal/dtls/symbols.js
@@ -44,6 +44,7 @@ module.exports = {
kSessionError: Symbol('dtls.session.error'),
kSessionClose: Symbol('dtls.session.close'),
kSessionKeylog: Symbol('dtls.session.keylog'),
+ kSessionTicket: Symbol('dtls.session.ticket'),
};
/* c8 ignore stop */
diff --git a/src/dtls/dtls.cc b/src/dtls/dtls.cc
index cc704eefd2a..2a5a28cad3e 100644
--- a/src/dtls/dtls.cc
+++ b/src/dtls/dtls.cc
@@ -75,6 +75,12 @@ void CreatePerContextProperties(Local<Object> target,
NODE_DEFINE_CONSTANT(target, SSL_VERIFY_NONE_VALUE);
NODE_DEFINE_CONSTANT(target, SSL_VERIFY_PEER_VALUE);
NODE_DEFINE_CONSTANT(target, SSL_VERIFY_FAIL_IF_NO_PEER_CERT_VALUE);
+
+ // Protocol versions accepted by DTLSContext.setProtocolVersions().
+ constexpr auto DTLS1_2_VERSION_VALUE = DTLS1_2_VERSION;
+ constexpr auto DTLS1_3_VERSION_VALUE = DTLS1_3_VERSION;
+ NODE_DEFINE_CONSTANT(target, DTLS1_2_VERSION_VALUE);
+ NODE_DEFINE_CONSTANT(target, DTLS1_3_VERSION_VALUE);
}
void CreatePerIsolateProperties(IsolateData* isolate_data,
diff --git a/src/dtls/dtls.h b/src/dtls/dtls.h
index 1beb23753d3..35c45d7b099 100644
--- a/src/dtls/dtls.h
+++ b/src/dtls/dtls.h
@@ -33,6 +33,18 @@ void RecordTimestampStat(Stats* stats) {
#define DTLS_STAT_FIELD(_, name) uint64_t name;
+// How long a server handshake may wait to complete the cookie exchange
+// before it is dropped. A real client answers a HelloVerifyRequest or
+// HelloRetryRequest within a round trip and retransmits its first
+// ClientHello on a 1s timer if the answer is lost, so this allows several
+// retransmits while keeping the state a forged source can pin short-lived.
+constexpr uint64_t kValidationTimeoutMs = 10000;
+
+// Most server handshakes that may be awaiting the cookie exchange at once.
+// Each holds an SSL with a possibly fragmented ClientHello buffered in it;
+// the oldest is dropped to make room for a new one.
+constexpr size_t kMaxPendingHandshakes = 1024;
+
// ============================================================================
// Stats X-macros: V(ENUM_NAME, field_name)
@@ -94,6 +106,7 @@ enum DTLSCallbackIndex {
DTLS_CB_SESSION_HANDSHAKE,
DTLS_CB_SESSION_MESSAGE,
DTLS_CB_SESSION_KEYLOG,
+ DTLS_CB_SESSION_TICKET,
DTLS_CB_COUNT
};
diff --git a/src/dtls/dtls_context.cc b/src/dtls/dtls_context.cc
index 96f3ab459ec..c4d9aa52a7f 100644
--- a/src/dtls/dtls_context.cc
+++ b/src/dtls/dtls_context.cc
@@ -132,6 +132,59 @@ void DTLSContext::BindToSSL(SSL* ssl) {
SSL_set_ex_data(ssl, PSKContextIndex(), this);
}
+static int PendingStateIndex() {
+ static const int index =
+ SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
+ return index;
+}
+
+void DTLSContext::SetPendingState(SSL* ssl, PendingHandshakeState* state) {
+ SSL_set_ex_data(ssl, PendingStateIndex(), state);
+}
+
+PendingHandshakeState* DTLSContext::GetPendingState(SSL* ssl) {
+ return static_cast<PendingHandshakeState*>(
+ SSL_get_ex_data(ssl, PendingStateIndex()));
+}
+
+bool DTLSContext::AllowsDTLS13() const {
+ // 0 is "no upper bound", which for this build means DTLS 1.3. DTLS version
+ // numbers count down, so a numerically smaller one is newer.
+ int max = SSL_CTX_get_max_proto_version(ctx_.get());
+ return max == 0 || max <= DTLS1_3_VERSION;
+}
+
+bool DTLSContext::IsUnvalidatedPeer(SSL* ssl) {
+ // A pending handshake has no session yet. A session promoted from one has
+ // been handed its second ClientHello but may not have verified the cookie
+ // in it -- a retransmitted first ClientHello is let through too.
+ auto* session = static_cast<DTLSSession*>(SSL_get_app_data(ssl));
+ if (session == nullptr) return GetPendingState(ssl) != nullptr;
+ return !session->address_validated();
+}
+
+int DTLSContext::NewSessionCallback(SSL* ssl, SSL_SESSION* sess) {
+ auto* session = static_cast<DTLSSession*>(SSL_get_app_data(ssl));
+ if (session != nullptr) session->OnNewSessionTicket();
+ // Not taking the reference: the session is read back through
+ // SSL_get1_session() when JavaScript asks for it.
+ return 0;
+}
+
+int DTLSContext::ClientHelloCallback(SSL* ssl, int* al, void* arg) {
+ // Only a bare pending handshake is suspended, and only once it has sent
+ // its cookie: the first ClientHello has to run through to produce the
+ // HelloVerifyRequest or HelloRetryRequest. Once the endpoint has wrapped
+ // the SSL in a session, the resumed handshake comes straight back here and
+ // carries on.
+ PendingHandshakeState* pending = GetPendingState(ssl);
+ if (pending != nullptr && pending->cookie_sent &&
+ SSL_get_app_data(ssl) == nullptr) {
+ return SSL_CLIENT_HELLO_RETRY;
+ }
+ return SSL_CLIENT_HELLO_SUCCESS;
+}
+
DTLSContext* DTLSContext::FromSSL(SSL* ssl) {
return static_cast<DTLSContext*>(SSL_get_ex_data(ssl, PSKContextIndex()));
}
@@ -162,6 +215,7 @@ Local<FunctionTemplate> DTLSContext::GetConstructorTemplate(Environment* env) {
SetProtoMethod(isolate, tmpl, "setSNIContexts", SetSNIContexts);
SetProtoMethod(isolate, tmpl, "setTicketKeys", SetTicketKeys);
SetProtoMethod(isolate, tmpl, "setPSK", SetPSK);
+ SetProtoMethod(isolate, tmpl, "setProtocolVersions", SetProtocolVersions);
env->set_dtls_context_constructor_template(tmpl);
}
@@ -194,6 +248,7 @@ void DTLSContext::RegisterExternalReferences(
registry->Register(SetSNIContexts);
registry->Register(SetTicketKeys);
registry->Register(SetPSK);
+ registry->Register(SetProtocolVersions);
}
// new DTLSContext(isServer)
@@ -262,7 +317,13 @@ void DTLSContext::New(const FunctionCallbackInfo<Value>& args) {
// session SSLs built by CreateFromSSL() for peers that have *already*
// completed the cookie exchange, which would leave them waiting for a
// second one. DTLSv1_listen() sets the option on the individual SSL it is
- // given (d1_lib.c:804), which is the correct scope.
+ // given (d1_lib.c:804), and the endpoint sets it on each pending
+ // handshake it creates, which is the correct scope.
+
+ // Inert except on a pending handshake; see ClientHelloCallback(). Set on
+ // every server context, not only the endpoint's, because the callback is
+ // read through the SSL's current SSL_CTX and SNI may have switched it.
+ SSL_CTX_set_client_hello_cb(ctx.get(), ClientHelloCallback, nullptr);
// Enable session caching for session resumption.
//
@@ -279,6 +340,8 @@ void DTLSContext::New(const FunctionCallbackInfo<Value>& args) {
// Client session caching for resumption.
SSL_CTX_set_session_cache_mode(
ctx.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL);
+ // Called because SSL_SESS_CACHE_CLIENT is set, NO_INTERNAL or not.
+ SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
}
// NOTE: We do NOT call SSL_CTX_set_default_verify_paths() here.
@@ -378,6 +441,33 @@ void DTLSContext::AddCACert(const FunctionCallbackInfo<Value>& args) {
}
}
+// setProtocolVersions(min, max), each DTLS1_2_VERSION or DTLS1_3_VERSION.
+// JavaScript validates the names and their order; this only refuses values
+// that are not one of the two versions this supports.
+void DTLSContext::SetProtocolVersions(const FunctionCallbackInfo<Value>& args) {
+ DTLSContext* ctx;
+ ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This());
+ Environment* env = ctx->env();
+
+ CHECK(args[0]->IsInt32());
+ CHECK(args[1]->IsInt32());
+ int min = args[0].As<Int32>()->Value();
+ int max = args[1].As<Int32>()->Value();
+ auto supported = [](int v) {
+ return v == DTLS1_2_VERSION || v == DTLS1_3_VERSION;
+ };
+ CHECK(supported(min));
+ CHECK(supported(max));
+
+ // Checked for the same reason the defaults are: a build that cannot do
+ // the version asked for would otherwise leave the bound wherever it was.
+ if (SSL_CTX_set_min_proto_version(ctx->ctx_.get(), min) != 1 ||
+ SSL_CTX_set_max_proto_version(ctx->ctx_.get(), max) != 1) {
+ return THROW_ERR_CRYPTO_OPERATION_FAILED(
+ env, "Failed to set the DTLS protocol version range");
+ }
+}
+
void DTLSContext::SetCiphers(const FunctionCallbackInfo<Value>& args) {
DTLSContext* ctx;
ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This());
@@ -582,6 +672,11 @@ int DTLSContext::SNISelectCallback(SSL* ssl, int* ad, void* arg) {
// no JavaScript inside the handshake. The callback is reached only when it
// has nothing to say.
if (chosen == nullptr && !ctx->sni_callback_.IsEmpty()) {
+ // No JavaScript for a peer that has not completed the cookie exchange.
+ // Carry on with the context already in place rather than refusing:
+ // under DTLS 1.3 the first ClientHello is processed in full to produce
+ // the HelloRetryRequest, and the callback runs for the second one.
+ if (IsUnvalidatedPeer(ssl)) return SSL_TLSEXT_ERR_OK;
chosen = ctx->SelectSNIContextFromCallback(ssl, servername);
}
@@ -716,6 +811,15 @@ unsigned int DTLSContext::PSKServerCallback(SSL* ssl,
if (ctx->psk_callback_.IsEmpty()) return 0;
+ // Unlike the SNI callback, this one runs for a peer that has not completed
+ // the cookie exchange. A DTLS 1.3 first ClientHello carries its PSK offer
+ // and is processed in full to produce the HelloRetryRequest, and the answer
+ // has to be the same both times: whether a PSK is available steers the
+ // choice of cipher suite toward one whose hash matches it, the
+ // HelloRetryRequest cookie records that choice, and the second
+ // ClientHello's binder is checked against a transcript built with it. So
+ // under DTLS 1.3 the callback is asked once per ClientHello.
+
Environment* env = ctx->env();
HandleScope scope(env->isolate());
Context::Scope context_scope(env->context());
@@ -1008,16 +1112,28 @@ size_t CanonicalizeAddress(const sockaddr* sa, unsigned char* out) {
// callbacks during DTLSv1_listen(), and every handshake fails with a
// handshake_failure alert. Doing it would mean lifting the 32-byte random out
// of the raw ClientHello, which CouldBeClientHello() already walks, and
-// stashing it next to current_cookie_peer_. During DTLSv1_listen() the peer
-// address comes from DTLSContext::current_cookie_peer_ (set synchronously
-// before the call); during the session handshake it comes from the
-// DTLSSession stored in SSL app_data.
+// stashing it next to current_cookie_peer_. During DTLSv1_listen() and
+// while a handshake is pending the peer address comes from
+// DTLSContext::current_cookie_peer_ (set synchronously before the call);
+// during the session handshake it comes from the DTLSSession stored in SSL
+// app_data.
+//
+// For DTLS 1.3 this is the application cookie OpenSSL embeds in, and
+// authenticates as part of, the HelloRetryRequest cookie: with no stateless
+// cookie callbacks installed it falls back to these.
bool DTLSContext::ComputeCookie(SSL* ssl,
uint64_t window,
unsigned char* out,
unsigned int* out_len) {
- SSL_CTX* ctx = SSL_get_SSL_CTX(ssl);
- DTLSContext* dtls_ctx = static_cast<DTLSContext*>(SSL_CTX_get_app_data(ctx));
+ // The context the SSL was created from, not SSL_get_SSL_CTX(): SNI can
+ // switch the latter while the first ClientHello is processed, and the
+ // cookie minted against one secret would then be checked against
+ // another. An SSL from DTLSv1_listen() is never bound, and never switched.
+ DTLSContext* dtls_ctx = FromSSL(ssl);
+ if (dtls_ctx == nullptr) {
+ dtls_ctx =
+ static_cast<DTLSContext*>(SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
+ }
CHECK_NOT_NULL(dtls_ctx);
// Message = canonical peer address followed by the 8-byte window counter.
@@ -1059,7 +1175,11 @@ int DTLSContext::CookieGenerateCallback(SSL* ssl,
unsigned char* cookie,
unsigned int* cookie_len) {
const uint64_t window = uv_hrtime() / kCookieWindowNs;
- return ComputeCookie(ssl, window, cookie, cookie_len) ? 1 : 0;
+ if (!ComputeCookie(ssl, window, cookie, cookie_len)) return 0;
+ if (PendingHandshakeState* pending = GetPendingState(ssl)) {
+ pending->cookie_sent = true;
+ }
+ return 1;
}
int DTLSContext::CookieVerifyCallback(SSL* ssl,
@@ -1076,6 +1196,11 @@ int DTLSContext::CookieVerifyCallback(SSL* ssl,
if (ComputeCookie(ssl, window - i, expected, &expected_len) &&
cookie_len == expected_len &&
CRYPTO_memcmp(cookie, expected, expected_len) == 0) {
+ // The peer has shown it receives at the address it sends from. A
+ // session promoted from a pending handshake waits on this before it
+ // is announced to JavaScript.
+ auto* session = static_cast<DTLSSession*>(SSL_get_app_data(ssl));
+ if (session != nullptr) session->OnAddressValidated();
return 1;
}
}
diff --git a/src/dtls/dtls_context.h b/src/dtls/dtls_context.h
index a49fc29f9d4..a9b30204b3d 100644
--- a/src/dtls/dtls_context.h
+++ b/src/dtls/dtls_context.h
@@ -20,6 +20,17 @@
namespace node::dtls {
+class DTLSSession;
+
+// Address validation progress for a server SSL that has not become a
+// DTLSSession yet. See DTLSEndpoint::AcceptPendingHandshake().
+struct PendingHandshakeState {
+ // Set once the cookie flight (HelloVerifyRequest for DTLS 1.2,
+ // HelloRetryRequest for DTLS 1.3) has been generated. The next
+ // ClientHello is the one expected to carry the cookie back.
+ bool cookie_sent = false;
+};
+
// DTLSContext wraps an SSL_CTX configured for DTLS.
// It manages certificate/key configuration, cipher selection,
// ALPN, and automatic cookie generation/verification for servers.
@@ -49,6 +60,17 @@ class DTLSContext final : public BaseObject {
// to the SSL rather than the SSL_CTX because SNI reassigns the latter.
void BindToSSL(SSL* ssl);
+ // Mark |ssl| as a server handshake whose peer address has not been
+ // validated yet, or clear the mark with nullptr. |state| is owned by the
+ // caller and must outlive the mark.
+ static void SetPendingState(SSL* ssl, PendingHandshakeState* state);
+ static PendingHandshakeState* GetPendingState(SSL* ssl);
+
+ // True if a handshake on this context may negotiate DTLS 1.3, which
+ // validates the peer address with a HelloRetryRequest cookie rather than
+ // the HelloVerifyRequest DTLSv1_listen() is limited to.
+ bool AllowsDTLS13() const;
+
// Set the peer address for cookie generation during DTLSv1_listen().
void set_cookie_peer(const SocketAddress& addr) {
current_cookie_peer_ = addr;
@@ -74,6 +96,27 @@ class DTLSContext final : public BaseObject {
static void SetSNIContexts(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetTicketKeys(const v8::FunctionCallbackInfo<v8::Value>& args);
static void SetPSK(const v8::FunctionCallbackInfo<v8::Value>& args);
+ static void SetProtocolVersions(
+ const v8::FunctionCallbackInfo<v8::Value>& args);
+
+ // Suspends a pending server handshake at the ClientHello that should carry
+ // the cookie back, before OpenSSL verifies it, so the endpoint can turn the
+ // bare SSL into a DTLSSession at a point where no OpenSSL call is in
+ // progress. Everything after cookie verification -- SNI, PSK, key
+ // derivation and the keylog lines it produces -- then runs against that
+ // session.
+ static int ClientHelloCallback(SSL* ssl, int* al, void* arg);
+
+ // True while |ssl| belongs to a peer that has not completed the cookie
+ // exchange. The JavaScript SNI callback is not run for such a peer: its
+ // source address may be forged. (The PSK callback has to be; see
+ // PSKServerCallback().)
+ static bool IsUnvalidatedPeer(SSL* ssl);
+
+ // Client: OpenSSL has a new resumable session for the connection. Under
+ // DTLS 1.2 that is at the end of the handshake; under DTLS 1.3 it is each
+ // NewSessionTicket, which arrives after the handshake has completed.
+ static int NewSessionCallback(SSL* ssl, SSL_SESSION* session);
// RFC 4279 pre-shared keys. The identity map is consulted first and needs
// no call into JavaScript; the callback, if there is one, is only reached
diff --git a/src/dtls/dtls_endpoint.cc b/src/dtls/dtls_endpoint.cc
index 7f85c13fc33..98907900998 100644
--- a/src/dtls/dtls_endpoint.cc
+++ b/src/dtls/dtls_endpoint.cc
@@ -316,6 +316,9 @@ void DTLSEndpoint::RemoveSession(const SocketAddress& addr) {
if (it != sessions_per_host_.end() && --it->second == 0) {
sessions_per_host_.erase(it);
}
+ } else {
+ // Never announced, so never counted.
+ validating_.erase(addr);
}
state_->session_count = sessions_.size();
@@ -330,6 +333,13 @@ void DTLSEndpoint::CloseGracefully() {
state_->closing = 1;
+ // Peers that never completed the cookie exchange get nothing: there is no
+ // association to close, and their address may be forged.
+ pending_.clear();
+ auto validating_copy = validating_;
+ validating_.clear();
+ for (auto& [addr, session] : validating_copy) session->Destroy();
+
// Close all sessions gracefully (this may send close_notify).
auto sessions_copy = sessions_;
sessions_.clear();
@@ -361,6 +371,11 @@ void DTLSEndpoint::Destroy() {
state_->destroyed = 1;
+ pending_.clear();
+ auto validating_copy = validating_;
+ validating_.clear();
+ for (auto& [addr, session] : validating_copy) session->Destroy();
+
// Copy session list to avoid iterator invalidation.
auto sessions_copy = sessions_;
sessions_.clear();
@@ -402,6 +417,7 @@ void DTLSEndpoint::SetCallbacks(Local<Object> callbacks) {
"onSessionHandshake",
"onSessionMessage",
"onSessionKeylog",
+ "onSessionTicket",
};
for (int i = 0; i < DTLS_CB_COUNT; i++) {
@@ -550,14 +566,39 @@ void DTLSEndpoint::ProcessDatagram(const uint8_t* data,
return;
}
+ // A session still waiting on its cookie takes the datagram the same way:
+ // the ClientHello it was handed may have been a retransmitted first one.
+ auto vit = validating_.find(remote);
+ if (vit != validating_.end()) {
+ // Held: Receive() can destroy the session, which erases this entry.
+ BaseObjectPtr<DTLSSession> session = vit->second;
+ session->Receive(data, len);
+ return;
+ }
+
// No existing session. If we're in server mode, try to accept.
- if (listening_ && server_context_) {
- AcceptConnection(data, len, remote);
+ if (!listening_ || !server_context_) return;
+
+ auto pit = pending_.find(remote);
+ if (pit != pending_.end()) {
+ if (uv_hrtime() / 1000000 < pit->second->expires_at) {
+ DrivePendingHandshake(data, len, remote);
+ return;
+ }
+ // Expired: start over as though this peer had never been seen.
+ pending_.erase(pit);
}
+
+ AcceptConnection(data, len, remote);
}
bool DTLSEndpoint::HasCapacityFor(const SocketAddress& remote) const {
- if (max_sessions_ != 0 && sessions_.size() >= max_sessions_) return false;
+ // A session waiting on its cookie becomes a real one the moment it is
+ // verified, without being asked again, so it holds a slot already.
+ if (max_sessions_ != 0 &&
+ sessions_.size() + validating_.size() >= max_sessions_) {
+ return false;
+ }
if (max_sessions_per_host_ != 0) {
auto it = sessions_per_host_.find(remote);
@@ -620,6 +661,11 @@ void DTLSEndpoint::AcceptConnection(const uint8_t* data,
return;
}
+ if (server_context_->AllowsDTLS13()) {
+ AcceptPendingHandshake(data, len, remote);
+ return;
+ }
+
HandleScope handle_scope(env()->isolate());
Context::Scope context_scope(env()->context());
@@ -732,6 +778,168 @@ void DTLSEndpoint::AcceptConnection(const uint8_t* data,
session->Start();
}
+bool DTLSEndpoint::MakeRoomForPendingHandshake() {
+ if (pending_.size() + validating_.size() < kMaxPendingHandshakes) {
+ return true;
+ }
+
+ const uint64_t now = uv_hrtime() / 1000000;
+ auto oldest = pending_.end();
+ for (auto it = pending_.begin(); it != pending_.end();) {
+ if (it->second->expires_at <= now) {
+ it = pending_.erase(it);
+ continue;
+ }
+ if (oldest == pending_.end() ||
+ it->second->expires_at < oldest->second->expires_at) {
+ oldest = it;
+ }
+ ++it;
+ }
+ if (pending_.size() + validating_.size() < kMaxPendingHandshakes) {
+ return true;
+ }
+
+ // Still full of live entries: a flood, or more genuine clients arriving
+ // at once than this allows for. Dropping the oldest means a flood can only
+ // push a real client out by outpacing its round trip, and that client
+ // retransmits and gets back in.
+ if (oldest == pending_.end()) return false;
+ pending_.erase(oldest);
+ return true;
+}
+
+void DTLSEndpoint::AcceptPendingHandshake(const uint8_t* data,
+ size_t len,
+ const SocketAddress& remote) {
+ if (!MakeRoomForPendingHandshake()) {
+ DTLS_STAT_INCREMENT(DTLSEndpointStats, server_busy_count);
+ return;
+ }
+
+ // As in AcceptConnection(): unauthenticated input, so OpenSSL failing on
+ // it is routine and what it queues is discarded.
+ ncrypto::MarkPopErrorOnReturn mark_pop_error_on_return;
+
+ auto pending = std::make_unique<PendingHandshake>();
+ pending->ssl.reset(SSL_new(server_context_->ssl_ctx()));
+ if (!pending->ssl) return;
+ SSL* ssl = pending->ssl.get();
+
+ // These become the session's enc_in_/enc_out_, so both have to preserve
+ // datagram boundaries -- see DTLSSession::Create().
+ auto in = ncrypto::BIOPointer::New(BIO_s_dgram_mem());
+ auto out = ncrypto::BIOPointer::New(BIO_s_dgram_mem());
+ if (!in || !out) return;
+ pending->enc_in = in.release();
+ pending->enc_out = out.release();
+ SSL_set_bio(ssl, pending->enc_in, pending->enc_out);
+
+ SSL_set_accept_state(ssl);
+ SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE | SSL_OP_NO_QUERY_MTU);
+ SSL_set_mtu(ssl, mtu_);
+ server_context_->BindToSSL(ssl);
+ DTLSContext::SetPendingState(ssl, &pending->state);
+ pending->expires_at = uv_hrtime() / 1000000 + kValidationTimeoutMs;
+
+ pending_[remote] = std::move(pending);
+ DrivePendingHandshake(data, len, remote);
+}
+
+void DTLSEndpoint::DrivePendingHandshake(const uint8_t* data,
+ size_t len,
+ const SocketAddress& remote) {
+ auto it = pending_.find(remote);
+ if (it == pending_.end()) return;
+ PendingHandshake* pending = it->second.get();
+
+ ncrypto::MarkPopErrorOnReturn mark_pop_error_on_return;
+
+ if (BIO_write(pending->enc_in, data, len) <= 0) return;
+
+ // The cookie callbacks find the peer here: there is no session yet.
+ server_context_->set_cookie_peer(remote);
+ int ret = SSL_do_handshake(pending->ssl.get());
+ int err = ret <= 0 ? SSL_get_error(pending->ssl.get(), ret) : SSL_ERROR_NONE;
+
+ // Whatever OpenSSL produced -- the cookie flight, or a retransmission of
+ // it for a retransmitted first ClientHello -- goes out now. Nothing more
+ // will: no retransmit timer runs for a pending handshake, so everything
+ // sent to an address that has not been validated is a reply to a datagram
+ // that came from it, and smaller than that datagram.
+ MaybeStackBuffer<uint8_t, 1500> buf;
+ for (;;) {
+ size_t pending_len = BIO_pending(pending->enc_out);
+ if (pending_len == 0) break;
+ buf.AllocateSufficientStorage(pending_len);
+ int n = BIO_read(pending->enc_out, buf.out(), pending_len);
+ if (n <= 0) break;
+ SendTo(remote, buf.out(), n);
+ }
+
+ if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) return;
+ if (err != SSL_ERROR_WANT_CLIENT_HELLO_CB) {
+ // A ClientHello OpenSSL would not accept, or -- which the cookie
+ // exchange rules out -- a handshake that finished without one.
+ pending_.erase(it);
+ return;
+ }
+
+ // Suspended at the ClientHello that should carry the cookie back. From
+ // here on the handshake runs through a DTLSSession, so that what follows
+ // cookie verification -- SNI, PSK, key derivation and its keylog lines --
+ // has a session to report to. The session stays unannounced, and
+ // invisible to JavaScript, until the cookie verifies.
+ std::unique_ptr<PendingHandshake> owned = std::move(it->second);
+ pending_.erase(it);
+ DTLSContext::SetPendingState(owned->ssl.get(), nullptr);
+
+ // The slot was free when the first ClientHello arrived; it may not be now.
+ if (!HasCapacityFor(remote)) {
+ DTLS_STAT_INCREMENT(DTLSEndpointStats, server_refused_count);
+ return;
+ }
+
+ HandleScope handle_scope(env()->isolate());
+ Context::Scope context_scope(env()->context());
+
+ auto session = DTLSSession::CreateFromSSL(env(),
+ this,
+ server_context_.get(),
+ std::move(owned->ssl),
+ owned->enc_in,
+ owned->enc_out,
+ remote);
+ if (!session) return;
+
+ session->AwaitAddressValidation();
+ validating_[remote] = session;
+
+ // Resumes the handshake at the suspended ClientHello. The session
+ // announces itself from inside if the cookie verifies, and destroys itself
+ // silently if it does not.
+ session->Start();
+}
+
+void DTLSEndpoint::AnnounceSession(DTLSSession* session_ptr) {
+ BaseObjectPtr<DTLSSession> session(session_ptr);
+ const SocketAddress remote = session->remote_address();
+
+ validating_.erase(remote);
+ sessions_[remote] = session;
+ sessions_per_host_[remote]++;
+ state_->session_count = sessions_.size();
+ DTLS_STAT_INCREMENT(DTLSEndpointStats, server_sessions);
+
+ uv_ref(reinterpret_cast<uv_handle_t*>(&handle_));
+
+ Local<Value> argv[] = {session->object()};
+ Local<Function> cb = GetCallback(DTLS_CB_SESSION_NEW);
+ if (!cb.IsEmpty()) {
+ MakeCallback(cb, 1, argv);
+ }
+}
+
// --- JS binding methods ---
void DTLSEndpoint::DoBind(const FunctionCallbackInfo<Value>& args) {
@@ -930,6 +1138,9 @@ void DTLSEndpoint::DoSetCallbacks(const FunctionCallbackInfo<Value>& args) {
void DTLSEndpoint::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("sessions", sessions_.size());
+ tracker->TrackFieldWithSize("pending_handshakes",
+ pending_.size() * sizeof(PendingHandshake));
+ tracker->TrackField("validating_sessions", validating_.size());
tracker->TrackFieldWithSize("recv_buf", recv_buf_.size());
}
diff --git a/src/dtls/dtls_endpoint.h b/src/dtls/dtls_endpoint.h
index 1511dfa2a64..0ce16580aae 100644
--- a/src/dtls/dtls_endpoint.h
+++ b/src/dtls/dtls_endpoint.h
@@ -13,6 +13,7 @@
#include <openssl/ssl.h>
+#include <memory>
#include <unordered_map>
#include <vector>
@@ -39,8 +40,10 @@ struct DTLSEndpointStats {
// DTLSEndpoint manages a single UDP socket and dispatches incoming
// datagrams to the appropriate DTLSSession based on the remote address.
-// For server mode, it handles stateless cookie exchange via DTLSv1_listen()
-// before creating new sessions.
+// For server mode, it validates each new peer's address with a cookie
+// exchange before creating a session for it: statelessly via
+// DTLSv1_listen() when only DTLS 1.2 is enabled, and through a pending
+// handshake when DTLS 1.3 is (see AcceptPendingHandshake()).
class DTLSEndpoint final : public HandleWrap {
public:
static v8::Local<v8::FunctionTemplate> GetConstructorTemplate(
@@ -79,6 +82,11 @@ class DTLSEndpoint final : public HandleWrap {
// Remove a session from the endpoint (called on session close/destroy).
void RemoveSession(const SocketAddress& addr);
+ // Enter a session promoted from a pending handshake into the session table
+ // and emit it to JavaScript. Called by the session once OpenSSL has
+ // verified the cookie its peer returned.
+ void AnnounceSession(DTLSSession* session);
+
// Close the endpoint gracefully (close all sessions first).
void CloseGracefully();
@@ -149,6 +157,43 @@ class DTLSEndpoint final : public HandleWrap {
size_t len,
const SocketAddress& remote);
+ // A server handshake that has not completed the cookie exchange. Bare: no
+ // DTLSSession and no JavaScript object, so a forged source address costs
+ // an SSL and nothing the garbage collector has to see.
+ //
+ // DTLSv1_listen() cannot be used once DTLS 1.3 is enabled. It only speaks
+ // HelloVerifyRequest, and quietly caps the handshake at DTLS 1.2 to make
+ // that work. Nor can the exchange be stateless the way DTLSv1_listen()
+ // makes it: a DTLS 1.3 ClientHello carrying a post-quantum key share does
+ // not fit in one datagram at the default MTU, and OpenSSL does not accept
+ // the second ClientHello (message_seq 1) on a fresh SSL. So the SSL is
+ // kept, with SSL_OP_COOKIE_EXCHANGE, and OpenSSL sends whichever of
+ // HelloVerifyRequest or HelloRetryRequest the negotiated version calls
+ // for, and retransmits it if the first ClientHello is retransmitted.
+ struct PendingHandshake {
+ ncrypto::SSLPointer ssl;
+ BIO* enc_in = nullptr; // Owned by ssl.
+ BIO* enc_out = nullptr; // Owned by ssl.
+ PendingHandshakeState state;
+ uint64_t expires_at = 0; // Milliseconds, uv_hrtime() based.
+ };
+
+ // Start a pending handshake for |remote| with its first datagram.
+ void AcceptPendingHandshake(const uint8_t* data,
+ size_t len,
+ const SocketAddress& remote);
+
+ // Feed a datagram to |remote|'s pending handshake. Once it is suspended at
+ // the ClientHello carrying the cookie back, wrap it in an unannounced
+ // DTLSSession and hand that the rest of the handshake.
+ void DrivePendingHandshake(const uint8_t* data,
+ size_t len,
+ const SocketAddress& remote);
+
+ // Drop expired pending handshakes and, if the table is still full, the
+ // oldest one. True if there is room for another.
+ bool MakeRoomForPendingHandshake();
+
uv_udp_t handle_;
// Reusable receive buffer for uv_udp_recv (see OnAlloc). libuv delivers one
@@ -167,6 +212,14 @@ class DTLSEndpoint final : public HandleWrap {
// seen.
SocketAddress::IpMap<uint32_t> sessions_per_host_;
+ // Server handshakes still completing the cookie exchange.
+ SocketAddress::PeerMap<std::unique_ptr<PendingHandshake>> pending_;
+
+ // Sessions promoted from a pending handshake whose cookie has not been
+ // verified yet. Not in sessions_, not counted, and not known to
+ // JavaScript; moved over by AnnounceSession().
+ SocketAddress::PeerMap<BaseObjectPtr<DTLSSession>> validating_;
+
// Server context (set when listening).
BaseObjectPtr<DTLSContext> server_context_;
diff --git a/src/dtls/dtls_session.cc b/src/dtls/dtls_session.cc
index d2fc9cd8639..85e57b3625c 100644
--- a/src/dtls/dtls_session.cc
+++ b/src/dtls/dtls_session.cc
@@ -119,6 +119,13 @@ DTLSSession::DTLSSession(Environment* env,
BaseObjectPtr<DTLSSession> strong_ref{this};
MarkPopErrorOnReturn mark_pop_error_on_return;
+ // Nothing to report for a peer that never proved
+ // it holds its address.
+ if (!announced_ && ValidationDeadlineExpired()) {
+ Destroy();
+ return;
+ }
+
// The deadline is checked before retransmitting, so
// an expired handshake stops rather than sends once
// more.
@@ -461,6 +468,7 @@ void DTLSSession::Cycle() {
// handshake recovered from.
EmitPendingError();
EmitSendError();
+ EmitSessionTicket();
}
void DTLSSession::CycleInner() {
@@ -470,8 +478,30 @@ void DTLSSession::CycleInner() {
// If handshake is not yet complete, drive it forward.
if (!handshake_complete_) {
int ret = SSL_do_handshake(ssl_.get());
+ int err = ret <= 0 ? SSL_get_error(ssl_.get(), ret) : SSL_ERROR_NONE;
+
+ if (!announced_) {
+ if (!address_validated_) {
+ // The peer has not shown it can receive at its address, so whatever
+ // happened stays here. A bad cookie still gets OpenSSL's
+ // illegal_parameter alert, which RFC 9147 section 5.1 requires and
+ // which is a handful of bytes; nothing else is sent to an address
+ // that may be forged.
+ EncOut();
+ if (err == SSL_ERROR_SSL) {
+ Destroy();
+ return;
+ }
+ UpdateTimer();
+ return;
+ }
+ // Announce before anything else is reported, so the error, handshake
+ // and message callbacks below have a wrapper to land on.
+ Announce();
+ if (destroyed_) return;
+ }
+
if (ret <= 0) {
- int err = SSL_get_error(ssl_.get(), ret);
if (err == SSL_ERROR_SSL) {
std::string message = FormatSSLError(err);
// Flush any fatal alert OpenSSL queued for the peer before emitting the
@@ -723,7 +753,63 @@ bool DTLSSession::PeerVerificationPassed() {
return false;
}
+void DTLSSession::AwaitAddressValidation() {
+ address_validated_ = false;
+ announced_ = false;
+ validation_deadline_ = uv_hrtime() / 1000000 + kValidationTimeoutMs;
+}
+
+bool DTLSSession::ValidationDeadlineExpired() const {
+ return validation_deadline_ != 0 &&
+ uv_hrtime() / 1000000 >= validation_deadline_;
+}
+
+void DTLSSession::Announce() {
+ announced_ = true;
+ validation_deadline_ = 0;
+ auto ep = endpoint_.get();
+ if (ep == nullptr) {
+ Destroy();
+ return;
+ }
+ ep->AnnounceSession(this);
+ // The new-session handler may have destroyed the session.
+ if (destroyed_) return;
+ FlushEarlyKeylog();
+}
+
+void DTLSSession::FlushEarlyKeylog() {
+ if (early_keylog_.empty()) return;
+ // Swapped out first: the handler may destroy the session, which discards
+ // whatever is still held.
+ std::vector<std::string> lines;
+ lines.swap(early_keylog_);
+ if (state_->has_keylog_listener) {
+ HandleScope handle_scope(env()->isolate());
+ Context::Scope context_scope(env()->context());
+ for (const std::string& line : lines) {
+ if (destroyed_) break;
+ Local<Value> str;
+ if (!ToV8Value(env()->context(), line).ToLocal(&str)) continue;
+ Local<Value> argv[] = {str};
+ EmitCallback(DTLS_CB_SESSION_KEYLOG, 1, argv);
+ }
+ }
+ for (std::string& line : lines) OPENSSL_cleanse(line.data(), line.size());
+}
+
+void DTLSSession::DiscardEarlyKeylog() {
+ for (std::string& line : early_keylog_) {
+ OPENSSL_cleanse(line.data(), line.size());
+ }
+ early_keylog_.clear();
+}
+
void DTLSSession::EmitHandshakeTimeout() {
+ if (!announced_) {
+ Destroy();
+ return;
+ }
HandleScope hs(env()->isolate());
Context::Scope cs(env()->context());
Local<Value> message;
@@ -739,7 +825,25 @@ void DTLSSession::UpdateTimer() {
if (destroyed_) return;
struct timeval tv;
- if (DTLSv1_get_timeout(ssl_.get(), &tv)) {
+ bool have_timeout = DTLSv1_get_timeout(ssl_.get(), &tv);
+
+ // An unannounced session has to wake at its validation deadline whether or
+ // not OpenSSL wants to retransmit anything: a peer that sent the one
+ // ClientHello and went quiet would otherwise hold the slot until the
+ // handshake deadline.
+ if (!announced_ && validation_deadline_ != 0) {
+ uint64_t now = uv_hrtime() / 1000000;
+ uint64_t remaining =
+ validation_deadline_ > now ? validation_deadline_ - now : 1;
+ if (have_timeout) {
+ uint64_t timeout_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
+ if (timeout_ms < remaining) remaining = timeout_ms == 0 ? 1 : timeout_ms;
+ }
+ retransmit_timer_.Update(remaining);
+ return;
+ }
+
+ if (have_timeout) {
uint64_t timeout_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
if (timeout_ms == 0) timeout_ms = 1; // Minimum 1ms.
@@ -787,13 +891,23 @@ int DTLSSession::Send(const uint8_t* data, size_t len) {
// DTLS carries application data in a single record per datagram and does
// not fragment it, so anything above the maximum plaintext record length is
// unsendable. Report the limit rather than letting SSL_write fail opaquely.
- if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
+ //
+ // One byte less under DTLS 1.3. RFC 8446 section 5.4 allows the full 2^14
+ // of content, but OpenSSL 4.1 checks a received DTLS 1.3 record against
+ // the maximum fragment length before removing the inner content type byte,
+ // so a full-sized record arrives one byte over and the receiver ends the
+ // association with record_overflow. Every OpenSSL-based peer -- including
+ // another Node.js -- is affected, so staying under it is not optional.
+ const size_t max_len = SSL_version(ssl_.get()) == DTLS1_3_VERSION
+ ? SSL3_RT_MAX_PLAIN_LENGTH - 1
+ : SSL3_RT_MAX_PLAIN_LENGTH;
+ if (len > max_len) {
THROW_ERR_OUT_OF_RANGE(
env(),
- "data is %zu bytes, which exceeds the %d byte maximum for a single "
+ "data is %zu bytes, which exceeds the %zu byte maximum for a single "
"DTLS record",
len,
- SSL3_RT_MAX_PLAIN_LENGTH);
+ max_len);
return -1;
}
@@ -872,6 +986,7 @@ void DTLSSession::Destroy() {
// A parked exception is a strong reference to a JS Error, whose stack
// normally reaches back to this session. Nothing will emit it now.
pending_error_.Reset();
+ DiscardEarlyKeylog();
// Promote to strong ref to keep endpoint alive during removal,
// then release our weak pointer.
@@ -884,6 +999,13 @@ void DTLSSession::SSLKeylogCallback(const SSL* ssl, const char* line) {
DTLSSession* session = static_cast<DTLSSession*>(SSL_get_app_data(ssl));
if (session == nullptr || session->destroyed_) return;
+ // Not announced yet, so there is no wrapper to ask whether anything is
+ // listening. Held in C++ until there is; see FlushEarlyKeylog().
+ if (!session->announced_) {
+ session->early_keylog_.emplace_back(line);
+ return;
+ }
+
// `line` carries the connection's secrets. Do not copy it into the JS heap
// unless something is actually listening -- once it is a JS string it is
// reachable from heap snapshots, core dumps and the inspector for as long as
@@ -927,6 +1049,14 @@ void DTLSSession::EmitSendError() {
EmitCallback(DTLS_CB_SESSION_ERROR, 1, argv);
}
+void DTLSSession::EmitSessionTicket() {
+ if (!ticket_pending_ || destroyed_ || !announced_) return;
+ ticket_pending_ = false;
+ HandleScope handle_scope(env()->isolate());
+ Local<Value> argv[] = {};
+ EmitCallback(DTLS_CB_SESSION_TICKET, 0, argv);
+}
+
void DTLSSession::EmitPendingError() {
if (pending_error_.IsEmpty() || destroyed_) return;
HandleScope handle_scope(env()->isolate());
@@ -1138,6 +1268,28 @@ void DTLSSession::ExportKeyingMaterial(
MarkPopErrorOnReturn mark_pop_error_on_return;
+ // The DTLS 1.3 exporter is HKDF-Expand-Label (RFC 8446 section 7.5), which
+ // cannot produce more than 255 hash lengths of output: 8160 bytes under a
+ // SHA-256 suite, 12240 under SHA-384. Reported as the range error it is
+ // rather than as OpenSSL's bare failure.
+ if (SSL_version(session->ssl_.get()) == DTLS1_3_VERSION) {
+ const SSL_CIPHER* cipher = SSL_get_current_cipher(session->ssl_.get());
+ const EVP_MD* md =
+ cipher != nullptr ? SSL_CIPHER_get_handshake_digest(cipher) : nullptr;
+ if (md != nullptr) {
+ const uint32_t max = 255 * static_cast<uint32_t>(EVP_MD_get_size(md));
+ if (length > max) {
+ return THROW_ERR_OUT_OF_RANGE(
+ env,
+ "The value of \"length\" is out of range. It must be <= %u "
+ "under DTLS 1.3 with %s. Received %u",
+ max,
+ SSL_CIPHER_get_name(cipher),
+ length);
+ }
+ }
+ }
+
std::vector<uint8_t> out(length);
int ret = SSL_export_keying_material(session->ssl_.get(),
out.data(),
@@ -1235,6 +1387,12 @@ void DTLSSession::GetSession(const FunctionCallbackInfo<Value>& args) {
ncrypto::SSLSessionPointer sess(SSL_get1_session(session->ssl_.get()));
if (!sess) return;
+ // A DTLS 1.3 connection has a session as soon as the handshake completes,
+ // but nothing to resume it with until the server's NewSessionTicket
+ // arrives. Handing that out would look like a ticket and buy a full
+ // handshake.
+ if (!SSL_SESSION_is_resumable(sess.get())) return;
+
int size = i2d_SSL_SESSION(sess.get(), nullptr);
if (size <= 0) return;
diff --git a/src/dtls/dtls_session.h b/src/dtls/dtls_session.h
index a80776dcffa..eacc0a8fad0 100644
--- a/src/dtls/dtls_session.h
+++ b/src/dtls/dtls_session.h
@@ -108,6 +108,21 @@ class DTLSSession final : public AsyncWrap {
bool is_handshake_complete() const { return handshake_complete_; }
bool is_closed() const { return closed_; }
+ // A server session promoted from a pending handshake starts out neither
+ // validated nor announced: the endpoint hands it the ClientHello that
+ // should carry the cookie back, and only once OpenSSL has verified that
+ // cookie is the session announced to JavaScript. Until then nothing is
+ // emitted, a failure tears it down silently, and the JavaScript SNI and PSK
+ // callbacks are not run for it. Every other session is both from the start.
+ void AwaitAddressValidation();
+ void OnAddressValidated() { address_validated_ = true; }
+ bool address_validated() const { return address_validated_; }
+ bool announced() const { return announced_; }
+
+ // A new resumable session is available; reported once Cycle() is done,
+ // since OpenSSL calls this from inside SSL_read() or SSL_do_handshake().
+ void OnNewSessionTicket() { ticket_pending_ = true; }
+
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(DTLSSession)
SET_SELF_SIZE(DTLSSession)
@@ -231,6 +246,16 @@ class DTLSSession final : public AsyncWrap {
// Emit a failure to put a record on the wire.
void EmitSendError();
+ // Emit a new resumable session reported by OnNewSessionTicket().
+ void EmitSessionTicket();
+
+ // Hand a newly validated session to the endpoint, which emits it to
+ // JavaScript, then deliver the keylog lines derived before that.
+ void Announce();
+ void FlushEarlyKeylog();
+ void DiscardEarlyKeylog();
+ bool ValidationDeadlineExpired() const;
+
BaseObjectWeakPtr<DTLSEndpoint> endpoint_;
ncrypto::SSLPointer ssl_;
@@ -249,6 +274,21 @@ class DTLSSession final : public AsyncWrap {
bool closed_ = false;
bool destroyed_ = false;
int cycle_depth_ = 0;
+ bool address_validated_ = true;
+ bool announced_ = true;
+ bool ticket_pending_ = false;
+
+ // Absolute time by which an unannounced session must validate its peer, or
+ // 0 once it has. Short and separate from the handshake deadline: a session
+ // here has been handed a ClientHello but not shown to hold the address.
+ uint64_t validation_deadline_ = 0;
+
+ // Keylog lines produced before the session was announced. Under DTLS 1.3
+ // the handshake secrets are derived while the cookie-bearing ClientHello is
+ // processed, before JavaScript has had a chance to attach a listener.
+ // Delivered after the announcement if one was attached, and cleansed
+ // either way.
+ std::vector<std::string> early_keylog_;
v8::Global<v8::Value> pending_error_;
diff --git a/test/parallel/test-dtls-address-validation.mjs b/test/parallel/test-dtls-address-validation.mjs
new file mode 100644
index 00000000000..1635844d61c
--- /dev/null
+++ b/test/parallel/test-dtls-address-validation.mjs
@@ -0,0 +1,234 @@
+// Flags: --experimental-dtls --no-warnings
+
+// Test: a server with DTLS 1.3 enabled validates each peer's address before
+// announcing a session for it.
+//
+// DTLSv1_listen() only speaks HelloVerifyRequest and caps the handshake at
+// DTLS 1.2, so once DTLS 1.3 is enabled the server keeps a pending SSL per
+// peer instead and lets OpenSSL send whichever of HelloVerifyRequest or
+// HelloRetryRequest the negotiated version calls for. These cases watch the
+// wire through a proxy to check that it does, that a session is only
+// announced once the cookie has come back from the address it was sent to,
+// and that losing the cookie flight does not strand the handshake.
+
+import { hasCrypto, mustCall, mustNotCall, skip } from '../common/index.mjs';
+import * as fixtures from '../common/fixtures.mjs';
+import assert from 'node:assert';
+import { once } from 'node:events';
+
+if (!hasCrypto) {
+ skip('missing crypto');
+}
+
+if (!process.features.dtls) {
+ skip('DTLS is not enabled');
+}
+
+const dgram = await import('node:dgram');
+const { connect, listen } = await import('node:dtls');
+
+const HOST = '127.0.0.1';
+const cert = fixtures.readKey('agent1-cert.pem').toString();
+const key = fixtures.readKey('agent1-key.pem').toString();
+
+const V12 = { minVersion: 'DTLSv1.2', maxVersion: 'DTLSv1.2' };
+const V13 = { minVersion: 'DTLSv1.3', maxVersion: 'DTLSv1.3' };
+const BOTH = { minVersion: 'DTLSv1.2', maxVersion: 'DTLSv1.3' };
+
+// SHA-256("HelloRetryRequest"), the ServerHello.random that marks a
+// HelloRetryRequest (RFC 8446 section 4.1.3).
+const HRR_RANDOM = Buffer.from(
+ 'cf21ad74e59a6111be1d8c021e65b891c2a211167abb8c5e079e09e2c8a8339c', 'hex');
+
+// The first handshake message in a plaintext DTLS record: a 13 byte record
+// header, then msg_type, and for a ServerHello its random 14 bytes later.
+function classify(datagram) {
+ if (datagram.length < 14 || datagram[0] !== 22) return 'other';
+ switch (datagram[13]) {
+ case 1: return 'ClientHello';
+ case 3: return 'HelloVerifyRequest';
+ case 2:
+ return datagram.length >= 59 &&
+ datagram.subarray(27, 59).equals(HRR_RANDOM) ?
+ 'HelloRetryRequest' : 'ServerHello';
+ default: return 'other';
+ }
+}
+
+// A one-client UDP proxy that records, and can drop, what passes through.
+async function createProxy(serverPort, { dropFromServer = () => false } = {}) {
+ const front = dgram.createSocket('udp4');
+ const back = dgram.createSocket('udp4');
+ const fromClient = [];
+ const fromServer = [];
+ let client;
+ front.on('message', (msg, rinfo) => {
+ client = rinfo;
+ fromClient.push(msg);
+ back.send(msg, serverPort, HOST);
+ });
+ back.on('message', (msg) => {
+ fromServer.push(msg);
+ if (dropFromServer(msg, fromServer.length)) return;
+ if (client) front.send(msg, client.port, client.address);
+ });
+ front.bind(0, HOST);
+ back.bind(0, HOST);
+ await Promise.all([once(front, 'listening'), once(back, 'listening')]);
+ return {
+ port: front.address().port,
+ fromClient,
+ fromServer,
+ close() { front.close(); back.close(); },
+ };
+}
+
+// DTLS 1.3 validates with a HelloRetryRequest, and the ClientHello it answers
+// does not fit in one datagram at the default MTU -- the post-quantum key
+// share alone is over a kilobyte -- so it arrives in fragments.
+{
+ const endpoint = listen(mustCall(), { cert, key, host: HOST, port: 0, ...BOTH });
+ const proxy = await createProxy(endpoint.address.port);
+
+ const client = connect(HOST, proxy.port, { rejectUnauthorized: false, ...V13 });
+ const { protocol } = await client.opened;
+ assert.strictEqual(protocol, 'DTLSv1.3');
+
+ assert.strictEqual(classify(proxy.fromServer[0]), 'HelloRetryRequest');
+ const hellos = proxy.fromClient.filter((d) => classify(d) === 'ClientHello');
+ // At least two datagrams for each of the two ClientHellos.
+ assert.ok(hellos.length >= 4, `${hellos.length} ClientHello datagrams`);
+
+ await client.close();
+ await endpoint.close();
+ proxy.close();
+}
+
+// The same server answers a DTLS 1.2 client with a HelloVerifyRequest.
+{
+ const endpoint = listen(mustCall(), { cert, key, host: HOST, port: 0, ...BOTH });
+ const proxy = await createProxy(endpoint.address.port);
+
+ const client = connect(HOST, proxy.port, { rejectUnauthorized: false, ...V12 });
+ assert.strictEqual((await client.opened).protocol, 'DTLSv1.2');
+ assert.strictEqual(classify(proxy.fromServer[0]), 'HelloVerifyRequest');
+
+ await client.close();
+ await endpoint.close();
+ proxy.close();
+}
+
+// A lost HelloRetryRequest is recovered by the client retransmitting its
+// first ClientHello. The server keeps no retransmit timer of its own for a
+// peer it has not validated; it answers the retransmission.
+{
+ const endpoint = listen(mustCall(), { cert, key, host: HOST, port: 0, ...BOTH });
+ const proxy = await createProxy(endpoint.address.port, {
+ dropFromServer: (msg, n) => n === 1,
+ });
+
+ const client = connect(HOST, proxy.port, { rejectUnauthorized: false, ...V13 });
+ assert.strictEqual((await client.opened).protocol, 'DTLSv1.3');
+ const retries = proxy.fromServer.filter(
+ (d) => classify(d) === 'HelloRetryRequest');
+ assert.ok(retries.length >= 2, `${retries.length} HelloRetryRequests`);
+
+ await client.close();
+ await endpoint.close();
+ proxy.close();
+}
+
+// Replaying a client's datagrams from a different address gets the replayer
+// no session. The first ClientHello only earns a HelloRetryRequest, which is
+// smaller than what was sent, and the second carries a cookie bound to the
+// original address, which does not verify from here and is answered with the
+// illegal_parameter alert RFC 9147 section 5.1 requires. That alert is sent
+// after the server has decided against the peer, so once it arrives nothing
+// more can be announced.
+{
+ const announced = [];
+ const endpoint = listen((session) => announced.push(session),
+ { cert, key, host: HOST, port: 0, ...BOTH });
+ const proxy = await createProxy(endpoint.address.port);
+
+ const client = connect(HOST, proxy.port, { rejectUnauthorized: false, ...V13 });
+ await client.opened;
+ assert.strictEqual(announced.length, 1);
+ await client.close();
+
+ const hellos = proxy.fromClient.filter((d) => classify(d) === 'ClientHello');
+ const replayer = dgram.createSocket('udp4');
+ const replies = [];
+ const answered = Promise.withResolvers();
+ replayer.on('message', (msg) => {
+ replies.push(msg);
+ if (replies.length === 2) answered.resolve();
+ });
+ replayer.bind(0, HOST);
+ await once(replayer, 'listening');
+
+ let sent = 0;
+ for (const datagram of hellos) {
+ sent += datagram.length;
+ replayer.send(datagram, endpoint.address.port, HOST);
+ }
+ await answered.promise;
+
+ assert.strictEqual(classify(replies[0]), 'HelloRetryRequest');
+ // A plaintext alert record: content type 21, level fatal(2),
+ // illegal_parameter(47).
+ assert.deepStrictEqual([replies[1][0], replies[1][13], replies[1][14]],
+ [21, 2, 47]);
+ assert.strictEqual(announced.length, 1);
+ const received = replies.reduce((n, d) => n + d.length, 0);
+ assert.ok(received < sent, `${received} bytes back for ${sent} sent`);
+
+ replayer.close();
+ await endpoint.close();
+ proxy.close();
+}
+
+// Garbage that is not a ClientHello is rejected before anything is created
+// for it, and gets no reply. The handshake that follows cannot complete
+// until the server has read everything queued ahead of it, so by then the
+// rejection has been counted.
+{
+ const endpoint = listen(mustCall(), { cert, key, host: HOST, port: 0, ...BOTH });
+ const junk = dgram.createSocket('udp4');
+ junk.on('message', mustNotCall());
+ junk.bind(0, HOST);
+ await once(junk, 'listening');
+ const sent = Promise.withResolvers();
+ junk.send(Buffer.alloc(64, 0x16), endpoint.address.port, HOST,
+ (err) => (err ? sent.reject(err) : sent.resolve()));
+ await sent.promise;
+
+ const client = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...BOTH,
+ });
+ assert.strictEqual((await client.opened).protocol, 'DTLSv1.3');
+ assert.strictEqual(endpoint.stats.serverRejectedCount, 1n);
+ await client.close();
+ junk.close();
+ await endpoint.close();
+}
+
+// maxSessions counts a session from the moment its cookie verifies, so a
+// second peer is refused while the first is open.
+{
+ const endpoint = listen(mustCall(), {
+ cert, key, host: HOST, port: 0, maxSessions: 1, ...BOTH,
+ });
+ const first = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...V13,
+ });
+ await first.opened;
+
+ const second = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, handshakeTimeout: 500, ...V13,
+ });
+ await assert.rejects(second.opened, /handshake timeout/);
+
+ await first.close();
+ await endpoint.close();
+}
diff --git a/test/parallel/test-dtls-version-13-features.mjs b/test/parallel/test-dtls-version-13-features.mjs
new file mode 100644
index 00000000000..4689bac4c91
--- /dev/null
+++ b/test/parallel/test-dtls-version-13-features.mjs
@@ -0,0 +1,242 @@
+// Flags: --experimental-dtls --no-warnings
+
+// Test: features that behave differently, or are reached by a different code
+// path, when DTLS 1.3 is negotiated.
+//
+// A DTLS 1.3 server does its address validation with a pending handshake
+// that only becomes a session once the cookie verifies, so everything the
+// handshake reports after that point -- keylog lines, SNI, PSK -- has to
+// reach a session JavaScript has not been given yet. Resumption moves after
+// the handshake, the exporter is HKDF based, and the record limit is one
+// byte lower.
+
+import { hasCrypto, mustCall, skip } from '../common/index.mjs';
+import * as fixtures from '../common/fixtures.mjs';
+import assert from 'node:assert';
+
+if (!hasCrypto) {
+ skip('missing crypto');
+}
+
+if (!process.features.dtls) {
+ skip('DTLS is not enabled');
+}
+
+const { connect, createSecureContext, listen } = await import('node:dtls');
+
+const HOST = '127.0.0.1';
+const cert = fixtures.readKey('agent1-cert.pem').toString();
+const key = fixtures.readKey('agent1-key.pem').toString();
+const ca = fixtures.readKey('ca1-cert.pem').toString();
+const V12 = { minVersion: 'DTLSv1.2', maxVersion: 'DTLSv1.2' };
+const V13 = { minVersion: 'DTLSv1.3', maxVersion: 'DTLSv1.3' };
+
+// Connect and return the client and the server's session for it.
+async function pair(serverOptions, clientOptions, onsession = () => {}) {
+ const serverSession = Promise.withResolvers();
+ const endpoint = listen((session) => {
+ onsession(session);
+ serverSession.resolve(session);
+ }, { host: HOST, port: 0, ...V13, ...serverOptions });
+ const client = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...V13, ...clientOptions,
+ });
+ await client.opened;
+ const server = await serverSession.promise;
+ await server.opened;
+ assert.strictEqual(client.protocol, 'DTLSv1.3');
+ return { endpoint, client, server };
+}
+
+// The server's handshake secrets are derived while the cookie-bearing
+// ClientHello is processed, before the session is announced. They are held
+// and delivered once a listener is attached in onsession.
+{
+ const serverLines = [];
+ const { endpoint, client } = await pair({ cert, key }, {}, (session) => {
+ session.onkeylog = (line) => serverLines.push(line.toString());
+ });
+ await client.close();
+ await endpoint.close();
+
+ const labels = (lines) => new Set(lines.map((l) => l.split(' ')[0]));
+ for (const label of [
+ 'CLIENT_HANDSHAKE_TRAFFIC_SECRET',
+ 'SERVER_HANDSHAKE_TRAFFIC_SECRET',
+ 'CLIENT_TRAFFIC_SECRET_0',
+ 'SERVER_TRAFFIC_SECRET_0',
+ 'EXPORTER_SECRET',
+ ]) {
+ assert.ok(labels(serverLines).has(label), `server ${label}`);
+ }
+}
+
+// ALPN.
+{
+ const { endpoint, client, server } = await pair(
+ { cert, key, alpn: ['coap', 'h2'] }, { alpn: ['coap'] });
+ assert.strictEqual(client.alpnProtocol, 'coap');
+ assert.strictEqual(server.alpnProtocol, 'coap');
+ await client.close();
+ await endpoint.close();
+}
+
+// SNI, from a map and from a callback. The callback is only asked about a
+// peer that has completed the cookie exchange, so once per handshake.
+{
+ const { endpoint, client, server } = await pair({
+ cert, key,
+ sni: { 'localhost': createSecureContext({ isServer: true, cert, key }) },
+ }, { servername: 'localhost' });
+ assert.strictEqual(server.servername, 'localhost');
+ await client.close();
+ await endpoint.close();
+}
+{
+ const asked = [];
+ const { endpoint, client, server } = await pair({
+ cert, key,
+ sni: (servername) => {
+ asked.push(servername);
+ return { cert, key };
+ },
+ }, { servername: 'localhost' });
+ assert.strictEqual(server.servername, 'localhost');
+ assert.deepStrictEqual(asked, ['localhost']);
+ await client.close();
+ await endpoint.close();
+}
+
+// PSK, from a map and from callbacks. DTLS 1.3 PSK authenticates without a
+// certificate, and the session reports it as authorized. The server
+// callback is asked for each ClientHello: the answer for the first steers
+// the cipher suite the HelloRetryRequest commits to. The client's is too,
+// since it builds a second ClientHello in answer to the HelloRetryRequest.
+{
+ const KEY = Buffer.from('0123456789abcdef0123456789abcdef', 'hex');
+ for (const [serverPsk, clientPsk] of [
+ [{ device: KEY }, { identity: 'device', key: KEY }],
+ [mustCall((identity) => (identity === 'device' ? KEY : undefined), 2),
+ mustCall(() => ({ identity: 'device', key: KEY }), 2)],
+ ]) {
+ const { endpoint, client, server } = await pair(
+ { psk: serverPsk }, { psk: clientPsk, rejectUnauthorized: true });
+ assert.strictEqual(client.authorized, true);
+ assert.strictEqual(client.peerCertificate, undefined);
+ assert.match(server.cipher.name, /SHA256$/);
+ await client.close();
+ await endpoint.close();
+ }
+}
+
+// A client certificate.
+{
+ const { endpoint, client, server } = await pair(
+ { cert, key, ca: [ca], requestCert: true }, { cert, key, ca: [ca] });
+ assert.ok(server.peerCertificate);
+ assert.strictEqual(server.authorized, true);
+ await client.close();
+ await endpoint.close();
+}
+
+// DTLS-SRTP keying.
+{
+ const profile = 'SRTP_AEAD_AES_128_GCM';
+ const { endpoint, client, server } = await pair(
+ { cert, key, srtp: profile }, { srtp: profile });
+ assert.strictEqual(client.srtpProfile, profile);
+ assert.strictEqual(server.srtpProfile, profile);
+ const label = 'EXTRACTOR-dtls_srtp';
+ assert.deepStrictEqual(client.exportKeyingMaterial(60, label),
+ server.exportKeyingMaterial(60, label));
+ await client.close();
+ await endpoint.close();
+}
+
+// The exporter is HKDF-Expand-Label, bounded at 255 hash lengths.
+{
+ const { endpoint, client } = await pair({ cert, key }, {});
+ const hashLength = /SHA384$/.test(client.cipher.name) ? 48 : 32;
+ const max = 255 * hashLength;
+ assert.strictEqual(client.exportKeyingMaterial(max, 'EXPORTER-x').length,
+ max);
+ assert.throws(() => client.exportKeyingMaterial(max + 1, 'EXPORTER-x'), {
+ code: 'ERR_OUT_OF_RANGE',
+ message: new RegExp(`<= ${max} under DTLS 1\\.3`),
+ });
+ await client.close();
+ await endpoint.close();
+}
+
+// The largest send is one byte under the 2^14 record limit, which OpenSSL
+// mis-measures on receipt under DTLS 1.3 and answers with record_overflow.
+{
+ const received = Promise.withResolvers();
+ const { endpoint, client } = await pair({ cert, key }, {}, (session) => {
+ session.onmessage = (data) => received.resolve(data.length);
+ });
+ assert.throws(() => client.send(Buffer.alloc(16384)), {
+ code: 'ERR_OUT_OF_RANGE', message: /16383 byte maximum/,
+ });
+ assert.strictEqual(client.send(Buffer.alloc(16383)), 16383);
+ assert.strictEqual(await received.promise, 16383);
+ await client.close();
+ await endpoint.close();
+}
+
+// Resumption. A DTLS 1.3 server issues its tickets after the handshake, so
+// there is nothing to resume with when opened settles; onsessionticket
+// reports each one as it arrives. Under DTLS 1.2 it reports the session the
+// handshake established.
+for (const versions of [V13, V12]) {
+ const endpoint = listen(() => {}, {
+ cert, key, host: HOST, port: 0, ...versions,
+ });
+ const first = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...versions,
+ });
+ // OpenSSL's server sends two tickets under DTLS 1.3 by default.
+ const expected = versions === V13 ? 2 : 1;
+ const tickets = [];
+ const allTickets = Promise.withResolvers();
+ first.onsessionticket = mustCall((t) => {
+ tickets.push(t);
+ if (tickets.length === expected) allTickets.resolve();
+ }, expected);
+ await first.opened;
+ if (versions === V13) {
+ assert.strictEqual(first.session, undefined);
+ }
+ await allTickets.promise;
+ const session = tickets[0];
+ assert.ok(Buffer.isBuffer(session));
+ await first.close();
+
+ const second = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, session, ...versions,
+ });
+ await second.opened;
+ assert.strictEqual(second.reused, true);
+ await second.close();
+ await endpoint.close();
+}
+
+// A ticket earned without verification is not spent with it.
+{
+ const endpoint = listen(() => {}, { cert, key, host: HOST, port: 0, ...V13 });
+ const first = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...V13,
+ });
+ const ticket = Promise.withResolvers();
+ first.onsessionticket = (t) => ticket.resolve(t);
+ await first.opened;
+ assert.strictEqual(first.authorized, false);
+ const session = await ticket.promise;
+ await first.close();
+
+ const second = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: true, session, ...V13,
+ });
+ await assert.rejects(second.opened, /Peer certificate verification failed/);
+ await endpoint.close();
+}
diff --git a/test/parallel/test-dtls-version.mjs b/test/parallel/test-dtls-version.mjs
new file mode 100644
index 00000000000..73ff9a6998c
--- /dev/null
+++ b/test/parallel/test-dtls-version.mjs
@@ -0,0 +1,115 @@
+// Flags: --experimental-dtls --no-warnings
+
+// Test: minVersion and maxVersion, and negotiation between DTLS 1.2 and 1.3.
+
+import { hasCrypto, skip } from '../common/index.mjs';
+import * as fixtures from '../common/fixtures.mjs';
+import assert from 'node:assert';
+
+if (!hasCrypto) {
+ skip('missing crypto');
+}
+
+if (!process.features.dtls) {
+ skip('DTLS is not enabled');
+}
+
+const { connect, createSecureContext, listen } = await import('node:dtls');
+
+const HOST = '127.0.0.1';
+const cert = fixtures.readKey('agent1-cert.pem').toString();
+const key = fixtures.readKey('agent1-key.pem').toString();
+
+const V12 = { minVersion: 'DTLSv1.2', maxVersion: 'DTLSv1.2' };
+const V13 = { minVersion: 'DTLSv1.3', maxVersion: 'DTLSv1.3' };
+const BOTH = { minVersion: 'DTLSv1.2', maxVersion: 'DTLSv1.3' };
+
+async function negotiate(serverVersions, clientVersions) {
+ const serverProtocol = Promise.withResolvers();
+ const endpoint = listen((session) => {
+ session.onhandshake = (protocol) => serverProtocol.resolve(protocol);
+ session.onmessage = (data) => session.send(data);
+ session.onerror = () => {};
+ }, { cert, key, host: HOST, port: 0, ...serverVersions });
+
+ const client = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, handshakeTimeout: 2000, ...clientVersions,
+ });
+ try {
+ const { protocol } = await client.opened;
+ assert.strictEqual(client.protocol, protocol);
+ assert.strictEqual(await serverProtocol.promise, protocol);
+
+ // And the association carries data in both directions.
+ const echoed = Promise.withResolvers();
+ client.onmessage = (data) => echoed.resolve(data.toString());
+ client.send('ping');
+ assert.strictEqual(await echoed.promise, 'ping');
+ await client.close();
+ return protocol;
+ } finally {
+ client.destroy();
+ await endpoint.close();
+ }
+}
+
+// The newest version both sides allow is chosen.
+for (const [server, client, expected] of [
+ [BOTH, BOTH, 'DTLSv1.3'],
+ [BOTH, V13, 'DTLSv1.3'],
+ [BOTH, V12, 'DTLSv1.2'],
+ [V13, BOTH, 'DTLSv1.3'],
+ [V12, BOTH, 'DTLSv1.2'],
+ [V13, V13, 'DTLSv1.3'],
+ [V12, V12, 'DTLSv1.2'],
+]) {
+ assert.strictEqual(await negotiate(server, client), expected,
+ `server ${server.maxVersion} client ${client.maxVersion}`);
+}
+
+// No common version is a handshake failure on the client, not a fallback.
+await assert.rejects(negotiate(V12, V13), /unsupported protocol/);
+await assert.rejects(negotiate(V13, V12), /protocol version/);
+
+// The default is DTLS 1.2 on both sides.
+assert.strictEqual(await negotiate({}, BOTH), 'DTLSv1.2');
+assert.strictEqual(await negotiate(BOTH, {}), 'DTLSv1.2');
+
+// A secure context carries the range.
+{
+ const context = createSecureContext({ isServer: true, cert, key, ...V13 });
+ const endpoint = listen(() => {}, {
+ host: HOST, port: 0, secureContext: context,
+ });
+ const client = connect(HOST, endpoint.address.port, {
+ rejectUnauthorized: false, ...BOTH,
+ });
+ assert.strictEqual((await client.opened).protocol, 'DTLSv1.3');
+ await client.close();
+ await endpoint.close();
+
+ // ...and cannot be overridden alongside one.
+ assert.throws(() => listen(() => {}, {
+ host: HOST, port: 0, secureContext: context, maxVersion: 'DTLSv1.2',
+ }), { code: 'ERR_INVALID_ARG_VALUE', message: /secureContext/ });
+}
+
+// Validation.
+for (const name of ['minVersion', 'maxVersion']) {
+ for (const bad of ['TLSv1.3', 'DTLSv1', 'DTLSv1.0', 'dtlsv1.3', 12, null]) {
+ assert.throws(
+ () => createSecureContext({ [name]: bad }),
+ { code: 'ERR_INVALID_ARG_VALUE' },
+ `${name}: ${bad}`);
+ }
+}
+
+assert.throws(
+ () => createSecureContext({ minVersion: 'DTLSv1.3', maxVersion: 'DTLSv1.2' }),
+ { code: 'ERR_INVALID_ARG_VALUE', message: /must not be newer/ });
+
+// Raising only the floor raises the default ceiling with it.
+assert.strictEqual(await negotiate({ minVersion: 'DTLSv1.3' }, BOTH),
+ 'DTLSv1.3');
+await assert.rejects(negotiate({ minVersion: 'DTLSv1.3' }, V12),
+ /protocol version/);