lemon-tls 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,17 +44,21 @@ import {
44
44
  import * as wire from './wire.js';
45
45
 
46
46
  // Extracted modules
47
- import { pick_scheme, sign_with_scheme, verify_with_scheme, default_signature_schemes, scheme_name } from './session/signing.js';
47
+ import { pick_scheme, sign_with_scheme, verify_with_scheme, default_signature_schemes, scheme_name, cert_allows_signing, ec_key_group, scheme_info, scheme_matches_key } from './session/signing.js';
48
48
  import createSecureContext from './secure_context.js';
49
- import { x25519_get_public_key, SUPPORTED_GROUPS as ECDH_SUPPORTED_GROUPS, generate_keypair as ecdh_generate_keypair, get_shared_secret as ecdh_get_shared_secret, is_supported_group,
49
+ import { SUPPORTED_GROUPS as ECDH_SUPPORTED_GROUPS, SERVER_DEFAULT_GROUPS as ECDH_SERVER_DEFAULT_GROUPS, generate_keypair as ecdh_generate_keypair, get_shared_secret as ecdh_get_shared_secret, is_supported_group,
50
50
  is_kem_group, kem_server_exchange, group_name as ecdh_group_name
51
51
  } from './session/ecdh.js';
52
52
  import { build_tls_message, parse_tls_message } from './session/message.js';
53
53
  import { encrypt_session_blob, decrypt_session_blob, encode_client_session, decode_client_session } from './session/ticket.js';
54
54
  import { parse_cert_compression, supported_cert_compression, compress_certificate_body, decompress_certificate_body, cert_compression_name } from './session/cert_compression.js';
55
- import { prepare_ech_server, server_process_client_hello, accept_confirmation, EXT_ECH,
55
+ import { parse_cert, issued_by, signed_by, self_signed, valid_at, validity_error,
56
+ check_path, matches_host, is_ip_literal } from './session/x509.js';
57
+ import * as PEM from 'cryptographic-formats/pem';
58
+ import { getRootCertificates } from './ca_store.js';
59
+ import { prepare_ech_server, server_process_client_hello, backend_client_hello, accept_confirmation, EXT_ECH,
56
60
  parse_ech_config_list, prepare_ech_client, client_hpke_setup, client_outer_ext_data, client_encode_inner,
57
- client_seal_outer, grease_ech_state, grease_ech_ext_data, hrr_ech_offset } from './session/ech.js';
61
+ client_seal_outer, client_hello_ech_ext, grease_ech_state, grease_ech_ext_data, hrr_ech_offset } from './session/ech.js';
58
62
 
59
63
  // RFC 8446 §4.1.3 downgrade-protection sentinels. A TLS 1.3-capable server that
60
64
  // negotiates a lower version stamps one of these into the last 8 bytes of
@@ -118,9 +122,10 @@ const EARLY_REPLAY_TIMEOUT_MS = 100;
118
122
  // (local_private_key). Gone with them.
119
123
  const PRIVATE_KEY_OBJECTS = new WeakMap();
120
124
 
121
- function _x509(x) {
122
- try { return new crypto.X509Certificate(Buffer.isBuffer(x) ? x : Buffer.from(x)); }
123
- catch (e) { return null; }
125
+ // A certificate from DER (session/x509.js), or null
126
+ function _cert(x) {
127
+ if (x == null) return null;
128
+ return parse_cert(x instanceof Uint8Array ? x : Buffer.from(x));
124
129
  }
125
130
  // Trust anchors, parsed once. The anchors are the same certificates on every
126
131
  // handshake — the platform bundle (~150 roots) or the caller's `ca` — and
@@ -135,11 +140,35 @@ function _x509(x) {
135
140
  const ANCHOR_CACHE_MAX = 1024;
136
141
  const _anchorByPem = new Map();
137
142
  const _anchorByObj = new WeakMap();
138
- function _anchorX509(a) {
143
+ // One `ca` entry: a PEM string or Buffer may hold a whole BUNDLE — many
144
+ // certificates, as node:tls takes them (and as a CA file is). Only the
145
+ // first CA of a bundle was once trusted, over TLS and DTLS alike. A DER
146
+ // Buffer (or anything else) is one certificate. A block that is not a
147
+ // certificate, a PEM block that does not decode, and a certificate that
148
+ // does not read are skipped — as node:tls skips them — and named in the
149
+ // LEMON_DEBUG log; the rest of the bundle stands.
150
+ function _parseAnchors(a) {
151
+ let pem = typeof a === 'string' ? a
152
+ : (Buffer.isBuffer(a) || a instanceof Uint8Array) && a.length > 10 && a[0] === 0x2d /* '-' */ ? Buffer.from(a).toString('latin1')
153
+ : null;
154
+ if (pem === null) { let x = _cert(a); return x ? [x] : []; }
155
+ let read;
156
+ try { read = PEM.decode_skipping(pem); } catch (e) { dbg('CA', 'no PEM block in a `ca` entry'); return []; }
157
+ for (const s of read.skipped) dbg('CA', 'skipped the ' + s.label + ' block at line ' + s.line + ': ' + s.code + ' — ' + s.detail);
158
+ let out = [];
159
+ for (let i = 0; i < read.blocks.length; i++) {
160
+ if (read.blocks[i].label !== 'CERTIFICATE') continue;
161
+ let x = _cert(read.blocks[i].der);
162
+ if (x) out.push(x);
163
+ else dbg('CA', 'skipped a certificate that does not read (block ' + (i + 1) + ')');
164
+ }
165
+ return out;
166
+ }
167
+ function _anchorX509s(a) {
139
168
  if (typeof a === 'string') {
140
169
  let hit = _anchorByPem.get(a);
141
170
  if (hit !== undefined) return hit;
142
- hit = _x509(a);
171
+ hit = _parseAnchors(a);
143
172
  if (_anchorByPem.size >= ANCHOR_CACHE_MAX) _anchorByPem.clear();
144
173
  _anchorByPem.set(a, hit);
145
174
  return hit;
@@ -147,22 +176,67 @@ function _anchorX509(a) {
147
176
  if (a && typeof a === 'object') {
148
177
  let hit = _anchorByObj.get(a);
149
178
  if (hit !== undefined) return hit;
150
- hit = _x509(a);
179
+ hit = _parseAnchors(a);
151
180
  _anchorByObj.set(a, hit);
152
181
  return hit;
153
182
  }
154
- return null;
183
+ return [];
155
184
  }
156
185
  function _sameCert(a, b) { return a.raw.length === b.raw.length && a.raw.equals(b.raw); }
157
- function _validNow(x509, now) {
158
- return !(now < new Date(x509.validFrom) || now > new Date(x509.validTo));
159
- }
160
- // The node:tls (OpenSSL) code for a certificate outside its validity window.
161
- function _validityError(x509, now) {
162
- return now < new Date(x509.validFrom) ? 'CERT_NOT_YET_VALID' : 'CERT_HAS_EXPIRED';
186
+
187
+ // The trust anchors of one `ca` (or the platform bundle), parsed and indexed
188
+ // by subject name. Each handshake used to try every anchor against the peer's
189
+ // chain — ~150 issuer checks against the platform bundle — where only the
190
+ // ones named as the issuer can be it. The key is cryptographic-formats' name_key:
191
+ // equal exactly when the names match (RFC 5280 §7.1, as OpenSSL compares
192
+ // them), so the index finds every anchor that could be the issuer and no
193
+ // other — a printed name, normalized, could miss one in an exotic encoding.
194
+ //
195
+ // Cached by the anchors array's identity, and checked entry by entry on every
196
+ // use (a pointer compare each): an application that changes the array in
197
+ // place — removes a CA — must not keep trusting it from a stale index. A
198
+ // single anchor (not an array) is indexed afresh each time: there is little
199
+ // to index.
200
+ const _storeByAnchors = new WeakMap();
201
+ const NO_ANCHORS = [];
202
+ function _trustStore(anchors) {
203
+ let entries = anchors == null ? [] : Array.isArray(anchors) ? anchors : [anchors];
204
+ let cacheable = Array.isArray(anchors);
205
+ if (cacheable) {
206
+ let hit = _storeByAnchors.get(anchors);
207
+ if (hit && hit.entries.length === entries.length && hit.entries.every((e, i) => e === entries[i])) return hit;
208
+ }
209
+ let list = [], bySubject = new Map();
210
+ for (let i = 0; i < entries.length; i++) {
211
+ let xs = _anchorX509s(entries[i]);
212
+ for (let k = 0; k < xs.length; k++) {
213
+ let key = xs[k].subjectKey, b = bySubject.get(key);
214
+ if (b) b.push(xs[k]); else bySubject.set(key, [xs[k]]);
215
+ list.push(xs[k]);
216
+ }
217
+ }
218
+ let store = {
219
+ entries: entries.slice(), list: list,
220
+ named: (key) => bySubject.get(key) || NO_ANCHORS,
221
+ };
222
+ if (cacheable) _storeByAnchors.set(anchors, store);
223
+ return store;
163
224
  }
164
- function _selfSigned(x509) {
165
- try { return !!x509.checkIssued(x509) && x509.verify(x509.publicKey); } catch (e) { return false; }
225
+ // The first of `candidates` (anchors) that issued `current`, signed it and
226
+ // is inside its validity window: true (pushed onto `path`). None: the
227
+ // validity error of the first that issued it but is outside its window, or
228
+ // null when none issued it. One that is the issuer by name (and key
229
+ // identifier) but whose key did not make the signature sets seen.badSignature.
230
+ function _anchorIssuer(current, candidates, now, path, seen) {
231
+ let expired = null;
232
+ for (const a of candidates) {
233
+ if (!issued_by(current, a)) continue;
234
+ if (!signed_by(current, a)) { seen.badSignature = true; continue; }
235
+ if (!valid_at(a, now)) { if (!expired) expired = { ok: false, error: validity_error(a, now) }; continue; }
236
+ path.push(a);
237
+ return true;
238
+ }
239
+ return expired;
166
240
  }
167
241
 
168
242
  /**
@@ -179,9 +253,11 @@ function _selfSigned(x509) {
179
253
  * outright — with rejectUnauthorized defaulting to true, which reads as if
180
254
  * verification were on.
181
255
  *
182
- * Each link has its signature verified, each non-leaf must actually assert
183
- * CA:TRUE, and every certificate in the path must be inside its validity
184
- * window. Intermediates come from the peer and are never trusted on their own;
256
+ * Each link has its signature verified, and every certificate in the path
257
+ * must be inside its validity window; then what each may do —
258
+ * basicConstraints, keyUsage, extendedKeyUsage for `purpose` ('server': we
259
+ * check a server's chain; 'client': a client's), name constraints, critical
260
+ * extensions — is session/x509.js's check_path. Intermediates come from the peer and are never trusted on their own;
185
261
  * only reaching an anchor ends the walk.
186
262
  *
187
263
  * Returns { ok: true, depth } or { ok: false, error }. The error codes are
@@ -192,61 +268,88 @@ function _selfSigned(x509) {
192
268
  * UNABLE_TO_VERIFY_LEAF_SIGNATURE the leaf alone, its issuer unknown
193
269
  * SELF_SIGNED_CERT_IN_CHAIN the chain ends in an untrusted root
194
270
  * UNABLE_TO_GET_ISSUER_CERT_LOCALLY the chain stops at an unknown issuer
195
- * INVALID_CA an issuer that is not a CA
271
+ * CERT_SIGNATURE_FAILURE the issuer, by name and key identifier,
272
+ * did not make the signature (and no
273
+ * other did) — OpenSSL's error 7
196
274
  * CERT_HAS_EXPIRED / CERT_NOT_YET_VALID a certificate in the path
275
+ * and check_path's: INVALID_CA, INVALID_PURPOSE, PATH_LENGTH_EXCEEDED,
276
+ * PERMITTED_VIOLATION, EXCLUDED_VIOLATION, SUBTREE_MINMAX,
277
+ * UNHANDLED_CRITICAL_EXTENSION, UNSUPPORTED_NAME_SYNTAX, CA_MD_TOO_WEAK
278
+ * (signed with MD2, MD4, MD5 or SHA-1), and UNSPECIFIED (name constraints
279
+ * too costly to check — OpenSSL's NAME_CHECK_MAX)
280
+ *
281
+ * The certificates are read by cryptographic-formats (session/x509.js's
282
+ * parse_cert); `leaf`, when given, is the leaf already read.
197
283
  */
198
- function verify_cert_chain(chainDer, anchors, now) {
284
+ function verify_cert_chain(chainDer, anchors, now, purpose, leaf) {
199
285
  if (!chainDer || chainDer.length === 0) return { ok: false, error: 'NO_PEER_CERTIFICATE' };
200
286
  now = now || new Date();
201
287
 
202
- const leaf = _x509(chainDer[0].cert || chainDer[0]);
288
+ leaf = leaf || _cert(chainDer[0].cert || chainDer[0]);
203
289
  if (!leaf) return { ok: false, error: 'CERTIFICATE_PARSE_ERROR' };
204
290
 
205
291
  const pool = [];
206
292
  for (let i = 1; i < chainDer.length; i++) {
207
- const x = _x509(chainDer[i].cert || chainDer[i]);
293
+ const x = _cert(chainDer[i].cert || chainDer[i]);
208
294
  if (x) pool.push(x);
209
295
  }
210
296
 
211
- const trusted = [];
212
- for (let i = 0; i < (anchors || []).length; i++) {
213
- const x = _anchorX509(anchors[i]);
214
- if (x) trusted.push(x);
215
- }
297
+ const store = _trustStore(anchors);
298
+ const trusted = store.list;
216
299
  if (trusted.length === 0) return { ok: false, error: 'NO_TRUST_ANCHORS' };
217
300
 
218
301
  let current = leaf;
219
302
  const used = new Set();
303
+ const path = [leaf];
304
+ // The path found, to its anchor: what each certificate in it may do
305
+ // (session/x509.js — basicConstraints, keyUsage, extKeyUsage, name
306
+ // constraints, critical extensions).
307
+ const done = function (depth) {
308
+ let err = check_path(path, purpose);
309
+ return err ? { ok: false, error: err } : { ok: true, depth: depth };
310
+ };
220
311
 
221
312
  for (let depth = 0; depth < MAX_CHAIN_DEPTH; depth++) {
222
313
  // Explicitly trusted certificate (pinned leaf, or a self-signed cert the
223
- // caller deliberately placed in the trust store).
224
- for (const a of trusted) if (_sameCert(current, a)) return { ok: true, depth: depth };
225
-
226
- for (const a of trusted) {
227
- try {
228
- if (current.checkIssued(a) && current.verify(a.publicKey)) {
229
- if (!_validNow(a, now)) return { ok: false, error: _validityError(a, now) };
230
- return { ok: true, depth: depth + 1 };
231
- }
232
- } catch (e) { /* try next anchor */ }
233
- }
314
+ // caller deliberately placed in the trust store). The leaf itself: the
315
+ // caller's trust in that very certificate, nothing to check above it.
316
+ // Only anchors whose subject is the name in question can match (the
317
+ // same certificate has the same subject; an issuer's subject is the
318
+ // issuer name) — a lookup, where every anchor was tried in turn.
319
+ for (const a of store.named(current.subjectKey)) if (_sameCert(current, a)) return depth === 0 ? { ok: true, depth: 0 } : done(depth);
320
+
321
+ // A candidate outside its validity window does not end the search:
322
+ // another may issue the same certificate (a renewed intermediate, or
323
+ // CA, of the same name and key — OpenSSL takes the valid one). Its
324
+ // error is the answer only when no valid issuer is found.
325
+ let expired = null, seen = { badSignature: false };
326
+ let r = _anchorIssuer(current, store.named(current.issuerKey), now, path, seen);
327
+ if (r === true) return done(depth + 1);
328
+ if (r) expired = r;
234
329
 
235
330
  let next = null;
236
331
  for (let i = 0; i < pool.length; i++) {
237
332
  if (used.has(i)) continue; // cycle guard
238
333
  const cand = pool[i];
239
- try {
240
- if (!current.checkIssued(cand)) continue;
241
- if (!current.verify(cand.publicKey)) continue;
242
- if (cand.ca !== true) return { ok: false, error: 'INVALID_CA' };
243
- if (!_validNow(cand, now)) return { ok: false, error: _validityError(cand, now) };
244
- used.add(i); next = cand; break;
245
- } catch (e) { /* try next candidate */ }
334
+ if (!issued_by(current, cand)) continue;
335
+ if (!signed_by(current, cand)) { seen.badSignature = true; continue; }
336
+ if (!valid_at(cand, now)) { if (!expired) expired = { ok: false, error: validity_error(cand, now) }; continue; }
337
+ used.add(i); next = cand; path.push(cand); break;
246
338
  }
339
+ // (The anchors are looked up by name_key, which is equal exactly when
340
+ // the names match: an anchor not in the index cannot be the issuer. A
341
+ // second pass over every anchor covered the printed-name key this
342
+ // replaced, which an exotic encoding could make miss.)
343
+ if (!next && expired) return expired;
344
+ // The issuer was there — its name, and its key identifier where the
345
+ // certificate names one — and its key did not make the signature: a
346
+ // certificate altered, or signed by another key of that name. OpenSSL
347
+ // takes the first by name and says so (error 7); here every candidate
348
+ // was tried first, so a right one after a wrong one still verifies.
349
+ if (!next && seen.badSignature) return { ok: false, error: 'CERT_SIGNATURE_FAILURE' };
247
350
 
248
351
  if (!next) {
249
- let selfSigned = _selfSigned(current);
352
+ let selfSigned = self_signed(current);
250
353
  return { ok: false, error: depth === 0
251
354
  ? (selfSigned ? 'DEPTH_ZERO_SELF_SIGNED_CERT' : 'UNABLE_TO_VERIFY_LEAF_SIGNATURE')
252
355
  : (selfSigned ? 'SELF_SIGNED_CERT_IN_CHAIN' : 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY') };
@@ -258,12 +361,51 @@ function verify_cert_chain(chainDer, anchors, now) {
258
361
  }
259
362
 
260
363
 
261
- // An IPv4 or IPv6 address literal (IPv6 with or without brackets) — what
262
- // SNI may never carry, and what a certificate is checked against by IP SAN.
263
- function is_ip_literal(host) {
264
- host = String(host);
265
- return /^(\d{1,3}\.){3}\d{1,3}$/.test(host) ||
266
- (host.indexOf(':') >= 0 && /^[0-9a-fA-F:.\[\]]+$/.test(host));
364
+ // The most content a record carries (wire.js).
365
+ const MAX_RECORD_PLAINTEXT = wire.MAX_RECORD_PLAINTEXT;
366
+
367
+ // The recordSizeLimit option: 64 to 2^14 + 1 (RFC 8449 §4), or undefined.
368
+ function checked_record_size_limit(v) {
369
+ if (v === undefined || v === null) return undefined;
370
+ if (!Number.isInteger(v) || v < 64 || v > 16385) throw new RangeError('recordSizeLimit must be an integer in [64, 16385], got ' + v);
371
+ return v;
372
+ }
373
+
374
+ // The connectionId option (DTLS, RFC 9146): the CID this side asks the peer
375
+ // to put in the records it sends us — bytes, up to 255 (empty: none, though
376
+ // it will put the peer's in its own) — or null, not offered. What `true`
377
+ // stands for is the DTLS layer's to say (DTLSSession); over TLS, where a
378
+ // CID has no use, it is nothing.
379
+ function checked_connection_id(v) {
380
+ if (v === undefined || v === null || v === false || v === true) return null;
381
+ if (v instanceof Uint8Array && v.length <= 255) return new Uint8Array(v);
382
+ throw new TypeError('connectionId must be a Buffer of at most 255 bytes');
383
+ }
384
+
385
+ // An external PSK (RFC 8446 §2.2): a key both sides hold from elsewhere,
386
+ // with its identity and the hash it is used with (§4.2.11 — SHA-256 when not
387
+ // said, as RFC 9257 §6 advises). TLS 1.3, psk_dhe_ke: a fresh ECDHE secret is
388
+ // mixed in, as in resumption. Its binder is the "ext binder" one (§7.1), so a
389
+ // key cannot pass for a resumption PSK or the other way round.
390
+ //
391
+ // `spec` is the client's psk option ({ identity, psk, hash }), or a server's
392
+ // pskCallback answer (the key, or { psk, hash }). The result is the shape the
393
+ // rest of the session uses: { psk, cipher, hash, external: true }, with the
394
+ // identity on the client.
395
+ const EXTERNAL_PSK_SUITE = { sha256: 0x1301, sha384: 0x1302 };
396
+ function psk_option_error(msg) { let e = new TypeError('external PSK: ' + msg); e.code = 'ERR_INVALID_ARG_VALUE'; return e; }
397
+ function external_psk(spec, withIdentity) {
398
+ let key = spec instanceof Uint8Array ? spec : spec && spec.psk;
399
+ if (!(key instanceof Uint8Array) || key.length === 0) throw psk_option_error('psk must be a non-empty Buffer or Uint8Array');
400
+ let hash = (spec instanceof Uint8Array || spec.hash == null) ? 'sha256' : String(spec.hash).toLowerCase().replace('-', '');
401
+ if (!EXTERNAL_PSK_SUITE[hash]) throw psk_option_error("hash must be 'sha256' or 'sha384', got " + spec.hash);
402
+ let out = { psk: new Uint8Array(key), cipher: EXTERNAL_PSK_SUITE[hash], hash: hash, external: true };
403
+ if (withIdentity) {
404
+ let id = typeof spec.identity === 'string' ? new Uint8Array(Buffer.from(spec.identity, 'utf8')) : spec.identity;
405
+ if (!(id instanceof Uint8Array) || id.length === 0 || id.length > 0xFFFF) throw psk_option_error('identity must be a string or bytes, 1 to 65535 long');
406
+ out.identity = new Uint8Array(id);
407
+ }
408
+ return out;
267
409
  }
268
410
 
269
411
 
@@ -282,11 +424,13 @@ function TLSSession(options){
282
424
  checkServerIdentity: typeof options.checkServerIdentity === 'function'
283
425
  ? options.checkServerIdentity : null,
284
426
  // When no `ca` is configured, chain against the platform trust store
285
- // instead of authorizing everything. Opt out with useDefaultCA:false —
286
- // DTLS does exactly that, since WebRTC peers are self-signed by design
287
- // and authenticated out of band via the SDP fingerprint.
427
+ // (ca_store.js — on both sides, and for a session used directly, as by
428
+ // QUIC: only connect() handed it on). Opt out with useDefaultCA:false —
429
+ // DTLS does, since WebRTC peers are self-signed by design and
430
+ // authenticated out of band via the SDP fingerprint (with
431
+ // rejectUnauthorized: false: no anchors is no authorization).
288
432
  useDefaultCA: options.useDefaultCA !== false,
289
- defaultCA: typeof options.defaultCA === 'function' ? options.defaultCA : null,
433
+ defaultCA: typeof options.defaultCA === 'function' ? options.defaultCA : getRootCertificates,
290
434
  // Node parity: synchronous ALPN selector, server side. Receives
291
435
  // { servername, protocols } and returns the chosen protocol, or undefined
292
436
  // to refuse with no_application_protocol. Mutually exclusive with
@@ -460,6 +604,19 @@ function TLSSession(options){
460
604
  remote_supported_cipher_suites: [],
461
605
  remote_supported_signature_algorithms: [],
462
606
  remote_supported_groups: [],
607
+ key_updates_asked: 0, // ours with update_requested, not yet answered
608
+ // record_size_limit (RFC 8449): ours (option: a number, undefined, or
609
+ // false — never), the peer's, and ours as it went out once both did.
610
+ record_size_limit: options.recordSizeLimit === false ? false : checked_record_size_limit(options.recordSizeLimit),
611
+ // DTLS Connection ID: ours (connectionId; null: not offered), and the
612
+ // peer's, once both sides have sent the extension (take_connection_id).
613
+ local_cid: checked_connection_id(options.connectionId),
614
+ server_configured: false, // server: 'hello' heard, the lists complete (see the ClientHello)
615
+ peer_cid: null,
616
+ peer_record_size_limit: null,
617
+ record_size_limit_agreed: null,
618
+ sig_checked: false, // server: our certificate's signature checked against the client's list
619
+ ch1_shape: null, // server: the first ClientHello, as the second must repeat it (ch_shape)
463
620
 
464
621
 
465
622
  //selected stuff...
@@ -582,6 +739,7 @@ function TLSSession(options){
582
739
  // ServerHello is validated against these (RFC 8446 §4.1.4).
583
740
  hrr_version: null,
584
741
  hrr_group: null,
742
+ hrr_sent_group: null, // server: the group its HelloRetryRequest asked for
585
743
  hrr_cipher: null,
586
744
 
587
745
  // DTLS cookie (set by DTLSSession via set_context)
@@ -594,6 +752,11 @@ function TLSSession(options){
594
752
  ticket_nonce_counter: 0,
595
753
  session_ticket_sent: false,
596
754
  psk_offered: null, // client: { identity, psk, cipher } offered in ClientHello
755
+ // External PSK (external_psk): the client's, to offer; the server's
756
+ // lookup by identity; and the identity of the one in use, on both sides.
757
+ external_psk: (!options.isServer && options.psk && options.psk.identity != null) ? external_psk(options.psk, true) : null,
758
+ pskCallback: options.isServer && typeof options.pskCallback === 'function' ? options.pskCallback : null,
759
+ psk_identity: null,
597
760
  // 0-RTT on this connection. offered: the client sent early_data;
598
761
  // candidate: the server found it acceptable but for ALPN and suite,
599
762
  // { cipher, alpn, secret }; pending: the replay check is out;
@@ -601,6 +764,11 @@ function TLSSession(options){
601
764
  // sessionAppData, given back.
602
765
  early: { offered: false, candidate: null, pending: false, status: null, alpn: null, appData: null, clientOffered: false, eoed: false },
603
766
  psk_accepted: false, // server accepted PSK → abbreviated handshake
767
+ psk_selected: 0, // server: the index of the identity it took
768
+ hs_in_last: null, // the last handshake message taken (handshake_gate)
769
+ ch1_key_shares: null, // client: the first hello's key shares (a cookie-only retry repeats them)
770
+ client_secure_renegotiation: false, // server: the client sent renegotiation_info or its SCSV (RFC 5746)
771
+ renegotiation_refusals: 0, // no_renegotiation warnings sent (TLS 1.2)
604
772
  isResumed: false, // true if PSK was accepted (1.3) or abbreviated handshake (1.2)
605
773
  hrr_hash: null, // client: the hash of the suite a HelloRetryRequest named
606
774
  resumed_ticket_data: null, // application data of the ticket resumed with (see ticketData)
@@ -639,6 +807,8 @@ function TLSSession(options){
639
807
  // the loop run again with the answer in context.
640
808
  sni_pending: false,
641
809
  tls12_client_session: null, // client: saved session to resume with (parsed sessionData)
810
+ tls12_ticket_blind: false, // client: its ticket offered with no session_id (DTLS, 1.3 offered too)
811
+ tls12_resume_maybe: false, // client: …and the ServerHello could be its resumption
642
812
  };
643
813
 
644
814
  /**
@@ -732,8 +902,173 @@ function TLSSession(options){
732
902
  // Introducing is_tls13_wire there and leaving a second copy of the same test
733
903
  // here would have recreated exactly the drift it was added to remove.
734
904
  function is13() { return wire.is_tls13_wire(context.selected_version); }
905
+ // A version list with TLS 1.3 or DTLS 1.3 in it. One test: written out
906
+ // by hand in a dozen places, two of them (the ECH backend's) knew TLS 1.3
907
+ // only, so over DTLS a backend never confirmed ECH (BoGo
908
+ // DTLS-ECH-Server-ECHInner*).
909
+ function lists13(list) { return Array.isArray(list) && list.some(wire.is_tls13_wire); }
735
910
  function is12() { return wire.is_tls12_wire(context.selected_version); }
736
911
 
912
+ // ── What the peer may send next (RFC 8446 §2, §4; RFC 5246 §7.3) ──
913
+ //
914
+ // From what has already been taken (context.hs_in_last, kept by the gate)
915
+ // and what the handshake has become (version, PSK, resumption, a
916
+ // certificate asked for, early data) — the state the handlers have already
917
+ // written. 'compressed_certificate' counts as 'certificate' (RFC 8879).
918
+ //
919
+ // TLS 1.3, client: ServerHello [HRR → ServerHello] → EncryptedExtensions
920
+ // → (PSK: Finished | [CertificateRequest] → Certificate
921
+ // → CertificateVerify → Finished); then NewSessionTicket,
922
+ // KeyUpdate.
923
+ // TLS 1.3, server: ClientHello [HRR → ClientHello] → [EndOfEarlyData]
924
+ // → [Certificate → (non-empty: CertificateVerify)]
925
+ // → Finished; then KeyUpdate.
926
+ // TLS 1.2, client: ServerHello → (resumed: [NewSessionTicket] → Finished
927
+ // | Certificate → [CertificateStatus] → ServerKeyExchange
928
+ // → [CertificateRequest] → ServerHelloDone
929
+ // → [NewSessionTicket] → Finished); then HelloRequest.
930
+ // TLS 1.2, server: ClientHello → (resumed: Finished | [Certificate]
931
+ // → ClientKeyExchange → (a certificate: CertificateVerify)
932
+ // → Finished); then ClientHello (renegotiation, refused).
933
+ // The handshake types by code, as handshake_expect() names them: the
934
+ // registry's names (wire.TLS_MESSAGE_TYPE), lowercase.
935
+ const HANDSHAKE_TYPE_NAMES = {};
936
+ for (const k in wire.TLS_MESSAGE_TYPE) HANDSHAKE_TYPE_NAMES[wire.TLS_MESSAGE_TYPE[k]] = k.toLowerCase();
937
+ function handshake_expect() {
938
+ let last = context.hs_in_last;
939
+ let v13 = is13(), v12 = is12();
940
+ if (last === null) return context.isServer ? ['client_hello'] : ['server_hello'];
941
+ let certSent = !!(context.remote_cert_chain && context.remote_cert_chain.length > 0);
942
+
943
+ if (context.isServer) {
944
+ if (last === 'client_hello') {
945
+ if (context.helloRetried === true && context.client_hellos_received === 1) return ['client_hello'];
946
+ if (v13) {
947
+ if (context.endOfEarlyData && context.early.status === 'accepted' && !context.early.eoed) return ['end_of_early_data'];
948
+ return context.certificateRequestSent ? ['certificate', 'compressed_certificate'] : ['finished'];
949
+ }
950
+ if (context.tls12_abbreviated) return ['finished'];
951
+ return context.certificateRequestSent ? ['certificate'] : ['client_key_exchange'];
952
+ }
953
+ if (last === 'end_of_early_data') return context.certificateRequestSent ? ['certificate', 'compressed_certificate'] : ['finished'];
954
+ if (last === 'certificate') {
955
+ if (v13) return certSent ? ['certificate_verify'] : ['finished'];
956
+ return ['client_key_exchange'];
957
+ }
958
+ if (last === 'client_key_exchange') return certSent ? ['certificate_verify'] : ['finished'];
959
+ if (last === 'certificate_verify') return ['finished'];
960
+ // finished, or a post-handshake message: the handshake is over.
961
+ return v13 ? ['key_update'] : ['client_hello'];
962
+ }
963
+
964
+ // client
965
+ if (last === 'hello_retry_request') return ['server_hello'];
966
+ if (last === 'server_hello') {
967
+ if (v13) return ['encrypted_extensions'];
968
+ if (context.tls12_resume_maybe) return ['certificate', 'new_session_ticket', 'finished'];
969
+ return context.tls12_abbreviated ? ['new_session_ticket', 'finished'] : ['certificate'];
970
+ }
971
+ if (last === 'encrypted_extensions') {
972
+ return context.psk_accepted ? ['finished'] : ['certificate_request', 'certificate', 'compressed_certificate'];
973
+ }
974
+ if (last === 'certificate_request') return v13 ? ['certificate', 'compressed_certificate'] : ['server_hello_done'];
975
+ if (last === 'certificate') return v13 ? ['certificate_verify'] : (context.requestOCSP ? ['certificate_status', 'server_key_exchange'] : ['server_key_exchange']);
976
+ if (last === 'certificate_status') return ['server_key_exchange'];
977
+ if (last === 'server_key_exchange') return ['certificate_request', 'server_hello_done'];
978
+ if (last === 'server_hello_done') return ['new_session_ticket', 'finished'];
979
+ if (last === 'certificate_verify') return ['finished'];
980
+ if (last === 'new_session_ticket' && v12 && context.state !== 'connected') return ['finished'];
981
+ // finished, or a post-handshake message.
982
+ return v13 ? ['new_session_ticket', 'key_update'] : ['hello_request'];
983
+ }
984
+
985
+ // A ServerHello / HelloRetryRequest against what this client offered.
986
+ // Returns null, or { alert, reason }.
987
+ // - the version: supported_versions, when there, names it — and only
988
+ // TLS 1.3 may be chosen that way (RFC 8446 §4.2.1: "MUST NOT" select
989
+ // 1.2 or below with it); without it, legacy_version. Either way one we
990
+ // offered: otherwise protocol_version (a server falling back to 1.2
991
+ // where 1.3 was our minimum included);
992
+ // - the cipher suite: one we offered, and one of that version (a TLS 1.3
993
+ // suite in a 1.2 ServerHello, and the reverse): illegal_parameter;
994
+ // - compression: null, the only one we offer;
995
+ // - TLS 1.2: not our TLS 1.3 compatibility session_id echoed back — that
996
+ // is no session of ours to resume (illegal_parameter).
997
+ function check_server_hello(message) {
998
+ let isHrr = message.random && uint8Equal(message.random, wire.TLS13_HRR_RANDOM);
999
+ let sv = Array.isArray(message.supported_versions) ? message.supported_versions : [];
1000
+ let hasSvExt = Array.isArray(message.extensions) && message.extensions.some(function (e) { return e && e.type === 0x002b; });
1001
+ let v = hasSvExt ? sv[0] : message.legacy_version;
1002
+ let local = context.local_supported_versions || [];
1003
+ if (hasSvExt && v !== wire.TLS_VERSION.TLS1_3 && v !== wire.DTLS_VERSION.DTLS1_3) {
1004
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: 'ServerHello supported_versions selects 0x' + (v >>> 0).toString(16) + ', which only TLS 1.3 may be selected with' };
1005
+ }
1006
+ if (local.length > 0 && local.indexOf(v) < 0) {
1007
+ return { alert: wire.TLS_ALERT.PROTOCOL_VERSION, reason: 'ServerHello selects version 0x' + (v >>> 0).toString(16) + ', which we did not offer' };
1008
+ }
1009
+ let cs = hello_cipher_suite(message);
1010
+ let offered = context.local_supported_cipher_suites || [];
1011
+ if (cs === null || (offered.length > 0 && offered.indexOf(cs) < 0)) {
1012
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: 'ServerHello selects cipher suite 0x' + ((cs || 0) >>> 0).toString(16) + ', which we did not offer' };
1013
+ }
1014
+ let meta = TLS_CIPHER_SUITES[cs];
1015
+ let v13 = wire.is_tls13_wire(v);
1016
+ if (meta && ((meta.sig === 'TLS13') !== v13)) {
1017
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: 'ServerHello cipher suite 0x' + (cs >>> 0).toString(16) + ' is not one of version 0x' + (v >>> 0).toString(16) };
1018
+ }
1019
+ let comp = Array.isArray(message.legacy_compression) ? message.legacy_compression[0] : 0;
1020
+ if (comp !== 0) return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: 'ServerHello selects compression method ' + comp };
1021
+ if (!v13 && !isHrr && !context.tls12_client_session && local.some(function (x) { return x === wire.TLS_VERSION.TLS1_3; }) &&
1022
+ context.local_session_id && context.local_session_id.length > 0 && message.session_id &&
1023
+ uint8Equal(message.session_id, context.local_session_id)) {
1024
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: 'TLS 1.2 ServerHello echoes our TLS 1.3 compatibility session_id' };
1025
+ }
1026
+ return null;
1027
+ }
1028
+
1029
+ // The gate itself: null when `message` may come now (and then it is the
1030
+ // last taken), otherwise why not.
1031
+ function handshake_gate(message) {
1032
+ let t = message.type;
1033
+ if (t === 'unknown_handshake' && message.handshake_type === 0) t = 'hello_request';
1034
+ let allowed = handshake_expect();
1035
+ if (allowed.indexOf(t) < 0) {
1036
+ return 'Unexpected ' + t + (context.hs_in_last ? ' after ' + context.hs_in_last : ' as the first message') +
1037
+ ' (expected ' + allowed.join(' or ') + ')';
1038
+ }
1039
+ if (t === 'compressed_certificate') t = 'certificate';
1040
+ if (t === 'server_hello' && message.random && uint8Equal(message.random, wire.TLS13_HRR_RANDOM)) {
1041
+ // One HelloRetryRequest at most (RFC 8446 §4.1.4).
1042
+ if (context.hs_in_last === 'hello_retry_request') return 'A second HelloRetryRequest';
1043
+ t = 'hello_retry_request';
1044
+ }
1045
+ context.hs_in_last = t;
1046
+ return null;
1047
+ }
1048
+ /**
1049
+ * A (D)TLS 1.3 ServerHello's — and HelloRetryRequest's — legacy_session_id:
1050
+ * the client's echoed over TLS (RFC 8446 §4.1.3), empty over DTLS 1.3
1051
+ * (RFC 9147 §5: "the server MUST NOT echo the 'legacy_session_id' value
1052
+ * from the client"). One rule for both messages, so they cannot drift
1053
+ * apart again.
1054
+ */
1055
+ function legacy_session_id_echo(version) {
1056
+ return version === wire.DTLS_VERSION.DTLS1_3 ? new Uint8Array(0) : context.remote_session_id;
1057
+ }
1058
+
1059
+ // DTLS or TLS: a DTLSSession sets DTLS versions before the first message;
1060
+ // a TLS session's, when set at all by then, are TLS ones. So: this session
1061
+ // runs over DTLS when its version list is DTLS. (One test — three copies
1062
+ // of it had grown here: isDtlsHello, an inline one, and this.)
1063
+ function dtls_transport() {
1064
+ return (context.local_supported_versions || []).some(function (v) { return (v & 0xff00) === 0xfe00; });
1065
+ }
1066
+ // This side's hello offers DTLS 1.3.
1067
+ function offersDtls13() {
1068
+ return !!(context.local_supported_versions &&
1069
+ context.local_supported_versions.indexOf(wire.DTLS_VERSION.DTLS1_3) >= 0);
1070
+ }
1071
+
737
1072
  /**
738
1073
  * Assemble the ClientHello extension list.
739
1074
  *
@@ -755,23 +1090,20 @@ function TLSSession(options){
755
1090
  function build_client_hello_extensions(opts) {
756
1091
  opts = opts || {};
757
1092
 
758
- let offers13 = context.local_supported_versions.some(function (v) {
759
- return v === wire.TLS_VERSION.TLS1_3 || v === wire.DTLS_VERSION.DTLS1_3;
760
- });
1093
+ let offers13 = lists13(context.local_supported_versions);
761
1094
  // "1.3-only" means every offered version is (D)TLS 1.3 — a QUIC-style
762
1095
  // profile that must not carry TLS 1.2 legacy extensions.
763
1096
  let tls13Only = context.local_supported_versions.length > 0 &&
764
- context.local_supported_versions.every(function (v) {
765
- return v === wire.TLS_VERSION.TLS1_3 || v === wire.DTLS_VERSION.DTLS1_3;
766
- });
1097
+ context.local_supported_versions.every(wire.is_tls13_wire);
767
1098
 
768
1099
  let extensions = [];
769
1100
 
770
1101
  if (offers13) {
771
- // With ECH, TLS 1.3 only (RFC 9849 §6.1: ECH is a TLS 1.3 mechanism; a
772
- // server steering to 1.2 would carry the hello's real name nowhere and
773
- // the public name in the clear).
774
- extensions.push({ type: 'SUPPORTED_VERSIONS', value: ech_on() ? context.local_supported_versions.filter(function (v) { return v === wire.TLS_VERSION.TLS1_3; })
1102
+ // With ECH, (D)TLS 1.3 only (RFC 9849 §1, §6.1: ECH is a 1.3 mechanism;
1103
+ // a server steering to 1.2 would carry the hello's real name nowhere
1104
+ // and the public name in the clear). DTLS 1.3 kept too: filtered to
1105
+ // TLS 1.3 alone, a DTLS hello offered no version at all.
1106
+ extensions.push({ type: 'SUPPORTED_VERSIONS', value: ech_on() ? context.local_supported_versions.filter(wire.is_tls13_wire)
775
1107
  : context.local_supported_versions });
776
1108
  }
777
1109
  // supported_groups is a CAPABILITY claim, not a copy of configuration.
@@ -808,6 +1140,10 @@ function TLSSession(options){
808
1140
  // in a 1.3-only hello.
809
1141
  extensions.push({ type: 'RENEGOTIATION_INFO', value: new Uint8Array(0) });
810
1142
  extensions.push({ type: 'EXTENDED_MASTER_SECRET', value: null });
1143
+ // ec_point_formats (RFC 8422 §5.1.2): a TLS 1.2 client offering ECC
1144
+ // suites "SHOULD" send it — and a strict server (Go crypto/tls) refuses
1145
+ // an ECDHE offer without it. Uncompressed only: the one format in use.
1146
+ extensions.push({ type: 'EC_POINT_FORMATS', value: [0] });
811
1147
  }
812
1148
  if (!context.isServer && context.requestOCSP) {
813
1149
  // status_request (RFC 6066 §8): an OCSP response for the server's
@@ -853,12 +1189,13 @@ function TLSSession(options){
853
1189
  // by the one function that builds both.
854
1190
  //
855
1191
  // It is a TLS 1.2 mechanism (1.3 resumes via NewSessionTicket/PSK), so it
856
- // is never offered in a 1.3-only profile. Skipped for DTLS as well:
857
- // implementations often do not handle RFC 5077 there and it broke interop
858
- // with openssl s_server -dtls1_2.
859
- let isDtlsProfile = context.local_supported_versions &&
860
- context.local_supported_versions.some(function (v) { return (v & 0xFF00) === 0xFE00; });
861
- if (!isDtlsProfile && !tls13Only && context.sessionTickets) {
1192
+ // is never offered in a 1.3-only profile. Over DTLS 1.2 as over TLS 1.2
1193
+ // (RFC 5077 is transport-agnostic; OpenSSL's DTLS supports it — checked
1194
+ // against openssl s_server -dtls1_2 / s_client -dtls1_2, dtls_resume_test).
1195
+ // It was left out of DTLS after an interop failure with s_server
1196
+ // -dtls1_2 that was ours: the DTLS server echoed the client's session_id
1197
+ // in every full handshake, which says "resumed" (fixed in r90).
1198
+ if (!tls13Only && context.sessionTickets) {
862
1199
  if (opts.sessionTicket) {
863
1200
  extensions.push({ type: 'SESSION_TICKET', value: opts.sessionTicket });
864
1201
  } else {
@@ -884,20 +1221,46 @@ function TLSSession(options){
884
1221
  for (let i = 0; i < context.local_extensions.length; i++) {
885
1222
  extensions.push(context.local_extensions[i]);
886
1223
  }
1224
+ // customExtensions (the documented option: [{ type, data }]) — raw
1225
+ // extensions to send as they are. Stored and never sent: an option in
1226
+ // the API and the typings that did nothing. A type the hello carries
1227
+ // already is not added twice (RFC 8446 §4.2), the assembler's own wins.
1228
+ for (let i = 0; i < context.customExtensions.length; i++) {
1229
+ let ce = context.customExtensions[i];
1230
+ if (!ce || typeof ce.type !== 'number') continue;
1231
+ let dup = false;
1232
+ for (let j = 0; j < extensions.length; j++) {
1233
+ let t = extensions[j] && extensions[j].type;
1234
+ if ((typeof t === 'number' ? t : wire.TLS_EXT[t]) === ce.type) { dup = true; break; }
1235
+ }
1236
+ if (!dup) extensions.push({ type: ce.type, data: ce.data instanceof Uint8Array ? ce.data : new Uint8Array(ce.data || []) });
1237
+ }
887
1238
 
888
1239
  // Encrypted Client Hello (RFC 9849). With a config: this list is the
889
1240
  // inner hello's, marked as such (§5: the inner extension, type 1) — the
890
1241
  // outer one is made from it (ech_split). Without one, and echGrease:
891
- // a GREASE extension (§6.2), a CH2's with an empty enc.
892
- if (!context.isServer && offers13 && !isDtlsProfile) {
1242
+ // a GREASE extension (§6.2) — the same bytes in a second hello
1243
+ // (grease_ech_ext_data). TLS 1.3 and DTLS 1.3 alike (RFC 9849 §1: "ECH
1244
+ // is supported in TLS 1.3, DTLS 1.3, and newer versions"). Left out over
1245
+ // DTLS, a client given a config connected without it — the server's real
1246
+ // name in the clear, and not a word said.
1247
+ if (!context.isServer && offers13) {
893
1248
  if (ech_on()) {
894
1249
  extensions.push({ type: EXT_ECH, data: new Uint8Array([1]) });
895
1250
  } else if (context.ech_grease) {
896
1251
  if (!context.ech.grease) { context.ech.grease = grease_ech_state(); context.ech.status = 'grease'; }
897
- extensions.push({ type: EXT_ECH, data: grease_ech_ext_data(context.ech.grease, context.helloRetried === true) });
1252
+ extensions.push({ type: EXT_ECH, data: grease_ech_ext_data(context.ech.grease) });
898
1253
  }
899
1254
  }
900
1255
 
1256
+ // record_size_limit (RFC 8449), when asked for: the largest record we
1257
+ // take. Not by default — as Chrome, which does not send it (Firefox does).
1258
+ if (!context.isServer && typeof context.record_size_limit === 'number') {
1259
+ extensions.push({ type: wire.TLS_EXT.RECORD_SIZE_LIMIT, data: u16_bytes(context.record_size_limit) });
1260
+ }
1261
+
1262
+ if (!context.isServer && context.local_cid !== null && dtls_transport()) extensions.push(connection_id_ext());
1263
+
901
1264
  if (context.grease) apply_grease(extensions);
902
1265
  if (context.permuteExtensions) extensions = permute_extensions(extensions);
903
1266
 
@@ -1043,9 +1406,9 @@ function TLSSession(options){
1043
1406
  *
1044
1407
  * What it changes, for anyone reaching for it as evasion: nothing this
1045
1408
  * library computes. JA4 and JA5 sort extensions before hashing, so both are
1046
- * byte-for-byte identical with this on or off. It defeats only JA3, the 2017
1047
- * fingerprint, which hashed extensions in wire order — and a client whose
1048
- * JA3 differs on every connection is itself a distinctive pattern.
1409
+ * byte-for-byte identical with this on or off. Only a fingerprint that
1410
+ * hashes extensions in wire order changes — and one that differs on every
1411
+ * connection is itself a distinctive pattern.
1049
1412
  *
1050
1413
  * Two ordering rules are preserved:
1051
1414
  *
@@ -1123,19 +1486,25 @@ function TLSSession(options){
1123
1486
  * in a later pass of the reactive loop). The caller decides scope from the
1124
1487
  * message's own supported_versions, which is authoritative.
1125
1488
  *
1126
- * TLS/DTLS 1.2 (RFC 5246 §7.4.1.4) is deliberately looser: unknown
1127
- * extensions must be ignored. Applying the 1.3 rule to a 1.2 handshake
1128
- * rejects entirely valid peers (the WebRTC regression against pion /
1129
- * webrtc-rs).
1489
+ * TLS/DTLS 1.2 has the same rule (RFC 5246 §7.4.1.4: "If a client
1490
+ * receives an extension type in ServerHello that it did not request in the
1491
+ * associated ClientHello, it MUST abort the handshake with an
1492
+ * unsupported_extension fatal alert"). It was once applied to 1.3 only,
1493
+ * after a WebRTC regression against pion / webrtc-rs: those servers answer
1494
+ * ec_point_formats, which our hello did not send. The hello sends it now
1495
+ * (RFC 8422 §5.1.2), so the rule holds for every version.
1130
1496
  *
1131
1497
  * One rule for every server-originated extension block (ServerHello,
1132
1498
  * EncryptedExtensions) — they all fail for the same reason and must fail
1133
1499
  * the same way. Returns true when the caller should stop processing.
1134
1500
  *
1135
- * HelloRetryRequest is handled earlier and returns before this point, so its
1136
- * cookie — which by definition we could not have offered — never lands here.
1501
+ * The HelloRetryRequest too (RFC 8446 §4.1.4), with `serverOwn`: its cookie
1502
+ * is the server's to send unasked (§4.2.2) — every other extension in it
1503
+ * is one we offered or unsupported_extension. It went unchecked: an
1504
+ * encrypted_client_hello in a retry to a client that offered no ECH was
1505
+ * taken, and the second hello sent.
1137
1506
  */
1138
- function reject_unsolicited_extensions(message, where) {
1507
+ function reject_unsolicited_extensions(message, where, serverOwn) {
1139
1508
  if (context.isServer) return false; // servers answer, not ask
1140
1509
  if (!Array.isArray(message.extensions)) return false;
1141
1510
  if (context.offered_extension_types.length === 0) return false; // nothing recorded yet
@@ -1152,6 +1521,7 @@ function TLSSession(options){
1152
1521
  // same class of over-strictness as the 1.2 regression noted above, only
1153
1522
  // with us on the rejecting side this time.
1154
1523
  if (is_grease_u16(et)) continue;
1524
+ if (serverOwn && serverOwn.indexOf(et) >= 0) continue;
1155
1525
 
1156
1526
  if (context.offered_extension_types.indexOf(et) < 0) {
1157
1527
  fatalAlert(wire.TLS_ALERT.UNSUPPORTED_EXTENSION,
@@ -1162,6 +1532,29 @@ function TLSSession(options){
1162
1532
  return false;
1163
1533
  }
1164
1534
 
1535
+ /**
1536
+ * The server's ALPN answer (RFC 7301 §3.1), one rule for both places it is
1537
+ * read: the TLS 1.2 ServerHello and the TLS 1.3 EncryptedExtensions.
1538
+ * Exactly one non-empty ProtocolName (decode_error otherwise), and one we
1539
+ * offered (illegal_parameter otherwise). Returns the protocol, or null
1540
+ * after the alert.
1541
+ */
1542
+ function server_alpn_choice(value) {
1543
+ let list = Array.isArray(value) ? value : [value];
1544
+ if (list.length !== 1 || typeof list[0] !== 'string' || list[0].length === 0) {
1545
+ fatalAlert(wire.TLS_ALERT.DECODE_ERROR,
1546
+ 'The server\'s ALPN answer must name exactly one protocol');
1547
+ return null;
1548
+ }
1549
+ let offered = context.local_supported_alpns;
1550
+ if (!Array.isArray(offered) || offered.indexOf(list[0]) < 0) {
1551
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
1552
+ 'Server selected an ALPN protocol that was not offered: ' + list[0]);
1553
+ return null;
1554
+ }
1555
+ return list[0];
1556
+ }
1557
+
1165
1558
  function note_offered_extensions(list) {
1166
1559
  if (!Array.isArray(context.offered_extension_types)) {
1167
1560
  context.offered_extension_types = [];
@@ -1188,12 +1581,67 @@ function TLSSession(options){
1188
1581
  * turn that into the appropriate alert for their context.
1189
1582
  */
1190
1583
  function peer_leaf_public_key() {
1191
- if (!context.remote_cert_chain || context.remote_cert_chain.length === 0) return null;
1192
- try {
1193
- return new crypto.X509Certificate(Buffer.from(context.remote_cert_chain[0].cert)).publicKey;
1194
- } catch (e) {
1195
- return null;
1584
+ let cert = peer_leaf_cert();
1585
+ return cert ? cert.publicKey() : null;
1586
+ }
1587
+
1588
+ // The peer's leaf, parsed once per certificate received. Three places read
1589
+ // it in one handshake — the chain check, the identity check, and the
1590
+ // signature over the handshake (CertificateVerify, or TLS 1.2's
1591
+ // ServerKeyExchange) — and each parsed it from the DER again. Keyed by the
1592
+ // bytes object itself: a new Certificate message (a new chain) is a new
1593
+ // object, and is parsed afresh. null when there is no leaf or it does not
1594
+ // parse.
1595
+ let peer_leaf = { der: null, cert: null };
1596
+ function peer_leaf_cert() {
1597
+ let chain = context.remote_cert_chain;
1598
+ if (!chain || chain.length === 0) return null;
1599
+ let der = chain[0].cert;
1600
+ if (peer_leaf.der !== der) peer_leaf = { der: der, cert: _cert(der) };
1601
+ return peer_leaf.cert;
1602
+ }
1603
+
1604
+ /**
1605
+ * The peer's handshake signature — TLS 1.3 CertificateVerify (either role),
1606
+ * TLS 1.2 CertificateVerify (a client's), TLS 1.2 ServerKeyExchange (a
1607
+ * server's) — checked in one place, in one order:
1608
+ *
1609
+ * 1. the signature itself, under the leaf's key (verify_with_scheme, which
1610
+ * also binds the scheme to the key type): decrypt_error if it fails;
1611
+ * 2. then the scheme: one we offered (RFC 8446 §4.4.3, RFC 5246 §7.4.8,
1612
+ * RFC 4492 §5.4 — "MUST be one of those present in" our
1613
+ * signature_algorithms, sent in the ClientHello or the
1614
+ * CertificateRequest): illegal_parameter if not. Not before 1: a
1615
+ * policy error must not stand in for a signature failure.
1616
+ *
1617
+ * It was three copies, one per message, and the scheme was held to what we
1618
+ * offered in none of them (1.3: removed on purpose; 1.2: never written) —
1619
+ * so `sigalgs` narrowed what we asked for, not what we took.
1620
+ *
1621
+ * Returns null when the signature stands; otherwise { alert, reason }, for
1622
+ * the caller's fatalAlert. On success, records it (peerSignatureVerified).
1623
+ */
1624
+ function check_peer_signature(version, scheme, tbs, signature, what) {
1625
+ let pub = peer_leaf_public_key();
1626
+ if (!pub) return { alert: wire.TLS_ALERT.BAD_CERTIFICATE, reason: 'Cannot read peer certificate public key' };
1627
+ // The scheme first, then the signature (RFC 8446 §4.4.3): one we did
1628
+ // not offer, one this version does not have, or one that is not the
1629
+ // key's is illegal_parameter — a bad signature under a good scheme is
1630
+ // decrypt_error. The signature was tried first, and a wrong scheme came
1631
+ // out as decrypt_error (tlsfuzzer).
1632
+ let offered = context.local_supported_signature_algorithms || [];
1633
+ if (offered.length > 0 && offered.indexOf(scheme) < 0) {
1634
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: what + ' signed with scheme 0x' + (scheme >>> 0).toString(16) + ', which was not offered' };
1635
+ }
1636
+ if (!scheme_matches_key(version, scheme, pub)) {
1637
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER, reason: what + ' signed with scheme 0x' + (scheme >>> 0).toString(16) + ', which is not one of the certificate\'s key at this version' };
1638
+ }
1639
+ if (verify_with_scheme(version, scheme, tbs, pub, signature) !== true) {
1640
+ return { alert: wire.TLS_ALERT.DECRYPT_ERROR, reason: what + ' signature verification failed' };
1196
1641
  }
1642
+ context.peerSignatureVerified = true;
1643
+ context.peerSignatureScheme = scheme;
1644
+ return null;
1197
1645
  }
1198
1646
 
1199
1647
  /**
@@ -1214,11 +1662,10 @@ function TLSSession(options){
1214
1662
 
1215
1663
  /* ====================== Encrypted Client Hello: client ===================== */
1216
1664
 
1217
- // A config to use, on a hello that offers TLS 1.3 (not DTLS: RFC 9849 is
1218
- // TLS's).
1665
+ // A config to use, on a hello that offers TLS 1.3 or DTLS 1.3 (RFC 9849
1666
+ // §1).
1219
1667
  function ech_on() {
1220
- return !context.isServer && context.ech_client !== null &&
1221
- context.local_supported_versions.indexOf(wire.TLS_VERSION.TLS1_3) >= 0;
1668
+ return !context.isServer && context.ech_client !== null && lists13(context.local_supported_versions);
1222
1669
  }
1223
1670
 
1224
1671
  function ext_code(e) { return typeof e.type === 'number' ? e.type : wire.TLS_EXT[e.type]; }
@@ -1234,13 +1681,20 @@ function TLSSession(options){
1234
1681
  * a post-quantum share, a ClientHello carrying it twice would not fit a
1235
1682
  * QUIC Initial packet.
1236
1683
  */
1684
+ // TLS 1.2's extensions — the inner hello offers TLS 1.3 alone (RFC 9849
1685
+ // §6.1, §7.1), so they belong to the outer one only, which may fall back:
1686
+ // renegotiation_info, extended_master_secret, session_ticket,
1687
+ // ec_point_formats. They were copied into the inner hello, which a server
1688
+ // reading it as the TLS 1.3 hello it must be refused.
1689
+ const ECH_OUTER_ONLY = { 0xff01: 1, 23: 1, 35: 1, 11: 1 };
1237
1690
  function ech_split(extensions) {
1238
- let sni = null, marker = null, psk = null, block = [];
1691
+ let sni = null, marker = null, psk = null, block = [], outerOnly = [];
1239
1692
  for (let i = 0; i < extensions.length; i++) {
1240
1693
  let e = extensions[i], c = ext_code(e);
1241
1694
  if (c === 0) sni = e;
1242
1695
  else if (c === EXT_ECH) marker = e;
1243
1696
  else if (c === 41) psk = e;
1697
+ else if (ECH_OUTER_ONLY[c]) outerOnly.push(e);
1244
1698
  else block.push(e);
1245
1699
  }
1246
1700
  extensions.length = 0;
@@ -1250,7 +1704,7 @@ function TLSSession(options){
1250
1704
  if (psk) extensions.push(psk);
1251
1705
  return {
1252
1706
  compressed: block.map(ext_code),
1253
- outer: [{ type: 'SERVER_NAME', value: context.ech_client.config.public_name }].concat(block),
1707
+ outer: [{ type: 'SERVER_NAME', value: context.ech_client.config.public_name }].concat(block, outerOnly),
1254
1708
  sniLength: sni ? Buffer.byteLength(String(context.local_sni)) : null
1255
1709
  };
1256
1710
  }
@@ -1259,25 +1713,28 @@ function TLSSession(options){
1259
1713
  * The inner hello (a handshake message, as the transcript has it) → the
1260
1714
  * outer one that goes on the wire, carrying it encrypted. The first
1261
1715
  * hello sets up the HPKE context; the second (after a HelloRetryRequest)
1262
- * uses it again with an empty enc (§6.1.5).
1716
+ * uses it again with an empty enc (§6.1.5) — when the HelloRetryRequest
1717
+ * confirmed ECH. When it did not (§6.1.4), the server goes on with the
1718
+ * outer hello as a plain TLS 1.3 one, and to it a second hello is the
1719
+ * first one again but for key_share, cookie and pre_shared_key (RFC 8446
1720
+ * §4.1.2): the encrypted_client_hello extension copied as it was. It was
1721
+ * sealed afresh, and the server saw an extension change (BoGo: "extension
1722
+ * 65037 in second ClientHello unexpectedly changed").
1263
1723
  */
1264
1724
  function ech_outer_hello(innerMsg, split, second) {
1265
1725
  let prep = context.ech_client, st = context.ech;
1726
+ let rejected = second && st.status === 'rejected';
1266
1727
  if (!second) { let hs = client_hpke_setup(prep); st.hpke = hs.context; st.enc = hs.enc; }
1267
- let encoded = client_encode_inner(innerMsg, split.compressed, prep.config.maximum_name_length, split.sniLength);
1268
- let extData = client_outer_ext_data(prep.kdf_id, prep.aead_id, prep.config.config_id,
1269
- second ? new Uint8Array(0) : st.enc, encoded.length + prep.suite.Nt);
1270
- let outerMsg = build_tls_message({
1271
- type: 'client_hello',
1272
- version: 0x0303,
1273
- random: st.outer_random,
1274
- session_id: context.local_session_id,
1275
- cookie: context.dtls_cookie,
1276
- cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
1277
- cipher_suite: context.local_supported_cipher_suites,
1278
- extensions: split.outer.concat([{ type: EXT_ECH, data: extData }], split.outerPsk ? [split.outerPsk] : []),
1279
- });
1280
- return client_seal_outer(outerMsg, st.hpke, encoded);
1728
+ let encoded = rejected ? null : client_encode_inner(innerMsg, split.compressed, prep.config.maximum_name_length, split.sniLength, dtls_transport());
1729
+ let extData = rejected ? st.ch1_ech_ext
1730
+ : client_outer_ext_data(prep.kdf_id, prep.aead_id, prep.config.config_id,
1731
+ second ? new Uint8Array(0) : st.enc, encoded.length + prep.suite.Nt);
1732
+ let outerMsg = build_tls_message(client_hello_params(st.outer_random, context.local_session_id,
1733
+ split.outer.concat([{ type: EXT_ECH, data: extData }], split.outerPsk ? [split.outerPsk] : [])));
1734
+ if (rejected) return outerMsg;
1735
+ let sealed = client_seal_outer(outerMsg, st.hpke, encoded, dtls_transport());
1736
+ if (!second) st.ch1_ech_ext = client_hello_ech_ext(sealed, dtls_transport());
1737
+ return sealed;
1281
1738
  }
1282
1739
 
1283
1740
  /**
@@ -1291,6 +1748,9 @@ function TLSSession(options){
1291
1748
  st.status = 'rejected';
1292
1749
  st.decided = true;
1293
1750
  st.verify_name = context.ech_client.config.public_name;
1751
+ // The inner hello's PSK is not this handshake's: the outer one offered a
1752
+ // decoy (§6.1.2). (A ServerHello that selects one is refused.)
1753
+ context.psk_offered = null;
1294
1754
  context.local_random = st.outer_random;
1295
1755
  context.transcript = [st.outer_ch1];
1296
1756
  context.transcriptHash = null; // rebuilt from the outer transcript when next asked
@@ -1341,6 +1801,25 @@ function TLSSession(options){
1341
1801
  return true;
1342
1802
  }
1343
1803
 
1804
+ // The application traffic secrets, to the layer above (its application
1805
+ // keys). Not for a client whose ECH was rejected (§6.1.6): it finishes
1806
+ // the handshake only to end it with ech_required — that connection carries
1807
+ // no application data, and a layer given the keys can take the handshake
1808
+ // for complete and the ECH error that follows for an aside (no retry with
1809
+ // retry_configs).
1810
+ function emit_app_secrets() {
1811
+ if (ech_rejected_client()) return;
1812
+ ev.emit('appSecrets', context.local_app_traffic_secret, context.remote_app_traffic_secret);
1813
+ _emitAppKeylog();
1814
+ }
1815
+
1816
+ // A client whose ECH the server did not take (its outer hello sent, the
1817
+ // status 'rejected'): the handshake runs as the public name, to end with
1818
+ // ech_required (§6.1.6).
1819
+ function ech_rejected_client() {
1820
+ return !context.isServer && context.ech.status === 'rejected' && !!context.ech.outer_ch1;
1821
+ }
1822
+
1344
1823
  /**
1345
1824
  * §6.1.6: ECH was rejected, and the server has proven itself for the
1346
1825
  * public_name (its Certificate, CertificateVerify and Finished checked).
@@ -1377,10 +1856,11 @@ function TLSSession(options){
1377
1856
  * cookie and pre_shared_key — an invariant that is only cheap to hold when a
1378
1857
  * single function produces it.
1379
1858
  */
1380
- function send_second_client_hello(keyShareGroup, keySharePublic, cookie) {
1859
+ function send_second_client_hello(keyShareGroup, keySharePublic, cookie, extraKeyShares) {
1381
1860
  let extensions = build_client_hello_extensions({
1382
1861
  keyShareGroup: keyShareGroup,
1383
1862
  keySharePublic: keySharePublic,
1863
+ extraKeyShares: extraKeyShares || null,
1384
1864
  cookie: cookie
1385
1865
  });
1386
1866
  let echSplit = ech_on() && context.ech.outer_ch1 ? ech_split(extensions) : null;
@@ -1402,11 +1882,10 @@ function TLSSession(options){
1402
1882
  context.psk_offered = null;
1403
1883
  } else {
1404
1884
  let hashLen = getHashFn(pskHash).outputLen;
1405
- let ticketAge = po.lifetime ? Math.min((Date.now() - (po.created || Date.now())) / 1000, po.lifetime) * 1000 : 0;
1406
1885
  pskExt = {
1407
1886
  type: 'PRE_SHARED_KEY',
1408
1887
  value: {
1409
- identities: [{ identity: po.identity, age: ((ticketAge + (po.age_add || 0)) & 0xFFFFFFFF) >>> 0 }],
1888
+ identities: [{ identity: po.identity, age: obfuscated_ticket_age(po) }],
1410
1889
  binders: [new Uint8Array(hashLen)]
1411
1890
  }
1412
1891
  };
@@ -1425,23 +1904,14 @@ function TLSSession(options){
1425
1904
  context.psk_offered = null;
1426
1905
  }
1427
1906
 
1428
- let ch2Params = {
1429
- type: 'client_hello',
1430
- version: 0x0303,
1431
- // Each hello repeats its own first random (RFC 8446 §4.1.2) — the
1432
- // inner one's, with ECH.
1433
- random: echSplit ? context.ech.inner_random : context.local_random,
1434
- session_id: context.local_session_id,
1435
- cookie: context.dtls_cookie,
1436
- cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
1437
- cipher_suite: context.local_supported_cipher_suites,
1438
- extensions: extensions,
1439
- };
1907
+ // Each hello repeats its own first random (RFC 8446 §4.1.2) — the
1908
+ // inner one's, with ECH.
1909
+ let ch2Params = client_hello_params(echSplit ? context.ech.inner_random : context.local_random, context.local_session_id, extensions);
1440
1910
  let ch2 = build_tls_message(ch2Params);
1441
1911
  if (pskExt) {
1442
1912
  let hashLen = getHashFn(pskHash).outputLen;
1443
1913
  let truncated = concatUint8Arrays(context.transcript.concat([ch2.slice(0, ch2.length - (2 + 1 + hashLen))]));
1444
- let binder_key = derive_binder_key(pskHash, context.psk_offered.psk, false, label_prefix());
1914
+ let binder_key = derive_binder_key(pskHash, context.psk_offered.psk, context.psk_offered.external === true, label_prefix());
1445
1915
  pskExt.value.binders = [compute_psk_binder(pskHash, binder_key, truncated, label_prefix())];
1446
1916
  ch2 = build_tls_message(ch2Params);
1447
1917
  }
@@ -1494,6 +1964,241 @@ function TLSSession(options){
1494
1964
  return meta ? meta.hash : null;
1495
1965
  }
1496
1966
 
1967
+ // May a server whose key is `keyObj` use `suite`? RFC 4492 §2 / RFC 5246
1968
+ // §7.4.2: a (D)TLS 1.2 suite names the authentication algorithm — an
1969
+ // ECDHE_RSA suite needs an RSA key, an ECDHE_ECDSA one an ECDSA (or EdDSA,
1970
+ // RFC 8422 §5.1.3) key, on a curve the client listed (§5.1.1: its
1971
+ // supported_groups names the curves it can verify on too — a P-384
1972
+ // certificate was chosen for a client of P-256 alone). TLS 1.3 suites
1973
+ // name none. The key's type unknown: no say.
1974
+ function suite_auth_ok(suite, keyObj) {
1975
+ let meta = TLS_CIPHER_SUITES[suite];
1976
+ if (!meta || !meta.sig || meta.sig === 'TLS13' || !keyObj) return true;
1977
+ let kt = keyObj.asymmetricKeyType;
1978
+ if (meta.sig === 'RSA') return kt === 'rsa' || kt === 'rsa-pss';
1979
+ if (meta.sig === 'ECDSA') {
1980
+ if (kt === 'ec' && context.remote_supported_groups.length > 0 &&
1981
+ context.remote_supported_groups.indexOf(ec_key_group(keyObj)) < 0) return false;
1982
+ return kt === 'ec' || kt === 'ed25519' || kt === 'ed448';
1983
+ }
1984
+ return true;
1985
+ }
1986
+
1987
+ // The client's signature_algorithms, and nothing else. TLS 1.2 without the
1988
+ // extension had SHA-1 assumed (RFC 5246 §7.4.1.4.1); RFC 9155 §3 updates
1989
+ // that: such a client gets handshake_failure, as one with no scheme we can
1990
+ // sign with does. Every suite here signs (ECDHE_RSA, ECDHE_ECDSA).
1991
+ function peer_signature_algorithms(v13) {
1992
+ return context.remote_supported_signature_algorithms || [];
1993
+ }
1994
+
1995
+ // A ClientHello as §4.1.2 compares two: what may not change between them.
1996
+ // The extensions as a set, by type: §4.1.2 lists what the second hello may
1997
+ // change, and their order is not a field of the hello — RFC 8446 §4.2
1998
+ // leaves it free ("may appear in any order", pre_shared_key last), and
1999
+ // wolfSSL does send its second hello in another order. Taking a new order
2000
+ // for a change refused every wolfSSL client after a HelloRetryRequest —
2001
+ // after every one, in DTLS 1.3, where the cookie always asks for one. A
2002
+ // type twice is refused when the hello is parsed (§4.2), so sorted by type
2003
+ // they compare one to one.
2004
+ const CH2_MAY_CHANGE = {};
2005
+ for (const t of [wire.TLS_EXT.KEY_SHARE, wire.TLS_EXT.COOKIE, wire.TLS_EXT.EARLY_DATA, wire.TLS_EXT.PRE_SHARED_KEY, wire.TLS_EXT.PADDING]) CH2_MAY_CHANGE[t] = 1;
2006
+ function ch_shape(m) {
2007
+ return {
2008
+ suites: (m.cipher_suites || []).join(','),
2009
+ sid: m.session_id ? Buffer.from(m.session_id).toString('hex') : '',
2010
+ exts: (m.extensions || []).filter(function (e) { return !CH2_MAY_CHANGE[e.type]; })
2011
+ .map(function (e) { return { type: e.type, data: Buffer.from(e.data || []) }; })
2012
+ .sort(function (x, y) { return x.type - y.type; }),
2013
+ };
2014
+ }
2015
+ function ch_shape_differs(a, b) {
2016
+ if (a.suites !== b.suites) return 'cipher_suites changed';
2017
+ if (a.sid !== b.sid) return 'legacy_session_id changed';
2018
+ if (a.exts.length !== b.exts.length) return 'extensions added or removed';
2019
+ for (let i = 0; i < a.exts.length; i++) {
2020
+ if (a.exts[i].type !== b.exts[i].type) return 'extensions changed (' + b.exts[i].type + ' where ' + a.exts[i].type + ' was)';
2021
+ if (!a.exts[i].data.equals(b.exts[i].data)) return 'extension ' + a.exts[i].type + ' changed';
2022
+ }
2023
+ return null;
2024
+ }
2025
+
2026
+ // Could a ServerHello of this suite resume `saved`? null, or why not: the
2027
+ // suite it was made with, and extended_master_secret as it was.
2028
+ function resume12_mismatch(saved, suite) {
2029
+ if (typeof saved.cipher === 'number' && suite !== null && suite !== saved.cipher) {
2030
+ return { alert: wire.TLS_ALERT.ILLEGAL_PARAMETER,
2031
+ reason: 'Resumed session with cipher suite 0x' + (suite >>> 0).toString(16) + ', but it was made with 0x' + (saved.cipher >>> 0).toString(16) };
2032
+ }
2033
+ if (!!saved.extended_master_secret !== !!context.use_extended_master_secret) {
2034
+ return { alert: wire.TLS_ALERT.HANDSHAKE_FAILURE,
2035
+ reason: saved.extended_master_secret ? 'Resumed a session made with extended_master_secret, without it'
2036
+ : 'Resumed a session made without extended_master_secret, with it' };
2037
+ }
2038
+ return null;
2039
+ }
2040
+
2041
+ // A TLS 1.2 resumption the client has learned of (its session_id echoed,
2042
+ // or — tls12_resume_maybe — the server's next message): the saved
2043
+ // session's state taken. False when the handshake was aborted.
2044
+ function commit_resume12(message) {
2045
+ let saved12 = context.tls12_client_session;
2046
+ context.tls12_resume_maybe = false;
2047
+ // A resumed session keeps what it was made with. The suite
2048
+ // (RFC 5246 §7.4.1.3: "the cipher suite ... from the session being
2049
+ // resumed"), and extended_master_secret both ways (RFC 7627 §5.3: a
2050
+ // client MUST abort when the ServerHello drops the extension the
2051
+ // session used, or adds one it did not) — the master secret was
2052
+ // derived one way and cannot be reread the other.
2053
+ let bad = resume12_mismatch(saved12, message ? hello_cipher_suite(message) : context.selected_cipher_suite);
2054
+ if (bad) { fatalAlert(bad.alert, bad.reason); return false; }
2055
+ context.tls12_abbreviated = true;
2056
+ context.isResumed = true;
2057
+ restore_client_session_peer(saved12);
2058
+ // Load master_secret and EMS flag from saved session
2059
+ set_context({
2060
+ base_secret: saved12.master_secret,
2061
+ use_extended_master_secret: !!saved12.extended_master_secret,
2062
+ // Mark as if remote_hello_done arrived — we won't actually receive it in abbreviated flow,
2063
+ // but the reactive loop uses this to gate CKE; we're skipping CKE anyway.
2064
+ remote_hello_done: true,
2065
+ // Pretend key_exchange_sent so Finished logic proceeds without real CKE
2066
+ key_exchange_sent: true,
2067
+ });
2068
+ return true;
2069
+ }
2070
+
2071
+ // ---- record_size_limit (RFC 8449) ----
2072
+ //
2073
+ // The value on the wire is the protocol's: in TLS 1.2 the largest
2074
+ // plaintext, in 1.3 the largest TLSInnerPlaintext — content and its type
2075
+ // byte (§4: so 2^14 + 1 at most, against 2^14). Ours is the option
2076
+ // (recordSizeLimit, 64 to 2^14 + 1); a server answering a client's without
2077
+ // one gives the protocol's maximum. recordSizeLimit: false — never sent,
2078
+ // nor answered.
2079
+ function u16_bytes(v) { return new Uint8Array([(v >> 8) & 0xff, v & 0xff]); }
2080
+ function take_record_size_limit(exts) {
2081
+ if (!Array.isArray(exts)) return true;
2082
+ for (let i = 0; i < exts.length; i++) {
2083
+ let e = exts[i];
2084
+ if (!e || e.type !== wire.TLS_EXT.RECORD_SIZE_LIMIT) continue;
2085
+ let d = e.data;
2086
+ if (!d || d.length !== 2) { fatalAlert(wire.TLS_ALERT.DECODE_ERROR, 'record_size_limit is not 2 bytes'); return false; }
2087
+ let v = (d[0] << 8) | d[1];
2088
+ // "MUST treat receipt of a smaller value as a fatal error and
2089
+ // generate an illegal_parameter alert" (§4).
2090
+ if (v < 64) { fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'record_size_limit ' + v + ', below 64'); return false; }
2091
+ context.peer_record_size_limit = v;
2092
+ // A client's own, sent, now answered.
2093
+ if (!context.isServer) context.record_size_limit_agreed = context.record_size_limit;
2094
+ }
2095
+ return true;
2096
+ }
2097
+ // ── DTLS Connection ID (RFC 9146; RFC 9147 §9) ──
2098
+ //
2099
+ // Each side sends the CID it wants in the records it RECEIVES — empty:
2100
+ // none, though it puts the other's in its own. The client offers its own
2101
+ // (connectionId); a server with one answers a client that offered, in the
2102
+ // ServerHello, in DTLS 1.2 and 1.3 alike. Over TLS it is not taken. The
2103
+ // record layer (DTLSSession) is told by 'connectionId', when it is settled.
2104
+ // ── A ClientHello's fields ──
2105
+ // Its random and session_id, our suites, these extensions — one shape for
2106
+ // every hello this client builds (the first, with or without a PSK or a
2107
+ // TLS 1.2 session; the second; ECH's outer one). `cipher_suites` (plural)
2108
+ // is what wire.js's builder reads: the singular key, once the only one
2109
+ // passed, was ignored, and wire.js put its own fallback list on the wire.
2110
+ // A PSK's obfuscated_ticket_age (RFC 8446 §4.2.11.1): the ticket's age in
2111
+ // ms, plus its age_add, mod 2^32 — 0 for an external PSK (no ticket).
2112
+ function obfuscated_ticket_age(p) {
2113
+ let age = p.lifetime ? Math.min((Date.now() - (p.created || Date.now())) / 1000, p.lifetime) * 1000 : 0;
2114
+ return ((age + (p.age_add || 0)) & 0xFFFFFFFF) >>> 0;
2115
+ }
2116
+
2117
+ function client_hello_params(random, sessionId, extensions) {
2118
+ return {
2119
+ type: 'client_hello',
2120
+ version: 0x0303,
2121
+ random: random,
2122
+ session_id: sessionId,
2123
+ cookie: context.dtls_cookie,
2124
+ cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
2125
+ cipher_suite: context.local_supported_cipher_suites,
2126
+ extensions: extensions,
2127
+ };
2128
+ }
2129
+
2130
+ function connection_id_ext() {
2131
+ let d = new Uint8Array(1 + context.local_cid.length);
2132
+ d[0] = context.local_cid.length;
2133
+ d.set(context.local_cid, 1);
2134
+ return { type: wire.TLS_EXT.CONNECTION_ID, data: d };
2135
+ }
2136
+ function connection_ids() {
2137
+ return context.peer_cid === null ? null : { local: new Uint8Array(context.local_cid), peer: new Uint8Array(context.peer_cid) };
2138
+ }
2139
+ function take_connection_id(exts) {
2140
+ context.peer_cid = null;
2141
+ if (context.local_cid === null || !dtls_transport() || !Array.isArray(exts)) return true;
2142
+ for (let i = 0; i < exts.length; i++) {
2143
+ let e = exts[i];
2144
+ if (!e || e.type !== wire.TLS_EXT.CONNECTION_ID) continue;
2145
+ let d = e.data;
2146
+ if (!d || d.length < 1 || d[0] !== d.length - 1) { fatalAlert(wire.TLS_ALERT.DECODE_ERROR, 'connection_id is malformed'); return false; }
2147
+ context.peer_cid = new Uint8Array(d.subarray(1));
2148
+ }
2149
+ if (context.peer_cid !== null) ev.emit('connectionId', connection_ids());
2150
+ return true;
2151
+ }
2152
+
2153
+ // The limits in force, by what each side sent (getRecordSizeLimit).
2154
+ function record_size_limits() {
2155
+ if (context.peer_record_size_limit === null || typeof context.record_size_limit_agreed !== 'number') return null;
2156
+ let typeByte = is13() ? 1 : 0;
2157
+ return {
2158
+ send: Math.min(MAX_RECORD_PLAINTEXT, context.peer_record_size_limit - typeByte),
2159
+ receive: Math.min(MAX_RECORD_PLAINTEXT, context.record_size_limit_agreed - typeByte),
2160
+ };
2161
+ }
2162
+
2163
+ // The server's record_size_limit for its answer, or null.
2164
+ function record_size_limit_answer() {
2165
+ if (!context.isServer || context.peer_record_size_limit === null || context.record_size_limit === false) return null;
2166
+ let max = MAX_RECORD_PLAINTEXT + (is13() ? 1 : 0);
2167
+ let v = typeof context.record_size_limit === 'number' ? Math.min(context.record_size_limit, max) : max;
2168
+ context.record_size_limit_agreed = v;
2169
+ return { type: wire.TLS_EXT.RECORD_SIZE_LIMIT, data: u16_bytes(v) };
2170
+ }
2171
+
2172
+ // The lists nothing configured, filled by role — the one place either
2173
+ // role's defaults are. The suites follow both halves of the versions on
2174
+ // offer: a 1.2-only profile has no 1.3 suite, and the reverse (a 1.2-only
2175
+ // one once advertised 0x1301..0x1303). Groups: a client offers
2176
+ // SUPPORTED_GROUPS; a server takes SERVER_DEFAULT_GROUPS (every
2177
+ // post-quantum group it has first — ecdh.js). A server's were left to
2178
+ // whoever built the session, and TLSSocket and DTLSSession each did it
2179
+ // their own way.
2180
+ function fill_default_lists() {
2181
+ if (context.local_supported_versions.length === 0) context.local_supported_versions = [wire.TLS_VERSION.TLS1_3, wire.TLS_VERSION.TLS1_2];
2182
+ let lv = context.local_supported_versions;
2183
+ if (context.local_supported_cipher_suites.length === 0) {
2184
+ context.local_supported_cipher_suites = default_cipher_suites(lists13(lv), lv.some(wire.is_tls12_wire));
2185
+ }
2186
+ if (context.local_supported_groups.length === 0) {
2187
+ context.local_supported_groups = (context.isServer ? ECDH_SERVER_DEFAULT_GROUPS : ECDH_SUPPORTED_GROUPS).slice();
2188
+ }
2189
+ if (context.local_supported_signature_algorithms.length === 0) {
2190
+ context.local_supported_signature_algorithms = default_signature_schemes();
2191
+ }
2192
+ }
2193
+
2194
+ // The largest handshake message taken: HANDSHAKE_MESSAGE_MAX (wire.js),
2195
+ // or maxHandshakeSize when smaller — the one limit for the record layers
2196
+ // (TLSSocket's reassembly, DTLSSession's) and for a certificate inflated
2197
+ // from its compressed form, which each computed it.
2198
+ function handshake_message_limit() {
2199
+ return context.maxHandshakeSize > 0 ? Math.min(context.maxHandshakeSize, wire.HANDSHAKE_MESSAGE_MAX) : wire.HANDSHAKE_MESSAGE_MAX;
2200
+ }
2201
+
1497
2202
  /**
1498
2203
  * Our certificate's private key as a crypto.KeyObject.
1499
2204
  *
@@ -1694,32 +2399,103 @@ function TLSSession(options){
1694
2399
  // why not; a server that requires an authorized client (requestCert +
1695
2400
  // rejectUnauthorized) accepts only a ticket that says so — anything else is
1696
2401
  // a full handshake, where the certificate is asked for again.
2402
+ //
2403
+ // A client that proved an external PSK is authenticated by it, with no
2404
+ // certificate: the ticket carries the identity instead (pi), and stands for
2405
+ // an authorized client the same way.
1697
2406
  function ticket_peer_fields() {
1698
2407
  if (!context.isServer) return {};
1699
2408
  // This handshake's certificate, or — resumed — the one the ticket
1700
2409
  // carried in: a ticket issued on a resumed connection carries it on.
1701
2410
  let chain = (context.remote_cert_chain && context.remote_cert_chain.length > 0) ? context.remote_cert_chain : context.resumed_peer_chain;
1702
2411
  let leaf = chain && chain.length > 0 && chain[0] ? chain[0].cert : null;
2412
+ let known = !!(leaf || context.psk_identity);
1703
2413
  return {
1704
2414
  pc: leaf || null,
1705
- pa: !!(leaf && context.peerAuthorized),
1706
- pe: leaf ? (context.authorizationError || null) : 'NO_PEER_CERTIFICATE',
2415
+ pi: context.psk_identity || null,
2416
+ pa: known && context.peerAuthorized === true,
2417
+ pe: known ? (context.authorizationError || null) : 'NO_PEER_CERTIFICATE',
1707
2418
  };
1708
2419
  }
1709
2420
  function ticket_peer_acceptable(state) {
1710
2421
  if (!(context.requestCert && context.rejectUnauthorized)) return true;
1711
- return !!(state && state.pa === true && state.pc);
2422
+ return !!(state && state.pa === true && (state.pc || state.pi));
1712
2423
  }
1713
2424
  // Kept apart from remote_cert_chain, which means "a Certificate arrived in
1714
2425
  // THIS handshake" — and so has to be proved by a CertificateVerify in it.
1715
2426
  // getPeerCertificate() answers with either.
1716
2427
  function restore_ticket_peer(state) {
1717
- if (!state || !state.pc) return;
1718
- context.resumed_peer_chain = [{ cert: state.pc }];
2428
+ if (!state || !(state.pc || state.pi)) return;
2429
+ context.resumed_peer_chain = state.pc ? [{ cert: state.pc }] : null;
2430
+ context.psk_identity = state.pi || null;
1719
2431
  context.peerAuthorized = state.pa === true;
1720
2432
  context.authorizationError = state.pa === true ? null : (state.pe || 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
1721
2433
  }
1722
2434
 
2435
+ // The peer proved the external PSK `identity` (its binder, then its
2436
+ // Finished): that is its authentication (RFC 8446 §2.2), on either side.
2437
+ function psk_authenticated_peer(identity) {
2438
+ context.psk_identity = identity;
2439
+ context.peerAuthorized = true;
2440
+ context.authorizationError = null;
2441
+ }
2442
+
2443
+ // Client: the external PSK, as the hello offers a PSK (the shape a saved
2444
+ // session has). It can only be used where the hello can carry it: TLS 1.3
2445
+ // offered, with a suite of its hash — otherwise this is a configuration
2446
+ // that cannot work, and is said so rather than silently not offered.
2447
+ function external_psk_offer() {
2448
+ let x = context.external_psk;
2449
+ if (!lists13(context.local_supported_versions)) throw psk_option_error('it needs TLS 1.3, and it is not offered');
2450
+ let suiteOk = context.local_supported_cipher_suites.some(function (cs) {
2451
+ return TLS_CIPHER_SUITES[cs] && TLS_CIPHER_SUITES[cs].tls === 13 && TLS_CIPHER_SUITES[cs].hash === x.hash;
2452
+ });
2453
+ if (!suiteOk) throw psk_option_error('it uses ' + x.hash + ', and no TLS 1.3 cipher suite with it is offered');
2454
+ return { psk: x.psk, ticket: x.identity, cipher: x.cipher, age_add: 0, external: true };
2455
+ }
2456
+
2457
+ // Server: the PSK an offered identity names — an external one
2458
+ // (pskCallback) first, as OpenSSL's find-session callback: a ticket of
2459
+ // ours is never one; then a 'psk' listener, when there is one and it
2460
+ // answers; then this session opens the ticket itself — it issued it, with
2461
+ // its own ticketKeys (open_ticket_13). That default used to live in
2462
+ // TLSSocket, so a TLSSession used on its own (QUIC) issued tickets it
2463
+ // could never accept. Null: none.
2464
+ function psk_for_identity(id) {
2465
+ let r = external_psk_lookup(id.identity);
2466
+ if (r === undefined) {
2467
+ ev.emit('psk', { identity: id.identity, obfuscatedAge: (id.age || 0) >>> 0 }, function (result) { r = result; });
2468
+ }
2469
+ if (r === undefined) r = open_ticket_13(id.identity);
2470
+ return r || null;
2471
+ }
2472
+
2473
+ // Server: the external PSK for this identity, from pskCallback — or
2474
+ // undefined, when there is no callback or it does not know the identity.
2475
+ function external_psk_lookup(identity) {
2476
+ if (!context.pskCallback) return undefined;
2477
+ let answer = context.pskCallback(new Uint8Array(identity));
2478
+ return answer == null ? undefined : external_psk(answer, false);
2479
+ }
2480
+
2481
+ // Server: the PSK picked from this hello is not used after all — a
2482
+ // HelloRetryRequest (the second hello decides again), or no suite of its
2483
+ // hash in common. Everything taking it brought along goes with it: the
2484
+ // ticket's data and peer, an external identity, the 0-RTT candidate. The
2485
+ // ticket's peer was left behind when no suite matched, so a full
2486
+ // handshake without a client certificate still reported the ticket's.
2487
+ function psk_dropped() {
2488
+ if (context.psk_identity || context.resumed_peer_chain) { context.peerAuthorized = false; context.authorizationError = null; }
2489
+ context.psk_accepted = false;
2490
+ context.isResumed = false;
2491
+ context.psk_offered = null;
2492
+ context.psk_identity = null;
2493
+ context.resumed_peer_chain = null;
2494
+ context.resumed_ticket_data = null;
2495
+ context.resumed_ticket_state = null;
2496
+ context.early.candidate = null;
2497
+ }
2498
+
1723
2499
  // Our Certificate message — compressed (RFC 8879) when the peer offered an
1724
2500
  // algorithm we have, by our preference, in TLS 1.3. The compressed form
1725
2501
  // is cached per chain and algorithm (cert_compression.js).
@@ -1816,20 +2592,26 @@ function TLSSession(options){
1816
2592
  // So the session carries the server's chain and the verdict on it; a
1817
2593
  // connection that requires an authorized server offers only a session that
1818
2594
  // says so.
2595
+ // A server that proved an external PSK has no chain: the identity stands
2596
+ // in for it (peer_psk_identity), as on the server's tickets.
1819
2597
  function client_session_peer_fields() {
1820
2598
  let chain = (context.remote_cert_chain && context.remote_cert_chain.length > 0) ? context.remote_cert_chain : context.resumed_peer_chain;
1821
2599
  let certs = chain ? chain.map(function (e) { return e.cert; }).filter(function (c) { return !!c; }) : [];
2600
+ let known = certs.length > 0 || !!context.psk_identity;
1822
2601
  return {
1823
2602
  peer_chain: certs.length > 0 ? certs : null,
1824
- peer_authorized: certs.length > 0 && context.peerAuthorized === true,
1825
- peer_error: certs.length > 0 ? (context.authorizationError || null) : 'NO_PEER_CERTIFICATE',
2603
+ peer_psk_identity: context.psk_identity || null,
2604
+ peer_authorized: known && context.peerAuthorized === true,
2605
+ peer_error: known ? (context.authorizationError || null) : 'NO_PEER_CERTIFICATE',
1826
2606
  };
1827
2607
  }
1828
2608
  function restore_client_session_peer(sessionData) {
1829
- if (!sessionData) return; // an external PSK: no saved server
1830
- let certs = sessionData && Array.isArray(sessionData.peer_chain) ? sessionData.peer_chain : null;
2609
+ if (!sessionData) return; // a legacy psk option: no saved server
2610
+ let certs = Array.isArray(sessionData.peer_chain) ? sessionData.peer_chain : null;
2611
+ let pskId = sessionData.peer_psk_identity || null;
1831
2612
  context.resumed_peer_chain = certs ? certs.map(function (c) { return { cert: c }; }) : null;
1832
- context.peerAuthorized = !!certs && sessionData.peer_authorized === true;
2613
+ context.psk_identity = pskId;
2614
+ context.peerAuthorized = !!(certs || pskId) && sessionData.peer_authorized === true;
1833
2615
  context.authorizationError = context.peerAuthorized ? null : (sessionData.peer_error || 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
1834
2616
  }
1835
2617
  // Whether a saved session may be offered on this connection. Not one for
@@ -1866,10 +2648,10 @@ function TLSSession(options){
1866
2648
  dbg('SRV-NST', 'issuing TLS 1.3 NST — cipher:', '0x' + context.selected_cipher_suite.toString(16),
1867
2649
  'hash:', hashName,
1868
2650
  'transcript len:', concatUint8Arrays(context.transcript).length);
1869
- dbg('SRV-NST', 'ticket_nonce:', hexPreview(ticket_nonce, 4),
2651
+ if (LEMON_DEBUG) dbg('SRV-NST', 'ticket_nonce:', hexPreview(ticket_nonce, 4),
1870
2652
  'age_add:', ticket_age_add,
1871
2653
  'lifetime:', ticket_lifetime);
1872
- dbg('SRV-NST', 'resumption_master_secret:', hexPreview(context.resumption_master_secret, 8),
2654
+ if (LEMON_DEBUG) dbg('SRV-NST', 'resumption_master_secret:', hexPreview(context.resumption_master_secret, 8),
1873
2655
  'derived psk:', hexPreview(psk, 8));
1874
2656
 
1875
2657
  // Ensure ticketKeys is 48 bytes (key_name + aes_key)
@@ -1969,8 +2751,50 @@ function TLSSession(options){
1969
2751
  return data;
1970
2752
  }
1971
2753
 
2754
+ /**
2755
+ * The peer authentication gate (see "Authentication gate" where the
2756
+ * handshake completes): null, or { alert, reason } — what the handshake
2757
+ * fails with. One function, asked at completion and, by a TLS 1.2 server,
2758
+ * before its own ChangeCipherSpec and Finished go out: there it ran only
2759
+ * after them, so a server that required a client certificate and got none
2760
+ * finished its side first and then sent certificate_required — a TLS 1.3
2761
+ * alert (DTLS-Fuzzer D4; OpenSSL answers handshake_failure at once).
2762
+ */
2763
+ function authentication_failure() {
2764
+ // Client: the server must have proved possession of its certificate
2765
+ // key — TLS 1.3 CertificateVerify, or the TLS 1.2 ServerKeyExchange
2766
+ // signature. PSK/abbreviated handshakes authenticate via the binder /
2767
+ // resumed master secret instead.
2768
+ if (!context.isServer && !context.psk_accepted && !context.tls12_abbreviated &&
2769
+ context.peerSignatureVerified !== true) {
2770
+ return { alert: wire.TLS_ALERT.UNEXPECTED_MESSAGE, reason: 'Handshake completed without a verified server signature' };
2771
+ }
2772
+ // Server-side client authentication: (a) must a certificate arrive at
2773
+ // all — policy; (b) one that did arrive must be proved — always.
2774
+ if (context.isServer && !context.psk_accepted && !context.tls12_abbreviated) {
2775
+ let clientCertPresent = !!(context.remote_cert_chain && context.remote_cert_chain.length > 0);
2776
+ // (a) required-but-absent: certificate_required is TLS 1.3's (RFC
2777
+ // 8446 §4.4.2.4); TLS 1.2 says handshake_failure (RFC 5246 §7.4.6).
2778
+ if (context.requestCert && context.rejectUnauthorized && !clientCertPresent) {
2779
+ return { alert: is13() ? wire.TLS_ALERT.CERTIFICATE_REQUIRED : wire.TLS_ALERT.HANDSHAKE_FAILURE,
2780
+ reason: 'Client certificate was required but none was provided' };
2781
+ }
2782
+ // (b) present-but-unproved.
2783
+ if (clientCertPresent && context.peerSignatureVerified !== true) {
2784
+ return { alert: wire.TLS_ALERT.UNEXPECTED_MESSAGE, reason: 'Client sent a certificate without a valid CertificateVerify' };
2785
+ }
2786
+ }
2787
+ return null;
2788
+ }
2789
+
2790
+ // The (D)TLS 1.3 key schedule's label prefix: "dtls13" over DTLS (RFC 9147
2791
+ // §5.9), "tls13 " otherwise — by the TRANSPORT, not the version chosen.
2792
+ // By selected_version, every derivation before the version is known took
2793
+ // "tls13 ": the PSK binder a DTLS client sends with its ClientHello, and the
2794
+ // server's check of it. Two lemon peers agreed with each other, and DTLS
2795
+ // 1.3 resumption with anyone else failed. (Only 1.3 derivations ask.)
1972
2796
  function label_prefix() {
1973
- return label_prefix_for(context.selected_version);
2797
+ return dtls_transport() ? LABEL_PREFIX_DTLS13 : LABEL_PREFIX_TLS13;
1974
2798
  }
1975
2799
 
1976
2800
  // For a version chosen in this pass but not yet committed to context
@@ -2079,13 +2903,45 @@ function TLSSession(options){
2079
2903
  * states, so a poisoned context can never keep producing messages), then
2080
2904
  * surfaces the reason to the owner via 'error'.
2081
2905
  */
2082
- function fatalAlert(description, msg) {
2906
+ // `code`: the error's, when it is not the alert's own (ERR_SSL_<NAME>) —
2907
+ // a certificate's verification result, as node:tls reports it.
2908
+ function fatalAlert(description, msg, code) {
2083
2909
  if (context.state === 'error' || context.state === 'closed') return;
2084
2910
  sendAlert(2, description); // sets context.state = 'error'
2085
- ev.emit('error', new Error(msg));
2911
+ ev.emit('error', wire.local_alert_error(description, msg, code));
2086
2912
  }
2087
2913
 
2088
- function process_income_message(data){
2914
+ /**
2915
+ * The exception net. Peer input reaches the handshake through two entry
2916
+ * points: message() (process_income_message) and set_context, which runs
2917
+ * the reactive loop. Anything either one throws — a crypto call refusing
2918
+ * its input, a bug — used to unwind into the transport's data handler and
2919
+ * take the whole process down: one client offering an unusable scheme was
2920
+ * enough (BoGo). Here every such throw ends this session only, the way a
2921
+ * protocol error does: an alert (the error's own alertDesc if it carries
2922
+ * one, internal_error otherwise, RFC 8446 §6.2), the session inert, and
2923
+ * the error itself on 'error'. Calls nested inside the loop pass straight
2924
+ * through; only the outermost one catches.
2925
+ */
2926
+ // Function declarations, so both entry points exist from the factory's
2927
+ // first line (the loop may run before this point is reached).
2928
+ function run_guarded(fn, arg) {
2929
+ if (run_guarded.depth > 0) return fn(arg);
2930
+ run_guarded.depth = 1;
2931
+ try {
2932
+ return fn(arg);
2933
+ } catch (e) {
2934
+ if (context.state !== 'error' && context.state !== 'closed') {
2935
+ let desc = (e && e.alertDesc) || wire.TLS_ALERT.INTERNAL_ERROR;
2936
+ sendAlert(2, desc);
2937
+ ev.emit('error', wire.local_alert_error(desc, e instanceof Error ? e : new Error(String(e))));
2938
+ }
2939
+ } finally {
2940
+ run_guarded.depth = 0;
2941
+ }
2942
+ }
2943
+ function process_income_message(data) { return run_guarded(process_income_message_unguarded, data); }
2944
+ function process_income_message_unguarded(data){
2089
2945
 
2090
2946
  // Terminal states: a fatal alert (ours or a parse failure) already ended
2091
2947
  // this session. Feeding more data must not resurrect the state machine.
@@ -2094,8 +2950,11 @@ function TLSSession(options){
2094
2950
  // Track handshake start time
2095
2951
  if (context.handshakeStartTime === null) context.handshakeStartTime = Date.now();
2096
2952
 
2097
- // Track handshake size and enforce limit
2098
- context.handshakeBytes += data.length;
2953
+ // Track handshake size and enforce limit — the handshake's: a message
2954
+ // after it (a ticket, a KeyUpdate) is one of its own, held to the
2955
+ // per-message limit where it is read. Counted on, a connection that
2956
+ // rekeyed now and then was ended at its 518th KeyUpdate.
2957
+ if (context.state !== 'connected') context.handshakeBytes += data.length;
2099
2958
  if (context.maxHandshakeSize > 0 && context.handshakeBytes > context.maxHandshakeSize) {
2100
2959
  // Must go through the same funnel as every other abort: previously this
2101
2960
  // emitted 'error' but sent no alert and left the session in a live state,
@@ -2110,9 +2969,31 @@ function TLSSession(options){
2110
2969
  // parse errors carrying .alertDesc (decode_error / illegal_parameter);
2111
2970
  // convert them to a fatal alert instead of letting them crash the
2112
2971
  // transport's data handler (remote DoS) or be silently swallowed.
2972
+ // A message the handshake is not waiting for is refused by its type,
2973
+ // before its body is read (the gate below, which needs the parsed
2974
+ // message for a HelloRetryRequest, decides the rest): a malformed one
2975
+ // out of turn was decode_error where unexpected_message is the answer
2976
+ // (tlsfuzzer).
2977
+ if (data.length > 0 && HANDSHAKE_TYPE_NAMES[data[0]] !== undefined) {
2978
+ let allowed = handshake_expect(), t = HANDSHAKE_TYPE_NAMES[data[0]];
2979
+ let ok = allowed.indexOf(t) >= 0 ||
2980
+ (t === 'server_hello' && allowed.indexOf('hello_retry_request') >= 0) ||
2981
+ (t === 'compressed_certificate' && allowed.indexOf('certificate') >= 0);
2982
+ if (!ok) {
2983
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'Unexpected ' + t +
2984
+ (context.hs_in_last ? ' after ' + context.hs_in_last : ' as the first message') + ' (expected ' + allowed.join(' or ') + ')');
2985
+ return;
2986
+ }
2987
+ }
2988
+
2989
+ // The first ClientHello as it came, before it is read: its fingerprint
2990
+ // (JA4, JA5) is there for a hello refused as malformed too — a scanner's
2991
+ // or a bot's, the one a server most wants to know.
2992
+ if (context.isServer && data.length > 0 && data[0] === 1 && context.rawClientHello === null) context.rawClientHello = data;
2993
+
2113
2994
  let message;
2114
2995
  try {
2115
- message = parse_tls_message(data, context.selected_version);
2996
+ message = parse_tls_message(data, context.selected_version, { dtls: dtls_transport() });
2116
2997
  } catch (e) {
2117
2998
  fatalAlert(e.alertDesc || wire.TLS_ALERT.DECODE_ERROR, 'Malformed handshake message: ' + e.message);
2118
2999
  return;
@@ -2141,6 +3022,70 @@ function TLSSession(options){
2141
3022
  // with no retry asked, a third — is unexpected_message. Before, it was
2142
3023
  // run through the handshake again: the SNI callback fired anew, and
2143
3024
  // with ECH the decrypted state of this connection was overwritten.
3025
+ // Renegotiation (TLS 1.2) is not done here: a ClientHello once the
3026
+ // handshake is over (server), a HelloRequest (client) are answered with
3027
+ // a no_renegotiation warning and otherwise left alone (RFC 5246 §7.2.2,
3028
+ // RFC 5746 §4.2, §4.4) — the peer decides whether to go on. A peer that
3029
+ // keeps asking is cut off.
3030
+ if (context.state === 'connected' && is12() &&
3031
+ ((context.isServer && message.type === 'client_hello') ||
3032
+ (!context.isServer && message.type === 'unknown_handshake' && message.handshake_type === 0))) {
3033
+ if (++context.renegotiation_refusals > 3) {
3034
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'Renegotiation asked for again after no_renegotiation');
3035
+ return;
3036
+ }
3037
+ sendAlert(wire.TLS_ALERT_LEVEL.WARNING, wire.TLS_ALERT.NO_RENEGOTIATION);
3038
+ return;
3039
+ }
3040
+
3041
+ // ── The handshake gate: is this message the one that may come now? ──
3042
+ // One table, every path, both roles, both versions (handshake_expect).
3043
+ // A message the handshake is not waiting for is unexpected_message here,
3044
+ // before any handler sees it — rather than taken by a handler that only
3045
+ // checks its own preconditions, after which the reactive loop waited for
3046
+ // a flag nothing would set: a ServerHello­Done without a ServerKeyExchange,
3047
+ // a ServerHello with a suite never offered, a second ServerHello… left a
3048
+ // client waiting forever (BoGo). The reactive loop is untouched: it still
3049
+ // decides what we send; this decides only what we take.
3050
+ {
3051
+ let gateWhy = handshake_gate(message);
3052
+ if (gateWhy) { fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, gateWhy); return; }
3053
+ }
3054
+
3055
+ // A ticket offered with no session_id (tls12_resume_maybe): the message
3056
+ // after the ServerHello says which handshake this is (RFC 5077 §3.4).
3057
+ if (!context.isServer && context.tls12_resume_maybe) {
3058
+ if (message.type === 'certificate') context.tls12_resume_maybe = false;
3059
+ else if (message.type === 'new_session_ticket' || message.type === 'finished') { if (!commit_resume12(null)) return; }
3060
+ }
3061
+
3062
+ // renegotiation_info in a first ClientHello (RFC 5746 §3.6): empty, or
3063
+ // "MUST abort the handshake" — handshake_failure. Whether the client
3064
+ // speaks it (the extension or TLS_EMPTY_RENEGOTIATION_INFO_SCSV, 0x00ff)
3065
+ // decides whether ours goes in the ServerHello.
3066
+ if (context.isServer && message.type === 'client_hello' && context.client_hellos_received === 0) {
3067
+ let ri = message.renegotiation_info;
3068
+ if (ri && ri.length > 0) {
3069
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'renegotiation_info not empty in an initial ClientHello');
3070
+ return;
3071
+ }
3072
+ context.client_secure_renegotiation = (ri !== undefined && ri !== null) ||
3073
+ (Array.isArray(message.cipher_suites) && message.cipher_suites.indexOf(0x00ff) >= 0);
3074
+ }
3075
+
3076
+ // RFC 8446 §D.5: "Any endpoint receiving a Hello message with
3077
+ // ClientHello.legacy_version or ServerHello.legacy_version set to 0x0300
3078
+ // MUST abort the handshake with a 'protocol_version' alert" — SSL 3.0 or
3079
+ // below, whatever supported_versions says. It was taken, with
3080
+ // supported_versions naming 1.3. (Over TLS: DTLS numbers its versions
3081
+ // downward, from 0xfeff.)
3082
+ if ((message.type === 'client_hello' || message.type === 'server_hello') && !dtls_transport() &&
3083
+ typeof message.legacy_version === 'number' && message.legacy_version <= 0x0300) {
3084
+ fatalAlert(wire.TLS_ALERT.PROTOCOL_VERSION, (message.type === 'client_hello' ? 'ClientHello' : 'ServerHello') +
3085
+ ' legacy_version 0x' + message.legacy_version.toString(16).padStart(4, '0') + ' (SSL 3.0 or below)');
3086
+ return;
3087
+ }
3088
+
2144
3089
  if (context.isServer && message.type === 'client_hello') {
2145
3090
  let n = context.client_hellos_received;
2146
3091
  if (!(n === 0 || (n === 1 && context.helloRetried === true && context.hello_sent === false))) {
@@ -2161,14 +3106,14 @@ function TLSSession(options){
2161
3106
  if (context.rawClientHello === null) context.rawClientHello = data;
2162
3107
  let echResult;
2163
3108
  try {
2164
- echResult = server_process_client_hello(context.ech_server, context.ech, data, context.helloRetried === true);
3109
+ echResult = server_process_client_hello(context.ech_server, context.ech, data, context.helloRetried === true, dtls_transport());
2165
3110
  } catch (e) {
2166
3111
  fatalAlert(e.alertDesc || wire.TLS_ALERT.ILLEGAL_PARAMETER, e.message);
2167
3112
  return;
2168
3113
  }
2169
3114
  if (echResult) {
2170
3115
  try {
2171
- message = parse_tls_message(echResult.data, context.selected_version);
3116
+ message = parse_tls_message(echResult.data, context.selected_version, { dtls: dtls_transport() });
2172
3117
  } catch (e) {
2173
3118
  fatalAlert(e.alertDesc || wire.TLS_ALERT.DECODE_ERROR, 'Malformed ClientHelloInner: ' + e.message);
2174
3119
  return;
@@ -2177,6 +3122,41 @@ function TLSSession(options){
2177
3122
  }
2178
3123
  }
2179
3124
 
3125
+ // Encrypted Client Hello, split mode (RFC 9849 §7.2): a server with no
3126
+ // ECH keys is the backend behind a client-facing server, and confirms a
3127
+ // ClientHelloInner it was passed (backend_client_hello). It ignored the
3128
+ // inner extension, so a client using ECH through a backend took ECH as
3129
+ // rejected (BoGo TLS-ECH-Server-ECHInner*). ECH is TLS 1.3's alone (§6.1):
3130
+ // in a hello that does not offer 1.3 the extension means nothing — and a
3131
+ // handshake that settles on an older version takes the acceptance back
3132
+ // (selected_version, set_context).
3133
+ if (context.isServer && message.type === 'client_hello' && !context.ech_server && lists13(message.supported_versions)) {
3134
+ try {
3135
+ backend_client_hello(context.ech, Array.isArray(message.extensions) ? message.extensions : [],
3136
+ message.random, context.client_hellos_received === 2);
3137
+ } catch (e) {
3138
+ fatalAlert(e.alertDesc || wire.TLS_ALERT.ILLEGAL_PARAMETER, e.message);
3139
+ return;
3140
+ }
3141
+ }
3142
+
3143
+ // The second ClientHello is the first again (RFC 8446 §4.1.2), but for
3144
+ // what the HelloRetryRequest changes: key_share, cookie, early_data
3145
+ // dropped, pre_shared_key (its ages and binders), padding. The same
3146
+ // suites, session_id, and the other extensions — the same ones, in the
3147
+ // same order, with the same bytes: illegal_parameter otherwise (BoGo,
3148
+ // OpenSSL). Its key share alone was checked; a reordered or changed
3149
+ // extension list was taken. (With ECH accepted, the inner hellos are
3150
+ // the ones compared.)
3151
+ if (context.isServer && message.type === 'client_hello') {
3152
+ let shape = ch_shape(message);
3153
+ if (context.client_hellos_received === 1) context.ch1_shape = shape;
3154
+ else if (context.client_hellos_received === 2 && context.ch1_shape) {
3155
+ let why = ch_shape_differs(context.ch1_shape, shape);
3156
+ if (why) { fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'Second ClientHello: ' + why); return; }
3157
+ }
3158
+ }
3159
+
2180
3160
  // Emit 'handshakeMessage' hook for every message
2181
3161
  ev.emit('handshakeMessage', message.type, data, message);
2182
3162
 
@@ -2205,14 +3185,14 @@ function TLSSession(options){
2205
3185
  // Never past HANDSHAKE_MESSAGE_MAX (wire.js): the declared length was
2206
3186
  // the 24-bit field's 16 MB, and a few hundred compressed bytes could
2207
3187
  // be inflated to it — in memory and time, before anything was verified.
2208
- let limit = context.maxHandshakeSize > 0 ? Math.min(context.maxHandshakeSize, wire.HANDSHAKE_MESSAGE_MAX) : wire.HANDSHAKE_MESSAGE_MAX;
2209
- let body = decompress_certificate_body(message.algorithm, message.compressed, message.uncompressed_length, limit);
3188
+ let body = decompress_certificate_body(message.algorithm, message.compressed, message.uncompressed_length, handshake_message_limit());
2210
3189
  if (!body) {
2211
3190
  fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE, 'CompressedCertificate does not decompress to its declared length');
2212
3191
  return;
2213
3192
  }
2214
3193
  let algorithm = message.algorithm;
2215
- try { message = wire.parse_certificate(body); }
3194
+ // CompressedCertificate is TLS 1.3's alone (RFC 8879 §4).
3195
+ try { message = wire.parse_certificate(body, true); }
2216
3196
  catch (e) { fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE, 'CompressedCertificate: ' + e.message); return; }
2217
3197
  message.type = 'certificate';
2218
3198
  message.compressed = true;
@@ -2221,6 +3201,16 @@ function TLSSession(options){
2221
3201
 
2222
3202
  if((context.isServer==false && message.type=='server_hello') || (context.isServer==true && message.type=='client_hello')){
2223
3203
 
3204
+ // ── Client: the ServerHello (or HelloRetryRequest) held to the
3205
+ // ClientHello, in one place, before anything is taken from it ──
3206
+ // A suite, a version, a compression method it could not have chosen
3207
+ // was taken as given — and the handshake then waited, the loop never
3208
+ // finding what it needed (BoGo: twelve hangs).
3209
+ if (!context.isServer && message.type === 'server_hello') {
3210
+ let shErr = check_server_hello(message);
3211
+ if (shErr) { fatalAlert(shErr.alert, shErr.reason); return; }
3212
+ }
3213
+
2224
3214
  // Server-side ClientHello policy checks — BEFORE the transcript push,
2225
3215
  // the 'clienthello' emit and set_context's reactive loop, because the
2226
3216
  // loop may synchronously build and send a ServerHello for a hello we
@@ -2238,10 +3228,9 @@ function TLSSession(options){
2238
3228
  // compression method: null. Enforced when 1.3 is on the table for
2239
3229
  // this negotiation (client offers it and we support it — an empty
2240
3230
  // local list means "not configured yet", which defaults to 1.3+1.2).
2241
- let sv = message.supported_versions || [];
2242
- let offers13 = sv.indexOf(wire.TLS_VERSION.TLS1_3) >= 0 || sv.indexOf(wire.DTLS_VERSION.DTLS1_3) >= 0;
3231
+ let offers13 = lists13(message.supported_versions);
2243
3232
  let lv = context.local_supported_versions || [];
2244
- let we13 = lv.length === 0 || lv.indexOf(wire.TLS_VERSION.TLS1_3) >= 0 || lv.indexOf(wire.DTLS_VERSION.DTLS1_3) >= 0;
3233
+ let we13 = lv.length === 0 || lists13(lv);
2245
3234
  if (offers13 && we13 && comp.length !== 1) {
2246
3235
  fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'TLS 1.3 ClientHello must offer exactly the null compression method');
2247
3236
  return;
@@ -2255,6 +3244,19 @@ function TLSSession(options){
2255
3244
  fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'pre_shared_key identities/binders count mismatch (' + nIds + '/' + nBinders + ')');
2256
3245
  return;
2257
3246
  }
3247
+ // ...and the last extension, its binders list the hello's last bytes
3248
+ // (§4.2.11: "MUST be the last extension", or illegal_parameter): the
3249
+ // binders are computed over the hello up to them.
3250
+ let chExts = Array.isArray(message.extensions) ? message.extensions : [];
3251
+ let lastExt = chExts[chExts.length - 1];
3252
+ let bindersLen = 0;
3253
+ for (let bi = 0; bi < nBinders; bi++) bindersLen += 1 + message.pre_shared_key.binders[bi].length;
3254
+ let ld = lastExt && lastExt.data;
3255
+ if (!lastExt || lastExt.type !== 41 || !ld || ld.length < 2 + bindersLen ||
3256
+ ((ld[ld.length - 2 - bindersLen] << 8) | ld[ld.length - 1 - bindersLen]) !== bindersLen) {
3257
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'pre_shared_key not the last extension, or its binders not the last bytes');
3258
+ return;
3259
+ }
2258
3260
  }
2259
3261
  }
2260
3262
 
@@ -2315,41 +3317,41 @@ function TLSSession(options){
2315
3317
  }
2316
3318
  let pskDheOffered = Array.isArray(message.psk_modes) && message.psk_modes.indexOf(1) >= 0;
2317
3319
  if (context.isServer && pskDheOffered && message.pre_shared_key && message.pre_shared_key.identities && message.pre_shared_key.identities.length > 0) {
2318
- let pskIdentity = message.pre_shared_key.identities[0];
2319
3320
  context.ticket_offered = true;
2320
- let pskBinder = message.pre_shared_key.binders ? message.pre_shared_key.binders[0] : null;
2321
-
2322
- dbg('SRV-PSK', 'received identity:', hexPreview(pskIdentity.identity, 24),
2323
- 'age:', (pskIdentity.age || 0) >>> 0,
2324
- 'received binder:', hexPreview(pskBinder, 16));
2325
-
2326
- // A 'psk' listener decides, when there is one and it answers. When
2327
- // nobody answers, this session opens the ticket itself — it issued it,
2328
- // with its own ticketKeys (see open_ticket_13). That default used to
2329
- // live in TLSSocket, so a TLSSession used on its own (QUIC) issued
2330
- // tickets it could never accept.
2331
- let pskResult;
2332
- ev.emit('psk', {
2333
- identity: pskIdentity.identity,
2334
- obfuscatedAge: (pskIdentity.age || 0) >>> 0
2335
- }, function(result) {
2336
- pskResult = result;
2337
- });
2338
- if (pskResult === undefined) pskResult = open_ticket_13(pskIdentity.identity);
2339
-
2340
- dbg('SRV-PSK', 'pskResult:', pskResult ? `psk=${hexPreview(pskResult.psk, 8)} cipher=0x${pskResult.cipher?.toString(16)}` : 'null (decrypt failed)');
2341
-
2342
- if (pskResult && pskResult.psk && !same_server_name(pskResult.sni, message.sni)) {
2343
- dbg('SRV-PSK', 'ticket for another server name — full handshake');
2344
- pskResult = null;
3321
+ // The first identity offered that this server can use (RFC 8446
3322
+ // §4.2.11: the client lists them, the server selects one) — a client
3323
+ // with a ticket and an external PSK sends both. Only the first was
3324
+ // looked at: with its ticket ahead of the PSK, the PSK was never
3325
+ // used. Its binder is the one at the same index.
3326
+ let pskIdentity = null, pskBinder = null, pskResult = null, pskIndex = -1;
3327
+ let offered = message.pre_shared_key.identities;
3328
+ for (let k = 0; k < offered.length && pskIndex < 0; k++) {
3329
+ let r = psk_for_identity(offered[k]);
3330
+ if (r && r.psk && !same_server_name(r.sni, message.sni)) {
3331
+ dbg('SRV-PSK', 'ticket for another server name — not used');
3332
+ r = null;
3333
+ }
3334
+ if (r && r.psk) {
3335
+ pskIdentity = offered[k];
3336
+ pskBinder = message.pre_shared_key.binders ? message.pre_shared_key.binders[k] : null;
3337
+ pskResult = r;
3338
+ pskIndex = k;
3339
+ }
2345
3340
  }
2346
- if (pskResult && pskResult.psk) {
3341
+ if (pskResult) {
2347
3342
  let pskCipher = pskResult.cipher || 0x1301;
2348
3343
  let hashName = TLS_CIPHER_SUITES[pskCipher] ? TLS_CIPHER_SUITES[pskCipher].hash : 'sha256';
2349
- let binder_key = derive_binder_key(hashName, pskResult.psk, false, label_prefix());
3344
+ let binder_key = derive_binder_key(hashName, pskResult.psk, pskResult.external === true, label_prefix());
2350
3345
 
2351
3346
  let hashLen = getHashFn(hashName).outputLen;
2352
- let bindersSize = 2 + 1 + hashLen;
3347
+ // The binders list, as it is on the wire, ends the hello (§4.2.11:
3348
+ // pre_shared_key is last): its 2-byte length, then each binder with
3349
+ // its 1-byte length. Taken as one binder of hashLen, as it was, a
3350
+ // client offering two tickets (h3spec does; a client that keeps
3351
+ // every ticket it is given does) never matched: always a full
3352
+ // handshake, never 0-RTT.
3353
+ let bindersSize = 2;
3354
+ for (let bi = 0; bi < message.pre_shared_key.binders.length; bi++) bindersSize += 1 + message.pre_shared_key.binders[bi].length;
2353
3355
  // After a HelloRetryRequest the binder covers message_hash and the
2354
3356
  // retry too (§4.2.11.2): what the transcript holds before this hello.
2355
3357
  let truncatedCH = data.slice(0, data.length - bindersSize);
@@ -2361,22 +3363,38 @@ function TLSSession(options){
2361
3363
  dbg('SRV-PSK', 'hash:', hashName, 'hashLen:', hashLen,
2362
3364
  'truncatedCH len:', truncatedCH.length,
2363
3365
  'full CH len:', data.length);
2364
- dbg('SRV-PSK', 'expected binder:', hexPreview(expectedBinder, 16));
2365
- dbg('SRV-PSK', 'received binder:', hexPreview(pskBinder, 16));
3366
+ if (LEMON_DEBUG) dbg('SRV-PSK', 'expected binder:', hexPreview(expectedBinder, 16));
3367
+ if (LEMON_DEBUG) dbg('SRV-PSK', 'received binder:', hexPreview(pskBinder, 16));
2366
3368
 
2367
3369
  // Constant-time binder comparison. A byte-by-byte early-exit compare
2368
3370
  // would let an attacker recover a valid binder via timing, one byte at
2369
3371
  // a time. timingSafeEqualU8 always compares the full length.
2370
3372
  let binderOk = timingSafeEqualU8(expectedBinder, pskBinder);
2371
3373
 
2372
- dbg('SRV-PSK', binderOk ? '✓ BINDER MATCH — psk_accepted' : '✗ BINDER MISMATCH — full handshake');
3374
+ dbg('SRV-PSK', binderOk ? '✓ BINDER MATCH — psk_accepted' : '✗ BINDER MISMATCH — decrypt_error');
3375
+
3376
+ // A ticket of ours, opened, whose binder does not verify: the
3377
+ // handshake ends (RFC 8446 §4.2.11: "MUST abort", decrypt_error) —
3378
+ // the hello was changed on the way, or the client does not hold the
3379
+ // PSK. It went on as a full handshake, which hid exactly the bug that
3380
+ // made every two-ticket hello miss. A ticket that cannot be opened
3381
+ // (expired, another key, another server) is still just not used.
3382
+ if (!binderOk) {
3383
+ fatalAlert(wire.TLS_ALERT.DECRYPT_ERROR, 'PSK binder does not verify');
3384
+ return;
3385
+ }
2373
3386
 
2374
3387
  if (binderOk) {
2375
3388
  context.psk_accepted = true;
2376
- context.isResumed = true;
2377
- context.resumed_ticket_data = pskResult.data != null ? pskResult.data : null;
2378
- context.resumed_ticket_state = pskResult.state != null ? pskResult.state : null;
2379
- if (pskResult.peer) restore_ticket_peer(pskResult.peer);
3389
+ context.psk_selected = pskIndex;
3390
+ if (pskResult.external) {
3391
+ psk_authenticated_peer(new Uint8Array(pskIdentity.identity));
3392
+ } else {
3393
+ context.isResumed = true;
3394
+ context.resumed_ticket_data = pskResult.data != null ? pskResult.data : null;
3395
+ context.resumed_ticket_state = pskResult.state != null ? pskResult.state : null;
3396
+ if (pskResult.peer) restore_ticket_peer(pskResult.peer);
3397
+ }
2380
3398
  context.psk_offered = {
2381
3399
  psk: pskResult.psk instanceof Uint8Array ? pskResult.psk : new Uint8Array(pskResult.psk),
2382
3400
  cipher: pskCipher,
@@ -2384,14 +3402,24 @@ function TLSSession(options){
2384
3402
  // (RFC 8446 §4.2.11), not the exact suite the ticket was issued
2385
3403
  // under. Stored here so selection does not have to re-derive it.
2386
3404
  hash: hashName,
3405
+ external: pskResult.external === true,
2387
3406
  };
2388
- if ('early_data' in message) early_consider(pskResult, pskIdentity, hashName);
3407
+ // 0-RTT only under the first identity (RFC 8446 §4.2.10).
3408
+ if ('early_data' in message && pskIndex === 0) early_consider(pskResult, pskIdentity, hashName);
2389
3409
  }
2390
3410
  }
2391
3411
  }
2392
3412
 
2393
3413
  // Client: detect if server accepted PSK from ServerHello (BEFORE set_context)
2394
3414
  if (!context.isServer && message.pre_shared_key && typeof message.pre_shared_key.selected === 'number') {
3415
+ // ECH rejected: the outer hello's PSK identity was a decoy (§6.1.2),
3416
+ // and a server that picks it — or any — is not one to go on with:
3417
+ // "the client MUST abort the handshake with an illegal_parameter
3418
+ // alert" (RFC 9849 §6.1.2). It went on, to ech_required at the end.
3419
+ if (ech_rejected_client()) {
3420
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'ECH rejected, and the ServerHello selects a pre_shared_key (RFC 9849 §6.1.2)');
3421
+ return;
3422
+ }
2395
3423
  // RFC 8446 §4.2.11: the server picks one of the identities offered
2396
3424
  // (one, here), with a suite of the PSK's hash — anything else is
2397
3425
  // illegal_parameter. A pre_shared_key nobody offered is an
@@ -2409,14 +3437,19 @@ function TLSSession(options){
2409
3437
  }
2410
3438
  dbg('CLI-PSK', '✓ server accepted PSK, selected_identity:', message.pre_shared_key.selected);
2411
3439
  context.psk_accepted = true;
2412
- context.isResumed = true;
2413
- restore_client_session_peer(context.psk_offered.session);
3440
+ if (context.psk_offered.external) {
3441
+ psk_authenticated_peer(context.psk_offered.identity);
3442
+ } else {
3443
+ context.isResumed = true;
3444
+ restore_client_session_peer(context.psk_offered.session);
3445
+ }
2414
3446
  } else if (!context.isServer && context.psk_offered && message.type === 'server_hello') {
2415
3447
  dbg('CLI-PSK', '✗ server did NOT include pre_shared_key in SH — full handshake');
2416
3448
  }
2417
3449
 
2418
3450
  // Client: detect HelloRetryRequest (ServerHello with magic random)
2419
3451
  if (!context.isServer && message.random && uint8Equal(message.random, wire.TLS13_HRR_RANDOM)) {
3452
+ if (reject_unsolicited_extensions(message, 'HelloRetryRequest', [wire.TLS_EXT.COOKIE])) return;
2420
3453
  context.helloRetried = true;
2421
3454
  early_client_result(false); // §4.2.10: no early data after a HelloRetryRequest
2422
3455
 
@@ -2513,10 +3546,18 @@ function TLSSession(options){
2513
3546
  // decoding ClientHello message"). Leave the DTLS field alone.
2514
3547
  });
2515
3548
 
2516
- let firstGroup = context.local_supported_groups[0];
2517
- let firstShare = context.local_key_groups[firstGroup]
2518
- ? context.local_key_groups[firstGroup].public_key : null;
2519
- send_second_client_hello(firstGroup, firstShare, hrrCookie);
3549
+ // A retry for the cookie alone: the second hello is the first
3550
+ // with the cookie (RFC 8446 §4.1.2) — every key share it had. Only
3551
+ // the first was kept: an X25519MLKEM768 + X25519 hello came back
3552
+ // with the hybrid share alone.
3553
+ let ks = context.ch1_key_shares;
3554
+ if (ks) send_second_client_hello(ks.group, ks.key_exchange, hrrCookie, ks.extra);
3555
+ else {
3556
+ let firstGroup = context.local_supported_groups[0];
3557
+ let firstShare = context.local_key_groups[firstGroup]
3558
+ ? context.local_key_groups[firstGroup].public_key : null;
3559
+ send_second_client_hello(firstGroup, firstShare, hrrCookie);
3560
+ }
2520
3561
  return;
2521
3562
  }
2522
3563
 
@@ -2603,11 +3644,9 @@ function TLSSession(options){
2603
3644
  // the decision on the message itself, which is authoritative.
2604
3645
  let sh_is_13 = false;
2605
3646
  if (Array.isArray(message.supported_versions)) {
2606
- sh_is_13 = message.supported_versions.indexOf(wire.TLS_VERSION.TLS1_3) >= 0 ||
2607
- message.supported_versions.indexOf(wire.DTLS_VERSION.DTLS1_3) >= 0;
3647
+ sh_is_13 = lists13(message.supported_versions);
2608
3648
  } else if (typeof message.supported_versions === 'number') {
2609
- sh_is_13 = message.supported_versions === wire.TLS_VERSION.TLS1_3 ||
2610
- message.supported_versions === wire.DTLS_VERSION.DTLS1_3;
3649
+ sh_is_13 = wire.is_tls13_wire(message.supported_versions);
2611
3650
  }
2612
3651
 
2613
3652
  // ── Second ServerHello must honour the HelloRetryRequest ──
@@ -2673,7 +3712,38 @@ function TLSSession(options){
2673
3712
  }
2674
3713
  }
2675
3714
 
2676
- if (sh_is_13 && reject_unsolicited_extensions(message, 'ServerHello')) return;
3715
+ // Every version: an extension we did not ask for is unsupported_extension
3716
+ // (RFC 8446 §4.2, RFC 5246 §7.4.1.4).
3717
+ if (reject_unsolicited_extensions(message, 'ServerHello')) return;
3718
+
3719
+ // record_size_limit: the client's (ClientHello), or the server's answer
3720
+ // (a TLS 1.2 ServerHello; 1.3's comes in EncryptedExtensions).
3721
+ if (!take_record_size_limit(message.extensions)) return;
3722
+ if (!take_connection_id(message.extensions)) return;
3723
+
3724
+ if (!context.isServer && message.type === 'server_hello') {
3725
+ if (sh_is_13) {
3726
+ // A TLS 1.3 ServerHello carries key establishment only (RFC 8446
3727
+ // §4.2's table); one we offered but that belongs in
3728
+ // EncryptedExtensions is illegal_parameter.
3729
+ // And connection_id: in the ServerHello in DTLS 1.3 too (RFC 9147 §9).
3730
+ let shOnly = [wire.TLS_EXT.SUPPORTED_VERSIONS, wire.TLS_EXT.KEY_SHARE, wire.TLS_EXT.PRE_SHARED_KEY, wire.TLS_EXT.CONNECTION_ID];
3731
+ let exts = Array.isArray(message.extensions) ? message.extensions : [];
3732
+ for (let xi = 0; xi < exts.length; xi++) {
3733
+ let xt = exts[xi] && exts[xi].type;
3734
+ if (typeof xt === 'number' && !is_grease_u16(xt) && shOnly.indexOf(xt) < 0) {
3735
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
3736
+ 'A TLS 1.3 ServerHello may not carry extension ' + xt);
3737
+ return;
3738
+ }
3739
+ }
3740
+ } else if (message.alpn !== undefined && message.alpn !== null) {
3741
+ // TLS 1.2: the ALPN answer is in the ServerHello itself.
3742
+ let alpnChosen = server_alpn_choice(message.alpn);
3743
+ if (alpnChosen === null) return;
3744
+ set_context({ selected_alpn: alpnChosen });
3745
+ }
3746
+ }
2677
3747
 
2678
3748
  // ── legacy_session_id_echo (RFC 8446 §4.1.3) ──
2679
3749
  // "A client which receives a legacy_session_id_echo field that does not
@@ -2754,14 +3824,38 @@ function TLSSession(options){
2754
3824
  // a handshake in a group it had not agreed to — and of two shares for
2755
3825
  // one group the first was taken, the second silently ignored: two
2756
3826
  // implementations reading one ClientHello two ways.
2757
- if (context.isServer === true && message.type === 'client_hello' &&
2758
- Array.isArray(message.key_groups) && message.key_groups.length > 0) {
2759
- // §9.2: "If containing a 'key_share' extension, it MUST also contain
2760
- // a 'supported_groups' extension" — missing_extension otherwise.
2761
- if (!Array.isArray(message.supported_groups)) {
3827
+ // §9.2: "If containing a 'supported_groups' extension, it MUST also
3828
+ // contain a 'key_share' extension, and vice versa. An empty
3829
+ // KeyShare.client_shares vector is permitted" — missing_extension
3830
+ // otherwise. Present is what counts, empty included: an empty key_share
3831
+ // with no supported_groups was answered with a HelloRetryRequest. The
3832
+ // other way round only for a hello that offers TLS 1.3 to a server that
3833
+ // speaks it: a TLS 1.2 client sends supported_groups alone.
3834
+ if (context.isServer === true && message.type === 'client_hello') {
3835
+ let hasShares = Array.isArray(message.key_groups);
3836
+ let hasGroups = Array.isArray(message.supported_groups);
3837
+ let lv13 = context.local_supported_versions || [];
3838
+ let both13 = lists13(message.supported_versions) && (lv13.length === 0 || lists13(lv13));
3839
+ if (hasShares && !hasGroups) {
2762
3840
  fatalAlert(wire.TLS_ALERT.MISSING_EXTENSION, 'ClientHello has key_share without supported_groups');
2763
3841
  return;
2764
3842
  }
3843
+ if (hasGroups && !hasShares && both13) {
3844
+ fatalAlert(wire.TLS_ALERT.MISSING_EXTENSION, 'ClientHello offering TLS 1.3 has supported_groups without key_share');
3845
+ return;
3846
+ }
3847
+ // Neither, and no pre_shared_key: "If not containing a
3848
+ // 'pre_shared_key' extension, it MUST contain both [...]
3849
+ // 'signature_algorithms' [...] and 'supported_groups'" (§9.2). With
3850
+ // nothing to agree a key on, nothing was sent at all — no ServerHello,
3851
+ // no alert — until the client's own timeout.
3852
+ if (!hasGroups && !hasShares && both13 && !message.pre_shared_key) {
3853
+ fatalAlert(wire.TLS_ALERT.MISSING_EXTENSION, 'ClientHello offering TLS 1.3 has no supported_groups (nor key_share)');
3854
+ return;
3855
+ }
3856
+ }
3857
+ if (context.isServer === true && message.type === 'client_hello' &&
3858
+ Array.isArray(message.key_groups) && message.key_groups.length > 0) {
2765
3859
  let offered = message.supported_groups;
2766
3860
  let seenShare = {};
2767
3861
  for (let ki = 0; ki < message.key_groups.length; ki++) {
@@ -2847,50 +3941,17 @@ function TLSSession(options){
2847
3941
  sniSync = false;
2848
3942
  }
2849
3943
 
2850
- set_context({
2851
- remote_random: message.random || null,
2852
- remote_sni: message.sni || null,
2853
- remote_session_id: message.session_id || null,
2854
- remote_supported_versions: (message.supported_versions && message.supported_versions.length > 0)
2855
- ? message.supported_versions
2856
- : (message.legacy_version ? [message.legacy_version] : []),
2857
- remote_supported_alpns: message.alpn || [],
2858
- remote_supported_cipher_suites: message.cipher_suites || [],
2859
- remote_supported_signature_algorithms: message.signature_algorithms || [],
2860
- remote_supported_groups: message.supported_groups || [],
2861
- remote_extensions: message.extensions || [],
2862
- add_remote_key_groups: message.key_groups || []
2863
- });
2864
-
2865
- // RFC 8446 §4.1.3: downgrade-protection check (client side).
2866
- // If we offered TLS 1.3 but the server steered us to a lower version, the
2867
- // server's random must NOT carry the downgrade sentinel — if it does, an
2868
- // active attacker forced the downgrade. HRR was already handled and
2869
- // returned above, so `message` here is a genuine ServerHello.
2870
- if (!context.isServer && message.type === 'server_hello' &&
2871
- context.local_supported_versions.indexOf(wire.TLS_VERSION.TLS1_3) >= 0 &&
2872
- context.selected_version !== null &&
2873
- context.selected_version !== wire.TLS_VERSION.TLS1_3 &&
2874
- context.selected_version !== wire.DTLS_VERSION.DTLS1_3 &&
2875
- message.random && message.random.length === 32) {
2876
-
2877
- let tail = message.random.subarray(24, 32);
2878
- if (timingSafeEqualU8(tail, DOWNGRADE_SENTINEL_TLS12) ||
2879
- timingSafeEqualU8(tail, DOWNGRADE_SENTINEL_TLS11)) {
2880
- dbg('DOWNGRADE', 'sentinel detected in ServerHello.random — aborting');
2881
- // Same abort funnel as everything else (fatalAlert = alert + terminal
2882
- // state + 'error'); the hand-rolled pair here predated it and was the
2883
- // one abort path that could drift out of sync with the rest.
2884
- fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
2885
- 'TLS downgrade attack detected (RFC 8446 §4.1.3 sentinel present)');
2886
- return;
2887
- }
2888
- }
2889
-
2890
3944
  // Server: TLS 1.2 resumption detection (only makes sense from ClientHello).
2891
3945
  // This runs BEFORE set_context's reactive loop picks a version, so we mark state
2892
3946
  // but defer the decision. The reactive loop will check tls12_abbreviated once
2893
3947
  // TLS 1.2 is actually selected.
3948
+ //
3949
+ // BEFORE the set_context below, which hands the loop the client's
3950
+ // offer: the loop may settle the version and the cipher suite in that
3951
+ // very pass (a DTLS 1.2-only server does — its version is known up
3952
+ // front), and the abbreviated handshake is decided in the pass that
3953
+ // picks the suite (the stored one). Read after it, the ticket came too
3954
+ // late: a valid one was accepted and the handshake went full anyway.
2894
3955
  if (context.isServer && message.type === 'client_hello') {
2895
3956
 
2896
3957
  // Was SessionTicket extension present? (empty or with data)
@@ -2948,13 +4009,69 @@ function TLSSession(options){
2948
4009
  // If no state resolved → full handshake. Reactive loop continues once pending clears.
2949
4010
  };
2950
4011
 
2951
- context.tls12_resume_pending = true;
2952
- ev.emit('resumeSession', offeredId, resumeCb);
4012
+ context.tls12_resume_pending = true;
4013
+ ev.emit('resumeSession', offeredId, resumeCb);
4014
+
4015
+ // If nobody listened (listenerCount === 0), immediately un-pend.
4016
+ if (ev.listenerCount('resumeSession') === 0) {
4017
+ resumeCb(null, null);
4018
+ }
4019
+ }
4020
+ }
4021
+
4022
+ // The second ClientHello, after a HelloRetryRequest that asked for a
4023
+ // group: its key_share holds that group's share and no other
4024
+ // (RFC 8446 §4.1.4, §4.2.8 — "illegal_parameter" otherwise). One for
4025
+ // another group left the server waiting, ServerHello held for a share
4026
+ // that was never coming (BoGo SecondClientHelloWrongCurve-TLS13).
4027
+ if (context.isServer && message.type === 'client_hello' && context.client_hellos_received === 2 &&
4028
+ context.hrr_sent_group !== null && context.hrr_sent_group !== undefined) {
4029
+ let kg = Array.isArray(message.key_groups) ? message.key_groups : [];
4030
+ if (kg.length !== 1 || kg[0].group !== context.hrr_sent_group) {
4031
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
4032
+ 'Second ClientHello does not carry (only) a key share for group 0x' +
4033
+ (context.hrr_sent_group >>> 0).toString(16) + ', which the HelloRetryRequest asked for');
4034
+ return;
4035
+ }
4036
+ }
4037
+
4038
+ set_context({
4039
+ remote_random: message.random || null,
4040
+ remote_sni: message.sni || null,
4041
+ remote_session_id: message.session_id || null,
4042
+ remote_supported_versions: (message.supported_versions && message.supported_versions.length > 0)
4043
+ ? message.supported_versions
4044
+ : (message.legacy_version ? [message.legacy_version] : []),
4045
+ remote_supported_alpns: message.alpn || [],
4046
+ remote_supported_cipher_suites: message.cipher_suites || [],
4047
+ remote_supported_signature_algorithms: message.signature_algorithms || [],
4048
+ remote_supported_groups: message.supported_groups || [],
4049
+ remote_extensions: message.extensions || [],
4050
+ add_remote_key_groups: message.key_groups || []
4051
+ });
4052
+
4053
+ // RFC 8446 §4.1.3: downgrade-protection check (client side).
4054
+ // If we offered TLS 1.3 but the server steered us to a lower version, the
4055
+ // server's random must NOT carry the downgrade sentinel — if it does, an
4056
+ // active attacker forced the downgrade. HRR was already handled and
4057
+ // returned above, so `message` here is a genuine ServerHello.
4058
+ if (!context.isServer && message.type === 'server_hello' &&
4059
+ lists13(context.local_supported_versions) &&
4060
+ context.selected_version !== null &&
4061
+ context.selected_version !== wire.TLS_VERSION.TLS1_3 &&
4062
+ context.selected_version !== wire.DTLS_VERSION.DTLS1_3 &&
4063
+ message.random && message.random.length === 32) {
2953
4064
 
2954
- // If nobody listened (listenerCount === 0), immediately un-pend.
2955
- if (ev.listenerCount('resumeSession') === 0) {
2956
- resumeCb(null, null);
2957
- }
4065
+ let tail = message.random.subarray(24, 32);
4066
+ if (timingSafeEqualU8(tail, DOWNGRADE_SENTINEL_TLS12) ||
4067
+ timingSafeEqualU8(tail, DOWNGRADE_SENTINEL_TLS11)) {
4068
+ dbg('DOWNGRADE', 'sentinel detected in ServerHello.random — aborting');
4069
+ // Same abort funnel as everything else (fatalAlert = alert + terminal
4070
+ // state + 'error'); the hand-rolled pair here predated it and was the
4071
+ // one abort path that could drift out of sync with the rest.
4072
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
4073
+ 'TLS downgrade attack detected (RFC 8446 §4.1.3 sentinel present)');
4074
+ return;
2958
4075
  }
2959
4076
  }
2960
4077
 
@@ -2972,7 +4089,7 @@ function TLSSession(options){
2972
4089
  let sentSid = context.local_session_id;
2973
4090
  let hasTicket = context.tls12_client_session.ticket && context.tls12_client_session.ticket.length > 0;
2974
4091
 
2975
- dbg('CLI-12RESUME', 'saved sid:', hexPreview(savedSid, 16),
4092
+ if (LEMON_DEBUG) dbg('CLI-12RESUME', 'saved sid:', hexPreview(savedSid, 16),
2976
4093
  'sent sid:', hexPreview(sentSid, 16),
2977
4094
  'received sid:', hexPreview(message.session_id, 16),
2978
4095
  'hasTicket:', hasTicket);
@@ -2994,25 +4111,36 @@ function TLSSession(options){
2994
4111
  dbg('CLI-12RESUME', '✗ no match — full handshake expected');
2995
4112
  }
2996
4113
 
2997
- if (abbreviatedDetected) {
2998
- context.tls12_abbreviated = true;
2999
- context.isResumed = true;
3000
- restore_client_session_peer(context.tls12_client_session);
3001
- // Load master_secret and EMS flag from saved session
3002
- set_context({
3003
- base_secret: context.tls12_client_session.master_secret,
3004
- use_extended_master_secret: !!context.tls12_client_session.extended_master_secret,
3005
- // Mark as if remote_hello_done arrived — we won't actually receive it in abbreviated flow,
3006
- // but the reactive loop uses this to gate CKE; we're skipping CKE anyway.
3007
- remote_hello_done: true,
3008
- // Pretend key_exchange_sent so Finished logic proceeds without real CKE
3009
- key_exchange_sent: true,
3010
- });
3011
- }
4114
+ if (abbreviatedDetected && !commit_resume12(message)) return;
4115
+ }
4116
+
4117
+ // Case (c): the ticket went with no session_id (a DTLS hello offering
4118
+ // 1.3 too): whatever the ServerHello's session_id, the message after
4119
+ // it decides (RFC 5077 §3.4) — a Certificate, a full handshake; a
4120
+ // NewSessionTicket or the Finished (in DTLS, its first epoch-1 record,
4121
+ // which only the resumed keys open: resumeCandidate12), the ticket
4122
+ // taken. A ServerHello that cannot be a resumption of it (another
4123
+ // suite, extended_master_secret otherwise) is a full handshake.
4124
+ if (!context.isServer && context.tls12_client_session && context.tls12_ticket_blind &&
4125
+ message.type === 'server_hello' && !context.tls12_abbreviated &&
4126
+ Array.isArray(message.supported_versions) && wire.is_tls12_wire(message.supported_versions[0])) {
4127
+ context.tls12_resume_maybe = resume12_mismatch(context.tls12_client_session, hello_cipher_suite(message)) === null;
3012
4128
  }
3013
4129
 
3014
4130
  ev.emit('hello');
3015
4131
 
4132
+ // A server decides nothing before 'hello' has been heard: its lists come
4133
+ // from the application — at construction (TLSSocket, DTLSSession), or
4134
+ // in its 'hello' listener (a bare TLSSession: QUIC) — and the defaults
4135
+ // fill what it left empty, now. Filled at the ClientHello, they let the
4136
+ // server answer before 'hello' came: QUIC's transport parameters and
4137
+ // ALPN missed the EncryptedExtensions.
4138
+ if (context.isServer) {
4139
+ fill_default_lists();
4140
+ context.server_configured = true;
4141
+ set_context({ run_loop: true });
4142
+ }
4143
+
3016
4144
 
3017
4145
 
3018
4146
 
@@ -3035,12 +4163,6 @@ function TLSSession(options){
3035
4163
  return;
3036
4164
  }
3037
4165
 
3038
- let skePubKey = peer_leaf_public_key();
3039
- if (!skePubKey) {
3040
- fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE, 'Cannot read server certificate public key');
3041
- return;
3042
- }
3043
-
3044
4166
  // Rebuild the exact signed payload: randoms in wire order (client
3045
4167
  // first) followed by the ServerECDHParams as they appeared.
3046
4168
  let ecdhParams = wire.build_server_ecdh_params(message.group, message.public_key);
@@ -3050,28 +4172,22 @@ function TLSSession(options){
3050
4172
  ecdhParams
3051
4173
  ]);
3052
4174
 
3053
- let skeOk = verify_with_scheme(
3054
- wire.TLS_VERSION.TLS1_2,
3055
- message.sig_alg,
3056
- skeTbs,
3057
- skePubKey,
3058
- message.signature
3059
- );
3060
-
3061
- // Same strict test as the CertificateVerify gate: fail closed.
3062
- if (skeOk !== true) {
3063
- fatalAlert(wire.TLS_ALERT.DECRYPT_ERROR, 'ServerKeyExchange signature verification failed');
3064
- return;
3065
- }
3066
-
3067
- context.peerSignatureVerified = true;
3068
- context.peerSignatureScheme = message.sig_alg;
4175
+ let skeBad = check_peer_signature(wire.TLS_VERSION.TLS1_2, message.sig_alg, skeTbs, message.signature, 'ServerKeyExchange');
4176
+ if (skeBad) { fatalAlert(skeBad.alert, skeBad.reason); return; }
3069
4177
  }
3070
4178
 
3071
4179
  if (is_ecdhe_suite(context.selected_cipher_suite)) {//ECDHE
3072
4180
 
3073
4181
  // ServerKeyExchange carries the group; ClientKeyExchange does not (server already chose it)
3074
4182
  let kex_group = message.group || context.selected_group;
4183
+ // A group we offered (RFC 8422 §5.4: from the client's
4184
+ // supported_groups) — one we cannot compute with left the client
4185
+ // waiting for a key pair that never came.
4186
+ if (message.type === 'server_key_exchange' && !context.isServer &&
4187
+ (context.local_supported_groups || []).indexOf(kex_group) < 0) {
4188
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'ServerKeyExchange in group 0x' + ((kex_group || 0) >>> 0).toString(16) + ', which we did not offer');
4189
+ return;
4190
+ }
3075
4191
 
3076
4192
  let kex_updates = {
3077
4193
  add_remote_key_groups: [
@@ -3088,16 +4204,6 @@ function TLSSession(options){
3088
4204
  }
3089
4205
  set_context(kex_updates);
3090
4206
 
3091
- }else if ([0x009E,0x009F,0x0033,0x0039,0x0067,0x006B].includes(context.selected_cipher_suite)==true) {//DHE
3092
-
3093
- let client_dh_y=message.body.slice(2);
3094
-
3095
- }else if ([0x002F,0x0035,0x003C,0x003D,0x0005,0x000A].includes(context.selected_cipher_suite)==true) {//RSA
3096
-
3097
- let enc_pms=message.body.slice(2);
3098
-
3099
- }else if ([0xC004,0xC005,0xC00B,0xC00C].includes(context.selected_cipher_suite)==true) {//ECDH
3100
-
3101
4207
  }
3102
4208
 
3103
4209
  }else if(message.type=='server_hello_done'){
@@ -3144,6 +4250,8 @@ function TLSSession(options){
3144
4250
  }
3145
4251
  }
3146
4252
 
4253
+ if (!take_record_size_limit(message.extensions)) return;
4254
+
3147
4255
  // ECH retry_configs (RFC 9849 §6.1.6): kept when ECH was rejected — a
3148
4256
  // well-formed ECHConfigList, or decode_error. After an acceptance the
3149
4257
  // server has no reason to send them (§6.1.4: unsupported_extension).
@@ -3211,20 +4319,9 @@ function TLSSession(options){
3211
4319
  // which for HTTP/2 means it cannot be used at all (RFC 9113 §3.2).
3212
4320
  let eeUpdate = { remote_supported_groups: message.supported_groups || [] };
3213
4321
  if (message.alpn !== undefined && message.alpn !== null) {
3214
- // The extension carries a list, but a server names exactly one
3215
- // protocol in its answer (RFC 7301 §3.2).
3216
- let chosenAlpn = Array.isArray(message.alpn) ? message.alpn[0] : message.alpn;
3217
- if (typeof chosenAlpn === 'string' && chosenAlpn.length > 0) {
3218
- // A server may only select something we offered; anything else is
3219
- // unnegotiable and must not be accepted.
3220
- if (context.local_supported_alpns &&
3221
- context.local_supported_alpns.indexOf(chosenAlpn) < 0) {
3222
- fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
3223
- 'Server selected an ALPN protocol that was not offered: ' + chosenAlpn);
3224
- return;
3225
- }
3226
- eeUpdate.selected_alpn = chosenAlpn;
3227
- }
4322
+ let chosenAlpn = server_alpn_choice(message.alpn);
4323
+ if (chosenAlpn === null) return;
4324
+ eeUpdate.selected_alpn = chosenAlpn;
3228
4325
  }
3229
4326
  set_context(eeUpdate);
3230
4327
 
@@ -3251,6 +4348,25 @@ function TLSSession(options){
3251
4348
 
3252
4349
  }else if(message.type=='certificate'){
3253
4350
 
4351
+ // A client sends a Certificate only when asked for one (RFC 8446
4352
+ // §4.4.2, RFC 5246 §7.4.6): unasked, unexpected_message. It was taken,
4353
+ // checked and kept — a peer certificate the server never wanted.
4354
+ if (context.isServer && !context.certificateRequestSent) {
4355
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'Certificate from a client that was not asked for one');
4356
+ return;
4357
+ }
4358
+
4359
+ // TLS 1.3 (RFC 8446 §4.4.2): the request context of a handshake
4360
+ // Certificate is empty — a server's always, a client's because the
4361
+ // CertificateRequest it answers had an empty one (ours do).
4362
+ if (is13()) {
4363
+ let certCtx = message.request_context || new Uint8Array(0);
4364
+ if (certCtx.length > 0) {
4365
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER, 'Certificate in the handshake with a non-empty certificate_request_context');
4366
+ return;
4367
+ }
4368
+ }
4369
+
3254
4370
  pushTranscript(data);
3255
4371
 
3256
4372
  let entries = message.entries || [];
@@ -3292,6 +4408,19 @@ function TLSSession(options){
3292
4408
  context.peerAuthorized = false; // no set_context setter for this field
3293
4409
  set_context({ remote_cert_chain: [] });
3294
4410
  } else {
4411
+ // The leaf must be a certificate at all: bad_certificate (RFC 8446
4412
+ // §6.2, RFC 5246 §7.2.2), whatever rejectUnauthorized says — there
4413
+ // is no key to verify the handshake's signature with. A leaf of a
4414
+ // byte or two of junk was taken without rejectUnauthorized, and the
4415
+ // handshake then failed at the CertificateVerify, as
4416
+ // unexpected_message (tlsfuzzer test-certificate-malformed). Parsed
4417
+ // here once, and kept for the checks after it (peer_leaf_cert).
4418
+ let leafCert = _cert(entries[0].cert);
4419
+ if (!leafCert) {
4420
+ fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE, 'The peer\'s certificate is not an X.509 certificate');
4421
+ return;
4422
+ }
4423
+ peer_leaf = { der: entries[0].cert, cert: leafCert };
3295
4424
  set_context({
3296
4425
  remote_cert_chain: entries,
3297
4426
  });
@@ -3300,13 +4429,42 @@ function TLSSession(options){
3300
4429
  validatePeerCertificate();
3301
4430
  if (context.rejectUnauthorized && !context.peerAuthorized) {
3302
4431
  fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE,
3303
- 'Peer certificate validation failed: ' + (context.authorizationError || 'unknown'));
4432
+ 'Peer certificate validation failed: ' + (context.authorizationError || 'unknown'),
4433
+ context.authorizationError || undefined);
4434
+ return;
4435
+ }
4436
+
4437
+ // The leaf's key will sign this handshake (CertificateVerify, or the
4438
+ // TLS 1.2 ServerKeyExchange), so its certificate must allow signing
4439
+ // (RFC 8446 §4.4.2.2, RFC 5280 §4.2.1.3) — whether or not the chain
4440
+ // is trusted: this is about what the key may do, not who vouches.
4441
+ if (cert_allows_signing(entries[0].cert) === false) {
4442
+ fatalAlert(wire.TLS_ALERT.UNSUPPORTED_CERTIFICATE,
4443
+ 'The peer certificate\'s keyUsage does not allow digitalSignature');
3304
4444
  return;
3305
4445
  }
4446
+
4447
+ // TLS 1.2 client (RFC 8422 §5.1.1): the server's ECDSA key must be
4448
+ // on a curve we named in supported_groups.
4449
+ if (!context.isServer && is12()) {
4450
+ let leafKey = peer_leaf_public_key();
4451
+ let leafGroup = leafKey ? ec_key_group(leafKey) : null;
4452
+ if (leafGroup !== null && (context.local_supported_groups || []).indexOf(leafGroup) < 0) {
4453
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
4454
+ 'The server\'s ECDSA certificate is on a curve we did not offer');
4455
+ return;
4456
+ }
4457
+ }
3306
4458
  }
3307
4459
 
3308
4460
  }else if(message.type=='certificate_verify'){
3309
4461
 
4462
+ // Likewise its CertificateVerify, and only after a certificate.
4463
+ if (context.isServer && (!context.certificateRequestSent || !context.remote_cert_chain || context.remote_cert_chain.length === 0)) {
4464
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'CertificateVerify from a client with no certificate asked for or sent');
4465
+ return;
4466
+ }
4467
+
3310
4468
  // RFC 8446 §4.4.3 — verify the peer's handshake signature.
3311
4469
  //
3312
4470
  // This is the step that actually authenticates the peer: without it,
@@ -3337,52 +4495,32 @@ function TLSSession(options){
3337
4495
  return;
3338
4496
  }
3339
4497
 
3340
- // Note on ordering: the cryptographic check below is the SECURITY
3341
- // decision and must be the thing that gates acceptance. An additional
3342
- // "was this scheme in our signature_algorithms" policy check
3343
- // (RFC 8446 §4.4.3) used to run FIRST here and abort with
3344
- // illegal_parameter. That was wrong in two ways: it let a
3345
- // scheme-decoding anomaly turn into a spurious rejection before the
3346
- // signature was ever checked, and it reported a policy error for what
3347
- // may be a signature failure. verify_with_scheme already rejects any
3348
- // scheme it cannot map to a (hash, algorithm, padding) triple, and
3349
- // binds the scheme to the certificate's key type, so an unoffered or
3350
- // unknown scheme still cannot verify.
3351
-
3352
- let peerPubKey = peer_leaf_public_key();
3353
- if (!peerPubKey) {
3354
- fatalAlert(wire.TLS_ALERT.BAD_CERTIFICATE, 'Cannot read peer certificate public key');
4498
+ let cvHashName = negotiated_hash();
4499
+ // The label follows the SIGNER's role, the opposite of ours.
4500
+ let tbs = build_cert_verify_tbs_with_hash(cvHashName, !context.isServer, get_transcript_hash(cvHashName));
4501
+ // DTLS 1.3 shares TLS 1.3's scheme semantics.
4502
+ let cvBad = check_peer_signature(wire.TLS_VERSION.TLS1_3, message.scheme, tbs, message.signature, 'CertificateVerify');
4503
+ if (cvBad) { fatalAlert(cvBad.alert, cvBad.reason); return; }
4504
+ } else {
4505
+
4506
+ // TLS 1.2 / DTLS 1.2 (RFC 5246 §7.4.8): the client's signature over
4507
+ // every handshake message up to this one — the bytes themselves, which
4508
+ // the scheme hashes; DTLS's transcript holds its own form (the
4509
+ // transcript hook), as for Finished. It was never checked: only the
4510
+ // 1.3 branch above verified, and the completion gate was 1.3-only too,
4511
+ // so a client presenting anyone's certificate — public data — with
4512
+ // random bytes for a signature, or none, was authorized as its owner.
4513
+ // Fail closed, as above.
4514
+ if (!context.isServer) {
4515
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'CertificateVerify from a TLS 1.2 server');
3355
4516
  return;
3356
4517
  }
3357
-
3358
- let cvHashName = negotiated_hash();
3359
- // isServer=false here means "we are the client, so the signature we
3360
- // are checking is the SERVER's" — the label follows the SIGNER's role,
3361
- // which is the opposite of ours.
3362
- let signerIsServer = !context.isServer;
3363
- let tbs = build_cert_verify_tbs_with_hash(cvHashName, signerIsServer, get_transcript_hash(cvHashName));
3364
-
3365
- let sigOk = verify_with_scheme(
3366
- wire.TLS_VERSION.TLS1_3, // DTLS 1.3 shares TLS 1.3 scheme semantics
3367
- message.scheme,
3368
- tbs,
3369
- peerPubKey,
3370
- message.signature
3371
- );
3372
-
3373
- // Gate on "is exactly true", not on truthiness. verify_with_scheme
3374
- // already returns a strict boolean, but writing the test this way means
3375
- // a future refactor that lets some path fall through returning
3376
- // undefined fails CLOSED rather than open. The distinction matters here
3377
- // more than almost anywhere else in the library: this single value is
3378
- // what stands between us and an unauthenticated peer.
3379
- if (sigOk !== true) {
3380
- fatalAlert(wire.TLS_ALERT.DECRYPT_ERROR, 'CertificateVerify signature verification failed');
4518
+ if (!context.remote_cert_chain || context.remote_cert_chain.length === 0) {
4519
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'CertificateVerify without a preceding Certificate');
3381
4520
  return;
3382
4521
  }
3383
-
3384
- context.peerSignatureVerified = true;
3385
- context.peerSignatureScheme = message.scheme;
4522
+ let cvBad12 = check_peer_signature(wire.TLS_VERSION.TLS1_2, message.scheme, concatUint8Arrays(context.transcript), message.signature, 'CertificateVerify');
4523
+ if (cvBad12) { fatalAlert(cvBad12.alert, cvBad12.reason); return; }
3386
4524
  }
3387
4525
 
3388
4526
  pushTranscript(data);
@@ -3411,7 +4549,9 @@ function TLSSession(options){
3411
4549
  //
3412
4550
  // Applies in both roles: a client checks the server's certificate, and a
3413
4551
  // server checks a client certificate it was offered.
3414
- if (is13() && context.remote_cert_chain && context.remote_cert_chain.length > 0 &&
4552
+ // Every version: in 1.2 a client's certificate is proved by its
4553
+ // CertificateVerify, the server's by its ServerKeyExchange signature.
4554
+ if (context.remote_cert_chain && context.remote_cert_chain.length > 0 &&
3415
4555
  context.peerSignatureVerified !== true) {
3416
4556
  fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE,
3417
4557
  'Finished received after a certificate that was never proved by a CertificateVerify');
@@ -3435,10 +4575,10 @@ function TLSSession(options){
3435
4575
  dbg('CLI-NST', 'received TLS 1.3 NST — cipher:', '0x' + context.selected_cipher_suite.toString(16),
3436
4576
  'hash:', hashName,
3437
4577
  'transcript len:', concatUint8Arrays(context.transcript).length);
3438
- dbg('CLI-NST', 'ticket_nonce:', hexPreview(message.ticket_nonce, 4),
4578
+ if (LEMON_DEBUG) dbg('CLI-NST', 'ticket_nonce:', hexPreview(message.ticket_nonce, 4),
3439
4579
  'age_add:', message.ticket_age_add,
3440
4580
  'lifetime:', message.ticket_lifetime);
3441
- dbg('CLI-NST', 'resumption_master_secret:', hexPreview(context.resumption_master_secret, 8),
4581
+ if (LEMON_DEBUG) dbg('CLI-NST', 'resumption_master_secret:', hexPreview(context.resumption_master_secret, 8),
3442
4582
  'derived psk:', hexPreview(psk, 8));
3443
4583
 
3444
4584
  // Encode opaque client-side session Buffer (JSON — user is responsible for secure storage)
@@ -3467,7 +4607,7 @@ function TLSSession(options){
3467
4607
  });
3468
4608
 
3469
4609
  ev.emit('session', session_blob);
3470
- } else if (context.selected_version === wire.TLS_VERSION.TLS1_2 && context.base_secret) {
4610
+ } else if (is12() && context.base_secret) { // TLS 1.2 and DTLS 1.2: the ticket and its transcript entry
3471
4611
  // TLS 1.2: NewSessionTicket is sent BEFORE server's CCS+Finished and is part of the
3472
4612
  // handshake transcript (RFC 5077 §3.3). Server's Finished hash covers this message,
3473
4613
  // so the client MUST include it in its transcript for verification to succeed.
@@ -3511,24 +4651,38 @@ function TLSSession(options){
3511
4651
 
3512
4652
  }else if(message.type=='key_update'){
3513
4653
 
4654
+ // Only once the handshake is done (RFC 8446 §4.6.3: "an
4655
+ // unexpected_message alert" for one before Finished). It used to be
4656
+ // passed over without a word.
4657
+ if(context.state!=='connected' || !is13()){
4658
+ fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE, 'KeyUpdate before the handshake is complete');
4659
+ return;
4660
+ }
4661
+
3514
4662
  // Peer is updating their traffic secret (we update our read key)
3515
- if(context.state==='connected' && (is13())){
4663
+ {
3516
4664
  let hashName = negotiated_hash();
3517
4665
  let hashLen = getHashLen(hashName);
3518
4666
  let newRemoteSecret = hkdf_expand_label(hashName, context.remote_app_traffic_secret, 'traffic upd', new Uint8Array(0), hashLen, label_prefix());
3519
4667
  context.remote_app_traffic_secret = newRemoteSecret;
3520
- ev.emit('keyUpdate', { direction: 'receive', secret: newRemoteSecret });
4668
+ // `answer`: one of ours asked for it (update_requested) — the peer's
4669
+ // reply, not a KeyUpdate of its own will. A record layer limiting
4670
+ // runs of them counts the others only: counting answers ended a
4671
+ // connection that rekeyed both ways now and then (BoringSSL's 32).
4672
+ let answer = message.request_update === 0 && context.key_updates_asked > 0;
4673
+ if (answer) context.key_updates_asked--;
4674
+ ev.emit('keyUpdate', { direction: 'receive', secret: newRemoteSecret, answer: answer });
3521
4675
 
3522
4676
  // If peer requested us to update too
3523
4677
  if(message.request_update === 1){
3524
- let newLocalSecret = hkdf_expand_label(hashName, context.local_app_traffic_secret, 'traffic upd', new Uint8Array(0), hashLen, label_prefix());
3525
- context.local_app_traffic_secret = newLocalSecret;
3526
-
3527
- // Send our KeyUpdate (not requesting back)
4678
+ // Ours, under the key it replaces — then the new secret (as in
4679
+ // requestKeyUpdate).
3528
4680
  let ku_data = build_tls_message({ type: 'key_update', request_update: 0 });
3529
4681
  ev.emit('message', 2, context.message_sent_seq, 'key_update', ku_data);
3530
4682
  context.message_sent_seq++;
3531
4683
 
4684
+ let newLocalSecret = hkdf_expand_label(hashName, context.local_app_traffic_secret, 'traffic upd', new Uint8Array(0), hashLen, label_prefix());
4685
+ context.local_app_traffic_secret = newLocalSecret;
3532
4686
  ev.emit('keyUpdate', { direction: 'send', secret: newLocalSecret });
3533
4687
  }
3534
4688
  }
@@ -3537,10 +4691,23 @@ function TLSSession(options){
3537
4691
 
3538
4692
  // Server is requesting a client certificate (TLS 1.3)
3539
4693
  if(!context.isServer){
4694
+ // The parser names the field request_context (wire.js); reading
4695
+ // certificate_request_context only meant every context read as empty.
4696
+ let crContext = message.request_context || message.certificate_request_context || new Uint8Array(0);
4697
+ // RFC 8446 §4.3.2: "This field SHALL be zero length unless used for
4698
+ // the post-handshake authentication exchanges" — and this one is in
4699
+ // the handshake (post-handshake auth is not offered).
4700
+ if (is13() && crContext.length > 0) {
4701
+ fatalAlert(wire.TLS_ALERT.ILLEGAL_PARAMETER,
4702
+ 'CertificateRequest in the handshake with a non-empty certificate_request_context');
4703
+ return;
4704
+ }
3540
4705
  pushTranscript(data);
3541
4706
  context.certificateRequested = true;
3542
- context.certificateRequestContext = message.certificate_request_context || new Uint8Array(0);
4707
+ context.certificateRequestContext = crContext;
3543
4708
  context.certificateRequestSigAlgs = message.signature_algorithms || [];
4709
+ // TLS 1.2 (RFC 5246 §7.4.4): the kinds of key the server will take.
4710
+ context.certificateRequestTypes = Array.isArray(message.certificate_types) ? message.certificate_types : null;
3544
4711
  ev.emit('certificateRequest', message);
3545
4712
  }
3546
4713
 
@@ -3562,7 +4729,8 @@ function TLSSession(options){
3562
4729
  }
3563
4730
 
3564
4731
 
3565
- function set_context(options){
4732
+ function set_context(options) { return run_guarded(set_context_unguarded, options); }
4733
+ function set_context_unguarded(options){
3566
4734
  // Terminal states are terminal: after a fatal alert ('error') or a close,
3567
4735
  // the reactive loop must not keep selecting parameters, deriving keys or
3568
4736
  // emitting messages. This is also what stops it from writing into a
@@ -3772,6 +4940,23 @@ function TLSSession(options){
3772
4940
  if(options.selected_version!==context.selected_version){
3773
4941
  context.selected_version=options.selected_version;
3774
4942
  has_changed=true;
4943
+ // A split-mode backend (backend_client_hello) accepted ECH for a
4944
+ // TLS 1.3 handshake; one on an older version has no ECH at all.
4945
+ if (context.ech.backend && options.selected_version != null && !wire.is_tls13_wire(options.selected_version)) {
4946
+ context.ech.status = null;
4947
+ context.ech.backend = false;
4948
+ }
4949
+ // A server on (D)TLS 1.2: the key shares of the ClientHello are
4950
+ // TLS 1.3's (key_share, RFC 8446 §4.2.8) and not this handshake's.
4951
+ // The client's key comes in its ClientKeyExchange. Kept, the
4952
+ // ClientHello's share for the group chosen was taken for the
4953
+ // client's key — the secret computed with it at once, and the
4954
+ // ClientKeyExchange's key then ignored (a share already there is
4955
+ // not replaced): bad_record_mac on the first record, with any
4956
+ // client that offers 1.3 too and sends a share for that group.
4957
+ if (context.isServer && options.selected_version != null && !wire.is_tls13_wire(options.selected_version)) {
4958
+ context.remote_key_groups = {};
4959
+ }
3775
4960
  }
3776
4961
  }
3777
4962
 
@@ -3911,10 +5096,7 @@ function TLSSession(options){
3911
5096
  if(context.remote_app_traffic_secret==null && options.remote_app_traffic_secret!==null){
3912
5097
  context.remote_app_traffic_secret=options.remote_app_traffic_secret;
3913
5098
  has_changed=true;
3914
- if(context.local_app_traffic_secret!==null){
3915
- ev.emit('appSecrets', context.local_app_traffic_secret, context.remote_app_traffic_secret);
3916
- _emitAppKeylog();
3917
- }
5099
+ if(context.local_app_traffic_secret!==null) emit_app_secrets();
3918
5100
  }
3919
5101
  }
3920
5102
 
@@ -3922,10 +5104,7 @@ function TLSSession(options){
3922
5104
  if(context.local_app_traffic_secret==null && options.local_app_traffic_secret!==null){
3923
5105
  context.local_app_traffic_secret=options.local_app_traffic_secret;
3924
5106
  has_changed=true;
3925
- if(context.remote_app_traffic_secret!==null){
3926
- ev.emit('appSecrets', context.local_app_traffic_secret, context.remote_app_traffic_secret);
3927
- _emitAppKeylog();
3928
- }
5107
+ if(context.remote_app_traffic_secret!==null) emit_app_secrets();
3929
5108
  }
3930
5109
  }
3931
5110
 
@@ -4040,8 +5219,9 @@ function TLSSession(options){
4040
5219
 
4041
5220
 
4042
5221
 
4043
- //select version...
4044
- if (context.selected_version == null && context.local_supported_versions.length > 0 && context.remote_supported_versions.length > 0) {
5222
+ //select version... (a server's, once it is configured: 'hello')
5223
+ if (context.selected_version == null && (!context.isServer || context.server_configured) &&
5224
+ context.local_supported_versions.length > 0 && context.remote_supported_versions.length > 0) {
4045
5225
  for (let i = 0; i < context.local_supported_versions.length; i++) {
4046
5226
  let v = context.local_supported_versions[i] | 0;
4047
5227
  for (let j = 0; j < context.remote_supported_versions.length; j++) {
@@ -4114,13 +5294,27 @@ function TLSSession(options){
4114
5294
  !context.sni_pending && pending('selected_version') != null && context.cert_private_key) {
4115
5295
  context.cert_chosen = true;
4116
5296
  let cv = pending('selected_version');
4117
- let sv = (cv === wire.TLS_VERSION.TLS1_3 || cv === wire.DTLS_VERSION.DTLS1_3) ? wire.TLS_VERSION.TLS1_3 : wire.TLS_VERSION.TLS1_2;
5297
+ let sv = wire.is_tls13_wire(cv) ? wire.TLS_VERSION.TLS1_3 : wire.TLS_VERSION.TLS1_2;
4118
5298
  let cands = [{ certificateChain: context.local_cert_chain, privateKey: context.cert_private_key }].concat(context.local_cert_alternates);
4119
- let peerAlgs = context.remote_supported_signature_algorithms || [];
5299
+ let peerAlgs = peer_signature_algorithms(sv === wire.TLS_VERSION.TLS1_3);
5300
+ // In TLS 1.2 the suite names the key's algorithm (and an ECDSA key
5301
+ // its curve among the client's groups): a pair is only one with a
5302
+ // suite both sides have for it. Chosen by the signature alone, an
5303
+ // ECDSA certificate went to a client of ECDHE_RSA suites only, and
5304
+ // no suite was left (handshake_failure).
5305
+ let usable = function (cand) {
5306
+ if (sv === wire.TLS_VERSION.TLS1_3) return true;
5307
+ let key = private_key_object(cand.privateKey);
5308
+ return context.local_supported_cipher_suites.some(function (cs) {
5309
+ return context.remote_supported_cipher_suites.indexOf(cs) >= 0 && is_usable_cipher_suite(cs) &&
5310
+ suite_matches_version(cs, cv) && suite_auth_ok(cs, key);
5311
+ });
5312
+ };
4120
5313
  let chosen = null;
4121
5314
  for (let i = 0; i < peerAlgs.length && chosen === null; i++) {
4122
5315
  for (let j = 0; j < cands.length; j++) {
4123
- if (pick_scheme(sv, private_key_object(cands[j].privateKey), [peerAlgs[i]], context.local_supported_signature_algorithms) !== null) { chosen = cands[j]; break; }
5316
+ if (usable(cands[j]) &&
5317
+ pick_scheme(sv, private_key_object(cands[j].privateKey), [peerAlgs[i]], context.local_supported_signature_algorithms) !== null) { chosen = cands[j]; break; }
4124
5318
  }
4125
5319
  }
4126
5320
  if (chosen !== null && chosen !== cands[0]) {
@@ -4181,7 +5375,22 @@ function TLSSession(options){
4181
5375
  let pskHash = context.psk_offered.hash;
4182
5376
  let chosen = null;
4183
5377
 
4184
- for (let i = 0; i < context.local_supported_cipher_suites.length; i++) {
5378
+ // Early data offered, and we take early data: the ticket's own
5379
+ // suite, if the client offers it — 0-RTT is accepted only under
5380
+ // "the same cipher suite" the ticket was issued with (RFC 8446
5381
+ // §4.2.10), and early_decide holds to that. Chosen by our order
5382
+ // alone, a ChaCha20 ticket resumed under AES-128-GCM (same hash,
5383
+ // allowed) and its early data was always refused.
5384
+ let ticketCs = context.psk_offered.cipher | 0;
5385
+ if (context.earlyData && context.early.offered && ticketCs &&
5386
+ context.local_supported_cipher_suites.indexOf(ticketCs) >= 0 &&
5387
+ context.remote_supported_cipher_suites.indexOf(ticketCs) >= 0 &&
5388
+ TLS_CIPHER_SUITES[ticketCs] && TLS_CIPHER_SUITES[ticketCs].hash === pskHash &&
5389
+ is_usable_cipher_suite(ticketCs)) {
5390
+ chosen = ticketCs;
5391
+ }
5392
+
5393
+ for (let i = 0; chosen === null && i < context.local_supported_cipher_suites.length; i++) {
4185
5394
  let cs = context.local_supported_cipher_suites[i] | 0;
4186
5395
  if (context.remote_supported_cipher_suites.indexOf(cs) < 0) continue;
4187
5396
  let meta = TLS_CIPHER_SUITES[cs];
@@ -4200,9 +5409,7 @@ function TLSSession(options){
4200
5409
  // let the normal path run a full handshake.
4201
5410
  dbg('SRV-PSK', 'no mutually-supported cipher with hash', pskHash,
4202
5411
  '— rejecting PSK, falling back to full handshake');
4203
- context.psk_accepted = false;
4204
- context.isResumed = false;
4205
- context.psk_offered = null;
5412
+ psk_dropped();
4206
5413
  }
4207
5414
  }
4208
5415
 
@@ -4218,24 +5425,11 @@ function TLSSession(options){
4218
5425
  // (the `sig` field), so this reads that authority rather than
4219
5426
  // re-deriving it. TLS 1.3 suites are authentication-agnostic
4220
5427
  // (sig: 'TLS13'), so they are never filtered here.
4221
- let localAuth = null;
4222
- if (context.isServer) {
4223
- try {
4224
- if (context.cert_private_key) {
4225
- let lk = local_private_key();
4226
- localAuth = lk ? lk.asymmetricKeyType : null;
4227
- }
4228
- } catch (e) { localAuth = null; }
5428
+ let localKey = null;
5429
+ if (context.isServer && context.cert_private_key) {
5430
+ try { localKey = local_private_key(); } catch (e) { localKey = null; }
4229
5431
  }
4230
-
4231
- let suiteAuthOk = function (suite) {
4232
- if (!context.isServer || localAuth === null) return true; // client, or key type unknown
4233
- let meta = TLS_CIPHER_SUITES[suite];
4234
- if (!meta || !meta.sig || meta.sig === 'TLS13') return true; // not auth-bound
4235
- if (meta.sig === 'RSA') return localAuth === 'rsa' || localAuth === 'rsa-pss';
4236
- if (meta.sig === 'ECDSA') return localAuth === 'ec';
4237
- return true;
4238
- };
5432
+ let suiteAuthOk = function (suite) { return !context.isServer || suite_auth_ok(suite, localKey); };
4239
5433
 
4240
5434
  // Whose order: the client's, as node:tls (OpenSSL) chooses by
4241
5435
  // default — honorCipherOrder: true for ours. It was always ours: a
@@ -4257,11 +5451,10 @@ function TLSSession(options){
4257
5451
  // peer cannot act on. This is the server-side mirror of not
4258
5452
  // OFFERING 1.3 suites from a 1.2-only client profile.
4259
5453
  if (!suite_matches_version(cs, pending('selected_version'))) continue;
4260
- // The suite table names more suites than the record layer can
4261
- // protect (CBC entries exist for parsing peer offers). Selecting a
4262
- // described-but-unimplemented suite yields a handshake that agrees
4263
- // on parameters and then cannot encrypt a record — the cipher-suite
4264
- // analogue of picking a key-exchange group we cannot compute.
5454
+ // Only a suite this library can carry through (is_usable_cipher_suite):
5455
+ // one merely described yields a handshake that agrees on parameters
5456
+ // and then cannot go on — the cipher-suite analogue of picking a
5457
+ // key-exchange group we cannot compute.
4265
5458
  if (!is_usable_cipher_suite(cs)) continue;
4266
5459
  for (let j2 = 0; j2 < context.remote_supported_cipher_suites.length; j2++) {
4267
5460
 
@@ -4282,13 +5475,20 @@ function TLSSession(options){
4282
5475
  // Runs once when all prerequisites are met (version + cipher selected, resume state present).
4283
5476
  if (context.isServer && context.tls12_resume_state && !context.tls12_abbreviated &&
4284
5477
  params_to_set.selected_cipher_suite != null &&
4285
- (context.selected_version === wire.TLS_VERSION.TLS1_2 || params_to_set.selected_version === wire.TLS_VERSION.TLS1_2)) {
5478
+ (is12() || wire.is_tls12_wire(params_to_set.selected_version))) {
4286
5479
 
4287
5480
  let storedEMS = !!context.tls12_resume_state.extended_master_secret;
4288
5481
  let clientEMS = !!context.use_extended_master_secret;
4289
5482
 
4290
- if (storedEMS !== clientEMS) {
4291
- // EMS mismatch: per RFC 7627 can't resume. Fall through to full handshake.
5483
+ if (storedEMS && !clientEMS) {
5484
+ // RFC 7627 §5.3: a session made with the extended master secret, a
5485
+ // hello now without it — "the server MUST abort the abbreviated
5486
+ // handshake": its master secret is not one this hello can be held
5487
+ // to. handshake_failure, as OpenSSL. It went on to a full handshake.
5488
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'Resumption without extended_master_secret of a session made with it');
5489
+ return;
5490
+ } else if (!storedEMS && clientEMS) {
5491
+ // The other way: not resumed, a full handshake (§5.3).
4292
5492
  context.tls12_resume_state = null;
4293
5493
  } else {
4294
5494
  // OK, we can do abbreviated. Use params_to_set for all state flags
@@ -4381,7 +5581,24 @@ function TLSSession(options){
4381
5581
 
4382
5582
 
4383
5583
  //select group...
4384
- if (context.selected_group == null){
5584
+ // TLS 1.2, a ClientHello without supported_groups: "the server is free
5585
+ // to choose any one of the elliptic curves" (RFC 8422 §4) — P-256, as
5586
+ // BoringSSL and OpenSSL take it (the curve every ECDHE client has).
5587
+ // The server waited for a list that was not coming, after its
5588
+ // ServerHello and Certificate.
5589
+ if (context.selected_group == null && context.isServer && context.remote_supported_groups.length === 0 &&
5590
+ context.remote_supported_cipher_suites.length > 0 && wire.is_tls12_wire(pending('selected_version'))) {
5591
+ let fallback = [0x0017, 0x001d].filter(function (g) { return context.local_supported_groups.indexOf(g) >= 0 && is_supported_group(g); });
5592
+ if (fallback.length > 0) params_to_set['selected_group'] = fallback[0];
5593
+ }
5594
+ // A server chooses once the version is known — which group, and how,
5595
+ // depends on it (a KEM group, or a key share, only in TLS 1.3). It
5596
+ // chose before: with `groups` configured (so its list was there before
5597
+ // 'hello'), a TLS 1.2 server picked the group by the client's TLS 1.3
5598
+ // key share, and computed the secret with that share before the
5599
+ // version was even chosen.
5600
+ if (context.selected_group == null && !('selected_group' in params_to_set) &&
5601
+ (!context.isServer || pending('selected_version') != null)){
4385
5602
  if(context.local_supported_groups.length > 0 && context.remote_supported_groups.length > 0) {
4386
5603
  // Two passes over our preference order. First: a group the client
4387
5604
  // already sent a key share for — the handshake goes on in one round
@@ -4426,7 +5643,7 @@ function TLSSession(options){
4426
5643
  let g = context.local_supported_groups[i];
4427
5644
  if (context.remote_supported_groups.indexOf(g) < 0) continue;
4428
5645
  if (!is_supported_group(g)) continue;
4429
- if (is_kem_group(g) && !selIs13) continue;
5646
+ if (!selIs13) break; // key shares are TLS 1.3's
4430
5647
  let rk = context.remote_key_groups[g];
4431
5648
  if (!rk || !rk.public_key) continue;
4432
5649
  params_to_set['selected_group'] = g;
@@ -4478,8 +5695,8 @@ function TLSSession(options){
4478
5695
  // Only the server decides these; the client validates the server's
4479
5696
  // choice elsewhere. A non-empty remote cipher list is the signal that a
4480
5697
  // ClientHello was actually processed, so we never fire before the peer
4481
- // has spoken.
4482
- if (context.isServer && context.remote_supported_cipher_suites.length > 0) {
5698
+ // has spoken — and is configured ('hello').
5699
+ if (context.isServer && context.server_configured && context.remote_supported_cipher_suites.length > 0) {
4483
5700
 
4484
5701
  let pickedVersion = pending('selected_version');
4485
5702
 
@@ -4516,12 +5733,34 @@ function TLSSession(options){
4516
5733
  // selected_group is set there and HelloRetryRequest handles it.
4517
5734
  let pickedGroup = pending('selected_group');
4518
5735
  if (pickedGroup === null &&
4519
- context.remote_supported_groups.length > 0 &&
5736
+ (context.remote_supported_groups.length > 0 || wire.is_tls12_wire(pickedVersion)) &&
4520
5737
  context.local_supported_groups.length > 0) {
4521
5738
  fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE,
4522
5739
  'No key-exchange group in common with the peer');
4523
5740
  return;
4524
5741
  }
5742
+
5743
+ // The signature our certificate will make (CertificateVerify in 1.3,
5744
+ // ServerKeyExchange in 1.2): one the client takes, decided with the
5745
+ // rest, before the ServerHello. It was found missing only when it was
5746
+ // due — after the ServerHello and the Certificate had gone out.
5747
+ // A resumption makes none.
5748
+ if (!context.sig_checked && pickedVersion !== null && pickedCipher !== null &&
5749
+ context.cert_private_key && !context.sni_pending && !context.psk_accepted &&
5750
+ !(wire.is_tls12_wire(pickedVersion) && context.tls12_resume_state)) {
5751
+ context.sig_checked = true;
5752
+ let v13 = wire.is_tls13_wire(pickedVersion);
5753
+ let peerAlgs = peer_signature_algorithms(v13);
5754
+ if (v13 && peerAlgs.length === 0) {
5755
+ fatalAlert(wire.TLS_ALERT.MISSING_EXTENSION, 'ClientHello without signature_algorithms (RFC 8446 §9.2)');
5756
+ return;
5757
+ }
5758
+ if (pick_scheme(v13 ? wire.TLS_VERSION.TLS1_3 : wire.TLS_VERSION.TLS1_2, local_private_key(), peerAlgs,
5759
+ context.local_supported_signature_algorithms) === null) {
5760
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'No signature scheme shared with the client for our certificate');
5761
+ return;
5762
+ }
5763
+ }
4525
5764
  }
4526
5765
 
4527
5766
  //create the key by the group if dont have...
@@ -4644,6 +5883,8 @@ function TLSSession(options){
4644
5883
  reset_transcript_hash(hashName);
4645
5884
 
4646
5885
  // Build and send HRR (it's a ServerHello with magic random)
5886
+ // What the second ClientHello must answer with (checked when it comes).
5887
+ context.hrr_sent_group = hrrGroupNow;
4647
5888
  let hrr_body = wire.build_hello_retry_request({
4648
5889
  cipher_suite: hrrCipherNow,
4649
5890
  // The version chosen in THIS pass (hrrVersionNow, above): it is
@@ -4655,7 +5896,10 @@ function TLSSession(options){
4655
5896
  // that followed.
4656
5897
  selected_version: hrrVersionNow,
4657
5898
  selected_group: hrrGroupNow,
4658
- session_id: context.remote_session_id,
5899
+ // A HelloRetryRequest is a ServerHello (RFC 8446 §4.1.4): the
5900
+ // same legacy_session_id_echo rule — empty over DTLS 1.3. It
5901
+ // echoed the client's here while the ServerHello did not.
5902
+ session_id: legacy_session_id_echo(hrrVersionNow),
4659
5903
  // ECH (RFC 9849 §7.2.1): accepted → 8 bytes confirming it,
4660
5904
  // computed below over this very message; rejected → 8 random
4661
5905
  // bytes, so a retry looks the same either way (§7.1, §10.10.4).
@@ -4678,13 +5922,7 @@ function TLSSession(options){
4678
5922
  // §4.2.11.2). It was kept from the first: a second hello with no
4679
5923
  // PSK, or another, still resumed with the first's — accepted on a
4680
5924
  // binder that never covered the hello it answered.
4681
- context.psk_accepted = false;
4682
- context.isResumed = false;
4683
- context.psk_offered = null;
4684
- context.resumed_ticket_data = null;
4685
- context.resumed_ticket_state = null;
4686
- context.early.candidate = null;
4687
- if (context.resumed_peer_chain) { context.resumed_peer_chain = null; context.peerAuthorized = false; context.authorizationError = null; }
5925
+ psk_dropped();
4688
5926
  context.remote_random = null;
4689
5927
  context.remote_extensions = [];
4690
5928
  context.remote_supported_versions = [];
@@ -4750,9 +5988,11 @@ function TLSSession(options){
4750
5988
  // lower, stamp the downgrade sentinel into the last 8 bytes of the
4751
5989
  // ServerHello random so a 1.3-capable client can detect the downgrade.
4752
5990
  // Only meaningful for a real ServerHello (not HRR, which reuses the
4753
- // magic HRR random), and only for the TLS transport (not DTLS here).
4754
- if (context.local_supported_versions.indexOf(wire.TLS_VERSION.TLS1_3) >= 0) {
4755
- if (context.selected_version === wire.TLS_VERSION.TLS1_2) {
5991
+ // magic HRR random). DTLS the same way (RFC 9147 §5.3 keeps
5992
+ // §4.1.3): a DTLS 1.3 server that settles on DTLS 1.2 stamps it too.
5993
+ if (lists13(context.local_supported_versions)) {
5994
+ if (context.selected_version === wire.TLS_VERSION.TLS1_2 ||
5995
+ context.selected_version === wire.DTLS_VERSION.DTLS1_2) {
4756
5996
  context.local_random.set(DOWNGRADE_SENTINEL_TLS12, 24);
4757
5997
  } else if (context.selected_version === wire.TLS_VERSION.TLS1_1 ||
4758
5998
  context.selected_version === wire.TLS_VERSION.TLS1_0) {
@@ -4781,8 +6021,9 @@ function TLSSession(options){
4781
6021
 
4782
6022
  // PSK accepted → include PRE_SHARED_KEY with selected identity index
4783
6023
  if (context.psk_accepted) {
4784
- shExtensions.push({ type: 'PRE_SHARED_KEY', value: { selected: 0 } });
6024
+ shExtensions.push({ type: 'PRE_SHARED_KEY', value: { selected: context.psk_selected } });
4785
6025
  }
6026
+ if (context.peer_cid !== null) shExtensions.push(connection_id_ext());
4786
6027
 
4787
6028
  build_message_params={
4788
6029
  type: 'server_hello',
@@ -4805,11 +6046,7 @@ function TLSSession(options){
4805
6046
  // enforces §5 sees an echo it never expected. This is exactly the
4806
6047
  // shape of the other DTLS 1.3 bugs: a legacy field whose meaning
4807
6048
  // inverted between the two protocols.
4808
- session_id: (function () {
4809
- // RFC 9147 §5 — see the note above.
4810
- let isDtls = context.selected_version === wire.DTLS_VERSION.DTLS1_3;
4811
- return isDtls ? new Uint8Array(0) : context.remote_session_id;
4812
- })(),
6049
+ session_id: legacy_session_id_echo(context.selected_version), // RFC 9147 §5 — see the note above
4813
6050
  cipher_suite: context.selected_cipher_suite,
4814
6051
  extensions: shExtensions
4815
6052
  };
@@ -4822,9 +6059,13 @@ function TLSSession(options){
4822
6059
  // Include renegotiation_info (empty for initial handshake) and extended_master_secret.
4823
6060
  // ALPN (type=16) — optional, echoes selected protocol.
4824
6061
 
4825
- let ext_list = [
6062
+ // renegotiation_info only for a client that signalled it — the
6063
+ // extension or the SCSV (RFC 5746 §3.6: "the server MUST include
6064
+ // an empty renegotiation_info" then; unasked, an extension the
6065
+ // client never offered, RFC 5246 §7.4.1.4).
6066
+ let ext_list = context.client_secure_renegotiation ? [
4826
6067
  { type: 'RENEGOTIATION_INFO', value: new Uint8Array(0) }
4827
- ];
6068
+ ] : [];
4828
6069
 
4829
6070
  // status_request, empty: a CertificateStatus follows the
4830
6071
  // Certificate (RFC 6066 §8). Only when there is one to send.
@@ -4869,11 +6110,14 @@ function TLSSession(options){
4869
6110
  ext_list.push({ type: 'ALPN', value: [ String(context.selected_alpn) ] });
4870
6111
  }
4871
6112
 
6113
+ let rsl12 = record_size_limit_answer();
6114
+ if (rsl12) ext_list.push(rsl12);
6115
+ if (context.peer_cid !== null) ext_list.push(connection_id_ext());
6116
+
4872
6117
  // SESSION_TICKET: RFC 5077 §3.2 — server echoes empty extension to signal it will
4873
6118
  // send a NewSessionTicket later. Skip for abbreviated handshake (per §3.3).
4874
- // Skip for DTLS — we don't emit NST in DTLS, so MUST NOT echo the ext either (§3.2).
4875
- let isDtls12Here = (context.selected_version === wire.DTLS_VERSION.DTLS1_2);
4876
- if (context.tls12_session_ticket_requested && !context.tls12_abbreviated && context.sessionTickets && !isDtls12Here) {
6119
+ // DTLS 1.2 the same: it issues its tickets too now.
6120
+ if (context.tls12_session_ticket_requested && !context.tls12_abbreviated && context.sessionTickets) {
4877
6121
  ext_list.push({ type: 'SESSION_TICKET', value: new Uint8Array(0) });
4878
6122
  }
4879
6123
 
@@ -4902,13 +6146,18 @@ function TLSSession(options){
4902
6146
  // Session ID: for abbreviated (resumed) handshake, MUST echo client's session_id
4903
6147
  // (RFC 5077 §3.4). For TLS 1.2 full handshake, generate a fresh 32-byte session_id
4904
6148
  // (matches OpenSSL/Node.js behavior for middlebox compatibility).
4905
- // For DTLS 1.2 full handshake: just echo client's session_id (no middlebox concern,
4906
- // and matches original lemon-tls behavior before my TLS 1.2 resumption changes).
6149
+ // For a DTLS 1.2 full handshake: an empty session_id. This server
6150
+ // keeps no DTLS sessions to resume, and an empty one says exactly
6151
+ // that (RFC 5246 §7.4.1.3: "the session will not be cached and
6152
+ // therefore cannot be resumed"). It used to echo the client's —
6153
+ // which is how a server says "resumed" (§7.4.1.2): a client that
6154
+ // offered its cached session took a full handshake for an
6155
+ // abbreviated one and failed.
4907
6156
  let sid_to_send;
4908
6157
  if (context.tls12_abbreviated) {
4909
6158
  sid_to_send = context.remote_session_id || new Uint8Array(0);
4910
6159
  } else if (context.selected_version === wire.DTLS_VERSION.DTLS1_2) {
4911
- sid_to_send = context.remote_session_id || new Uint8Array(0);
6160
+ sid_to_send = new Uint8Array(0);
4912
6161
  } else if (context.sessionIdStore && !context.sessionIdStore()) {
4913
6162
  sid_to_send = new Uint8Array(0); // nothing would keep it: see sessionIdStore
4914
6163
  } else {
@@ -5115,6 +6364,9 @@ function TLSSession(options){
5115
6364
  if (eeGroups.length > 0) extensions.push({ type: 'SUPPORTED_GROUPS', value: eeGroups });
5116
6365
  }
5117
6366
 
6367
+ let rsl = record_size_limit_answer();
6368
+ if (rsl) extensions.push(rsl);
6369
+
5118
6370
  // DTLS-SRTP answer (RFC 5764 §4.1). One profile, empty MKI.
5119
6371
  let srtpSel = negotiate_srtp_profile();
5120
6372
  if (srtpSel !== null) {
@@ -5167,6 +6419,15 @@ function TLSSession(options){
5167
6419
  context.message_sent_seq++;
5168
6420
  }
5169
6421
 
6422
+ // A full handshake and no certificate to present — a server that takes
6423
+ // external PSKs only, and a client with none it knows: handshake_failure.
6424
+ // It stopped here, with no Certificate and no alert, until the client
6425
+ // gave up.
6426
+ if (context.isServer && context.hello_sent && !context.cert_sent && context.local_cert_chain === null &&
6427
+ !context.psk_accepted && !context.tls12_abbreviated && !context.sni_pending) {
6428
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'No certificate to present, and no PSK in common with the client');
6429
+ return;
6430
+ }
5170
6431
  if(context.isServer==true && context.cert_sent==false && context.local_cert_chain!==null && !context.psk_accepted && !context.tls12_abbreviated){
5171
6432
  // When may we put our Certificate on the wire?
5172
6433
  // 1.3: it is encrypted, so it follows EncryptedExtensions and needs
@@ -5302,6 +6563,37 @@ function TLSSession(options){
5302
6563
  if (context.certificateRequested && !context.clientCertSent) {
5303
6564
  context.clientCertSent = true;
5304
6565
 
6566
+ // The client's cert / key options (tls.connect's): what the 1.3
6567
+ // path sends. This one read only local_cert_chain, which a
6568
+ // client's options never fill — so a TLS 1.2 client sent an
6569
+ // empty Certificate whatever it was given.
6570
+ if ((!context.local_cert_chain || context.local_cert_chain.length === 0) && context.clientCert && context.clientKey) {
6571
+ let cc = { key: context.clientKey, cert: context.clientCert };
6572
+ if (context.clientKeyPassphrase) cc.passphrase = context.clientKeyPassphrase;
6573
+ let ccCtx;
6574
+ // A key that is not the certificate's (or unreadable): the
6575
+ // handshake ends here, an alert sent — it threw out of the
6576
+ // record layer, uncaught.
6577
+ try { ccCtx = createSecureContext(cc); }
6578
+ catch (e) { fatalAlert(wire.TLS_ALERT.INTERNAL_ERROR, 'client certificate: ' + e.message); return; }
6579
+ context.local_cert_chain = ccCtx.certificateChain;
6580
+ context.cert_private_key = ccCtx.privateKey;
6581
+ }
6582
+
6583
+ // certificate_types (RFC 5246 §7.4.4, RFC 8422 §5.5): the kinds
6584
+ // of key the server will take — rsa_sign (1), ecdsa_sign (64,
6585
+ // which also covers EdDSA). A certificate of another kind is not
6586
+ // sent; the empty Certificate says "none", and the server
6587
+ // decides whether that is enough.
6588
+ if (Array.isArray(context.certificateRequestTypes) && context.local_cert_chain && context.local_cert_chain.length > 0) {
6589
+ let ownKey = local_private_key();
6590
+ let kt = null;
6591
+ try { kt = ownKey && ownKey.asymmetricKeyType; } catch (e) { kt = null; }
6592
+ let need = (kt === 'rsa' || kt === 'rsa-pss') ? 1
6593
+ : (kt === 'ec' || kt === 'ed25519' || kt === 'ed448') ? 64 : -1;
6594
+ if (context.certificateRequestTypes.indexOf(need) < 0) context.local_cert_chain = [];
6595
+ }
6596
+
5305
6597
  // Build TLS 1.2 Certificate message
5306
6598
  let certEntries = [];
5307
6599
  if (context.local_cert_chain && context.local_cert_chain.length > 0) {
@@ -5359,7 +6651,13 @@ function TLSSession(options){
5359
6651
  let cert_key_obj = local_private_key();
5360
6652
  let reqAlgs = peer_requested_sig_algs();
5361
6653
  let scheme = pick_scheme(wire.TLS_VERSION.TLS1_2, cert_key_obj, reqAlgs, context.local_supported_signature_algorithms);
5362
- let signature = sign_with_scheme(wire.TLS_VERSION.TLS1_2, scheme, transcript_data, cert_key_obj);
6654
+ let signature = scheme === null ? null : sign_with_scheme(wire.TLS_VERSION.TLS1_2, scheme, transcript_data, cert_key_obj);
6655
+ // As for TLS 1.3: no shared scheme is handshake_failure, not a
6656
+ // crash on a null signature.
6657
+ if (scheme === null || !signature) {
6658
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'No signature scheme shared with server for client certificate');
6659
+ return;
6660
+ }
5363
6661
 
5364
6662
  // Build CertificateVerify: scheme(2) + sig_length(2) + sig
5365
6663
  let cvBody = new Uint8Array(2 + 2 + signature.length);
@@ -5390,9 +6688,15 @@ function TLSSession(options){
5390
6688
 
5391
6689
  let cert_private_key_obj = local_private_key();
5392
6690
 
5393
- let scheme12 = pick_scheme(wire.TLS_VERSION.TLS1_2, cert_private_key_obj, context.remote_supported_signature_algorithms, context.local_supported_signature_algorithms);
5394
-
5395
- let sig_data = sign_with_scheme(wire.TLS_VERSION.TLS1_2, scheme12, tbs_data, cert_private_key_obj);
6691
+ let scheme12 = pick_scheme(wire.TLS_VERSION.TLS1_2, cert_private_key_obj, peer_signature_algorithms(false), context.local_supported_signature_algorithms);
6692
+ let sig_data = scheme12 === null ? null : sign_with_scheme(wire.TLS_VERSION.TLS1_2, scheme12, tbs_data, cert_private_key_obj);
6693
+ // No scheme our key can sign with that the client accepts (or the
6694
+ // signing failed): handshake_failure. It went out with sig_alg 0
6695
+ // and an empty signature, for the client to refuse.
6696
+ if (scheme12 === null || !sig_data || sig_data.length === 0) {
6697
+ fatalAlert(wire.TLS_ALERT.HANDSHAKE_FAILURE, 'No signature scheme shared with the client for ServerKeyExchange');
6698
+ return;
6699
+ }
5396
6700
 
5397
6701
 
5398
6702
  let message_data = build_tls_message({
@@ -5439,7 +6743,12 @@ function TLSSession(options){
5439
6743
  // most other 1.2 deployments use RSA. The client picks whichever
5440
6744
  // matches its certificate.
5441
6745
  certificate_types: [1, 64],
5442
- signature_algorithms: context.local_supported_signature_algorithms || [],
6746
+ // Those of TLS 1.2 only (scheme_info: ML-DSA is TLS 1.3's,
6747
+ // draft-ietf-tls-mldsa §3). All were listed: a strict client
6748
+ // (tlsfuzzer) refused a request naming schemes 1.2 has not.
6749
+ signature_algorithms: (context.local_supported_signature_algorithms || []).filter(function (sc) {
6750
+ return scheme_info(wire.TLS_VERSION.TLS1_2, sc) !== null;
6751
+ }),
5443
6752
  certificate_authorities: [], // empty: accept any CA
5444
6753
  });
5445
6754
  let cr_data = wire.build_message(wire.TLS_MESSAGE_TYPE.CERTIFICATE_REQUEST, cr_body);
@@ -5476,9 +6785,9 @@ function TLSSession(options){
5476
6785
  // via SESSION_TICKET ext in SH (which we don't add for abbreviated per RFC 5077 §3.2),
5477
6786
  // so sending NST would cause "unexpected message" errors on strict clients (e.g. openssl).
5478
6787
  // Renewal is optional per RFC 5077 §3.3 — safer to skip it in abbreviated.
5479
- // Excluded for DTLS 1.2 — implementations (e.g. openssl s_server -dtls1_2) don't always
5480
- // support it well. Revisit if needed.
5481
- if (context.selected_version === wire.TLS_VERSION.TLS1_2 &&
6788
+ // DTLS 1.2 as well (see the SessionTicket note in the hello assembler).
6789
+ if ((context.selected_version === wire.TLS_VERSION.TLS1_2 ||
6790
+ context.selected_version === wire.DTLS_VERSION.DTLS1_2) &&
5482
6791
  context.isServer && !context.tls12_newsession_sent && context.sessionTickets &&
5483
6792
  context.tls12_session_ticket_requested && !context.tls12_abbreviated &&
5484
6793
  context.base_secret) {
@@ -5539,13 +6848,6 @@ function TLSSession(options){
5539
6848
  }
5540
6849
  }
5541
6850
 
5542
- // ECH rejected (RFC 9849 §6.1.6): the server's flight has been checked
5543
- // — for the public_name — and nothing of ours follows it.
5544
- if (context.isServer === false && context.ech.status === 'rejected' && context.ech.outer_ch1 &&
5545
- context.remote_finished_ok === true && context.finished_sent === false) {
5546
- ech_abort_rejected();
5547
- return;
5548
- }
5549
6851
 
5550
6852
  // Client, TLS over TCP, early data taken: EndOfEarlyData under the
5551
6853
  // early key, first in the second flight (RFC 8446 §4.5) — epoch 3 for
@@ -5565,13 +6867,18 @@ function TLSSession(options){
5565
6867
  context.remote_finished_ok==true && context.local_handshake_traffic_secret!==null){
5566
6868
  context.clientCertSent = true;
5567
6869
 
5568
- if(context.clientCert && context.clientKey){
6870
+ // ECH rejected: our certificate is not for the public_name's server —
6871
+ // an empty Certificate (RFC 9849 §6.1.7), and the handshake finishes
6872
+ // (then ech_required: the authentication gate).
6873
+ if(context.clientCert && context.clientKey && !ech_rejected_client()){
5569
6874
  // Send client certificate
5570
6875
  // Only include passphrase when there is one — node:crypto treats an
5571
6876
  // explicit null as an error rather than as "no passphrase".
5572
6877
  let certOpts = { key: context.clientKey, cert: context.clientCert };
5573
6878
  if (context.clientKeyPassphrase) certOpts.passphrase = context.clientKeyPassphrase;
5574
- let certCtx = createSecureContext(certOpts);
6879
+ let certCtx;
6880
+ try { certCtx = createSecureContext(certOpts); }
6881
+ catch (e) { fatalAlert(wire.TLS_ALERT.INTERNAL_ERROR, 'client certificate: ' + e.message); return; }
5575
6882
  let cert_data = certificate_message(certCtx.certificateChain, context.certificateRequestContext || new Uint8Array(0));
5576
6883
  pushTranscript(cert_data);
5577
6884
  ev.emit('message', 1, context.message_sent_seq, 'certificate', cert_data);
@@ -5714,6 +7021,13 @@ function TLSSession(options){
5714
7021
 
5715
7022
  if (can_send_finished) {
5716
7023
 
7024
+ // A full-handshake server's Finished answers the client's flight:
7025
+ // it is not sent for a client that has not authenticated.
7026
+ if (context.isServer && !context.tls12_abbreviated) {
7027
+ let authFail = authentication_failure();
7028
+ if (authFail) { fatalAlert(authFail.alert, authFail.reason); return; }
7029
+ }
7030
+
5717
7031
  let finishedHashName = negotiated_hash();
5718
7032
  let transcript_hash = get_transcript_hash(finishedHashName);
5719
7033
 
@@ -5854,7 +7168,7 @@ function TLSSession(options){
5854
7168
  ' hash=' + remoteFinHashName);
5855
7169
  console.log('[lemon-fin] transcript(' + _t.length + '): ' + _list.join(' → '));
5856
7170
  console.log('[lemon-fin] transcriptHash=' +
5857
- _hex(get_transcript_hash(remoteFinHashName, label_prefix())));
7171
+ _hex(get_transcript_hash(remoteFinHashName)));
5858
7172
  console.log('[lemon-fin] remoteSecret=' + _hex(context.remote_handshake_traffic_secret));
5859
7173
  console.log('[lemon-fin] peerSent=' + _hex(context.remote_finished));
5860
7174
  console.log('[lemon-fin] weExpect=' + _hex(params_to_set['expected_remote_finished']));
@@ -5962,55 +7276,21 @@ function TLSSession(options){
5962
7276
  // the durable place for a MUST-have-happened invariant is the state
5963
7277
  // transition it guards, not the event that usually satisfies it.
5964
7278
 
5965
- // Client: the server must have proved possession of its certificate
5966
- // key — TLS 1.3 CertificateVerify, or the TLS 1.2 ServerKeyExchange
5967
- // signature. PSK/abbreviated handshakes authenticate via the binder /
5968
- // resumed master secret instead.
5969
- if (!context.isServer && !context.psk_accepted && !context.tls12_abbreviated &&
5970
- context.peerSignatureVerified !== true) {
5971
- fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE,
5972
- 'Handshake completed without a verified server signature');
7279
+ let authFail = authentication_failure();
7280
+ if (authFail) { fatalAlert(authFail.alert, authFail.reason); return; }
7281
+
7282
+ // ECH rejected (RFC 9849 §6.1.6): "If both authentication and the
7283
+ // handshake complete successfully, the client [...] then abort[s] the
7284
+ // connection with an ech_required alert" — here, after our Finished
7285
+ // and before anything is sent or reported as connected. It aborted
7286
+ // as soon as the server's flight was checked, before its own: a
7287
+ // server that asked for a certificate never saw the empty one
7288
+ // (§6.1.7), nor the handshake finished.
7289
+ if (ech_rejected_client()) {
7290
+ ech_abort_rejected();
5973
7291
  return;
5974
7292
  }
5975
7293
 
5976
- // Server-side client authentication. Two DIFFERENT questions, which
5977
- // were previously collapsed into one condition:
5978
- //
5979
- // (a) Must a client certificate arrive at all? -> policy, and only
5980
- // when we both asked for one and refuse to proceed without it.
5981
- // (b) If a certificate DID arrive, must it be proved? -> ALWAYS.
5982
- //
5983
- // Collapsing them meant a server with requestCert but without
5984
- // rejectUnauthorized skipped the whole block, so a client could send a
5985
- // certificate — any certificate, including one it does not own — and
5986
- // never prove possession, because the CertificateVerify check lived
5987
- // behind the (a) policy flag. Presenting someone else's certificate is
5988
- // an impersonation, not a policy preference, so (b) cannot be optional.
5989
- if (context.isServer && !context.psk_accepted && !context.tls12_abbreviated) {
5990
-
5991
- let clientCertPresent = !!(context.remote_cert_chain && context.remote_cert_chain.length > 0);
5992
-
5993
- // (a) required-but-absent
5994
- if (context.requestCert && context.rejectUnauthorized && !clientCertPresent) {
5995
- fatalAlert(wire.TLS_ALERT.CERTIFICATE_REQUIRED,
5996
- 'Client certificate was required but none was provided');
5997
- return;
5998
- }
5999
-
6000
- // (b) present-but-unproved. Unconditional: it applies even when the
6001
- // certificate was optional, because the question is not "did we want
6002
- // one" but "does this peer own the one it sent". In TLS 1.2 the
6003
- // client's CertificateVerify sets peerSignatureVerified the same way.
6004
- if (clientCertPresent &&
6005
- (context.selected_version === wire.TLS_VERSION.TLS1_3 ||
6006
- context.selected_version === wire.DTLS_VERSION.DTLS1_3) &&
6007
- context.peerSignatureVerified !== true) {
6008
- fatalAlert(wire.TLS_ALERT.UNEXPECTED_MESSAGE,
6009
- 'Client sent a certificate without a valid CertificateVerify');
6010
- return;
6011
- }
6012
- }
6013
-
6014
7294
  context.state='connected';
6015
7295
  context.handshakeEndTime = Date.now();
6016
7296
 
@@ -6023,13 +7303,17 @@ function TLSSession(options){
6023
7303
  // TLS 1.3: compute resumption_master_secret (both client and server need it)
6024
7304
  if ((is13()) && context.tls13_master_secret && !context.resumption_master_secret) {
6025
7305
  let hashName = negotiated_hash();
7306
+ // The prefix is derive_resumption_master_secret_with_hash's fourth
7307
+ // argument. It went to get_transcript_hash, which takes one, so
7308
+ // "res master" was derived with "tls13 " over DTLS too.
6026
7309
  context.resumption_master_secret = derive_resumption_master_secret_with_hash(
6027
- hashName, context.tls13_master_secret, get_transcript_hash(hashName, label_prefix())
7310
+ hashName, context.tls13_master_secret, get_transcript_hash(hashName), label_prefix()
6028
7311
  );
6029
7312
  }
6030
7313
 
6031
7314
  // TLS 1.3 server: send NewSessionTicket
6032
- // Two after a full handshake, one after a resumption — as OpenSSL and
7315
+ // Two after a full handshake (an external PSK's too: it resumed
7316
+ // nothing), one after a resumption — as OpenSSL and
6033
7317
  // BoringSSL issue them: a client uses each ticket once (RFC 8446 §C.4:
6034
7318
  // a ticket reused links the connections, and its 0-RTT is refused as
6035
7319
  // a replay), so a client opening two connections at once — or the
@@ -6037,7 +7321,7 @@ function TLSSession(options){
6037
7321
  if ((is13()) && context.isServer && !context.session_ticket_sent && context.sessionTickets && context.resumption_master_secret) {
6038
7322
  context.session_ticket_sent = true;
6039
7323
  issue_ticket_13();
6040
- if (!context.psk_accepted) issue_ticket_13();
7324
+ if (!context.isResumed) issue_ticket_13();
6041
7325
  }
6042
7326
 
6043
7327
  ev.emit('secureConnect');
@@ -6085,8 +7369,9 @@ function TLSSession(options){
6085
7369
  // Fires at secureConnect when the server gave us a non-empty session_id but no
6086
7370
  // NewSessionTicket — the client's only way to resume is via Session ID, so we must
6087
7371
  // give the user a blob containing session_id + master_secret to pass back later.
6088
- // TLS 1.2 only (DTLS 1.2 excluded for now).
6089
- if (context.selected_version === wire.TLS_VERSION.TLS1_2 &&
7372
+ // TLS 1.2 and DTLS 1.2 (a DTLS server that keeps sessions by id —
7373
+ // OpenSSL's: RFC 9147 §5.3 lets the client offer that id back).
7374
+ if (is12() &&
6090
7375
  !context.isServer && !context.tls12_abbreviated && !context.tls12_client_session_emitted &&
6091
7376
  context.remote_session_id && context.remote_session_id.length > 0 &&
6092
7377
  context.base_secret && context.remote_finished_ok) {
@@ -6145,7 +7430,7 @@ function TLSSession(options){
6145
7430
  * Returns true to continue, false when the caller should stop — the failure
6146
7431
  * state is already recorded on context by then.
6147
7432
  */
6148
- function checkIdentity(x509) {
7433
+ function checkIdentity(cert) {
6149
7434
  // ECH rejected: the server answered as the config's public_name, and
6150
7435
  // must prove that name (RFC 9849 §6.1.6), not the one in the inner hello.
6151
7436
  let expectName = context.ech.verify_name || context.local_sni;
@@ -6168,17 +7453,12 @@ function TLSSession(options){
6168
7453
  return true;
6169
7454
  }
6170
7455
 
6171
- // checkHost matches DNS names and ignores IP SANs entirely, so a
6172
- // connection to a literal address whose certificate carries the matching
6173
- // IP SAN was rejected. RFC 6066 says SNI carries host names only, but this
6174
- // field is populated from whatever the caller connected to, so an address
6175
- // does land here. X509Certificate exposes checkIP for exactly this.
6176
- let host = String(expectName);
6177
- let ok = is_ip_literal(host)
6178
- ? !!x509.checkIP(host.replace(/^\[|\]$/g, ''))
6179
- : !!x509.checkHost(host);
6180
-
6181
- if (!ok) {
7456
+ // RFC 6066 says SNI carries host names only, but this field is populated
7457
+ // from whatever the caller connected to, so an address does land here:
7458
+ // matches_host compares it with the iPAddress names (a connection to a
7459
+ // literal address was once rejected whatever its certificate said).
7460
+ // session/x509.js: the subjectAltName only, whole-label wildcards.
7461
+ if (!matches_host(cert, expectName)) {
6182
7462
  context.authorizationError = 'ERR_TLS_CERT_ALTNAME_INVALID';
6183
7463
  context.peerAuthorized = false;
6184
7464
  return false;
@@ -6194,18 +7474,22 @@ function TLSSession(options){
6194
7474
  }
6195
7475
 
6196
7476
  try {
6197
- // Parse the leaf certificate (first in chain)
6198
- let certDer = context.remote_cert_chain[0].cert;
6199
- let x509 = new crypto.X509Certificate(certDer);
7477
+ // The leaf certificate (first in chain)
7478
+ let cert = peer_leaf_cert();
7479
+ if (!cert) {
7480
+ context.authorizationError = 'CERTIFICATE_PARSE_ERROR';
7481
+ context.peerAuthorized = false;
7482
+ return;
7483
+ }
6200
7484
 
6201
7485
  // Check validity dates
6202
7486
  let now = new Date();
6203
- if (now < new Date(x509.validFrom)) {
7487
+ if (now.getTime() < cert.notBefore) {
6204
7488
  context.authorizationError = 'CERT_NOT_YET_VALID';
6205
7489
  context.peerAuthorized = false;
6206
7490
  return;
6207
7491
  }
6208
- if (now > new Date(x509.validTo)) {
7492
+ if (now.getTime() > cert.notAfter) {
6209
7493
  context.authorizationError = 'CERT_HAS_EXPIRED';
6210
7494
  context.peerAuthorized = false;
6211
7495
  return;
@@ -6237,21 +7521,21 @@ function TLSSession(options){
6237
7521
  if (roots && roots.length > 0) anchors = roots;
6238
7522
  }
6239
7523
 
7524
+ // No anchors (useDefaultCA: false, and no `ca`): nothing to chain to,
7525
+ // so not authorized — node:tls's answer. It was authorized, with a
7526
+ // note (certChainUnverified): a server with requestCert and
7527
+ // rejectUnauthorized took any self-signed client certificate (mTLS
7528
+ // bypassed), a client any self-signed server one with the right name.
7529
+ // A caller that authenticates otherwise (WebRTC: the SDP fingerprint)
7530
+ // says so with rejectUnauthorized: false.
6240
7531
  if (anchors == null ||
6241
7532
  (Array.isArray(anchors) && anchors.length === 0)) {
6242
- // The identity check still runs here. It is the only check left, and
6243
- // skipping it would make "no CA configured" mean "no verification at
6244
- // all" — including any fingerprint pin the caller installed precisely
6245
- // because there is no CA to chain to.
6246
- if (!checkIdentity(x509)) return;
6247
- context.peerAuthorized = true;
6248
- context.authorizationError = null;
6249
- context.certChainUnverified = true; // no trust anchors were available
7533
+ context.authorizationError = self_signed(cert) ? 'DEPTH_ZERO_SELF_SIGNED_CERT' : 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY';
7534
+ context.peerAuthorized = false;
6250
7535
  return;
6251
7536
  }
6252
7537
 
6253
- let cas = Array.isArray(anchors) ? anchors : [anchors];
6254
- let chainResult = verify_cert_chain(context.remote_cert_chain, cas, now);
7538
+ let chainResult = verify_cert_chain(context.remote_cert_chain, anchors, now, context.isServer ? 'client' : 'server', cert);
6255
7539
  if (!chainResult.ok) {
6256
7540
  context.authorizationError = chainResult.error;
6257
7541
  context.peerAuthorized = false;
@@ -6267,7 +7551,7 @@ function TLSSession(options){
6267
7551
  // never verified — the hook author reasonably assumes the CA check
6268
7552
  // already happened. Running identity before the chain quietly turns
6269
7553
  // every such pin into the ONLY check.
6270
- if (!checkIdentity(x509)) return;
7554
+ if (!checkIdentity(cert)) return;
6271
7555
 
6272
7556
  // All checks passed
6273
7557
  context.peerAuthorized = true;
@@ -6346,371 +7630,355 @@ function TLSSession(options){
6346
7630
  }
6347
7631
 
6348
7632
 
7633
+ // The ClientHello goes on the next tick, once the layer above has its
7634
+ // listeners. What fails building it (a configuration that cannot be
7635
+ // offered — an external PSK with no TLS 1.3 — or anything else) is this
7636
+ // session's 'error', as anything later is: thrown from a timer, it took
7637
+ // the process down. Nothing was sent, so there is no alert to send.
6349
7638
  if(context.isServer==false){
6350
7639
  setTimeout(function(){
7640
+ if (context.state === 'closed' || context.state === 'error') return;
7641
+ try { send_client_hello(); }
7642
+ catch (e) { context.state = 'error'; ev.emit('error', e instanceof Error ? e : new Error(String(e))); }
7643
+ },0);
7644
+ }
6351
7645
 
6352
- if(context.local_random==null){
6353
- context.local_random=new Uint8Array(crypto.randomBytes(32));
6354
- }
7646
+ function send_client_hello(){
6355
7647
 
6356
- if(context.local_session_id==null){
6357
- context.local_session_id=new Uint8Array(crypto.randomBytes(32));
6358
- }
7648
+ if(context.local_random==null){
7649
+ context.local_random=new Uint8Array(crypto.randomBytes(32));
7650
+ }
6359
7651
 
6360
- // TLS 1.3-only mode (QUIC and any client that offers no other version):
6361
- // the ClientHello must not carry TLS 1.2 baggage. QUIC mandates TLS 1.3
6362
- // (RFC 9001), and strict 1.3-only stacks reject hellos with legacy
6363
- // artifacts. Detected from the configured versions, so plain TLS over
6364
- // TCP (which offers 1.3+1.2) keeps the full compatibility behavior.
6365
- // Which versions does this profile actually offer? The suite list must
6366
- // follow BOTH answers, not just one of them.
6367
- //
6368
- // The old form asked only "is this 1.3-only?" and hardcoded the 1.3 half
6369
- // to true, so a 1.2-ONLY profile still advertised 0x1301..0x1303. Those
6370
- // suites cannot be negotiated at 1.2 — a TLS 1.3 suite is meaningless in
6371
- // a 1.2 handshake — so the hello claimed capabilities the profile had
6372
- // ruled out. The asymmetry was invisible because only the 1.3-only case
6373
- // had ever been considered.
6374
- let offers13 = context.local_supported_versions.length === 0 ||
6375
- context.local_supported_versions.indexOf(wire.TLS_VERSION.TLS1_3) >= 0 ||
6376
- context.local_supported_versions.indexOf(wire.DTLS_VERSION.DTLS1_3) >= 0;
6377
- let offers12 = context.local_supported_versions.length === 0 ||
6378
- context.local_supported_versions.some(v => v !== wire.TLS_VERSION.TLS1_3 &&
6379
- v !== wire.DTLS_VERSION.DTLS1_3);
7652
+ if(context.local_session_id==null){
7653
+ context.local_session_id=new Uint8Array(crypto.randomBytes(32));
7654
+ }
6380
7655
 
6381
- if(context.local_supported_cipher_suites.length<=0){
6382
- // crypto.js owns the default suite list; we only say which halves apply.
6383
- context.local_supported_cipher_suites = default_cipher_suites(offers13, offers12);
6384
- }
7656
+ // TLS 1.3-only mode (QUIC and any client that offers no other version):
7657
+ // the ClientHello must not carry TLS 1.2 baggage. QUIC mandates TLS 1.3
7658
+ // (RFC 9001), and strict 1.3-only stacks reject hellos with legacy
7659
+ // artifacts. Detected from the configured versions, so plain TLS over
7660
+ // TCP (which offers 1.3+1.2) keeps the full compatibility behavior.
7661
+ // Which versions does this profile actually offer? The suite list must
7662
+ // follow BOTH answers, not just one of them.
7663
+ //
7664
+ // The old form asked only "is this 1.3-only?" and hardcoded the 1.3 half
7665
+ // to true, so a 1.2-ONLY profile still advertised 0x1301..0x1303. Those
7666
+ // suites cannot be negotiated at 1.2 — a TLS 1.3 suite is meaningless in
7667
+ // a 1.2 handshake — so the hello claimed capabilities the profile had
7668
+ // ruled out. The asymmetry was invisible because only the 1.3-only case
7669
+ // had ever been considered.
7670
+ fill_default_lists();
7671
+ let offers13 = lists13(context.local_supported_versions);
7672
+
7673
+ // Initial key_share: generate for our most-preferred group that we can
7674
+ // actually PRODUCE a share for. If the server wants a different one it
7675
+ // sends HelloRetryRequest, handled above.
7676
+ //
7677
+ // The list may name groups ecdh.js does not implement — a configured
7678
+ // curve list is not a capability list, and a post-quantum group can sit
7679
+ // in it because a caller passed it straight through. generate_keypair
7680
+ // returns null for those (it does not throw), and this code used to read
7681
+ // `.public_key` off that null and crash the whole session with a
7682
+ // TypeError before a single byte was sent. Skip what we cannot make; if
7683
+ // that leaves nothing, say so plainly rather than dying.
7684
+ let initialGroup = null;
7685
+ let initialKp = null;
7686
+ for (let gi = 0; gi < context.local_supported_groups.length; gi++) {
7687
+ let g = context.local_supported_groups[gi];
7688
+ if (!is_supported_group(g)) continue;
7689
+ if (!offers13 && is_kem_group(g)) continue; // not in a 1.2-only hello (see above)
7690
+ let kp = ecdh_generate_keypair(g);
7691
+ if (!kp) continue;
7692
+ initialGroup = g;
7693
+ initialKp = kp;
7694
+ break;
7695
+ }
6385
7696
 
6386
- if(context.local_supported_groups.length<=0){
6387
- context.local_supported_groups = ECDH_SUPPORTED_GROUPS.slice(); // whatever ecdh.js implements
6388
- }
7697
+ if (initialKp === null) {
7698
+ fatalAlert(wire.TLS_ALERT.INTERNAL_ERROR,
7699
+ 'No configured key-exchange group is implemented — cannot build a key_share');
7700
+ return;
7701
+ }
6389
7702
 
6390
- if(context.local_supported_versions.length<=0){
6391
- context.local_supported_versions=[0x0304, 0x0303]; // TLS 1.3, TLS 1.2
6392
- }
7703
+ let public_key = initialKp.public_key;
6393
7704
 
6394
- // Initial key_share: generate for our most-preferred group that we can
6395
- // actually PRODUCE a share for. If the server wants a different one it
6396
- // sends HelloRetryRequest, handled above.
6397
- //
6398
- // The list may name groups ecdh.js does not implement — a configured
6399
- // curve list is not a capability list, and a post-quantum group can sit
6400
- // in it because a caller passed it straight through. generate_keypair
6401
- // returns null for those (it does not throw), and this code used to read
6402
- // `.public_key` off that null and crash the whole session with a
6403
- // TypeError before a single byte was sent. Skip what we cannot make; if
6404
- // that leaves nothing, say so plainly rather than dying.
6405
- let initialGroup = null;
6406
- let initialKp = null;
7705
+ context.local_key_groups[initialGroup]={
7706
+ public_key: initialKp.public_key,
7707
+ private_key: initialKp.private_key
7708
+ };
7709
+
7710
+ // A post-quantum group first gets a classical share beside it — the
7711
+ // next implemented non-KEM group in the list — as browsers do. A server
7712
+ // without the hybrid group then uses the classical share at once; with
7713
+ // only the hybrid share it would have to ask again (HelloRetryRequest),
7714
+ // a round trip on every connection to a classical server. Each share's
7715
+ // key stays in local_key_groups, so whichever the server picks is there.
7716
+ let extraKeyShares = null;
7717
+ if (is_kem_group(initialGroup)) {
6407
7718
  for (let gi = 0; gi < context.local_supported_groups.length; gi++) {
6408
- let g = context.local_supported_groups[gi];
6409
- if (!is_supported_group(g)) continue;
6410
- if (!offers13 && is_kem_group(g)) continue; // not in a 1.2-only hello (see above)
6411
- let kp = ecdh_generate_keypair(g);
6412
- if (!kp) continue;
6413
- initialGroup = g;
6414
- initialKp = kp;
7719
+ let g2 = context.local_supported_groups[gi];
7720
+ if (g2 === initialGroup || is_kem_group(g2) || !is_supported_group(g2)) continue;
7721
+ let kp2 = ecdh_generate_keypair(g2);
7722
+ if (!kp2) continue;
7723
+ context.local_key_groups[g2] = { public_key: kp2.public_key, private_key: kp2.private_key };
7724
+ extraKeyShares = [{ group: g2, key_exchange: kp2.public_key }];
6415
7725
  break;
6416
7726
  }
7727
+ }
6417
7728
 
6418
- if (initialKp === null) {
6419
- fatalAlert(wire.TLS_ALERT.INTERNAL_ERROR,
6420
- 'No configured key-exchange group is implemented — cannot build a key_share');
6421
- return;
6422
- }
6423
-
6424
- let public_key = initialKp.public_key;
7729
+ // Honor the configured signature algorithms; the hardcoded list is only
7730
+ // the default when none were set (previously the configured list was
7731
+ // ignored here — while the HRR CH2 hardcoded its own, so CH1 and CH2
7732
+ // could differ, violating RFC 8446 §4.1.2's exact-match requirement).
7733
+ let ch_sigalgs = (context.local_supported_signature_algorithms &&
7734
+ context.local_supported_signature_algorithms.length > 0)
7735
+ ? context.local_supported_signature_algorithms
7736
+ : default_signature_schemes(); // signing.js owns the list
7737
+ context.local_supported_signature_algorithms = ch_sigalgs; // for CH2 reuse
7738
+
7739
+ // supported_versions (43) and key_share (51) are the TLS 1.3
7740
+ // negotiation machinery (RFC 8446 §4.1.2, §4.2.8). Offer them only
7741
+ // when 1.3 is actually in the offered version set — a pure 1.2
7742
+ // hello must look like a 1.2 hello, exactly as OpenSSL/BoringSSL
7743
+ // behave with max_version=1.2. Previously both were emitted
7744
+ // unconditionally, so even a maxVersion:'DTLSv1.2' profile (the
7745
+ // WebRTC default) advertised a single-entry supported_versions and
7746
+ // a dangling key_share: spec-legal (receivers MUST ignore unknown
7747
+ // extensions, RFC 5246 §7.4.1.4) but non-canonical — and fatal to
7748
+ // at least one deployed stack (webrtc-dtls ≤0.7 hard-errors on any
7749
+ // extension outside its known set, then poisons its replay window
7750
+ // so no retransmission can ever recover the handshake).
7751
+ // Same assembler as the post-HelloRetryRequest CH2 (RFC 8446 §4.1.2
7752
+ // requires the two hellos to be identical apart from key_share/cookie).
7753
+ // Kept for a HelloRetryRequest that asks for no group (a cookie
7754
+ // alone): the second hello repeats these shares, all of them.
7755
+ context.ch1_key_shares = { group: initialGroup, key_exchange: public_key, extra: extraKeyShares };
7756
+ let extensions = build_client_hello_extensions({
7757
+ keyShareGroup: initialGroup,
7758
+ keySharePublic: public_key,
7759
+ extraKeyShares: extraKeyShares,
7760
+ cookie: null
7761
+ });
6425
7762
 
6426
- context.local_key_groups[initialGroup]={
6427
- public_key: initialKp.public_key,
6428
- private_key: initialKp.private_key
6429
- };
7763
+ // ECH: this list is the inner hello's; the outer one is made from it
7764
+ // once the inner hello — its PSK binder included — is complete.
7765
+ let echSplit = null;
7766
+ if (ech_on()) {
7767
+ context.ech.inner_random = context.local_random;
7768
+ context.ech.outer_random = new Uint8Array(crypto.randomBytes(32));
7769
+ echSplit = ech_split(extensions);
7770
+ }
6430
7771
 
6431
- // A post-quantum group first gets a classical share beside it — the
6432
- // next implemented non-KEM group in the list — as browsers do. A server
6433
- // without the hybrid group then uses the classical share at once; with
6434
- // only the hybrid share it would have to ask again (HelloRetryRequest),
6435
- // a round trip on every connection to a classical server. Each share's
6436
- // key stays in local_key_groups, so whichever the server picks is there.
6437
- let extraKeyShares = null;
6438
- if (is_kem_group(initialGroup)) {
6439
- for (let gi = 0; gi < context.local_supported_groups.length; gi++) {
6440
- let g2 = context.local_supported_groups[gi];
6441
- if (g2 === initialGroup || is_kem_group(g2) || !is_supported_group(g2)) continue;
6442
- let kp2 = ecdh_generate_keypair(g2);
6443
- if (!kp2) continue;
6444
- context.local_key_groups[g2] = { public_key: kp2.public_key, private_key: kp2.private_key };
6445
- extraKeyShares = [{ group: g2, key_exchange: kp2.public_key }];
6446
- break;
6447
- }
6448
- }
6449
-
6450
- // Honor the configured signature algorithms; the hardcoded list is only
6451
- // the default when none were set (previously the configured list was
6452
- // ignored here — while the HRR CH2 hardcoded its own, so CH1 and CH2
6453
- // could differ, violating RFC 8446 §4.1.2's exact-match requirement).
6454
- let ch_sigalgs = (context.local_supported_signature_algorithms &&
6455
- context.local_supported_signature_algorithms.length > 0)
6456
- ? context.local_supported_signature_algorithms
6457
- : default_signature_schemes(); // signing.js owns the list
6458
- context.local_supported_signature_algorithms = ch_sigalgs; // for CH2 reuse
6459
-
6460
- // supported_versions (43) and key_share (51) are the TLS 1.3
6461
- // negotiation machinery (RFC 8446 §4.1.2, §4.2.8). Offer them only
6462
- // when 1.3 is actually in the offered version set — a pure 1.2
6463
- // hello must look like a 1.2 hello, exactly as OpenSSL/BoringSSL
6464
- // behave with max_version=1.2. Previously both were emitted
6465
- // unconditionally, so even a maxVersion:'DTLSv1.2' profile (the
6466
- // WebRTC default) advertised a single-entry supported_versions and
6467
- // a dangling key_share: spec-legal (receivers MUST ignore unknown
6468
- // extensions, RFC 5246 §7.4.1.4) but non-canonical — and fatal to
6469
- // at least one deployed stack (webrtc-dtls ≤0.7 hard-errors on any
6470
- // extension outside its known set, then poisons its replay window
6471
- // so no retransmission can ever recover the handshake).
6472
- // Same assembler as the post-HelloRetryRequest CH2 (RFC 8446 §4.1.2
6473
- // requires the two hellos to be identical apart from key_share/cookie).
6474
- let extensions = build_client_hello_extensions({
6475
- keyShareGroup: initialGroup,
6476
- keySharePublic: public_key,
6477
- extraKeyShares: extraKeyShares,
6478
- cookie: null
6479
- });
7772
+ // What the hello offers as its PSK: the external one, when there is one
7773
+ // — the connection's credential, which a server that knows it takes — or
7774
+ // else a saved session. A ticket offered in its place could leave a
7775
+ // server that takes PSKs only with nothing to go on (one it no longer
7776
+ // opens; one for another server name, not offered at all), and no way
7777
+ // back to the PSK.
7778
+ let sessionData = null;
7779
+ if (context.external_psk) {
7780
+ sessionData = external_psk_offer();
7781
+ } else if (options.session) {
7782
+ // options.session may be a Buffer/Uint8Array (Node.js style) or a plain object (legacy)
7783
+ if (options.session instanceof Uint8Array || Buffer.isBuffer(options.session)) {
7784
+ sessionData = decode_client_session(options.session);
7785
+ } else if (typeof options.session === 'object') {
7786
+ sessionData = options.session; // legacy: already-structured object
7787
+ }
7788
+ // A saved session: only where it may be (client_session_usable).
7789
+ if (sessionData && !client_session_usable(sessionData)) sessionData = null;
7790
+ } else if (options.psk) {
7791
+ sessionData = options.psk; // legacy: a resumption PSK, already structured
7792
+ }
6480
7793
 
6481
- // ECH: this list is the inner hello's; the outer one is made from it
6482
- // once the inner hello — its PSK binder included — is complete.
6483
- let echSplit = null;
6484
- if (ech_on()) {
6485
- context.ech.inner_random = context.local_random;
6486
- context.ech.outer_random = new Uint8Array(crypto.randomBytes(32));
6487
- echSplit = ech_split(extensions);
6488
- }
6489
-
6490
- // Resumption: check if session was provided (opaque Buffer) — decode to structured data
6491
- let sessionData = null;
6492
- if (options.session) {
6493
- // options.session may be a Buffer/Uint8Array (Node.js style) or a plain object (legacy)
6494
- if (options.session instanceof Uint8Array || Buffer.isBuffer(options.session)) {
6495
- sessionData = decode_client_session(options.session);
6496
- } else if (typeof options.session === 'object') {
6497
- sessionData = options.session; // legacy: already-structured object
6498
- }
6499
- // A saved session: only where it may be (client_session_usable). An
6500
- // external PSK (options.psk) authenticates the server by itself.
6501
- if (sessionData && !client_session_usable(sessionData)) sessionData = null;
6502
- } else if (options.psk) {
6503
- sessionData = options.psk; // legacy path
6504
- }
6505
-
6506
- let message_data;
6507
-
6508
- // TLS 1.3 PSK resumption (sessionData contains psk)
6509
- if (sessionData && sessionData.psk && sessionData.ticket && sessionData.cipher) {
6510
- // psk_key_exchange_modes (psk_dhe_ke) is already in the hello: the
6511
- // assembler adds it to every hello that offers 1.3.
6512
-
6513
- // Save PSK for later verification
6514
- context.psk_offered = {
6515
- identity: sessionData.ticket,
6516
- psk: sessionData.psk instanceof Uint8Array ? sessionData.psk : new Uint8Array(sessionData.psk),
6517
- cipher: sessionData.cipher,
6518
- age_add: sessionData.age_add || 0,
6519
- created: sessionData.created, lifetime: sessionData.lifetime, // the age again, in a second hello
6520
- session: options.session ? sessionData : null, // the server it was made with (restore_client_session_peer)
6521
- };
7794
+ let message_data;
7795
+
7796
+ // TLS 1.3 PSK resumption (sessionData contains psk)
7797
+ if (sessionData && sessionData.psk && sessionData.ticket && sessionData.cipher) {
7798
+ // psk_key_exchange_modes (psk_dhe_ke) is already in the hello: the
7799
+ // assembler adds it to every hello that offers 1.3.
7800
+
7801
+ // Save PSK for later verification
7802
+ context.psk_offered = {
7803
+ identity: sessionData.ticket,
7804
+ psk: sessionData.psk instanceof Uint8Array ? sessionData.psk : new Uint8Array(sessionData.psk),
7805
+ cipher: sessionData.cipher,
7806
+ age_add: sessionData.age_add || 0,
7807
+ created: sessionData.created, lifetime: sessionData.lifetime, // the age again, in a second hello
7808
+ session: options.session ? sessionData : null, // the server it was made with (restore_client_session_peer)
7809
+ external: sessionData.external === true,
7810
+ };
6522
7811
 
6523
- // Compute obfuscated ticket age
6524
- let ticketAge = sessionData.lifetime ? Math.min((Date.now() - (sessionData.created || Date.now())) / 1000, sessionData.lifetime) * 1000 : 0;
6525
- let obfuscatedAge = ((ticketAge + (sessionData.age_add || 0)) & 0xFFFFFFFF) >>> 0;
7812
+ // Compute obfuscated ticket age
7813
+ let obfuscatedAge = obfuscated_ticket_age(sessionData);
6526
7814
 
6527
- // Build ClientHello with placeholder binder to compute truncated hash
6528
- let hashName = TLS_CIPHER_SUITES[sessionData.cipher] ? TLS_CIPHER_SUITES[sessionData.cipher].hash : 'sha256';
6529
- let hashLen = getHashFn(hashName).outputLen;
6530
- let placeholderBinder = new Uint8Array(hashLen);
7815
+ // Build ClientHello with placeholder binder to compute truncated hash
7816
+ let hashName = TLS_CIPHER_SUITES[sessionData.cipher] ? TLS_CIPHER_SUITES[sessionData.cipher].hash : 'sha256';
7817
+ let hashLen = getHashFn(hashName).outputLen;
7818
+ let placeholderBinder = new Uint8Array(hashLen);
6531
7819
 
6532
- let pskExt = {
7820
+ let pskExt = {
7821
+ type: 'PRE_SHARED_KEY',
7822
+ value: {
7823
+ identities: [{ identity: sessionData.ticket, age: obfuscatedAge }],
7824
+ binders: [placeholderBinder]
7825
+ }
7826
+ };
7827
+ // 0-RTT (RFC 8446 §4.2.10): offered with a ticket that allows it,
7828
+ // when the ALPN it was made with is one offered now (the server must
7829
+ // pick it again). With ECH too (RFC 9849 §6.1): the early data is
7830
+ // the inner hello's — its keys from the inner transcript, which a
7831
+ // server that decrypts it uses — and early_data goes in the outer
7832
+ // hello as well, so a server that does not decrypt it knows to skip
7833
+ // what follows (RFC 8446 §4.2.10). Early data was never offered with
7834
+ // ECH: a client using ECH paid a round trip on every resumption.
7835
+ if (context.earlyData && (sessionData.max_early_data >>> 0) > 0 &&
7836
+ (!sessionData.alpn || (context.local_supported_alpns || []).indexOf(sessionData.alpn) >= 0)) {
7837
+ let edExt = { type: wire.TLS_EXT.EARLY_DATA, data: new Uint8Array(0) };
7838
+ extensions.push(edExt);
7839
+ note_offered_extensions([edExt]);
7840
+ if (echSplit) echSplit.outer.push(edExt);
7841
+ context.early.offered = true;
7842
+ context.early.alpn = sessionData.alpn || null;
7843
+ context.early.maxEarly = sessionData.max_early_data >>> 0;
7844
+ context.early.appData = sessionData.qa != null ? sessionData.qa : null;
7845
+ }
7846
+ extensions.push(pskExt); // MUST be last
7847
+ note_offered_extensions([pskExt]);
7848
+ // ECH: the ticket is the inner hello's alone; the outer one carries
7849
+ // a pre_shared_key of the same shape with random contents (RFC 9849
7850
+ // §10.12.3), so it does not show resumption was attempted — and a
7851
+ // server that does not decrypt finds no ticket there, and does a
7852
+ // full handshake. Last in the outer hello too.
7853
+ if (echSplit) {
7854
+ echSplit.outerPsk = {
6533
7855
  type: 'PRE_SHARED_KEY',
6534
7856
  value: {
6535
- identities: [{ identity: sessionData.ticket, age: obfuscatedAge }],
6536
- binders: [placeholderBinder]
7857
+ identities: [{ identity: new Uint8Array(crypto.randomBytes(sessionData.ticket.length)), age: crypto.randomBytes(4).readUInt32BE(0) }],
7858
+ binders: [new Uint8Array(crypto.randomBytes(hashLen))]
6537
7859
  }
6538
7860
  };
6539
- // 0-RTT (RFC 8446 §4.2.10): offered with a ticket that allows it,
6540
- // when the ALPN it was made with is one offered now (the server must
6541
- // pick it again). With ECH too (RFC 9849 §6.1): the early data is
6542
- // the inner hello's — its keys from the inner transcript, which a
6543
- // server that decrypts it uses — and early_data goes in the outer
6544
- // hello as well, so a server that does not decrypt it knows to skip
6545
- // what follows (RFC 8446 §4.2.10). Early data was never offered with
6546
- // ECH: a client using ECH paid a round trip on every resumption.
6547
- if (context.earlyData && (sessionData.max_early_data >>> 0) > 0 &&
6548
- (!sessionData.alpn || (context.local_supported_alpns || []).indexOf(sessionData.alpn) >= 0)) {
6549
- let edExt = { type: wire.TLS_EXT.EARLY_DATA, data: new Uint8Array(0) };
6550
- extensions.push(edExt);
6551
- note_offered_extensions([edExt]);
6552
- if (echSplit) echSplit.outer.push(edExt);
6553
- context.early.offered = true;
6554
- context.early.alpn = sessionData.alpn || null;
6555
- context.early.maxEarly = sessionData.max_early_data >>> 0;
6556
- context.early.appData = sessionData.qa != null ? sessionData.qa : null;
6557
- }
6558
- extensions.push(pskExt); // MUST be last
6559
- note_offered_extensions([pskExt]);
6560
- // ECH: the ticket is the inner hello's alone; the outer one carries
6561
- // a pre_shared_key of the same shape with random contents (RFC 9849
6562
- // §10.12.3), so it does not show resumption was attempted — and a
6563
- // server that does not decrypt finds no ticket there, and does a
6564
- // full handshake. Last in the outer hello too.
6565
- if (echSplit) {
6566
- echSplit.outerPsk = {
6567
- type: 'PRE_SHARED_KEY',
6568
- value: {
6569
- identities: [{ identity: new Uint8Array(crypto.randomBytes(sessionData.ticket.length)), age: crypto.randomBytes(4).readUInt32BE(0) }],
6570
- binders: [new Uint8Array(crypto.randomBytes(hashLen))]
6571
- }
6572
- };
6573
- }
7861
+ }
6574
7862
 
6575
- // Build the full message with placeholder
6576
- let build_message_params = {
6577
- type: 'client_hello',
6578
- version: 0x0303,
6579
- random: context.local_random,
6580
- session_id: context.local_session_id,
6581
- cookie: context.dtls_cookie,
6582
- // BUGFIX: `cipher_suites` (plural) is what wire.js's client_hello
6583
- // builder actually reads; the singular key was silently ignored and
6584
- // wire.js substituted its own hardcoded fallback list — the
6585
- // configured cipher suites never reached the wire. Both names passed.
6586
- cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
6587
- cipher_suite: context.local_supported_cipher_suites,
6588
- extensions: extensions
6589
- };
6590
- let tempMessage = build_tls_message(build_message_params);
6591
-
6592
- // Truncation point: message length - binders vec (2 + 1 + hashLen)
6593
- let bindersSize = 2 + 1 + hashLen;
6594
- let truncatedMessage = tempMessage.slice(0, tempMessage.length - bindersSize);
6595
-
6596
- // Compute real binder
6597
- let binder_key = derive_binder_key(hashName, context.psk_offered.psk, false, label_prefix());
6598
- let binder = compute_psk_binder(hashName, binder_key, truncatedMessage, label_prefix());
6599
-
6600
- dbg('CLI-PSK', 'ticket:', hexPreview(sessionData.ticket, 24),
6601
- 'cipher:', '0x' + sessionData.cipher.toString(16),
6602
- 'hash:', hashName);
6603
- dbg('CLI-PSK', 'psk:', hexPreview(sessionData.psk, 8),
6604
- 'age_add:', sessionData.age_add,
6605
- 'lifetime:', sessionData.lifetime,
6606
- 'ticketAge (ms):', ticketAge,
6607
- 'obfuscatedAge:', obfuscatedAge);
6608
- dbg('CLI-PSK', 'truncatedMessage len:', truncatedMessage.length,
6609
- 'full CH len (after real binder):', 'see next');
6610
- dbg('CLI-PSK', 'sent binder:', hexPreview(binder, 16));
6611
-
6612
- // Rebuild with real binder
6613
- pskExt.value.binders = [binder];
6614
- message_data = build_tls_message(build_message_params);
6615
-
6616
- } else if (!echSplit && sessionData && sessionData.v === 12 && sessionData.master_secret) {
6617
- // TLS 1.2 resumption: session ID and/or SessionTicket
6618
- // Save for later verification when ServerHello arrives
6619
- context.tls12_client_session = sessionData;
6620
-
6621
- // Only advertise SESSION_TICKET ext if we actually have a ticket to present.
6622
- // If we only have a session_id (no ticket), don't include empty SESSION_TICKET ext:
6623
- // servers with SSL_OP_NO_TICKET can behave inconsistently when the extension appears
6624
- // alongside a session_id resumption attempt — they may skip the session_id lookup.
6625
- // Fill in the ticket on the SESSION_TICKET entry the assembler already
6626
- // produced, rather than pushing a second one — two extensions of the
6627
- // same type is itself a protocol violation (RFC 8446 §4.2), and it
6628
- // would also change CH2's extension list relative to CH1. If the
6629
- // assembler did not emit one (1.3-only or DTLS profile), there is
6630
- // nothing to resume with here anyway.
6631
- if (sessionData.ticket && sessionData.ticket.length > 0) {
6632
- let stEntry = null;
6633
- for (let ei = 0; ei < extensions.length; ei++) {
6634
- if (extensions[ei] && extensions[ei].type === 'SESSION_TICKET') { stEntry = extensions[ei]; break; }
6635
- }
6636
- if (stEntry) stEntry.value = sessionData.ticket;
6637
- }
6638
-
6639
- // If we have a session_id → put it in ClientHello.session_id (overrides the random one)
6640
- let sid = context.local_session_id;
6641
- if (sessionData.session_id && sessionData.session_id.length > 0) {
6642
- sid = sessionData.session_id;
6643
- context.local_session_id = sid;
6644
- }
6645
-
6646
- let build_message_params = {
6647
- type: 'client_hello',
6648
- version: 0x0303,
6649
- random: context.local_random,
6650
- session_id: sid,
6651
- cookie: context.dtls_cookie,
6652
- // BUGFIX: `cipher_suites` (plural) is what wire.js's client_hello
6653
- // builder actually reads; the singular key was silently ignored and
6654
- // wire.js substituted its own hardcoded fallback list — the
6655
- // configured cipher suites never reached the wire. Both names passed.
6656
- cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
6657
- cipher_suite: context.local_supported_cipher_suites,
6658
- extensions: extensions
6659
- };
6660
- message_data = build_tls_message(build_message_params);
7863
+ // Build the full message with placeholder
7864
+ let build_message_params = client_hello_params(context.local_random, context.local_session_id, extensions);
7865
+ let tempMessage = build_tls_message(build_message_params);
7866
+
7867
+ // Truncation point: message length - binders vec (2 + 1 + hashLen)
7868
+ let bindersSize = 2 + 1 + hashLen;
7869
+ let truncatedMessage = tempMessage.slice(0, tempMessage.length - bindersSize);
7870
+
7871
+ // Compute real binder
7872
+ let binder_key = derive_binder_key(hashName, context.psk_offered.psk, context.psk_offered.external === true, label_prefix());
7873
+ let binder = compute_psk_binder(hashName, binder_key, truncatedMessage, label_prefix());
7874
+
7875
+ if (LEMON_DEBUG) dbg('CLI-PSK', 'ticket:', hexPreview(sessionData.ticket, 24),
7876
+ 'cipher:', '0x' + sessionData.cipher.toString(16),
7877
+ 'hash:', hashName);
7878
+ if (LEMON_DEBUG) dbg('CLI-PSK', 'psk:', hexPreview(sessionData.psk, 8),
7879
+ 'age_add:', sessionData.age_add,
7880
+ 'lifetime:', sessionData.lifetime,
7881
+ 'obfuscatedAge:', obfuscatedAge);
7882
+ dbg('CLI-PSK', 'truncatedMessage len:', truncatedMessage.length,
7883
+ 'full CH len (after real binder):', 'see next');
7884
+ if (LEMON_DEBUG) dbg('CLI-PSK', 'sent binder:', hexPreview(binder, 16));
7885
+
7886
+ // Rebuild with real binder
7887
+ pskExt.value.binders = [binder];
7888
+ message_data = build_tls_message(build_message_params);
7889
+
7890
+ } else if (!echSplit && sessionData && sessionData.v === 12 && sessionData.master_secret) {
7891
+ // TLS 1.2 resumption: session ID and/or SessionTicket
7892
+ // Save for later verification when ServerHello arrives
7893
+ context.tls12_client_session = sessionData;
7894
+
7895
+ // Only advertise SESSION_TICKET ext if we actually have a ticket to present.
7896
+ // If we only have a session_id (no ticket), don't include empty SESSION_TICKET ext:
7897
+ // servers with SSL_OP_NO_TICKET can behave inconsistently when the extension appears
7898
+ // alongside a session_id resumption attempt — they may skip the session_id lookup.
7899
+ // Fill in the ticket on the SESSION_TICKET entry the assembler already
7900
+ // produced, rather than pushing a second one — two extensions of the
7901
+ // same type is itself a protocol violation (RFC 8446 §4.2), and it
7902
+ // would also change CH2's extension list relative to CH1. If the
7903
+ // assembler did not emit one (1.3-only or DTLS profile), there is
7904
+ // nothing to resume with here anyway.
7905
+ // DTLS: the ClientHello's session_id is empty (dtls_session pins it:
7906
+ // RFC 9147 §5.3, and webrtc-dtls ≤0.7 misparses any other). A ticket
7907
+ // is recognised as accepted by the server echoing a session_id we
7908
+ // sent with it (RFC 5077 §3.4; case (b) at the ServerHello). So,
7909
+ // presenting a ticket over DTLS 1.2 alone: a fresh 32-byte
7910
+ // session_id. Offering DTLS 1.3 as well, RFC 9147 §5.3 allows the
7911
+ // hello only a session_id a pre-1.3 server set: the ticket goes with
7912
+ // none, and what follows the ServerHello says (RFC 5077 §3.4: "the
7913
+ // client ... can detect ... by the receipt of" the server's
7914
+ // NewSessionTicket or ChangeCipherSpec, where a full handshake has
7915
+ // its Certificate) — tls12_resume_maybe. The ticket stayed home: a
7916
+ // client offering both versions, the default, never resumed DTLS 1.2.
7917
+ let dtlsTicket = dtls_transport() && sessionData.ticket && sessionData.ticket.length > 0 &&
7918
+ !(sessionData.session_id && sessionData.session_id.length > 0);
7919
+ let presentTicket = !!(sessionData.ticket && sessionData.ticket.length > 0);
7920
+ context.tls12_ticket_blind = !!(presentTicket && dtlsTicket && offersDtls13());
7921
+ if (presentTicket) {
7922
+ let stEntry = null;
7923
+ for (let ei = 0; ei < extensions.length; ei++) {
7924
+ if (extensions[ei] && extensions[ei].type === 'SESSION_TICKET') { stEntry = extensions[ei]; break; }
7925
+ }
7926
+ if (stEntry) stEntry.value = sessionData.ticket;
7927
+ }
7928
+ if (!presentTicket && !(sessionData.session_id && sessionData.session_id.length > 0)) {
7929
+ context.tls12_client_session = null; // nothing offered: a full handshake
7930
+ }
7931
+
7932
+ // If we have a session_id → put it in ClientHello.session_id (overrides the random one)
7933
+ let sid = context.local_session_id;
7934
+ if (sessionData.session_id && sessionData.session_id.length > 0) {
7935
+ sid = sessionData.session_id;
7936
+ context.local_session_id = sid;
7937
+ } else if (presentTicket && dtlsTicket && !context.tls12_ticket_blind && (!sid || sid.length === 0)) {
7938
+ sid = new Uint8Array(crypto.randomBytes(32));
7939
+ context.local_session_id = sid;
7940
+ }
7941
+
7942
+ let build_message_params = client_hello_params(context.local_random, sid, extensions);
7943
+ message_data = build_tls_message(build_message_params);
6661
7944
 
6662
- } else {
6663
- // No resumption — advertise empty SessionTicket extension to offer support.
6664
- // Skip for DTLS (DTLS clients/servers often don't implement RFC 5077 fully,
6665
- // and adding it caused interop issues with openssl s_server -dtls1_2).
6666
- // Standard ClientHello
6667
- let build_message_params = {
6668
- type: 'client_hello',
6669
- version: 0x0303,
6670
- random: context.local_random,
6671
- session_id: context.local_session_id,
6672
- cookie: context.dtls_cookie,
6673
- // BUGFIX: `cipher_suites` (plural) is what wire.js's client_hello
6674
- // builder actually reads; the singular key was silently ignored and
6675
- // wire.js substituted its own hardcoded fallback list — the
6676
- // configured cipher suites never reached the wire. Both names passed.
6677
- cipher_suites: grease_cipher_suites(context.local_supported_cipher_suites),
6678
- cipher_suite: context.local_supported_cipher_suites,
6679
- extensions: extensions
6680
- };
6681
- message_data = build_tls_message(build_message_params);
6682
- }
7945
+ } else {
7946
+ // No resumption — the assembler advertised an empty SessionTicket
7947
+ // extension (TLS and DTLS 1.2) to offer support.
7948
+ // Standard ClientHello
7949
+ let build_message_params = client_hello_params(context.local_random, context.local_session_id, extensions);
7950
+ message_data = build_tls_message(build_message_params);
7951
+ }
6683
7952
 
6684
- // ECH: what goes on the wire is the outer hello; the transcript has the
6685
- // inner one until the ServerHello says which (ech_decide).
6686
- let onWire = message_data;
6687
- if (echSplit) {
6688
- onWire = ech_outer_hello(message_data, echSplit, false);
6689
- context.ech.outer_ch1 = onWire;
6690
- }
7953
+ // ECH: what goes on the wire is the outer hello; the transcript has the
7954
+ // inner one until the ServerHello says which (ech_decide).
7955
+ let onWire = message_data;
7956
+ if (echSplit) {
7957
+ onWire = ech_outer_hello(message_data, echSplit, false);
7958
+ context.ech.outer_ch1 = onWire;
7959
+ }
6691
7960
 
6692
- // Client side: our own ClientHello is what a server fingerprints us by.
6693
- // First one wins — a post-HRR retry must not replace the original offer.
6694
- if (context.rawClientHello === null) context.rawClientHello = onWire;
7961
+ // Client side: our own ClientHello is what a server fingerprints us by.
7962
+ // First one wins — a post-HRR retry must not replace the original offer.
7963
+ if (context.rawClientHello === null) context.rawClientHello = onWire;
6695
7964
 
6696
- pushTranscript(message_data);
7965
+ pushTranscript(message_data);
6697
7966
 
6698
- context.hello_sent=true;
7967
+ context.hello_sent=true;
6699
7968
 
6700
- // 0-RTT offered: its secret, from the PSK and this ClientHello — before
6701
- // the hello goes, so the layer above has the key for what follows it.
6702
- if (context.early.offered && context.psk_offered) {
6703
- let edHash = TLS_CIPHER_SUITES[context.psk_offered.cipher] ? TLS_CIPHER_SUITES[context.psk_offered.cipher].hash : 'sha256';
6704
- let edSecret = derive_client_early_traffic_secret(edHash, context.psk_offered.psk, get_transcript_hash(edHash), label_prefix());
6705
- _emitKeylogSingle('CLIENT_EARLY_TRAFFIC_SECRET', edSecret);
6706
- ev.emit('earlySecret', edSecret, { cipher: context.psk_offered.cipher, alpn: context.early.alpn, appData: context.early.appData, maxEarlyData: context.early.maxEarly });
6707
- }
7969
+ // 0-RTT offered: its secret, from the PSK and this ClientHello — before
7970
+ // the hello goes, so the layer above has the key for what follows it.
7971
+ if (context.early.offered && context.psk_offered) {
7972
+ let edHash = TLS_CIPHER_SUITES[context.psk_offered.cipher] ? TLS_CIPHER_SUITES[context.psk_offered.cipher].hash : 'sha256';
7973
+ let edSecret = derive_client_early_traffic_secret(edHash, context.psk_offered.psk, get_transcript_hash(edHash), label_prefix());
7974
+ _emitKeylogSingle('CLIENT_EARLY_TRAFFIC_SECRET', edSecret);
7975
+ ev.emit('earlySecret', edSecret, { cipher: context.psk_offered.cipher, alpn: context.early.alpn, appData: context.early.appData, maxEarlyData: context.early.maxEarly });
7976
+ }
6708
7977
 
6709
- ev.emit('message',0,context.message_sent_seq,'hello',onWire);
7978
+ ev.emit('message',0,context.message_sent_seq,'hello',onWire);
6710
7979
 
6711
- context.message_sent_seq++;
7980
+ context.message_sent_seq++;
6712
7981
 
6713
- },0);
6714
7982
  }
6715
7983
 
6716
7984
 
@@ -6728,9 +7996,8 @@ function TLSSession(options){
6728
7996
  * The narrower `(v & 0x0f0f) === 0x0a0a` test used before also matched
6729
7997
  * non-GREASE values such as 0x1a2a, so it is not a safe stand-in.
6730
7998
  */
6731
- function fp_is_grease(v) {
6732
- return (v & 0x0f0f) === 0x0a0a && ((v >>> 8) & 0xff) === (v & 0xff);
6733
- }
7999
+ // (is_grease_u16, above: one test for the whole session.)
8000
+ const fp_is_grease = is_grease_u16;
6734
8001
 
6735
8002
  function fp_no_grease(list) {
6736
8003
  let out = [];
@@ -6759,7 +8026,7 @@ function TLSSession(options){
6759
8026
  if (context[cacheKey] !== null) return context[cacheKey];
6760
8027
  if (!context[rawKey]) return null;
6761
8028
  try {
6762
- context[cacheKey] = parse_tls_message(context[rawKey]);
8029
+ context[cacheKey] = parse_tls_message(context[rawKey], undefined, { lenient: true });
6763
8030
  } catch (e) {
6764
8031
  context[cacheKey] = false;
6765
8032
  return null;
@@ -6768,6 +8035,14 @@ function TLSSession(options){
6768
8035
  }
6769
8036
 
6770
8037
  function fp_hello() { return fp_parse('client'); }
8038
+ // JA4 / JA4S / JA5 alike: a DTLS hello (by its legacy_version) or session,
8039
+ // and the protocol letter — 'd' or 't', unless the caller names one.
8040
+ function fp_is_dtls(hello) {
8041
+ return ((hello.legacy_version & 0xFF00) === 0xFE00) || ((context.selected_version & 0xFF00) === 0xFE00);
8042
+ }
8043
+ function fp_proto(opts, isDTLS) {
8044
+ return (opts && opts.protocol) ? String(opts.protocol).charAt(0) : (isDTLS ? 'd' : 't');
8045
+ }
6771
8046
  function fp_shello() { return fp_parse('server'); }
6772
8047
 
6773
8048
  /** Signature schemes in WIRE ORDER (JA4 deliberately does not sort these). */
@@ -6890,7 +8165,7 @@ function TLSSession(options){
6890
8165
  *
6891
8166
  * Ciphers and extensions are sorted before hashing, so a client that
6892
8167
  * shuffles extension order per connection still produces a stable
6893
- * fingerprint — the main reason to prefer this over JA3. Signature
8168
+ * fingerprint. Signature
6894
8169
  * algorithms are appended in WIRE ORDER, unsorted, which is what preserves
6895
8170
  * uniqueness after that sort.
6896
8171
  *
@@ -6901,11 +8176,7 @@ function TLSSession(options){
6901
8176
  let hello = fp_hello();
6902
8177
  if (!hello) return null;
6903
8178
  try {
6904
- let isDTLS = ((hello.legacy_version & 0xFF00) === 0xFE00) ||
6905
- ((context.selected_version & 0xFF00) === 0xFE00);
6906
-
6907
- let proto = (opts && opts.protocol) ? String(opts.protocol).charAt(0)
6908
- : (isDTLS ? 'd' : 't');
8179
+ let isDTLS = fp_is_dtls(hello), proto = fp_proto(opts, isDTLS);
6909
8180
 
6910
8181
  let verStr = fp_version_string(hello, isDTLS);
6911
8182
 
@@ -6962,10 +8233,7 @@ function TLSSession(options){
6962
8233
  let hello = fp_shello();
6963
8234
  if (!hello) return null;
6964
8235
  try {
6965
- let isDTLS = ((hello.legacy_version & 0xFF00) === 0xFE00) ||
6966
- ((context.selected_version & 0xFF00) === 0xFE00);
6967
- let proto = (opts && opts.protocol) ? String(opts.protocol).charAt(0)
6968
- : (isDTLS ? 'd' : 't');
8236
+ let isDTLS = fp_is_dtls(hello), proto = fp_proto(opts, isDTLS);
6969
8237
 
6970
8238
  // Extensions here are NOT GREASE-filtered, unlike every list in JA4.
6971
8239
  // The reference implementations filter GREASE only out of the server's
@@ -7035,10 +8303,7 @@ function TLSSession(options){
7035
8303
  let hello = fp_hello();
7036
8304
  if (!hello) return null;
7037
8305
  try {
7038
- let isDTLS = ((hello.legacy_version & 0xFF00) === 0xFE00) ||
7039
- ((context.selected_version & 0xFF00) === 0xFE00);
7040
- let proto = (opts && opts.protocol) ? String(opts.protocol).charAt(0)
7041
- : (isDTLS ? 'd' : 't');
8306
+ let isDTLS = fp_is_dtls(hello), proto = fp_proto(opts, isDTLS);
7042
8307
  let verStr = fp_version_string(hello, isDTLS);
7043
8308
 
7044
8309
  let allExts = (hello.extensions || []).map(function(e){ return e.type; });
@@ -7231,13 +8496,39 @@ function TLSSession(options){
7231
8496
  getEchStatus: function(){
7232
8497
  return context.ech.status;
7233
8498
  },
8499
+ /** The largest handshake message this session takes (bytes, header included). */
8500
+ handshakeMessageLimit: function(){ return handshake_message_limit(); },
8501
+
8502
+ /**
8503
+ * record_size_limit (RFC 8449), once both sides have sent theirs: the
8504
+ * most content a record may carry — `send`, toward the peer (its limit);
8505
+ * `receive`, from it (ours) — or null (not negotiated: 2^14 both ways).
8506
+ * The record layer applies both.
8507
+ */
8508
+ getRecordSizeLimit: function(){ return record_size_limits(); },
8509
+
8510
+ /** The most content a record we send may carry: the peer's
8511
+ * record_size_limit, or 2^14 — what the record layers cut to. */
8512
+ recordSendLimit: function(){ let l = record_size_limits(); return l ? l.send : MAX_RECORD_PLAINTEXT; },
8513
+
8514
+ /**
8515
+ * Server, ECH split mode (RFC 9849 §3.1): true when this server is the
8516
+ * backend, and ECH was accepted by the client-facing server in front of
8517
+ * it — getEchStatus() is 'accepted' either way (the name went encrypted),
8518
+ * this says who decrypted it. BoringSSL's SSL_ech_accepted is false on
8519
+ * such a backend; this is that distinction, without changing what
8520
+ * 'accepted' means here.
8521
+ */
8522
+ isEchBackend: function(){
8523
+ return context.isServer && context.ech.status === 'accepted' && context.ech.backend === true;
8524
+ },
7234
8525
 
7235
- /** 0-RTT on this connection: null (not offered), 'accepted', 'rejected'
7236
- * — the server's verdict, once given (EncryptedExtensions). */
7237
8526
  // Server: whether the ClientHello offered early data at all — taken or
7238
8527
  // not; not taken, the record layer skips it (RFC 8446 §4.2.10).
7239
8528
  earlyDataOfferedByPeer: function(){ return context.early.clientOffered === true; },
7240
8529
 
8530
+ /** 0-RTT on this connection: null (not offered), 'accepted', 'rejected'
8531
+ * — the server's verdict, once given (EncryptedExtensions). */
7241
8532
  getEarlyDataStatus: function(){
7242
8533
  if (!context.early.offered) return null;
7243
8534
  return context.early.status;
@@ -7260,6 +8551,12 @@ function TLSSession(options){
7260
8551
  return context.selected_alpn || null;
7261
8552
  },
7262
8553
 
8554
+ /** The identity of the external PSK this connection was authenticated
8555
+ * with (or resumed from a connection that was), as bytes — or null. */
8556
+ getPskIdentity: function(){
8557
+ return context.psk_identity ? new Uint8Array(context.psk_identity) : null;
8558
+ },
8559
+
7263
8560
  /** Returns the remote certificate chain, or null. */
7264
8561
  getPeerCertificate: function(){
7265
8562
  return context.remote_cert_chain || context.resumed_peer_chain || null;
@@ -7308,6 +8605,23 @@ function TLSSession(options){
7308
8605
  /** The authorization error string, or null if authorized. */
7309
8606
  get authorizationError() { return context.authorizationError; },
7310
8607
 
8608
+ /**
8609
+ * DTLS 1.2, a ticket offered with no session_id and the ServerHello
8610
+ * read: the saved session's master secret, while the handshake could
8611
+ * still be its resumption — for the record layer to try an epoch-1
8612
+ * record under the keys it gives (the server's Finished, its
8613
+ * ChangeCipherSpec before it) — else null. commitResume12() takes the
8614
+ * resumption once a record has opened under them.
8615
+ */
8616
+ resumeCandidate12: function(){
8617
+ return (!context.isServer && context.tls12_resume_maybe && context.tls12_client_session)
8618
+ ? context.tls12_client_session.master_secret : null;
8619
+ },
8620
+ commitResume12: function(){
8621
+ if (!context.isServer && context.tls12_resume_maybe) return commit_resume12(null);
8622
+ return false;
8623
+ },
8624
+
7311
8625
  /** Returns traffic secrets for record-layer key derivation.
7312
8626
  * Individual fields are null until negotiated.
7313
8627
  * TLS 1.3: use localAppSecret/remoteAppSecret after secureConnect.
@@ -7376,7 +8690,8 @@ function TLSSession(options){
7376
8690
  },
7377
8691
 
7378
8692
  exportKeyingMaterial: function(length, label, context_value){
7379
- if (!context.selected_cipher_suite || !length || !label) return null;
8693
+ // An empty label is a label (RFC 5705 §4: "label" is any string).
8694
+ if (!context.selected_cipher_suite || !length || label === null || label === undefined) return null;
7380
8695
  var suite = TLS_CIPHER_SUITES[context.selected_cipher_suite];
7381
8696
  if (!suite) return null;
7382
8697
  var is13 = (context.selected_version === wire.TLS_VERSION.TLS1_3 ||
@@ -7454,7 +8769,7 @@ function TLSSession(options){
7454
8769
  let cipherInfo = context.selected_cipher_suite ? TLS_CIPHER_SUITES[context.selected_cipher_suite] : null;
7455
8770
  return {
7456
8771
  version: context.selected_version,
7457
- versionName: context.selected_version === 0x0304 ? 'TLSv1.3' : context.selected_version === 0xFEFC ? 'DTLSv1.3' : context.selected_version === 0x0303 ? 'TLSv1.2' : context.selected_version === 0xFEFD ? 'DTLSv1.2' : null,
8772
+ versionName: wire.version_name(context.selected_version),
7458
8773
  cipher: context.selected_cipher_suite,
7459
8774
  cipherName: cipherInfo ? cipherInfo.name : null,
7460
8775
  group: context.selected_group,
@@ -7507,15 +8822,19 @@ function TLSSession(options){
7507
8822
  let hashName = negotiated_hash();
7508
8823
  let hashLen = getHashLen(hashName);
7509
8824
 
7510
- // Derive new local traffic secret
7511
- let newLocalSecret = hkdf_expand_label(hashName, context.local_app_traffic_secret, 'traffic upd', new Uint8Array(0), hashLen, label_prefix());
7512
- context.local_app_traffic_secret = newLocalSecret;
7513
-
7514
- // Send KeyUpdate message
8825
+ // The KeyUpdate goes out under the key it replaces (RFC 8446 §4.6.3:
8826
+ // the sender updates "after sending"), and only then the secret
8827
+ // changes. The secret was replaced first: a record layer that derives
8828
+ // its write key lazily — nothing written yet — derived it from the new
8829
+ // secret, sealed the KeyUpdate under that, and the peer, still on the
8830
+ // old key, saw bad_record_mac.
7515
8831
  let ku_data = build_tls_message({ type: 'key_update', request_update: requestPeer ? 1 : 0 });
7516
8832
  ev.emit('message', 2, context.message_sent_seq, 'key_update', ku_data);
7517
8833
  context.message_sent_seq++;
8834
+ if (requestPeer) context.key_updates_asked++;
7518
8835
 
8836
+ let newLocalSecret = hkdf_expand_label(hashName, context.local_app_traffic_secret, 'traffic upd', new Uint8Array(0), hashLen, label_prefix());
8837
+ context.local_app_traffic_secret = newLocalSecret;
7519
8838
  ev.emit('keyUpdate', { direction: 'send', secret: newLocalSecret });
7520
8839
  },
7521
8840
  };