Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

TLS implementation notes (RFC map)

================================================================================
 TLS LAYER IMPLEMENTATION
 Analysis of the units implementing TLS 1.0, TLS 1.1, TLS 1.2 and TLS 1.3
 (StreamSec Security Library for Embarcadero Delphi)
================================================================================

Generated: 2026-06-05
Regenerated: 2026-10-23d (TLS 1.2: a ServerKeyExchange signed with
                          rsa_pss_rsae_* is accepted (section 3.4). TLS 1.0/1.1
                          with VersionMinorMin lowered: records carry the
                          negotiated version, supported_versions reaches down
                          to the floor, VersionMinorMax caps both ends and sends
                          no TLS_FALLBACK_SCSV (sections 3.1, 4.1).)
Regenerated: 2026-10-23c (FPC legacy DES exclusion and record-free TLS
                          qualification corrected in section 12.)
Regenerated: 2026-10-23b (pointers to test files, which do not ship, removed;
                          section 10 TESTS & INTEROP is restated as
                          what the tests proved, without the file list.)
Regenerated: 2026-10-23  (RECORD-FREE TLS 1.3 FOR QUIC is now section 12, ahead
                          of the end-of-file banner, and documents opt-in QUIC
                          early data: EnableQUICEarlyData, the ticket context
                          and the conditions for accepting it.)
Regenerated: 2026-09-26  (THE TLS 1.2 DEFAULTS: finite-field DHE (RFC 10015),
                          DSA, and MD5, SHA-1 and SHA-224 as handshake
                          signature hashes (RFC 9155) are off, and the Simple
                          internal server behind the TLS, HTTPS and REST
                          clients and the async server no longer presets CBC
                          and DHE. A certificate chain signed over MD2, MD5 or
                          SHA-1 is refused - the hash floor of PKIX.txt.
                          Sections 3.4, 5.)
Regenerated: 2026-08-12  (Four areas since the last release:
                          [1] RFC 10024 "PQ/T Hybrid Key Agreement Mechanisms
                          for TLS 1.3" published (Standards Track, August 2026)
                          - the standardized form of draft-ietf-tls-ecdhe-mlkem.
                          The implemented codepoints, share layout and shared-
                          secret order are unchanged from the draft; a
                          compliance audit against the RFC's normative text
                          added the missing peer key_share VALIDATION: exact
                          per-group share lengths, the uncompressed-point format
                          and on-curve checks for Weierstrass shares, the
                          all-zero X25519/X448 shared-secret abort, and the
                          illegal_parameter-vs-internal_error alert split for
                          ML-KEM failures, each with a new qualified alert
                          reason code. The pre-standard Kyber768Draft00 groups
                          (25497/25498) are obsoleted by the RFC and were never
                          implemented here. Interop revalidated vs OpenSSL 3.5.7
                          both directions (classical, pure ML-KEM, all three
                          hybrids) plus a new hostile-key_share probe. Sections
                          2, 5, 9, 10.
                          [2] AES IMPLEMENTATION SELECTION: the record layer now
                          obtains its AES cipher classes from the cipher-class
                          registry instead of naming stAES's table classes
                          directly. The direct reference had pinned ALL TLS bulk
                          AES - 1.2 CBC and GCM, 1.3 GCM - to the cache-timing-
                          leaky table implementation, so TLS never used AES-NI.
                          With the pin removed: AES-NI hardware where the CPU
                          has it (Delphi Win32 AND Win64 and FPC on SysV x86-64;
                          ~1.5 GB/s/core, was ~610 MB/s), and the NEW stAESCT
                          constant-time bitsliced AES everywhere else (x86/x64
                          without AES-NI, non-x86 targets; ~40-50 MB/s/core).
                          All 14 supported compilers assemble the Win32 arm.
                          Verified by FIPS-197 + RFC 3394 KATs, a 900-case
                          three-implementation agreement check, and live TLS 1.3
                          and TLS 1.2 CBC/GCM handshakes through the re-routed
                          record layer. See sections 3.5, 9, 10.
                          [3] TLS 1.2 ECDHE PEER-POINT VALIDATION brought level
                          with [1]: the 1.2 key exchange enforces the RFC 8422
                          sec.5.4.1 uncompressed point format, guards the point
                          decoder's nil return for off-curve and malformed
                          points, and aborts on the all-zero X25519/X448 shared
                          secret that sec.5.11 requires (small-order peer
                          points). Both endpoints, both key-exchange messages,
                          and the client's premaster derivation. Sections 9,
                          10.
                          [4] TRUST ANCHORS AS A COMPONENT: the public root set
                          is compiled into the library - StreamSec.Mobile.CCADB
                          (TsmCCADBTrustAnchors) over the embedded list in
                          StreamSec.Mobile.CCADBRoots, the CCADB / Mozilla root
                          program filtered to the websites trust bit, carrying
                          the day it was taken and the URL it came from. One
                          instance per trust domain, installed before
                          TLSSetupClient can run, and NOT for a listener -
                          there the root store is also the anchor set for
                          client certificates - and not for a client leg
                          either, unless WHICH anchor is needed cannot be
                          settled at compile time nor at configuration time,
                          but only at run time, because the peer is not known
                          before then. Sections 1, 7, 9.)
Regenerated: 2026-07-22  (fact-check pass picking up OUT-OF-BAND changes not covered
                          by 18b..e: [1] CORRECTION - OfferTLS13 now DEFAULTS TO TRUE
                          (TlsClass.Create), so a plain component offers/accepts 1.3
                          by default; VersionMinorMax=cTLS12vmm bounds only the
                          legacy_version byte, not the offer (secs 0, 6). [2] a
                          PER-CONNECTION secondary DRBG now supplies all wire-visible
                          randomness (ConnRandom/ConnRandomBuf/ConnRandomBytes, the
                          record-layer PRNG, TLS_NewRandom's aPRNG); key seeds stay
                          on the primary. Fixed a predictability bug: ticket_age_add
                          was a byte-swapped timestamp with no random bits + session_id
                          never hit a DRBG (secs 7, 9). [3] ACME tls-alpn-01 SERVER
                          responder API (AddTLSAcmeALPN/RFC 8737, challenge-slot gate,
                          FindExpiringTLSServerCertificatesEx) - server side only,
                          protocol in ACME.txt (secs 2, 4.5). [4] the 0-RTT policy is
                          the TEarlyDataMode tri-state (edmDisabled/edmAccept/
                          edmRejectAndRetry) + pull-API EarlyDataPending/Status
                          (sec 6). None of these are this session's ticket/ALPN work.)
Regenerated: 2026-07-18e (the 1.3 CLIENT can now OFFER a list of PSK identities
                          (completing the server-side scan above). ResumptionTicket
                          is identity 0; new AddResumptionTicket adds extras 1..N
                          (same PRF hash). AppendPSKExtensions emits N identities +
                          N placeholder binders (EncodePreSharedKeyCHList) and
                          PatchPSKBinder fills each per-ticket binder over the same
                          truncated ClientHello; the client accepts an in-range
                          selected_identity and keys the schedule off THAT ticket's
                          PSK. End-to-end GREEN: offering
                          [consumed #1, valid #2] resumes on identity 1 (the server
                          scans past the consumed one; #1 was proven unusable, so a
                          resume can only be #2). See section 6.)
Regenerated: 2026-07-18d (the 1.3 server now scans the FULL pre_shared_key
                          OfferedPsks list, not just the first identity.
                          ParseClientPreSharedKey returns ALL identities paired
                          with their binders; HandleClientHello13 tries each in
                          order and resumes on the first known+matching+binder-
                          verified ticket, echoing its index as selected_identity
                          (was hardcoded 0). A per-candidate mismatch now SKIPS
                          (a group mismatch is no longer a fatal abort) -> full
                          handshake if none match; 0-RTT stays first-identity only;
                          the scan is capped at 12. Verified: parser positional
                          pairing / count-mismatch / short-binder + single-identity
                          resume/single-use regression
                          GREEN. See section 6.)
Regenerated: 2026-07-18c (TLS 1.3 resumption tickets are now SINGLE-USE with BATCH
                          issuance. A ticket is consumed (removed from the store) on
                          resumption, but only AFTER the PSK binder verifies, so a
                          cleartext ticket identity cannot be used to burn a ticket
                          (Tls13PeekServerTicket returns a private clone; the binder
                          is verified off the store lock; Tls13ConsumeServerTicket
                          removes the original, idempotent). Because single-use means
                          one ticket per connection, each handshake now issues
                          Options.SessionTicketCount tickets (default 6 = the browser
                          HTTP/1.1 per-host connection limit), each with a distinct
                          nonce/PSK/identity. GOTCHA FIXED en route: TTLSOptions.
                          AssignTo did not copy the new field, so a value set on the
                          wrapper never reached the engine (caught by testing a
                          NON-default count). Verified our-server<->our-client
                          (batch=configurable, reuse->full) and vs
                          OpenSSL 3.5.6 (reused ticket -> full, fresh ticket ->
                          resume). See section 6.)
Regenerated: 2026-07-18b (TLS 1.3 ALPN (RFC 7301) NEGOTIATION IMPLEMENTED - was a
                          gap: 1.3 carries the server's selected protocol in the
                          encrypted EncryptedExtensions, not the plaintext
                          ServerHello, and neither side handled it. Server now runs
                          PickProtocol over the ClientHello list, echoes the choice
                          via EncodeALPNExtension in the EE, and fatally alerts
                          no_application_protocol (120) on an offered-but-unsupported
                          set; client extracts it back out (Tls13EEExtractALPN) and
                          validates it like the 1.2 client. Crucially the negotiated
                          protocol now drives 1.3 certificate selection per-connection
                          - fixing the reported outage where activating an ACME
                          tls-alpn-01 responder hijacked the cert for ordinary
                          http/1.1 traffic. Interop GREEN both directions vs OpenSSL
                          3.5.6 s_server/s_client -alpn. See sections 2, 4.3, 4.5.)
Regenerated: 2026-07-18  (server certificate cache: RSA keyUsage is now honoured
                          per ROLE - a digitalSignature-only RSA leaf serves
                          DHE_RSA/ECDHE_RSA and the 1.3 flight, while
                          keyEncipherment stays required only for static-RSA key
                          transport; noted InternalAddTLSServerCert's silent drop
                          of unrecognized (KEA, sig) pairs. Chain building now
                          auto-fetches missing intermediates via the AIA caIssuers
                          URL, and the issuer-validity ENCLOSURE check became the
                          tVerifyValidityPeriodMode switch (details in PKIX.txt
                          sec.3; cross-refs in section 9). ExportChainToTLS no
                          longer drops the deepest cert of a truncated chain
                          (see PKIX.txt sec.5/13). EC scalar
                          mul now runs the workspace Solinas multipliers (4-6.5x
                          Win64, dudect green) - section 7. See sections 4.5, 7,
                          9.)
Regenerated: 2026-07-13  (RFC 9954 "Hybrid Key Exchange in TLS 1.3" published
                          (Informational, July 2026 - the published form of
                          draft-ietf-tls-hybrid-design); added to the RFC map and
                          section 5. No code change was needed: the hybrid
                          ECDHE+ML-KEM groups already implement its construction -
                          bare concatenation of key_share and of the shared secret
                          in the group's order, no per-part KDF, no length
                          prefixes, injected at the (EC)DHE key-schedule position.
                          Audited sec.3.2: this client uses OPTION 1 (fully
                          independent generation) - it emits ONE KeyShareEntry per
                          ClientHello (ChooseTls13Group) with both halves freshly
                          generated, so no component key pair is reused across key
                          shares; HRR covers the non-preferred groups.
                          Verified against the code and interop-tested GREEN for
                          all three groups vs OpenSSL 3.5.6 s_server restricted to
                          each group.)
Regenerated: 2026-07-12  (TLS 1.3 tracked to RFC 9846, the refresh that OBSOLETES
                          RFC 8446: post-handshake KeyUpdate in both directions +
                          the sec.5.5 usage-limit rekey; a configurable minimum
                          protocol version (VersionMinorMin, RFC 8996 - 1.0/1.1
                          off by default); the general_error / unknown_psk_identity
                          alerts. See sections 4.1, 4.6, 9, 10. Full fact-check vs
                          code same day (3 fixes): the constant-time-ECDSA unit
                          reference, the TLS-1.1 cipher-class inheritance tree, and
                          added the iCertificate.SameCert content-identity note.)
Regenerated: 2026-07-07  (OCSP stapling automated end-to-end for TLS 1.2 AND 1.3;
                          1.3 server certificate/key/staple now served from the
                          TsmStreamSecII cache (SNI + signature_algorithms aware);
                          1.3 server-side mTLS; ticket-store maintenance; test
                          inventory added - sections 4.5, 6, 9, 10)
Regenerated: 2026-06-06  (TLS 1.3 + post-quantum + ChaCha20-Poly1305 now shipping;
                          legacy generations removed from this audit - see note)

--------------------------------------------------------------------------------
0. SUMMARY - ONE PRODUCTION TLS STACK
--------------------------------------------------------------------------------

The shipping TLS implementation is the "StreamSec.Mobile.Tls*" stack. It is a
fully wired, bidirectional state machine that now negotiates TLS 1.0 through
TLS 1.3. The protocol version on the wire is a {major,minor} byte pair; major is
always 3, and minor selects the version:

    3.1 = TLS 1.0   (minor 1)   RFC 2246
    3.2 = TLS 1.1   (minor 2)   RFC 4346
    3.3 = TLS 1.2   (minor 3)   RFC 5246
    3.4 = TLS 1.3   (minor 4)   RFC 8446   *** but NOT negotiated via this field;
                                see section 4 - 1.3 keeps 0x0303 on the wire and
                                signals itself through the supported_versions ext.

Internally the engine names the versions in StreamSec.Mobile.TlsConst.pas:
    cTLS10vmm = 1, cTLS11vmm = 2, cTLS12vmm = 3, cTLS13vmm = 4.

TLS 1.3 is fully implemented (client AND server, mutual-auth/mTLS, session
resumption, and 0-RTT early data in both directions) and interop-tested against
OpenSSL 3.5.x. TLS 1.3 is now offered and accepted BY DEFAULT: OfferTLS13 defaults
to True (set in TCustomTLS_ContentLayer.Create), so a plain component's client
offers supported_versions + key_share and its server accepts 1.3 with no per-session
opt-in. VersionMinorMax stays cTLS12vmm, but that bounds only the legacy_version
byte, NOT the 1.3 offer; cTLS13vmm is used only as the NEGOTIATED selector inside the
engine and the key schedule, and is never written into a record header or a
legacy_version field (those stay 0x0303). Set OfferTLS13 := False (per session via
OnTLSAddContentLayer, or on the component) to force a pure TLS 1.2 handshake.

NOTE ON SCOPE: this document covers exclusively the production
"StreamSec.Mobile.Tls*" stack. Any earlier, superseded TLS frameworks are
obsolete and are intentionally not described here.

This document maps each unit to the relevant RFCs (and the post-quantum drafts),
describes what each protocol version requires and how it is implemented, and
documents the inter-unit dependencies and how each unit is consumed.


================================================================================
1. UNIT INVENTORY  (the production TLS layer)
================================================================================

CORE PROTOCOL
  StreamSec.Mobile.TlsConst.pas      Version constants, alert codes, content
                                     types, record-size limits.
  StreamSec.Mobile.Tls.pas           Handshake/record structures, the TLS 1.0-1.2
                                     state machine, ClientHello/ServerHello and
                                     ServerKeyExchange encode/decode, extensions,
                                     TLS_PRF, Finished verify_data.
  StreamSec.Mobile.TlsClass.pas      Higher-level classes; TLSOptions (cipher /
                                     group / version preferences, ALPN,
                                     BulkCipherChaCha20Poly1305, SupportedGroups,
                                     OfferTLS13, EarlyData / MaxEarlyDataSize).
  StreamSec.Mobile.TlsLayer.pas      TTLS_RecordLayer (record driver) and
                                     TTLS_HandshakeProtocol (the handshake driver,
                                     including ALL the TLS 1.3 branches: Handle*
                                     Hello13, HandleTLS13ServerFlight, key-schedule
                                     install, early data, tickets, HRR).
  StreamSec.Mobile.TlsEncryption.pas Bulk cipher / AEAD record protection for
                                     every version (the tTLSEncryption* classes).
  StreamSec.Mobile.TlsInternalServer.pas    Server-side handshake driver (1.2 and
                                     the full 1.3 server flight, ticket issuance,
                                     HelloRetryRequest).
  StreamSec.Mobile.TlsInternalServerReg.pas Design-time/registration glue.

TLS 1.3 ADDITIONS (new units)
  StreamSec.Mobile.Tls13KeySchedule.pas   RFC 8446 sec.7 key schedule (HKDF-based;
                                     reuses tHKDFExtract / tHKDFExpand from stKDF).
  StreamSec.Mobile.Tls13Handshake.pas     RFC 8446 sec.4 wire encode/decode:
                                     extensions, EncryptedExtensions,
                                     CertificateVerify, Finished, NamedGroup and
                                     SignatureScheme code points (incl. PQ).

COMPONENT INTEGRATION / TRANSPORT
  StreamSec.Mobile.StreamSecII.pas   The drop-in TLS component (TsmStreamSecII):
                                     TLSOptions surface, events, ticket store.
  StreamSec.Mobile.X509Comp.pas      Certificate/key component integration.
  StreamSec.Mobile.TlsSocket.pas     Socket-bound convenience layer.
  StreamSec.Mobile.CCADB.pas         TsmCCADBTrustAnchors: the public root set
                                     as the anchors of ONE engine (section 7).
  StreamSec.Mobile.CCADBRoots.pas    The embedded set: the roots as PEM, the
                                     day it was taken, the source URL.
  StreamSec.Mobile.CCADBReg.pas      Design-time registration + palette icon.

INDY SERVER IOHANDLERS (demo adapters, XE3 and later)
  AfterAccept arms implicit TLS without exchanging records. The first encrypted
  read or write performs the handshake, normally in the connection thread;
  failures reach that connection's OnException handler. OnConnect can run before
  TLS authentication: call the accepted IOHandler's StartSSL there if it needs
  the client certificate or negotiated TLS details before doing I/O. Keep
  encrypted I/O out of listener callbacks such as OnContextCreated, because the
  thread doing the first encrypted I/O owns the handshake. Explicit STARTTLS
  from passthrough mode and outbound client handshakes start immediately.

TLS 1.2 SESSION RESUMPTION
  An accepted cached session uses the abbreviated ServerHello, CCS and Finished
  flight. A server declining the session must send the full authenticated
  flight. Resumption retains the cached version, cipher suite and compression
  method; a peer cannot change that tuple while reusing the session ID.
  Finished verification is still required before the new handshake completes.
  During legacy renegotiation, CCS is protected by the old connection keys;
  the receiver authenticates it before installing the new read keys and refuses
  a repeated installation. TLS 1.3 dummy CCS handling remains separate.

SHARED HELPER
  stTlsUtils.pas                     tRandom record, UnixTime, byte-swap,
                                     TLS_NewRandom (the Hello Random builder).


================================================================================
2. RFC MAP - WHICH RFC DEFINES WHAT, AND WHERE IT IS IMPLEMENTED
================================================================================

PROTOCOL VERSIONS
  RFC 2246  - TLS 1.0.   Record layer, MD5^SHA1 PRF, CBC with IMPLICIT IV,
              MD5+SHA1 Finished. (TLS_PRF in Tls.pas; tTLSEncryption10* ciphers.)
  RFC 4346  - TLS 1.1.   Adds the EXPLICIT per-record CBC IV (anti-BEAST) and
              improved padding handling. (tTLSEncryption11Block.)
  RFC 5246  - TLS 1.2.   PRF collapses to a single cipher-defined HMAC (SHA-256 /
              SHA-384); AEAD support; signature_algorithms extension.
  RFC 8446  - TLS 1.3.   New HKDF key schedule, encrypted handshake, 1-RTT/0-RTT,
              HelloRetryRequest, post-ServerHello encryption. See sections 4-6.

CIPHER SUITES & AEAD
  RFC 3268  - AES cipher suites for TLS (IDs $2F..$3A).
  RFC 4132  - Camellia cipher suites ($41..$46 / $84..$89).
  RFC 4492 / RFC 8422 - ECC cipher suites, ECDHE key exchange, named curves and
              point formats, plus EdDSA (Ed25519/Ed448) signing in TLS.
  RFC 5288  - AES-GCM cipher suites for TLS 1.2 (tTLSEncryption12Aead).
  RFC 5289  - ECDHE-ECDSA / ECDHE-RSA AES-GCM-SHA256/384 suites (the common 1.2
              AEAD suites; KeyExchangeAlg keaECDHE + bcaAES*_GCM).
  RFC 5116 / NIST SP800-38D - GCM AEAD construction (4-byte implicit salt ||
              8-byte explicit nonce, seqnum-based).
  RFC 7539 / RFC 8439 - ChaCha20-Poly1305 AEAD (stChaCha20Poly1305).
  RFC 7905  - ChaCha20-Poly1305 cipher suites for TLS 1.2 (implicit-nonce AEAD;
              tTLSEncryption12Poly1305). The 1.3 ChaCha suite is in RFC 8446.

EXTENSIONS & HARDENING
  RFC 6066  - Hello extensions (server_name / SNI is emitted and parsed).
  RFC 7301  - Application-Layer Protocol Negotiation (ALPN, ext 16). Offered in the
              ClientHello (both generations); the server's selected protocol is
              echoed in the 1.2 ServerHello and, in 1.3, in the (encrypted)
              EncryptedExtensions (RFC 8446 sec.4.2). See sections 4.3 / 4.5.
  RFC 8737  - ACME tls-alpn-01: the SERVER side (acme-tls/1 challenge cert with the
              id-pe-acmeIdentifier extension) is provided by AddTLSAcmeALPN - see
              section 4.5. The ACME client protocol itself lives in ACME.txt.
  RFC 5246 sec.7.4.1.4 - signature_algorithms extension (hash/sig pairs).
  RFC 5746  - Secure Renegotiation Indication (renegotiation_info, $FF01).
  RFC 7366  - Encrypt-then-MAC (encrypt_then_mac extension; tTLSEncryption10/11
              BlockEtM classes).
  RFC 7507  - TLS_FALLBACK_SCSV ($56,$00) downgrade-protection signalling cipher
              suite, complemented by the RFC 8446 sec.4.1.3 downgrade sentinel.
  RFC 8447  - IANA TLS registry: the 1.3 extension/code points used by the
              handshake (supported_versions=43, key_share=51, pre_shared_key=41,
              psk_key_exchange_modes=45, early_data=42, cookie=44,
              signature_algorithms_cert=50).
  RFC 8449  - record_size_limit extension (ext 28; the 1.3 replacement for
              max_fragment_length).

TLS 1.3 KEY SCHEDULE / GROUPS / SIGNATURES
  RFC 5869  - HKDF (Extract-and-Expand). Basis of the 1.3 key schedule
              (HKDF-Expand-Label / Derive-Secret, RFC 8446 sec.7.1). Implemented
              in stKDF (tHKDFExtract/tHKDFExpand), framed by Tls13KeySchedule.
  RFC 7748  - X25519 / X448 ECDHE groups (NamedGroup $001D / $001E).
  RFC 8410  - Ed25519 / Ed448 algorithm identifiers (CertificateVerify signing).
  RFC 6979  - Deterministic (and now constant-time) ECDSA nonce - used when the
              engine produces the ECDSA signature in CertificateVerify /
              ServerKeyExchange. (Implementation: the dlssaDSAFixedTime scheme in
              StreamSec.DSI.DiscreteLog + the constant-time FixedGroupOpIteration
              in StreamSec.DSI.ECArith.)

0-RTT / EARLY DATA
  RFC 8446 sec.2.3, 4.2.10 (early_data ext), 4.6.1 (NewSessionTicket /
              max_early_data_size), 4.5 (EndOfEarlyData), sec.8 (anti-replay).
  RFC 8470  - "Using Early Data in HTTP" (the `Early-Data: 1` request header and
              `425 Too Early` response) - the contract for the consumer that
              drives one request per early-data flight.

POST-QUANTUM (TLS 1.3)  - see section 5
  FIPS 203  - ML-KEM (Kyber).  Key encapsulation for the 1.3 key_share.
  FIPS 204  - ML-DSA (Dilithium).  SignatureScheme for CertificateVerify.
  RFC 9954  - Hybrid Key Exchange in TLS 1.3 (Informational, July 2026; the
              published form of draft-ietf-tls-hybrid-design). Defines the
              CONSTRUCTION our hybrid groups use - not the codepoints: the
              key_share is the bare concatenation of the component key_exchange
              values in the NamedGroup's order, the shared secret is their bare
              concatenation in the SAME order (no per-part KDF, no length
              prefixes), injected in place of the (EC)DHE secret in the key
              schedule. IMPLEMENTED - see section 5.
  draft-ietf-tls-mlkem            - pure ML-KEM NamedGroups ($0200..$0202).
              (Pure ML-KEM is not hybrid, so RFC 9954 does not apply to it.)
  RFC 10024 - PQ/T Hybrid Key Agreement Mechanisms for TLS 1.3 (Standards
              Track, August 2026; the published form of
              draft-ietf-tls-ecdhe-mlkem): the hybrid ECDHE+ML-KEM groups
              SecP256r1MLKEM768 ($11EB), X25519MLKEM768 ($11EC),
              SecP384r1MLKEM1024 ($11ED) - the codepoints, share layout and
              shared-secret order for the RFC 9954 construction, plus the
              normative peer-share validation (sec.4.1-4.3): exact share
              lengths, the FIPS 203 sec.7.2 encapsulation-key check, the
              RFC 9846 sec.4.3.8.2 EC point checks, and the all-zero X25519
              shared-secret abort. IMPLEMENTED - see sections 5 and 9. The RFC
              also obsoletes the pre-standard X25519Kyber768Draft00 (25497) /
              SecP256r1Kyber768Draft00 (25498) groups (IANA Recommended=D);
              this library never implemented them and does not accept them.
  draft-ietf-tls-mldsa            - ML-DSA SignatureSchemes ($0904..$0906).


================================================================================
3. PER-PROTOCOL IMPLEMENTATION DETAIL  (TLS 1.0 / 1.1 / 1.2)
================================================================================

--------------------------------------------------------------------------------
3.1  RECORD LAYER  (RFC 2246/4346/5246 sec.6)
--------------------------------------------------------------------------------
A TLS record is a 5-byte header [ContentType(1) | Version(2) | Length(2)] plus
the fragment. StreamSec.Mobile.TlsLayer.pas (TTLS_RecordLayer) is the driver:
  - Explicit version negotiation (FVersion.minor in [1,2,3] => TLS 1.0/1.1/1.2;
    minor 4 is never written - see section 4), CCS bookkeeping, pending vs active
    security parameters.
  - Plaintext/compressed/ciphertext length limits come from TlsConst
    (MaxPlainTextLength = 16384, MaxCompressedLength = 16384+1024,
    MaxCipherTextLength = 16384+2048 = the record_overflow limit).
  - The driver deliberately IGNORES legacy_record_version on input (the version
    checks on the decode paths are commented out) - which is exactly the
    1.3-friendly behaviour the spec requires.
  - On OUTPUT a record carries the negotiated version: from the ServerHello on,
    the version the hellos selected (3.1, 3.2 or 3.3); before it, 3 and
    VersionMinorMax, which RFC 5246 appendix E.1 allows on a ClientHello; and
    0x0303 on every TLS 1.3 record (RFC 8446 sec.5.1). OpenSSL refuses a record
    of any other version once the version is settled.
  - The record layer delegates the actual crypto to the active tTLSEncryption*
    object (section 3.5), selected when keys are installed.

--------------------------------------------------------------------------------
3.2  KEY DERIVATION / PRF  (the biggest per-version difference)
--------------------------------------------------------------------------------
TLS 1.0 / 1.1 PRF  - PRF = P_MD5(S1,...) XOR P_SHA1(S2,...), the secret split in
half (RFC 2246 sec.5). Identical for 1.0 and 1.1.

TLS 1.2 PRF  - a single HMAC with a cipher-suite-selected hash (SHA-256 default,
SHA-384 for the GCM-SHA384 suites), NO MD5/SHA1 split (RFC 5246 sec.5).

Both live in StreamSec.Mobile.Tls.pas as TLS_PRF, driven from the handshake:
  - master secret = PRF(premaster, "master secret",
      clientRandom||serverRandom, 48)                       (sec.8.1)
  - key block     = PRF(masterSecret, "key expansion",
      serverRandom||clientRandom, KeyBlockLength)           (sec.6.3)
The hash carried by the negotiated cipher suite automatically selects the correct
1.0/1.1 vs 1.2 PRF.

TLS 1.3 does NOT use TLS_PRF at all - it has an HKDF key schedule (section 4.2).

--------------------------------------------------------------------------------
3.3  FINISHED MESSAGE  (RFC 2246/4346/5246 sec.7.4.9)
--------------------------------------------------------------------------------
Computed inside the Mobile handshake driver, version-aware:
  - TLS 1.0/1.1: verify_data = PRF(masterSecret, "client finished"/"server
    finished", MD5||SHA1 handshake hash, 12).
  - TLS 1.2:     verify_data = PRF(masterSecret, "client/server finished",
    Hash(handshake messages), 12) with the cipher-suite PRF hash.
  - TLS 1.3:     Finished = HMAC(finished_key, Transcript-Hash(...)) - see 4.3.

--------------------------------------------------------------------------------
3.4  CIPHER SUITES & KEY EXCHANGE
--------------------------------------------------------------------------------
StreamSec.Mobile.Tls.pas decodes a negotiated suite into a {KeyExchangeAlg,
SignAlg, bulk cipher, MAC/PRF hash} tuple. Supported families:
  - Key exchange: RSA, DH/DHE, ECDH/ECDHE (keaECDHE), and (1.3) the (EC)DHE +
    ML-KEM key_share path.
  - Authentication: RSA (PKCS#1 v1.5 and PSS), ECDSA, EdDSA (Ed25519/Ed448),
    and (1.3) ML-DSA. The client lists rsa_pss_rsae_sha256/384/512 in every
    ClientHello, so a TLS 1.2 server may sign its ServerKeyExchange with them -
    OpenSSL does when it orders signature algorithms by its own preference
    (s_server -serverpref, nginx ssl_prefer_server_ciphers) - and the client
    accepts that, as RFC 8446 sec.4.2.3 requires of a client that offers them:
    MGF1 over the signed hash, a salt as long as the hash.
  - Anonymous key exchange - DH_anon and ECDH_anon, enabled by
    TLSOptions.SignatureAnon (prNotAllowed by default) - authenticates
    neither peer. It is deprecated and not maintained.
  - Bulk: 3DES-CBC, AES-128/256-CBC, Camellia, AES-128/256-GCM,
    ChaCha20-Poly1305.
ServerKeyExchange for ECDHE is built by InternalEncodeServerKeaECDHE; the curve
list is governed by the SupportedGroups property (TlsClass).

WHAT A NEW ENGINE OFFERS IN TLS 1.2 - TTLSOptions as constructed, which every
TLS component uses, TsmTLSClient, the HTTPS and REST clients and
TsmAsyncTLSServer included: the AEAD suites (AES-128/256-GCM,
ChaCha20-Poly1305) over ECDHE, signed with RSA or ECDSA. Off, each behind its
own TLSOptions property: the CBC suites (BulkCipherAES128/AES256), 3DES and
RC4, static RSA key transport (KeyAgreementRSA), finite-field DHE
(KeyAgreementDHE; RFC 10015), DSA (SignatureDSS), and MD5, SHA-1 and SHA-224
as handshake signature hashes (HashAlgorithmSHA1; RFC 9155).
Client signature_algorithms and supported_groups list enabled handshake
algorithms. A server's CertificateRequest separates permitted client key types
from the signature pairs that can also apply to issuers. SHA-1/SHA-224 handshake
signatures require explicit HashAlgorithmSHA1 legacy policy; TLS 1.2 client
CertificateVerify never selects MD5, and servers refuse it. The server gives an
ECDSA suite to a client that offers ECDSA over
SHA-256, SHA-384 and SHA-512, and an RSA-signed suite to one that offers RSA
over at least one of them.

--------------------------------------------------------------------------------
3.5  BULK ENCRYPTION / MAC / IV  (StreamSec.Mobile.TlsEncryption.pas)
--------------------------------------------------------------------------------
Class hierarchy (the record-protection objects the record layer drives):

  tTLSEncryption
    +- tTLSEncryption10            TLS 1.0 base (HMAC MAC, implicit-IV CBC)
    |    +- tTLSEncryption10Stream       stream cipher (e.g. RC4) variant
    |    +- tTLSEncryption10Block        CBC, IMPLICIT IV (RFC 2246)
    |    |    +- tTLSEncryption11Block       explicit per-record IV (RFC 4346 6.2.3.2)
    |    +- tTLSEncryption10BlockEtM     CBC + Encrypt-then-MAC (RFC 7366)
    |         +- tTLSEncryption11BlockEtM   explicit-IV CBC + EtM
    +- tTLSEncryption12Aead        AES-GCM AEAD for TLS 1.2 (RFC 5288/5289)
    +- tTLSEncryption12Poly1305    ChaCha20-Poly1305 for TLS 1.2 (RFC 7905)
    +- tTLSEncryption13Aead        TLS 1.3 AEAD (RFC 8446): AES-GCM OR
                                   ChaCha20-Poly1305, selected by the suite.

  MAC (CBC/stream suites): MAC = HMAC(seqnum || record-header || fragment),
  seqnum written 64-bit big-endian. Encrypt-then-MAC (RFC 7366) reverses the
  order (MAC over the ciphertext) when the encrypt_then_mac extension is agreed.

  IV - the 1.0 vs 1.1 difference: tTLSEncryption10Block uses an IMPLICIT IV
  (chained from the previous record); tTLSEncryption11Block prepends a fresh
  random EXPLICIT IV per record (the RFC 4346 anti-CBC-chaining fix), inherited by
  the 1.2 block ciphers.

  AEAD (TLS 1.2, tTLSEncryption12Aead / 12Poly1305):
    * No HMAC (mac_algorithm = haNull).
    * AES-GCM nonce = 4-byte implicit salt (from the key block) || 8-byte explicit
      nonce in the record (RFC 5288). ChaCha20-Poly1305 (RFC 7905) instead derives
      the nonce implicitly = write_iv XOR seqnum (no explicit nonce on the wire).
    * AAD = seqnum(8) || record header(5); 16-byte tag.

  WHICH AES IMPLEMENTATION RUNS (since 2026-08-03). The record layer resolves
  its AES cipher classes through the cipher-class registry -
  MustFindCipherClass(caRijndael, cmCBC / cmCTR / cmGCM) in TlsLayer's
  ChangeCipherSpec and InstallTLS13TrafficKeys - never by naming a class.
  Three implementations compete for those registry slots:

    stAES    table-driven software AES (the historical implementation). Its
             lookups are indexed by key/data bytes, i.e. cache-timing
             variable. NO registered AES mode resolves to it any more; it is
             reached only if an application leaves both units below out of a
             statically linked build.
    stAESNI  hardware AES. Registers when the CPU has the instructions:
             AES-NI on Delphi Win32 AND Win64 and on FPC SysV x86-64
             (Linux/macOS/BSD) - ~1.5 GB/s per core measured - and, since
             2026-08-09, the ARMv8 crypto extensions (AESE/AESD/AESMC/
             AESIMC) on FPC aarch64 Linux, Android and macOS: 1090 MB/s
             measured on an Apple M1. NOT on Delphi's ARM targets: those
             compilers reject inline assembler outright, so Delphi
             mobile/macOS-ARM keeps the constant-time path.
    stAESCT  constant-time bitsliced software AES (Boyar-Peralta S-box
             circuit, after BearSSL aes_ct; endian- and alignment-neutral).
             Registers on exactly the complement of stAESNI's predicate (the
             same CPUID probe): x86 CPUs without AES-NI (either bitness) and
             every non-x86 target. ~40-50 MB/s per core - the machines that
             pay this cost are the machines that were leaking.

  The TLS client and server units force-link stAESNI and stAESCT, so a
  statically linked application gets the right implementation with no crypto
  units in its uses clause. ChaCha20-Poly1305 is unaffected: one
  implementation, already constant-time.

  HISTORY NOTE: until 2026-08-03 the record layer referenced stAES's classes
  DIRECTLY, which pinned every TLS bulk AES operation to the table
  implementation regardless of what was registered - TLS never used AES-NI
  before this change, on any machine.

  CHOOSING A SUITE ON A DELPHI NON-WINDOWS BUILD. The hardware AES arms are
  reached by a Delphi WIN32/WIN64 compile, and under FPC by SysV x86-64 and
  by aarch64 Linux/Android. A DELPHI build for Linux64, macOS, iOS or
  Android has NO hardware AES path at all - the probe finds no arm, and AES
  resolves to the constant-time software implementation. On the ARM targets
  that is not a gap a define could close: the ARMv8 crypto extensions ARE
  implemented here (see stAESNI), but only for FPC, because Delphi's ARM
  compilers reject inline assembler ("E1025 Unsupported language feature:
  'ASM'"). So the advice below is about DELPHI non-Windows builds
  specifically; an FPC aarch64 Linux build gets hardware AES and does not
  need it.

  On those platforms PREFER ChaCha20-Poly1305, and the reason is
  performance, not security - both are constant-time. Measured on one x64
  core (the ratio is what matters; the absolute numbers are this machine):

      ChaCha20-Poly1305       ~180 MB/s     one implementation, every target
      AES-GCM, constant-time   ~80-95 MB/s  what a Delphi POSIX build runs
      AES-GCM, AES-NI          ~1900 MB/s   Windows/FPC-SysV x86-64 only

  So on a Delphi POSIX or mobile build ChaCha20-Poly1305 is roughly twice
  the throughput of the AES suites, while on Windows the same preference
  costs an order of magnitude. This is why the preference is worth setting
  per target rather than globally.

  It is already the default: TTLSOptions.BulkCipherChaCha20Poly1305 is
  prPrefer, and the SSH side lists chacha20-poly1305@openssh.com first. But
  a DEFAULT preference is not a guarantee - in TLS the SERVER selects from
  the client's offer, so a client that wants ChaCha20-Poly1305 on these
  targets should also demote the AES suites (set BulkCipherAES128 /
  BulkCipherAES256 from prPrefer to prAllowed, or to prNotAllowed to
  exclude them outright) rather than merely preferring ChaCha. A server
  controls the choice directly through the same options.
  CLIENTS are where this matters most in practice, because Delphi's POSIX
  and mobile targets are overwhelmingly client-side deployments.

--------------------------------------------------------------------------------
3.6  HANDSHAKE & EXTENSIONS  (RFC 5246 sec.7.4, RFC 6066, RFC 5746, RFC 7366)
--------------------------------------------------------------------------------
StreamSec.Mobile.Tls.pas contains the full bidirectional 1.2 handshake: version
negotiation (clamped to VersionMinorMax on both ends), premaster handling (the
PMS carries the client_version rollback check, sec.7.4.7.1), session
resumption, and the extensions:
  - server_name / SNI (RFC 6066),
  - signature_algorithms (RFC 5246 sec.7.4.1.4.1),
  - renegotiation_info (RFC 5746),
  - encrypt_then_mac (RFC 7366),
  - supported_groups / ec_point_formats (RFC 8422),
  - ALPN (RFC 7301, via TlsClass),
  - and the TLS 1.3 extension set (section 4).
The server side lives in StreamSec.Mobile.TlsInternalServer.pas.

--------------------------------------------------------------------------------
3.7  ALERTS  (RFC 5246 sec.7.2)
--------------------------------------------------------------------------------
StreamSec.Mobile.TlsConst.pas defines the alert code set (close_notify=0 ..
no_renegotiation=100) with RFC text in comments, plus inappropriate_fallback=86
(RFC 7507), unknown_psk_identity=115, certificate_required=116 (RFC 8446 1.3),
general_error=117 (NEW in RFC 9846) and no_application_protocol=120 (RFC 7301).
AlertMsg(code) returns a human-readable description (name + RFC text) for every
one, for logging; assign OnTLSIncomingAlert / OnTLSOutgoingAlert on a server to
log peer/emitted alerts instead of having them raised as exceptions.

--------------------------------------------------------------------------------
3.8  CONNECTION / SESSION STATE
--------------------------------------------------------------------------------
TTLS_RecordLayer holds the active and pending security parameters. On key install
it instantiates the correct tTLSEncryption* read/write objects - this is where the
negotiated version + suite finally selects the concrete cipher implementation. For
TLS 1.2 this is triggered by ChangeCipherSpec; for TLS 1.3 it is triggered by
handshake progress (section 4.4), not by CCS.


================================================================================
4. TLS 1.3  (RFC 8446) - AS IMPLEMENTED
================================================================================

TLS 1.3 is fully implemented on BOTH ends and interop-tested vs OpenSSL 3.5.x:
1-RTT handshake, mutual authentication (mTLS), HelloRetryRequest, session
resumption (PSK), and 0-RTT early data in both directions.

--------------------------------------------------------------------------------
4.1  VERSION NEGOTIATION  (RFC 8446 sec.4.1.3, 4.2.1)
--------------------------------------------------------------------------------
  - ClientHello.legacy_version and the record legacy_record_version stay 0x0303;
    the real offer is the supported_versions extension (ext 43): 0x0304, then
    every version from VersionMinorMax down to VersionMinorMin - [0x0304,0x0303]
    by default. A server that sees the extension uses only it (RFC 8446
    sec.4.2.1), so a version left out could not be negotiated at all.
  - ServerHello also shows 0x0303 and signals 1.3 only via supported_versions =
    0x0304. On seeing it, the client sets NegotiatedVersion := cTLS13vmm and
    switches to the 1.3 code path (HandleServerHello13).
  - HelloRetryRequest is a ServerHello whose Random equals the fixed
    "HelloRetryRequest" SHA-256 constant; the client resends ClientHello with a
    key_share for the server-selected group (and the cookie, if given), bounded to
    one retry. The server emits an HRR when the client's key_share misses an
    accepted-and-allowed group (EncodeKeyShareHRR; the second ClientHello is
    bound by the synthetic message_hash(CH1) || HRR || CH2 transcript).
  - DOWNGRADE PROTECTION (sec.4.1.3): when 1.3 was offered but the server picked
    <=1.2, the client checks the server Random does NOT end in the
    "DOWNGRD\x01"/"\x00" sentinels; the server STAMPS that sentinel when it falls
    back. This complements TLS_FALLBACK_SCSV (RFC 7507), which the client adds
    when the connection's FallbackSCSV is set - a fallback retry the
    application makes - and the server backstops (the SCSV check compares the
    effective maximum, so it is active for 1.3->1.2 downgrades, not just
    1.2->1.1). A lowered VersionMinorMax adds no SCSV: it is a setting, and RFC
    7507 sec.4 counts a version "completely disabled by client settings" as not
    supported.
  - MINIMUM VERSION FLOOR (RFC 8996 / RFC 9846): the global var
    StreamSec.Mobile.TlsConst.VersionMinorMin (default cTLS12vmm) is the LOWEST
    version the engine will negotiate. RFC 8996 deprecates - and RFC 9846 forbids
    negotiating - TLS 1.0/1.1, so both ends reject a selection below the floor with
    a protocol_version alert: the SERVER when the version it would pick from the
    ClientHello is below it, the CLIENT when the ServerHello selects below it.
    Lower it (to cTLS11vmm / cTLS10vmm) only to interoperate with obsolete legacy
    peers; it must satisfy VersionMinorMin <= VersionMinorMax.
  - REACHING A LEGACY PEER: lower VersionMinorMin and leave VersionMinorMax
    alone. TLS 1.0 and 1.1 have no AEAD suite, so also allow the CBC suites
    (BulkCipherAES128 / BulkCipherAES256) and their SHA-1 MAC
    (HashAlgorithmSHA1). Both variables are process-wide. HTTP/2 refuses
    anything below TLS 1.2 (RFC 9113 sec.9.2; HTTP.txt).
  - CEILING: VersionMinorMax caps both ends. The server selects the lower of
    the client's version and it (RFC 5246 sec.7.4.1.3); the client refuses a
    ServerHello above it with protocol_version (RFC 5246 appendix E.1). TLS 1.3
    is not under it: a server that offers TLS 1.3 (TsmAsyncTLSServer always
    does) speaks 1.3 and the versions up to the ceiling, and when it negotiates
    one of those it stamps the DOWNGRD sentinel - so a client that offered TLS
    1.2 refuses a 1.1 handshake with it, as RFC 8446 sec.4.1.3 asks.

--------------------------------------------------------------------------------
4.2  KEY SCHEDULE  (StreamSec.Mobile.Tls13KeySchedule.pas, RFC 8446 sec.7)
--------------------------------------------------------------------------------
HKDF-based (RFC 5869), NOT the 1.2 PRF. The unit reuses tHKDFExtract /
tHKDFExpand from stKDF and adds the TLS-1.3 label framing (HKDF-Expand-Label /
Derive-Secret). It walks the sec.7.1 secret ladder:
    0 -> HKDF-Extract(PSK)            = Early Secret
      -> Derive-Secret("c e traffic") = client_early_traffic_secret (0-RTT)
    Derive-Secret("derived"); HKDF-Extract(ECDHE/KEM) = Handshake Secret
      -> client/server_handshake_traffic_secret
    Derive-Secret("derived"); HKDF-Extract(0)         = Master Secret
      -> client/server_application_traffic_secret_0,
         exporter_master_secret, resumption_master_secret.
Per-secret {key,iv} via HkdfExpandLabel("key"/"iv") and the Finished key
("finished"). The hash (SHA-256 / SHA-384) is fixed by the cipher suite
(RFC 8446 Appendix B.4).

--------------------------------------------------------------------------------
4.3  HANDSHAKE MESSAGES & EXTENSIONS  (StreamSec.Mobile.Tls13Handshake.pas)
--------------------------------------------------------------------------------
Wire encode/decode kept separate from the 1.2 state machine. Handshake types:
new_session_ticket=4, end_of_early_data=5, encrypted_extensions=8, certificate=11,
certificate_request=13, certificate_verify=15, finished=20, key_update=24,
message_hash=254. Extension code points per RFC 8446/8447/8449 (section 2).
  - EncryptedExtensions, the 1.3 Certificate (per-cert extensions),
    CertificateVerify (SignatureScheme codes: rsa_pss_rsae_sha256=$0804,
    ecdsa_secp256r1_sha256=$0403, ed25519=$0807, ml-dsa-44=$0904, ...), and the
    1.3 Finished (= HMAC(finished_key, Transcript-Hash)).
  - The handshake DRIVER (TTLS_HandshakeProtocol in TlsLayer) calls these from
    HandleClientHello13 / HandleServerHello13 / HandleTLS13ServerFlight.
  - ALPN (RFC 7301, ext 16): unlike TLS 1.2 (which echoes the selected protocol in
    the plaintext ServerHello), 1.3 carries the server's choice in the encrypted
    EncryptedExtensions. The server negotiates via PickProtocol over the client's
    protocol_name_list (EncodeALPNExtension into the EE), and a client that offered
    ALPN with NO supported overlap is rejected with a fatal no_application_protocol
    (120) alert; the client extracts the selected protocol back out of the EE
    (Tls13EEExtractALPN in HandleTLS13ServerFlight) and validates it against its
    offer exactly as the 1.2 client does. Interop-tested GREEN both directions vs
    OpenSSL 3.5.6 (s_server / s_client -alpn), including the 120-alert path.

--------------------------------------------------------------------------------
4.4  RECORD LAYER CHANGES  (TLS 1.3)
--------------------------------------------------------------------------------
  - Ciphertext always carries content_type = 23; the true type is the last
    non-zero byte of the decrypted TLSInnerPlaintext (after stripping zero
    padding). On encrypt the real type is appended, then padding.
  - AEAD nonce = write_iv XOR seqnum (left-padded); AAD = the 5-byte record header
    (tTLSEncryption13Aead). The same class serves AES-GCM and ChaCha20-Poly1305.
  - ChangeCipherSpec is a dummy "middlebox compatibility" record: accepted and
    DISCARDED without changing keys. Key changes are driven by handshake progress
    ("install handshake keys" / "install application keys"), fed from the key
    schedule (4.2), replacing the CCS-driven key change of 1.2.
  - Cipher suites: TLS_AES_128_GCM_SHA256 ($1301), TLS_AES_256_GCM_SHA384 ($1302),
    TLS_CHACHA20_POLY1305_SHA256 ($1303) - all three resolved by
    SetTls13CipherFromSuite (and served by tTLSEncryption13Aead). Both sides
    negotiate all three, driven by the TLSOptions bulk-cipher preferences
    (BulkCipherAES128GCM / BulkCipherAES256GCM / BulkCipherChaCha20Poly1305 -
    the same gates as the 1.2 suites, e.g. RFC 7905 ChaCha20):
      * CLIENT offer: each enabled suite is offered, ranked prPrefer before
        prAllowed (ties: $1301, $1302, $1303); nothing enabled falls back to
        offering $1301. The client rejects a ServerHello/HelloRetryRequest
        naming a suite it did not offer (illegal_parameter, RFC 8446 sec.4.1.3).
      * SERVER selection (HandleClientHello13): picks the client-offered suite
        the preferences rank highest (prPrefer beats prAllowed, prNotAllowed
        excludes; ties keep the client's order), falling back to the first
        offered AES-GCM suite (the RFC 8446 sec.9.1 mandatory-to-implement
        floor) if the preferences would rule out every offered suite.
      * 0-RTT is suite-exact (RFC 8446 sec.4.2.10): early data is encrypted
        under the TICKET's AEAD, so the client offers early_data only while the
        ticket's suite is still in its offer, and the server accepts 0-RTT only
        when the negotiated suite equals the ticket's suite (the matching hash
        that suffices for 1-RTT PSK resumption is NOT enough - e.g. a $1303
        ticket resumed on a $1301 connection resumes but rejects early data).

--------------------------------------------------------------------------------
4.5  SERVER CERTIFICATE SELECTION & SERVER-SIDE mTLS  (TLS 1.3)
--------------------------------------------------------------------------------
  CERTIFICATE / KEY / STAPLE FROM THE CACHE: the 1.3 server flight
  (SendTLS13ServerCertAndVerify) selects its leaf from the SAME per-algorithm
  cache the 1.2 server uses (the TsmStreamSecII FTLS12Keys store populated by
  TLSSetupServer), via GetMyServerCertificate -> the OnGetCertificate /
  DoTLSGetCertificate path - NOT by scanning MyCertificates. Because the classical
  TSignatureAlgorithm enum cannot index the 1.3-only leaf algorithms, the cache's
  signature index is the widened TSignatureAlgorithm13 (sa13Anon/RSA/DSS/ECDSA at
  the classical ordinals, plus sa13Ed25519 / sa13Ed448 / sa13MLDSA44/65/87);
  TLSSetupServer adds EdDSA / ML-DSA leaves under [keaECDHE, sa13*], and
  FindCreatePrivateKeyTLS has a widened overload that serves the private key
  (EdDSA / ML-DSA keys are handed out as their native key objects, not wrapped).
  RSA leaf keyUsage is evaluated per ROLE when the cache is populated: the
  static-RSA row requires keyEncipherment, while a digitalSignature-only RSA
  leaf populates the signing row that serves DHE_RSA / ECDHE_RSA and the
  1.3 flight - so such a leaf serves those exchanges rather than disabling RSA
  outright. Note that the cache
  populator TsmStreamSecII.InternalAddTLSServerCert dispatches on EXACT
  (key-exchange, signature) pairs and SILENTLY ignores unrecognized
  combinations (and pairs whose private key fails Validate against the cert's
  public key) - a leaf that never appears in the cache is a silent no-op, not
  an error.
  Consequences:
    * SNI is honoured: HandleClientHello13 stores the ClientHello server_name in
      DNSNameToCheck, so a multi-certificate (virtual-host) server picks the
      per-host leaf exactly as in 1.2; EncryptedExtensions acks server_name on a
      full handshake (RFC 6066), and resumption is SNI-bound (the ticket records
      the ServerName it was issued under; a mismatched PSK falls back to a full
      handshake rather than aborting).
    * ALPN drives cert selection per-connection: HandleClientHello13 runs
      PickProtocol over the client's protocol_name_list BEFORE the leaf is chosen,
      which narrows the connection's ApplicationProtocols to the single negotiated
      protocol. InternalGetMyServerCertificate passes that (ApplicationProtocols[0])
      to OnGetCertificate / DoTLSGetCertificate, which routes an acme-tls/1
      connection to the FTLSAcmeKeys challenge cert and everything else to the
      normal FTLS12Keys leaf. Before this fix the 1.3 path never negotiated ALPN,
      so the static ApplicationProtocols[0] was used for every connection - the
      moment an ACME tls-alpn-01 responder was activated it hijacked the
      certificate for ordinary http/1.1 / h2 traffic (the reported outage). See 4.3.
    * ACME tls-alpn-01 SERVER responder (server side only): AddTLSAcmeALPN /
      RemoveTLSAcmeALPN provision and clear the acme-tls/1 challenge certificate
      (self-signed, carrying the RFC 8737 id-pe-acmeIdentifier over the key
      authorization) + its key, so the acme-tls/1 selection above answers the CA's
      validation probe (handshake only, then close). TryBeginAcmeChallenge /
      EndAcmeChallenge serialise the single challenge slot with a critical section
      (FAcmeChallengeGate, non-blocking TryEnter) so several TsmAcmeRenewalManager
      instances sharing one server do not collide, and
      FindExpiringTLSServerCertificatesEx(elapsedFraction, list) selects the leaves
      due for renewal. The ACME account/order/finalize PROTOCOL (and the PKCS#10 CSR
      builder) are documented separately - see ACME.txt (and PKIX.txt for the CSR).
    * signature_algorithms is honoured: the flight walks a fixed sig-index
      preference and picks the first cached leaf that can produce a
      SignatureScheme the client offered (ECDSA schemes are curve-matched).
    * signature_algorithms_cert (ext 50) is honoured for the leaf's OWN
      signature (falls back to signature_algorithms when absent); no usable
      combination aborts with handshake_failure / no_common_cipher_suite.
    * The OCSP staple is fetched from the same cache record (section 9).
    * Cache lookups (leaf selection, the FindCreatePrivateKeyTLS key match, and the
      per-cert OCSP-staple get/set) match a certificate to its cache slot by
      CONTENT identity - iCertificate.SameCert (GetStruct.Compare), NOT object
      identity - so a re-imported or hot-rotated but byte-identical leaf still
      resolves to its cached key and staple. (See PKIX.txt section 3.)

  SERVER-SIDE mTLS (client authentication): the 1.3 server now honours the same
  two levers as 1.2 - Options.RequestClientCertificate and
  Options.RequireClientCertificate (BOTH DEFAULT TRUE; a deployment that does not
  want client authentication must set both False):
    * When requesting, the server sends CertificateRequest
      (EncodeCertificateRequest13: empty context + signature_algorithms) between
      EncryptedExtensions and Certificate - suppressed on a PSK resumption
      (RFC 8446 sec.4.3.2).
    * The client Certificate / CertificateVerify are validated role-aware
      (chain into the client-cert slot, digitalSignature required,
      CertificateVerify checked against the "TLS 1.3, client
      CertificateVerify" context); ordering is enforced (unsolicited or duplicate
      client Certificate = unexpected_message).
    * EXTENDED KEY USAGE: a client certificate whose extendedKeyUsage extension
      does not list id-kp-clientAuth is refused with unsupported_certificate
      (43). A certificate with NO extendedKeyUsage extension at all is
      ACCEPTED: tCertificate.CheckExtKeyUsage answers True when the extension
      is absent, which is RFC 5280's generic reading (a certificate that states
      no purpose is not restricted to one), and the TLS check asks only it.
      This is deliberate and unchanged. A deployment whose client profile must
      carry clientAuth enforces that where the certificates are issued, or in
      its own authorization step after the handshake
      (CheckExtKeyUsagePolicy(..., ekupRequire) in StreamSec.DSI.PkixCert
      demands the extension's presence).
    * An empty client Certificate is legal when only REQUESTED; when REQUIRED it
      is rejected at the client Finished with the RFC 8446 certificate_required
      alert (116). A certificate that does not chain to the server's RootCerts
      gets unknown_ca (48).
      On TLS 1.2 an empty required Certificate produces fatal handshake_failure
      (40), as RFC 5246 sec.7.4.6 specifies. A raising outgoing-alert handler
      preserves that rejection; it is not reclassified as internal_error.
    * ON A PSK RESUMPTION THERE IS NO CLIENT CERTIFICATE. The server sends no
      CertificateRequest then, the ticket does not carry the original one, and
      the session's ClientCertificate is nil, so RequireClientCertificate does
      not force one either. A listener that authorizes on the client
      certificate either sets Options.SessionResumption := False (full
      handshakes only) or treats a nil certificate as "not authenticated".
  READING THE CLIENT CERTIFICATE after the handshake: the content layer's
  ClientCertificate; on TsmAsyncTLSServer, iTLSConnectionInfo.PeerCertificate
  on the transport (AsyncTLSServer.txt section 8.2), which the HTTP server
  exposes as Request.Connection.TransportInfo (HTTP.txt section 2.1); and in a
  Snif method served by TsnipTLSServer, TsnipTLSServer.CurrentPeerCertificate
  (or IsnipTLSTransportInfo on TsnifClassServer.CurrentContext.Connection).
  Every one of them reports a certificate the handshake has already accepted;
  what is left for the application is authorization.
  THE CertificateVerify SCHEME MUST MATCH THE KEY, in both directions: the
  EdDSA and ML-DSA SignatureSchemes each name one key type and parameter set
  (ed25519/ed448, ml-dsa-44/65/87 - draft-ietf-tls-mldsa), and a
  CertificateVerify whose scheme is not the one the certificate's key
  belongs to is refused with illegal_parameter (47) before its signature is
  looked at - by the server for the client's, by the client for the
  server's. Which schemes an end accepts at all is its Options
  (SignatureEdDSA / SignatureMLDSA / SignatureCompositeMLDSA). These peer
  preferences are independent of the local signing-certificate family; an
  EdDSA server can accept an allowed ML-DSA client, and conversely. Explicit
  prNotAllowed is retained. Local signing still needs an actual eligible key.
  A client identity is selected against CertificateRequest's signature and
  certificate-signature schemes rather than sending an incompatible first
  signing certificate. Certificate purpose, trust, validity and issuer
  constraints remain separate checks.
  Server startup checks cached local identities separately when own
  certificates were configured or rejected. Peer acceptance does not make
  a rejected local certificate usable. Fresh/key-only dynamic callbacks,
  explicit anonymous service and enabled live PSK ticket state retain their
  certificate-free setup paths. ClearCertificates clears a remembered own
  certificate rejection used in startup diagnostics.

--------------------------------------------------------------------------------
4.6  POST-HANDSHAKE KEYUPDATE  (RFC 8446 / RFC 9846 sec.4.6.3 + sec.5.5)
--------------------------------------------------------------------------------
  Either peer may, after the handshake, rotate its sending keys by sending a
  KeyUpdate (handshake type 24) - the receiver advances its matching receiving
  keys. Each direction advances application_traffic_secret_N -> N+1 via
  HKDF-Expand-Label(secret,"traffic upd",...) (the record layer's UpdateTLS13Key,
  reusing TTls13KeySchedule.UpdateTrafficSecret) and reinstalls the AEAD, which
  resets that direction's record sequence number to 0 (sec.5.3). KeyUpdate is NOT
  part of the handshake transcript.
    * RECEIVE (both roles): the post-handshake dispatch in HandleTLS13ServerFlight
      (client) and HandleTLS13ClientFlight (server) routes type 24 to
      HandleTLS13KeyUpdate, which advances the read key and, when the peer sent
      update_requested, replies with its own KeyUpdate (update_not_requested -
      never requesting back, which would loop) and advances the write key.
    * SEND: SendTLS13KeyUpdate sends the KeyUpdate under the CURRENT write key,
      then switches the write key. Exposed to the application as
      TTLS_ContentLayer.KeyUpdate(aRequestPeerUpdate, Response).
    * USAGE-LIMIT REKEY (sec.5.5, upgraded to MUST in RFC 9846): the record layer
      counts records encrypted under the current write key; for AES-GCM, once the
      count reaches a safe margin below the 2^24.5 confidentiality limit (2^24),
      the application-data send path emits a KeyUpdate BEFORE the next record.
      (ChaCha20-Poly1305 has no confidentiality limit within the 2^64 sequence
      space and is not forced.)
    * DoS CAP (RFC 9846): a burst of KeyUpdates with no intervening application
      data is rejected (unexpected_message) after a small bound; the counter
      resets whenever application data is delivered.
  Validated in-process both directions x both request modes x either initiator,
  and vs openssl s_client (its 'K'/'k' key-update commands):
  our server processes OpenSSL's KeyUpdate and keeps decrypting the
  post-rotation records.


================================================================================
5. POST-QUANTUM & MODERN KEY EXCHANGE IN TLS 1.3
================================================================================

All driven by the TLSOptions surface (SupportedGroups / OfferTLS13) and emitted
as key_share + supported_groups in the ClientHello; the server selects one.

  CLASSICAL ECDHE groups (RFC 8422 / RFC 7748): secp256r1 ($0017),
  secp384r1 ($0018), secp521r1 ($0019), x25519 ($001D), x448 ($001E). The
  FFDHE groups ffdhe2048 to ffdhe8192 are listed in supported_groups only when
  TLSOptions.KeyAgreementDHE allows the TLS 1.2 DHE suites; a TLS 1.3 key
  exchange over them is not implemented.

  PURE ML-KEM (FIPS 203; draft-ietf-tls-mlkem): mlkem512 ($0200),
  mlkem768 ($0201), mlkem1024 ($0202). The key_share carries the ML-KEM
  encapsulation key (client) / ciphertext (server); the shared secret is the
  32-byte ML-KEM secret fed directly into HKDF-Extract (no extra KDF).

  HYBRID ECDHE + ML-KEM - the RFC 9954 construction, with the codepoints/order
  from RFC 10024 (Standards Track, August 2026; formerly
  draft-ietf-tls-ecdhe-mlkem / draft-kwiatkowski-tls-ecdhe-mlkem):
  secp256r1mlkem768 ($11EB), x25519mlkem768 ($11EC), secp384r1mlkem1024 ($11ED).
  The key_share and shared secret are the raw concatenation of the two parts in a
  group-specific order (x25519mlkem768 puts ML-KEM first; the SecP* groups put
  ECDH first); the TLS key schedule HKDF-extracts the concatenation. The server
  side splits the peer key_share by the fixed EC public-key length, runs ECDH +
  ML-KEM-Decapsulate, and re-concatenates (HandleServerHello13 / the server
  mirror in TlsInternalServer).

  PEER KEY_SHARE VALIDATION (RFC 10024 sec.4.1-4.3; RFC 9846 sec.4.3.8.2 +
  sec.7.4.2) - enforced by both endpoints for the classical 1.3 EC groups, the
  pure ML-KEM groups and the hybrids, each failure with its own qualified alert
  reason code (see section 9):
    - The peer share must have the EXACT length of the selected group (RFC
      10024 sec.4.1/4.2 tabulates them; Tls13MLKEMCiphertextLen /
      Tls13MLKEMEncapsKeyLen in TlsLayer) -> illegal_parameter.
    - A Weierstrass EC share must be an UNCOMPRESSED point ($04 leading byte -
      this also rejects the $00 point-at-infinity encoding) that decodes onto
      the curve; the decoder returns nil for an off-curve or malformed point
      and the callers now test for it -> illegal_parameter.
    - An all-zero X25519/X448 ECDH OUTPUT aborts (small-order peer point; the
      input-side decoder already rejects u=0 itself) -> illegal_parameter.
    - The server runs the FIPS 203 sec.7.2 encapsulation-key check (exact
      length + coefficient-encoding round-trip, tMLKEMPublicKey.Validate) on
      the client's ML-KEM key -> illegal_parameter.
    - A wrong-length ML-KEM ciphertext is the peer's fault ->
      illegal_parameter; once lengths/keys have been validated, a KEM
      encapsulation/decapsulation failure is OURS -> internal_error.
  This IS RFC 9954 sec.3: the concatenation carries no per-part KDF and no length
  prefixes (each part's length is fixed once the group is fixed), and the result
  is inserted in place of the (EC)DHE secret in the key schedule. NOTE the
  contrast with the LAMPS composite-KEM combiner used for CMS/SSH
  (SHA3-256(mlkemSS||tradSS||...)) - that is a DIFFERENT construction and must
  NOT be used here.

  RFC 9954 sec.3.2 ("Transmitting Public Keys and Ciphertexts") offers the client
  TWO options: (1) fully independent generation - fresh randomness per component
  per NamedGroup entry; or (2) reusing one component's key pair across several
  KeyShareEntry records, to avoid shipping the same (large) ML-KEM public key
  twice when several hybrids are offered.
  THIS CLIENT USES OPTION 1 (fully independent generation). It never reuses a
  component key pair across key shares - and cannot, because it sends exactly ONE
  KeyShareEntry per ClientHello: BuildTLS13ClientHelloExtensions takes the single
  group returned by ChooseTls13Group and emits one EncodeKeyShareEntry; the other
  enabled groups are advertised in supported_groups only. Both halves are freshly
  generated for every ClientHello (GetDSIEC.NewKeys + MustGetDSIML.KEMKeyGen), and
  a HelloRetryRequest re-runs the same builder for the server-selected group, so
  the resend is a fresh key pair too (and HRR may not re-select the group already
  sent). Consequence: the duplicate-ML-KEM-key cost sec.3.2 warns about never
  arises here; the trade-off we pay instead is one extra round-trip (HRR) when the
  server prefers a group we did not pre-share. (BuildClientHello13Extensions in
  Tls13Handshake takes a concatenation of entries and would permit multi-share
  offers, but nothing calls it - the live client path is the single-share one.)
  Interop (2026-07-13): all three groups handshake GREEN against
  `openssl s_server -tls1_3 -groups <G>` (OpenSSL 3.5.6), each with the server
  restricted to that one group and our client set to the same
  group: x25519mlkem768, secp256r1mlkem768, secp384r1mlkem1024.
  Revalidated (2026-08-11, OpenSSL 3.5.7) after the RFC 10024 validation pass:
  both directions x {x25519, P-256, MLKEM768, all three hybrids} handshake
  GREEN, and the hostile-key_share probe (section 10) draws a clean fatal
  illegal_parameter for every malformed-share case.

  SIGNATURES: classical (RSA-PKCS1, RSA-PSS, ECDSA) plus EdDSA (ed25519 $0807,
  ed448 $0808; RFC 8410) and ML-DSA (FIPS 204; draft-ietf-tls-mldsa: ml-dsa-44
  $0904, ml-dsa-65 $0905, ml-dsa-87 $0906) in CertificateVerify. The ECDSA
  signature produced for CertificateVerify uses the constant-time RFC 6979 path
  (the dlssaDSAFixedTime scheme in StreamSec.DSI.DiscreteLog + FixedGroupOpIteration
  in StreamSec.DSI.ECArith).

  RSA-PSS keys: rsa_pss_pss_sha256/384/512 (0809/080A/080B) use an
  id-RSASSA-PSS SPKI; rsa_pss_rsae_* uses rsaEncryption. Selection validates
  the key's hash, MGF and minimum-salt restrictions, not just the family name.
  Ordinary RSA using a PSS signature is not a PSS-restricted subject key.
  Certificate-signature selection is separate: present issuer PSS parameters
  must match the certificate signature parameters exactly (RFC 9846 4.2.3).
  CertificateVerify uses the key's minimum-salt restriction instead.

  EXPERIMENTAL COMPOSITE SIGNATURES: SignatureCompositeMLDSA is OFF by
  default. The current TLS composite draft has unassigned wire identifiers.
  StreamSec FE30..FE3F are PRIVATE-USE values for its sixteen implemented
  LAMPS profiles, requiring explicit agreement and opt-in at both peers.
  They are not IANA assignments and do not imply public interoperability.
  Thirteen profiles can sign CertificateVerify; FE31, FE35 and FE37 are
  RSA-PKCS1 composite certificate-signature-only profiles. The separate
  signature_algorithms_cert extension can advertise those certificate
  signatures without offering them for CertificateVerify. Outbound chain
  selection refuses missing or unoffered certificate-signature mappings.
  Composite keys loaded from PFX enter the signing key ring and serving
  cache. Key selection and signature verification bind the profile to SPKI.
  Malformed, empty or duplicate signature-list extensions are rejected.
  Verification checks the actual locally advertised schemes, retained as an
  owned handshake snapshot; a callback cannot broaden that transmitted offer.
  A HelloRetryRequest preserves the first ClientHello's signature lists.
  None of these PQ schemes is advertised on an explicit TLS 1.2 path.
  RFC 9851 section 2 restricts PQ TLS work to TLS 1.3 or later.

  PEER CERTIFICATEVERIFY DIAGNOSTICS: TCustomTLS_ContentLayer exposes
  PeerCertificateVerifyScheme and PeerCertificateVerifySchemeAvailable.
  Read the availability Boolean first. The Word is an observed complete
  message, including a complete message subsequently rejected for policy or
  signature failure; it is NOT a successful-authentication verdict. TLS 1.3
  records the peer in both roles. TLS 1.2 records the client's explicit
  hash/signature pair at the server, not the server's ServerKeyExchange.
  TLS 1.0/1.1 implicit schemes and PSK/resumption without CertificateVerify
  stay unavailable. Malformed/truncated vectors do not become observations.
  New handshakes reset the value; KeyUpdate and close retain it.
  Do not derive this fact from the certificate issuer signature or the
  cipher suite's hash. Composite ML-KEM remains separate key-agreement work.


================================================================================
6. 0-RTT EARLY DATA  (RFC 8446 + RFC 8470) - AS IMPLEMENTED
================================================================================

Both directions are implemented and interop-tested (full -> resume -> 0-RTT,
including `openssl s_client -early_data` "Early data was accepted").

  CLIENT: on a resumption ticket that advertised max_early_data_size, the client
  derives the early-traffic key from the resumption PSK over
  Transcript-Hash(ClientHello), installs it, and emits the queued 0-RTT payload as
  application_data immediately after the ClientHello (SendTLS13EarlyData),
  terminated by EndOfEarlyData. If EncryptedExtensions does not echo early_data,
  the client replays the request over the established 1-RTT channel.

  SERVER (data via streams, not events): the consumer interface routes 0-RTT
  plaintext to a separate stream:
      Accept(Src, EarlyData, Response)
      DecodeData(Src, Data, EarlyData, Response)
  (plus TLSAccept / TLSDecodeData). 1-RTT data goes to Data; 0-RTT data goes to
  EarlyData. OMITTING the EarlyData stream makes the server refuse 0-RTT - the
  secure default. Policy is the TEarlyDataMode enum on Options.EarlyData:
  edmDisabled (default - never advertise/accept 0-RTT), edmAccept (accept and
  deliver), or edmRejectAndRetry (advertise nothing so the client replays over
  1-RTT); MaxEarlyDataSize caps the advertised size. A pull consumer that does not
  use the stream split can instead poll EarlyDataPending / EarlyDataStatus and
  TakeEarlyDataDelivered to locate the 0-RTT/1-RTT boundary in its own buffer.

  ANTI-REPLAY (RFC 8446 sec.8): the engine raises OnTLSCheckEarlyDataReplay before
  accepting 0-RTT; the application owns a single-use ticket / strike-register and
  sets Accept := False on any repeat. Tickets are issued via NewSessionTicket
  (an in-memory ticket store on TsmStreamSecII) and bound to the resumption PSK;
  a group mismatch on resume is a fatal abort.

  TICKET LIFECYCLE / MAINTENANCE:
    * NewSessionTicket is a POST-handshake message: it is produced by the
      TLSDecodeData call that consumes the client Finished and rides out in THAT
      call's Response - a server loop must keep transmitting every Response, or
      no ticket ever reaches the wire ("resumption tickets: No" on a scanner).
    * SINGLE-USE: a ticket is CONSUMED (removed from the store) the moment it is
      resumed - but only AFTER the PSK binder verifies, so a ticket identity
      (which travels in cleartext in the ClientHello) cannot be used by an
      on-path attacker to burn a victim's ticket. Reuse of a consumed ticket
      falls back to a full handshake. The lookup takes a private CLONE
      (Tls13PeekServerTicket) to verify the binder off the store lock, then
      Tls13ConsumeServerTicket removes the original (idempotent, so a concurrent
      resume of the same ticket just no-ops rather than double-freeing).
    * BATCH ISSUANCE: because tickets are single-use, each handshake issues a
      BATCH so a client has one per parallel connection - Options.SessionTicketCount
      tickets (default 6 = the per-host connection limit contemporary browsers
      apply to HTTP/1.1; clamped to [1,255]). Each ticket in the batch gets a
      distinct one-byte nonce (hence a distinct resumption PSK) and a distinct
      random identity. Tls13ServerTicketCount exposes the live store size.
    * Tickets are SNI-bound (issued under the connection's server_name; a PSK
      offered for another name falls back to a full handshake).
    * FULL OfferedPsks LIST: a ClientHello may offer SEVERAL PSK identities (each
      with its own binder). ParseClientPreSharedKey returns them ALL (positionally
      paired identity<->binder), and HandleClientHello13 SCANS them in order,
      resuming on the first whose ticket is known and matches (suite hash / SNI /
      group) and whose binder verifies - echoing that index as selected_identity in
      the ServerHello. The binder transcript (truncated ClientHello) is
      identical for every identity, so it is computed once. A candidate that
      mismatches is SKIPPED (a group mismatch is a skip, NOT a fatal abort);
      if none match, a full handshake runs. 0-RTT is honoured only
      for identity 0 (RFC 8446 sec.4.2.10). The scan is capped (12) against a
      hostile many-identity offer.
    * The in-memory store self-limits: expired tickets are reaped on insert and
      on every resumption lookup, PruneExpiredTls13Tickets prunes explicitly, and
      the prune is folded into ClearExpiredTLSSessions so the existing
      ClearExpiredSessionKeys housekeeping bounds the 1.3 store too.
    * CLIENT resumption: each issued ticket is surfaced through the content
      layer's OnNewSessionTicket and the component event OnTLSNewSessionTicket
      (TsmStreamSecII wires both in TLSAdd*Session); the consumer Clones the
      ticket and offers it on the next connection via ResumptionTicket;
      IsResumedSession reports acceptance.
    * CLIENT offers a LIST: the primary ResumptionTicket is PSK identity 0 (the
      only 0-RTT-capable one); AddResumptionTicket adds extras (identities 1..N).
      Since the server's tickets are single-use, presenting several lets the server
      pick one not yet consumed (its selected_identity says which, and the client
      keys off that ticket's PSK). Extras must share the primary's PRF hash (others
      are dropped, since one offer's binders share the hash); AppendPSKExtensions
      encodes N identities + N placeholder binders (EncodePreSharedKeyCHList) and
      PatchPSKBinder fills each binder (per-ticket PSK, over the SAME truncated
      ClientHello). The client accepts a selected_identity only within the range it
      offered.

  SERVER SETUP: call TLSSetupServer before accepting; TLS 1.3 is accepted by
  default (OfferTLS13 defaults True - clear it per session via OnTLSAddContentLayer,
  or on the component, to force 1.2); drive the ClientHello with TLSAccept but the
  client CCS + Finished with TLSDecodeData.


================================================================================
7. SUPPORTING UNITS & CONSUMERS
================================================================================

stTlsUtils.pas
  - tRandom packed record (gmt_unix_time + 28 random bytes) = the Hello Random
    (RFC sec.4.1.2 / 7.4.1.2). TLS_NewRandom(var Random; aPRNG: iRawRandom = nil)
    fills it (UnixTime big-endian + random bytes from aPRNG, or the global RawRandom
    when nil); the TLS layer passes the connection's secondary DRBG (section 9).
    Also byte-swap / interlocked / TSC helpers.

stKDF.pas
  - tHKDFExtract / tHKDFExpand (RFC 5869) - reused unchanged by the 1.3 key
    schedule. Also the legacy KDFs.

StreamSec.Mobile.CCADB.pas  (with .CCADBRoots and .CCADBReg)
  - FOR ONE CASE ONLY: a peer whose issuer cannot be known before run time. If
    the program chose the authority at COMPILE time, compile that root in; if
    the operator can name it at CONFIGURATION time, let them name it
    (LoadRootCertsFromFile). A certificate in a store anchors everything that
    store validates, so a public set does not buy trust in one destination - it
    lets every authority in it vouch for every peer that engine verifies. The
    cases it is for are the ones where nothing narrower can be chosen: the MX
    host for a recipient domain that arrived with a message, that domain's
    mta-sts policy host, a URL the program was handed. WHAT ARRIVES LATE IS THE
    PEER, NOT THE ANCHORS - those still go in at load time, as below.
  - The public root set as trust anchors, compiled in. TsmCCADBTrustAnchors is
    dropped beside a TLS engine, Engine is pointed at it, and the roots go into
    that engine's RootCerts store when loading finishes - before the
    application's own TLSSetupClient and before anything has connected, which is
    where anchors want to be. (A root added later is not lost: every session is
    handed the engine's LIVE root store.) AutoInstall = False defers it;
    Install(engine) and the plain function AddCCADBRoots do the same for an
    engine built at run time. Both return how many of the set the store
    accepted. A root that cannot be installed is named through OnProblem rather
    than raised - a program holding all but one of the anchors is a working
    program - and installing the set twice is harmless, a certificate the store
    already holds being matched rather than stored again.
  - The embedded set is the CCADB / Mozilla root program filtered to the
    WEBSITES trust bit, which is exactly the question "may this server prove
    who it says it is". It is DATED: the class functions Established, Source
    and RootCount report the day the list was taken, the URL it came from and
    how many roots it holds, so an application can log the age of the trust it
    is running on. A root program removes CAs as well as adding them, so
    refreshing the set is a library release.
  - ONE INSTANCE PER TRUST DOMAIN. There is deliberately no process-wide
    default and no fallback engine - see section 9.

CRYPTO PRIMITIVES resolved at run time by the cipher classes:
  stAes / stDes / stGHash (GCM) / stChaCha20Poly1305 / stSHA* / stRandom, and the
  StreamSec.DSI.* public-key stack (ECC, EdDSA/CurveEd, ML-KEM, ML-DSA, RSA/IFC,
  FFC) for key agreement and CertificateVerify. EC scalar multiplication (the
  ECDHE key_share + ECDSA hot path) now dispatches through the workspace
  multipliers (InternalMulWs / InternalMulFixedWs) with Solinas fast reduction
  on P-192..P-521 - about 4-6.5x faster on Win64, dudect-checked constant-time
  (see PKIX.txt section 8).
  The legacy stDes provider and its dependent code paths are excluded under
  FPC. The other TLS providers remain intentionally linked.

WHO USES THE TLS LAYER
  - StreamSec.Mobile.StreamSecII (TsmStreamSecII) + X509Comp are the drop-in TLS
    components the application instantiates; TlsSocket binds them to a socket.
  - The SSH stack reuses stTlsUtils (tRandom, byte-swap, UnixTime) but implements
    its own transport - it shares the TLS utility layer, not the record layer.


================================================================================
8. DEPENDENCY GRAPH  (".pas uses" relationships)
================================================================================

Legend:  A -> B  means  "unit A depends on (uses) unit B".

  StreamSec.Mobile.TlsConst       -> (leaf: version + alert + content-type consts)
  StreamSec.Mobile.Tls13KeySchedule -> stDERUtils, stSecUtils, stKDF
                                     (leaf-ish: only tBytes/THashClass; no Mobile
                                      deps, so the record layer can use it without
                                      a cycle.)
  StreamSec.Mobile.Tls13Handshake -> stDERUtils, stSecUtils,
                                     StreamSec.Mobile.Tls13KeySchedule
  StreamSec.Mobile.TlsEncryption  -> the bulk cipher primitives + TlsConst
                                     (provides the tTLSEncryption* objects)
  StreamSec.Mobile.Tls            -> TlsConst (+ the DSI crypto units)
  StreamSec.Mobile.TlsClass       -> Tls, TlsConst (policy / TLSOptions surface)
  StreamSec.Mobile.TlsInternalServer -> Tls, TlsConst, Tls13Handshake,
                                     Tls13KeySchedule (server flight, tickets, HRR)
  StreamSec.Mobile.TlsLayer       -> stDERUtils, stSecUtils, stTlsUtils,
                                     StreamSec.DSI.* (PkixCert, PKTypes, IFC, FFC,
                                     ECC, EdDSA, ML-KEM, ML-DSA),
                                     TlsConst, Tls, TlsClass, TlsEncryption,
                                     Tls13KeySchedule, Tls13Handshake,
                                     X509Comp, StreamSecII
                                     (the top-level record + handshake driver;
                                      hosts all the 1.3 branches.)
  StreamSec.Mobile.StreamSecII / X509Comp / TlsSocket
                                  -> the above; the components the app uses.


================================================================================
9. NOTABLE SECURITY BEHAVIOUR
================================================================================
  - PER-CONNECTION SECONDARY DRBG: every value written to the WIRE is drawn from the
    connection's own secondary generator - TCustomTLS_ContentLayer.ConnRandom
    (= stRandom.GetRawRandom(True)) / ConnRandomBuf / ConnRandomBytes, the record
    layer's tTLSEncryption.PRNG / TTLS_RecordLayer.PRNG, and TLS_NewRandom's aPRNG.
    This covers the hello randoms, the TLS 1.2 session_id, the CBC explicit record
    IV, and the 1.3 ticket identity + ticket_age_add; key-generation seeds stay on
    the PRIMARY generator. It also FIXED a predictability bug: ticket_age_add used to
    be the byte-swapped Unix timestamp with NO random bits (identical across a batch,
    weakening the RFC 8446 sec.4.6.1 obfuscated_ticket_age), and the session_id never
    touched a DRBG at all.
  - TLS 1.3 KEY_SHARE VALIDATION (RFC 10024 / RFC 9846): both endpoints enforce
    exact per-group share lengths, uncompressed-format + on-curve EC point
    checks (nil-guarding the decoder, which reports an invalid point by
    returning nil rather than raising), the all-zero X25519/X448 shared-secret
    abort, and the FIPS 203 sec.7.2 encapsulation-key check - each rejected
    with fatal illegal_parameter; post-validation KEM failures are reported as
    internal_error instead of being blamed on the peer. Every check carries a
    distinct reason code in bits 8-23 of the alert (client_key_share_format,
    client_ec_point_invalid, client_kem_key_invalid, client_zero_shared_secret,
    kem_encaps_failed; server_* and kem_decaps_failed for the client side) -
    OnTLSOutgoingAlert + AlertMsg decode them; the wire carries only the low
    byte. Section 5 has the per-check contract.
  - TLS 1.2 ECDHE PEER-POINT VALIDATION (RFC 8422 sec.5.4.1 / sec.5.11): the
    same three checks are enforced on the 1.2 key exchange. A Weierstrass point
    must carry the uncompressed-format leading byte ($04 - which also rejects
    the $00 point-at-infinity encoding); the point decoder reports an off-curve
    or malformed point by returning nil rather than raising, and every caller
    tests for it; and an all-zero X25519/X448 ECDH output aborts, catching the
    small-order peer points that a zero u-coordinate check alone does not see.
    Both endpoints and both messages are covered - the server validates the
    ClientKeyExchange point, the client validates the ServerKeyExchange point
    and re-checks the derived secret before it becomes the premaster. A
    rejected point ends the handshake through the normal alert path; none of
    them reaches the scalar multiplication.
  - BEAST prevention: for versions below TLS 1.1 on the SERVER end, CBC suites are
    refused. Mitigates the TLS 1.0 CBC IV-chaining (BEAST) weakness that RFC 4346
    fixed with explicit IVs.
  - Padding/MAC errors are reported uniformly as bad_record_mac (RFC 5246
    sec.6.2.3.2 / the Lucky-13 guidance), never a distinct decryption_failed.
  - Encrypt-then-MAC (RFC 7366) is offered for CBC suites, removing the MAC-then-
    encrypt timing surface when the peer agrees.
  - TLS 1.3 downgrade protection: the RFC 8446 sec.4.1.3 "DOWNGRD" sentinel
    (server stamps, client detects) plus TLS_FALLBACK_SCSV (RFC 7507), with the
    SCSV backstop comparing the EFFECTIVE maximum so it covers 1.3->1.2 downgrades.
  - Cross-version resumption is blocked: saved PSKs / session keys are bound to the
    version that produced them, so a 1.2 ticket cannot be replayed into a 1.3
    handshake (or vice-versa).
  - 0-RTT is replay-protected: omitting the EarlyData stream refuses 0-RTT, and
    OnTLSCheckEarlyDataReplay lets the application enforce single-use tickets.
  - Secret-material zeroization: handshake/traffic secrets, ticket PSKs and the
    24-bit-length record-encoder scratch buffers are wiped (ProtectClear); a
    historical under-wipe in the handshake-length reassembly (shr-vs-shl) was fixed
    so reused buffers retain no residual secret bytes.
  - ECDSA signatures (CertificateVerify / ServerKeyExchange) use the constant-time,
    RFC 6979-deterministic path, removing the classic nonce-timing side channel.
  - CONSTANT-TIME TAG ACCEPTANCE: every AEAD/MAC acceptance decision - GCM and
    ChaCha20-Poly1305 on the record layer, plus CCM/EAX/OMAC/XCBC-MAC - compares
    through stSecUtils.EqualMemConstantTime, whose running time depends only on
    the tag length. A CompareMem-style early exit would leak how many leading
    bytes of a forged tag were correct. VerifyFinalBuf returning False is what
    the record layer maps to bad_record_mac (section 3.5).
  - CONSTANT-TIME AES where hardware AES is absent: bulk AES resolves through the
    cipher-class registry to AES-NI (stAESNI) on CPUs that have it and to the
    bitsliced constant-time stAESCT everywhere else, closing the classic AES
    cache-timing channel of the table implementation for every TLS suite. The
    key schedule is constant-time too (bitsliced SubWord). Section 3.5 has the
    selection table and cost figures.
  - TRUST ANCHORS ARE A TRUST DOMAIN, NOT A SETTING: an engine's RootCerts store
    is at once the anchor set for the peer chains it validates, the source of
    intermediates it completes a chain from, and - on a LISTENER - the issuers
    whose CLIENT certificates it will accept and the names it offers in a
    CertificateRequest. Public roots therefore belong on a client leg that talks
    to the internet at large, and nowhere else: installed on a server they make
    every certificate any public CA ever issued a valid client credential, which
    on a mail host that relays on a client certificate is an open relay. That is
    why the public set is a COMPONENT (TsmCCADBTrustAnchors, section 7) with no
    process-wide default and no fallback engine: one instance per trust domain,
    so the trust that reaches a connection is the trust someone chose for it.
    AND NOT EVERY CLIENT LEG - choosing an engine is not the same as choosing an
    anchor. Where the authority is settled at compile time, or nameable by the
    operator at configuration time, install THAT root and nothing else; the
    compiled-in set is for the leg whose peer is not known until run time, and
    for no other.
  - CERTIFICATE REVOCATION: revocation is checked DURING chain validation. Assign
    the optional TsmCustomTLSInternalServer.Ocsp (a TsmOcsp) to enable online OCSP
    (RFC 6960 / 8954 / 5019); the server binds its RootCerts store to the Ocsp
    client automatically, so the trust anchors that validate the chain also
    resolve the OCSP issuer/responder. When Ocsp is unassigned (e.g. a pure
    server), the check falls back to CRLs. CRLs are only trusted when
    signature-valid AND fresh (thisUpdate <= now <= nextUpdate), with stale ones
    refreshed via AbstractOcsp.FetchCRL; verdicts are cached per certificate.
    RevocationPolicy (rpIgnore / rpSoftFail / rpHardFail, default soft-fail) and
    CRLClockSkew are published on the server (delegated to RootCerts). The check
    PREFERS a stapled response the peer supplied (see stapling below) and only
    queries the responder itself when no valid staple arrived. OCSP-over-HTTPS
    reuses the library's own TLS client (GlobalServer.TLSAddClientSession), with a
    reentrancy guard so it does not recurse into revocation. Full RFC 5280 path
    validation (name / policy constraints) is done by the trust store (PKIX.txt
    sections 3-4).
  - MISSING INTERMEDIATES (AIA CHASE): when the configured identity carries only
    the leaf, chain building auto-fetches the missing intermediates by following
    the AIA caIssuers URL (FindCACert/ChaseCAIssuers; wired automatically by the
    TLS server component next to the CRL/OCSP fetchers, committed to the store
    only when the chain anchors in a trusted cert, failed URLs negative-cached
    for 300 s, never run during the transport's own TLS handshake) - so
    TLSSetupServer can serve a full wire chain from a leaf-only PFX. Details in
    PKIX.txt section 3.
  - ISSUER-VALIDITY ENCLOSURE: whether a leaf must be validity-ENCLOSED by its
    issuer is now the tVerifyValidityPeriodMode switch (vvpmFull default /
    vvpmNotBefore / vvpmRelaxed = plain RFC 5280), set process-wide via
    tCertificate.SetVerifyValidityPeriodMismatch. TLS-visible consequences:
    under the default, a leaf that outlives its issuer is dropped at import
    (MyCerts = 0 -> every ClientHello aborts no_common_cipher_suite), and an
    enclosure failure during verification surfaces as crcInvalidSignature.
    Details in PKIX.txt section 3.
  - OCSP STAPLING (in-band, TLS 1.2 AND TLS 1.3): implemented in BOTH directions
    and on BOTH protocol generations (RFC 6066 status_request / CertificateStatus
    for 1.2; the RFC 8446 sec.4.4.2.1 CertificateEntry status_request extension
    for 1.3). Wire encoders: StreamSec.Mobile.Tls13Handshake
    (EncodeCertStatusExtension / EncodeStatusRequestCH / the 3-arg
    EncodeCertificate13) for 1.3, and Tls12EncodeCertificateStatus /
    HandleCertificateStatus (TlsLayer) + the status_request flags in the
    ClientHello/ServerHello codecs (Tls.pas) for 1.2.
      * SERVER (automated): assigning the component's Ocsp (a TsmOcsp) is the
        single switch. Each server leaf's DER OCSPResponse is fetched from the
        responder named by Ocsp.ResponderURL (when set; otherwise the leaf's
        AIA id-ad-ocsp URL), cached PER CERTIFICATE in the same FTLS12Keys
        record as the cert + key, and stapled whenever a client asks. The
        fetch is LAZY (on first demand) with a BACKGROUND warm-up thread
        started by TLSSetupServer (startup never blocks
        on the responder), refreshed shortly before the response's nextUpdate,
        completed + cached even if the requesting client disconnects, and
        serialised so concurrent connections share one in-flight fetch;
        ReplaceTLSServerCertificate re-warms a hot-rotated leaf. A per-session
        staple set via OnTLSAddContentLayer (Client.OcspStaple) still takes
        precedence; only definitive responder answers (good / revoked) are
        stapled.
      * CLIENT (prefer-staple): the client requests a staple whenever 1.3 is
        offered (the default): status_request is part of the 1.3 ClientHello
        extension block, and since that same ClientHello also negotiates 1.2, a
        1.2 server sees the extension too. (A 1.2-only session with
        OfferTLS13 = False - e.g. the SCSV fallback retry - sends no
        status_request and gets no staple.) The client exposes any received
        staple via OcspStaple and - when an Ocsp component is assigned -
        VALIDATES it (TsmOcsp.ValidateStapledResponse: signature, CertID match,
        freshness; no nonce) inside the revocation check. A valid staple
        satisfies revocation; a LIVE OCSP query is made only when the server did
        not staple (or the staple is stale/invalid).
    Interop: OpenSSL 3.5.6 both ways on both versions ("openssl s_client
    [-tls1_2] -status": Cert Status good, Verify 0; s_server -status_file -> our
    client), plus the no-app-code auto-fetch matrix {TLS 1.2, TLS 1.3} x
    {openssl ocsp responder via AIA, in-process TstOcspServer} - all green.
  - ALERT HANDLING (consumer note): TsmCustomTLSInternalServer raises
    EIncomingTLSAlert / EOutgoingTLSAlert ONLY while OnTLSIncomingAlert /
    OnTLSOutgoingAlert are unassigned - a long-running server should assign both
    (log via AlertMsg) so peer alerts (unknown_ca from a browser, decode_error
    from an aborted preconnect, a resumption group mismatch) are logged instead
    of thrown. After a FATAL alert a TsmStreamSecII-managed session is released
    when TLSDecodeData returns normally; under a raising handler it stays
    registered until TLSClose. Do not touch a previously fetched content-layer
    reference on the alert path.
  - CLOSE CONTRACT (content layer, both roles, both versions; RFC 8446 section
    6.2: "MUST close the connection without sending or receiving any
    additional data"): a session that sent or received a fatal error alert is
    Closed for good (property Closed; Active is False). The call that produced
    or read the alert returns its normal result - unless an alert handler
    raised - and the alert record it sent is the last thing in its Response,
    also when a handler raised. The consumer writes those Response bytes to
    the transport, writes NOTHING else (it discards any application data or
    records still queued for the peer) and closes the transport. The session
    then refuses all input and output: DecodeData discards Src and returns -1;
    EncodeData, Close, KeyUpdate, Connect and Accept return -1; none of them
    writes a byte or calls an alert event. EncodeData also returns -1 and
    writes nothing before the FIRST handshake completes (RFC 8446 section 2;
    RFC 5246 section 7.3: "Application data MUST NOT be sent prior to the
    completion of the first handshake"), so a TLS 1.2 renegotiation does not
    stop it; the TLS 1.3 server's 0.5-RTT window is the one
    exception (client 0-RTT data is sent through EarlyData with the
    ClientHello, never through EncodeData).
  - CLOSE_NOTIFY STATE MACHINE (both roles, both versions): close_notify is
    not an error, and it goes out at warning level (RFC 8446 section 6: the
    severity is "implicit in the type of alert"; RFC 5246 section 7.2: a
    fatal alert invalidates the session). Like ChangeCipherSpec in TLS 1.2 it
    is tracked per direction - CloseNotifySent and CloseNotifyReceived - by
    one handler used by Close and by the received alert, and Active becomes
    False only once both directions are closed, in either order. After this
    side's Close it sends nothing more (EncodeData, KeyUpdate and Connect
    return -1; a second Close returns 0) and still reads the peer's data,
    alerts and TLS 1.3 KeyUpdate and NewSessionTicket; a new handshake from
    the peer is ignored. After the peer's close_notify, at either level,
    nothing more is read (RFC 8446 section 6.1: "Any data received after a
    closure alert has been received MUST be ignored"); data that came before
    it in the same input is still delivered. TLS 1.3 may still send data and
    then its own close_notify (section 6.1: "Either party MAY initiate a
    close of its write side of the connection"); TLS 1.2 only answers with
    its own close_notify, and EncodeData returns -1 (RFC 5246 section 7.2.1:
    "The other party MUST respond with a close_notify alert of its own and
    close down the connection immediately, discarding any pending writes").
    TsmStreamSecII.TLSDecodeData releases a session only when it is no
    longer Active (a fatal alert, or both directions closed), so after the
    peer's close_notify TLSClose still finds it and answers. TLSClose
    releases the session after sending this side's close_notify, so through
    the UserData / SessionID calls the peer's records after it are not read;
    to read them, drive the content layer directly. A consumer learns of the
    peer's close from CloseNotifyReceived, not from Active (which stays True
    until this side answers): it hands over the data delivered before the
    close_notify, on TLS 1.3 may still send its reply, then calls Close and
    closes the transport. TsmAsyncTLSServer delivers every byte that came
    before the close_notify to its session first (also when the session has
    paused receiving) and then answers: at once on TLS 1.2, and on TLS 1.3
    when the session closes or the idle deadline expires (30 seconds when
    IdleTimeout is 0). A FIN after the close_notify, or a FIN alone, ends
    the connection at once unless the session implements iAppSessionShutdown
    (AsyncTLSServer.txt): then the session is told ReceiveClosed and may still
    reply, and its Close sends this side's close_notify. The mail transport
    returns that data first; on TLS 1.2 it answers at once, on TLS 1.3 the
    reply to that data goes out and the next read answers and reports the
    close. A close_notify that came with the handshake's last read is
    answered by the first read after it. TAbstractTLSSocket (also for a
    close_notify that came with the handshake's last read) and the snip TLS
    octet connection answer at once and then disconnect. TsmCustomTLSClient,
    the snip TLS client and tHttpTransport end a handshake on the peer's
    close_notify; after the handshake they learn of the peer's close from
    the transport only. This side's close_notify before the handshake
    completed (the acme-tls/1 validation handshake, or Close mid-handshake)
    ends the session at once.
  - ALERT DOWNGRADE (TESTING ONLY - DO NOT USE IN PRODUCTION): an outgoing
    alert handler that sets Fatal := False on bad_certificate,
    unsupported_certificate, certificate_unknown, certificate_expired,
    certificate_revoked, user_canceled, no_renegotiation or
    no_application_protocol sends the alert as a warning. A downgraded
    identity (name, IP, URI) or usage (EKU, Netscape type, keyUsage) alert
    lets the handshake go on with the server certificate the client refused,
    which then counts as accepted. A downgraded chain-validation alert leaves
    no certificate accepted (ServerCertificate nil, ServerCertificateAccepted
    False): TLS 1.3 then ends the handshake with unexpected_message at
    CertificateVerify; TLS 1.2 (EC)DHE suites go on with a ServerKeyExchange
    whose signature is not checked, and static RSA ends with internal_error
    at ClientKeyExchange. On TLS 1.2 the handshake goes on only with a peer
    that honours the warning level, such as this library's server when its
    OnTLSIncomingAlert handler does not raise on a warning
    (TsmCustomTLSInternalServer's default handler raises on every alert
    except close_notify). On TLS 1.3 a downgraded certificate alert or
    no_application_protocol is a warning-level error alert, which RFC 8446
    section 6 forbids: "All the alerts listed in Section 6.2 MUST be sent
    with AlertLevel=fatal and MUST be treated as error alerts when received
    regardless of the AlertLevel in the message." A conforming TLS 1.3 peer,
    this library included, therefore closes the connection on receipt: the
    downgrade changes only what this side sends. On a server session a
    downgraded alert leaves no client certificate (ClientCertificate nil).
    (user_canceled is a closure alert in TLS 1.3; no_renegotiation does not
    exist there.) It exists for tests; every other code is always fatal,
    except close_notify, which is reported with Fatal = False and always
    goes out at warning level, whatever the handler sets.
  - RECEIVED ALERTS ON TLS 1.3: a received error alert ends the session
    whatever its level, as RFC 8446 section 6 requires. The only other
    closure alert, user_canceled, is reported to OnIncomingAlert /
    OnTLSIncomingAlert with Fatal = False and the session goes on; a
    consumer that does not want to go on closes it. On TLS 1.2 the alert's
    own level decides, as before.
  - READING THE SERVER CERTIFICATE (client): ServerCertificate holds the leaf
    from the server's Certificate message once its chain validates. It keeps
    that leaf when the client then rejects its name, IP, URI or usage, so an
    outgoing alert handler can inspect the certificate that was checked.
    Read ServerCertificateAccepted to learn whether the client accepted it
    in this handshake. It is False at handshake start and while checks run,
    and remains False after rejection, including when an alert handler raises.
    Name, IP, URI and usage mismatches are fatal on both versions; only a
    handler that downgrades the alert (above, testing only) lets the
    handshake continue, and then the certificate counts as accepted.

    A nil certificate is not an acceptance or handshake-completion verdict.
    On a fresh session it is nil before the Certificate message, after a
    chain-validation failure, on an anonymous TLS 1.2 suite and on TLS 1.3
    PSK resumption. A resumed session (TLS 1.3 PSK, or TLS 1.2 session ID)
    has ServerCertificateAccepted False and ServerCertificate nil, with
    Encrypted and IsResumedSession True. A renegotiation that fails
    before its Certificate leaves the previous certificate readable with
    ServerCertificateAccepted False; an empty or unparseable TLS 1.2
    Certificate can also leave that earlier certificate. The chain importer's
    nil on a TLS 1.2 chain failure is retained; no validated leaf was returned.
    Encrypted can still describe the earlier completed TLS 1.2 handshake
    during a failed renegotiation. Check Active and LastAlertCode as well.

    For diagnostics after the call, the caller must own the layer: drive a
    layer from TLSAddClientSession directly, or extract it with
    FindTLSSession(...,True). A TAbstractTLSSocket drops its session when the
    handshake fails, so read a refused certificate in OnTLSOutgoingAlert;
    its certificate-name caches are cleared when a new connection starts. A
    previously fetched reference to a released session must not be used.
    A client session that has ended - a fatal alert, this side's Close or
    the peer's close_notify at either level - never restarts: Connect on it
    returns -1 and writes nothing. No alert is sent and no alert handler is
    called, because the connection is already closed; LastAlertCode keeps
    any alert recorded, close_notify (code 0) included, and becomes
    unexpected_message only when no alert was recorded. Accept on a client
    session returns -1, writes nothing and leaves LastAlertCode as it is; so
    does Accept on a server session after either side's close_notify. The
    TLS 1.3 client takes the server's flight in the order of RFC 8446
    section 2 and each message once; it takes a CertificateVerify only after a
    certificate it accepted in the same handshake, and after the handshake
    only NewSessionTicket and KeyUpdate; a PSK-resumed handshake takes no
    Certificate, CertificateRequest or CertificateVerify.


================================================================================
10. TESTS & INTEROP
================================================================================
  What the tests have proven. The interop peer is OpenSSL 3.5.x
  (section 4).

  HANDSHAKES, RESUMPTION, 0-RTT, KEYUPDATE
    - The key schedule matches the RFC 8446 sec.7 key-schedule vectors.
    - Our client against "openssl s_server -tls1_3": 1-RTT, optionally mTLS
      with a client certificate from a PFX, with the curve / group
      overridden, and in FALLBACK_SCSV mode.
    - Our server against "openssl s_client" over a loop of connections, on
      TLS 1.3 and TLS 1.2.
    - PSK resumption and 0-RTT early data, our client against
      "openssl s_server -tls1_3 [-early_data]", with the ticket captured
      in-process; the -sess_out / -sess_in s_client runs belong to the
      server-side tests.
    - NewSessionTicket issuance and PSK resumption, our server against our
      client over an in-memory pump (no early data): BATCH issuance of
      SessionTicketCount tickets (configurable) and SINGLE-USE - re-offering
      a consumed ticket gets a full handshake. Against
      OpenSSL the server side takes the same ticket count and logs the
      ticket-store count after issuing.
    - Post-handshake KeyUpdate, both directions x both request modes x
      either initiator, and the RFC 8996 / 9846 minimum-version floor,
      in-process between our server and our client.
    - The sec.4.1.3 downgrade-sentinel helpers (SetDowngradeSentinel /
      HasDowngradeSentinel) are checked byte by byte; TLS_FALLBACK_SCSV
      itself is exercised by the client's fallback mode.
    - For browser tests, a TLS 1.3 HTTPS server: per-request close,
      resumption on, alert-event logging.
    - Mutual TLS library to library with plain ML-DSA-65 certificates made in
      the run, over TsmAsyncTLSServer + TsnipTLSServer requiring a client
      certificate with resumption off: a serverAuth+clientAuth leaf, a
      clientAuth-only leaf and a leaf with no extendedKeyUsage are accepted,
      and the Snif method reads exactly the presented certificate through
      TsnipTLSServer.CurrentPeerCertificate; no certificate
      (certificate_required), a serverAuth-only leaf (unsupported_certificate)
      and an untrusted issuer (unknown_ca) are refused before any call.

  OCSP STAPLING
    - Automated stapling with NO application staple code - the server's
      Ocsp set to a TsmOcsp and nothing else - across {TLS 1.2, TLS 1.3} x
      {openssl ocsp responder via AIA, in-process TstOcspServer}.
    - A probe of a live server reports the
      OCSP staple, the NewSessionTicket and ticket resumption.

  HOSTILE PEER INPUT - inputs OpenSSL cannot be driven to produce
    - TLS 1.3: a hostile-key_share probe (python3, raw sockets) sends our
      running server a ClientHello with a malformed share and gets a fatal
      illegal_parameter (47) for each case: x25519 u=0, x25519 u=1
      (small-order -> all-zero ECDH output), an off-curve P-256 point, a
      compressed P-256 point, a wrong-length hybrid share, and a corrupt
      ML-KEM encapsulation key (fails the FIPS 203 sec.7.2 round-trip).
      This exercises the RFC 10024 / 9846 validation paths.
    - TLS 1.3: a hand-built peer signs CertificateVerify with an ML-DSA-65 key
      and labels it 0x0904 (ml-dsa-44), 0x0906 (ml-dsa-87) or 0x0807
      (ed25519); our server (for the client's CertificateVerify) and our
      client (for the server's) refuse each with illegal_parameter (47) and
      complete with 0x0905.
    - TLS 1.2: the ECDHE decoders, driven directly rather than over a
      socket, accept valid points on both curve families and reject
      compressed points, the point at infinity, off-curve points, a zero
      u-coordinate and the small-order X25519 points u=1 and u=p-1, at all
      three call sites - the ClientKeyExchange decode (server), the
      ServerKeyExchange decode (client) and the premaster derivation
      (client).

  AES IMPLEMENTATION SELECTION, Win32 + Win64: the stAESCT self-test (S-box
  circuit vs table, FIPS-197 B / C.1-3, RFC 3394, round-trips), 900-case
  stAESCT = stAES = stAESNI block agreement, per-platform registration
  asserts, and a throughput comparison. Under FPC, a counterpart in the
  regression run covers Linux x86-64 with AES-NI plus MIPS / PPC big-endian.

  The CMS / PKIX and fixed-time-ECDSA results are in PKIX.txt (sections 13
  and 8).


================================================================================
11. QUICK-ANSWER TABLE - VERSION x FEATURE x WHERE
================================================================================
Feature \ Version    TLS 1.0 (3.1)   TLS 1.1 (3.2)   TLS 1.2 (3.3)   TLS 1.3 (0x0304)
------------------   -------------   -------------   -------------   ----------------
Record framing       TlsLayer        TlsLayer        TlsLayer        TlsLayer (inner-
                     (TTLS_Record)   (same)          (same)          type, dummy CCS)
Key derivation       MD5^SHA1 PRF    MD5^SHA1 PRF    SHA-256/384 PRF HKDF schedule
                     (TLS_PRF)       (TLS_PRF)       (TLS_PRF)       (Tls13KeySchedule)
CBC IV               implicit        explicit        explicit        n/a (AEAD only)
                     (Enc10Block)    (Enc11Block)    (inherited)
Encrypt-then-MAC     RFC 7366        RFC 7366        RFC 7366        n/a
                     (Enc10BlockEtM) (Enc11BlockEtM) (inherited)
Finished             MD5+SHA1 PRF    MD5+SHA1 PRF    PRF(SHA-256)    HMAC(finished_
                                                                     key, transcript)
AEAD                 n/a             n/a             AES-GCM (5288/   AES-GCM +
                                                     5289),          ChaCha20 (8446);
                                                     ChaCha20 (7905) Enc13Aead
Cipher suites        Enc10*          Enc11*          Enc12*          $1301/$1302/$1303
Key exchange         RSA/DH/ECDHE    (same)          (same)          (EC)DHE + ML-KEM
                                                                     (pure & hybrid)
Auth / sig           RSA/ECDSA       (same)          + EdDSA/PSS     + EdDSA + ML-DSA
Negotiation/state    Mobile.Tls      Mobile.Tls      Mobile.Tls      TlsLayer 1.3
                     (driver)        (driver)        (driver)        branches
Resumption           session ID      session ID      session ID      PSK + tickets
0-RTT early data     n/a             n/a             n/a             yes (sec.6)
OCSP stapling        n/a             n/a             CertStatus msg  CertificateEntry
                                                     (RFC 6066)      ext; both ends
                                                                     automated (sec.9)
Client auth (mTLS)   CertificateReq  (same)          (same)          CertificateRequest
                     (1.2 pipeline)                                  13 + cert_required


================================================================================
12. RECORD-FREE TLS 1.3 FOR QUIC
================================================================================

TsmStreamSecII.TLSAddQUICClientSession / TLSAddQUICServerSession configure
record-free sessions from the same TLSOptions, certificates and ALPN settings
as the corresponding TLS record sessions. Supply an iQUICTLSHandler and the
local encoded transport-parameter bytes. Cast the result to TTLS_ContentLayer
to call StartQUIC and ReceiveQUICHandshake. Its RecordLayer property is nil.

Start the session once. Feed ordered, reassembled CRYPTO bytes separately at
qtlInitial, qtlHandshake or qtlApplication. Fragmented messages are retained;
individual handshake messages are limited to 1 MiB. QUIC performs packet and
CRYPTO reassembly before delivery. TLS requires TLS 1.3 and ALPN, and exchanges
the quic_transport_parameters extension in ClientHello/EncryptedExtensions.
The transport validates the parameter encoding and connection-ID context.

HandshakeData emits raw handshake messages at their encryption level. It emits
Finished at Handshake and NewSessionTicket at Application even when later
traffic secrets are already available. TrafficSecret identifies the level,
direction (aIncoming is the local receive direction), suite and hash. These
are traffic secrets; derive QUIC packet keys with
TTls13KeySchedule.QUICPacketKeys, using the actual QUIC wire version.
QUICInitialSecrets derives the client/server Initial secrets from that version
and the destination connection ID. Initial protection is independent of TLS.
QUIC retains and discards each level's keys and performs QUIC key updates.

The transport serializes calls. Handler callbacks must return before entering
the same session again; queue emitted bytes for deferred delivery when pumping
two sessions in memory. A callback exception makes the session inactive.
TransportParameters is a tentative validation callback: peer authentication is
complete only when the handshake succeeds. OnHandshakeDone reports TLS
completion; QUIC handshake confirmation remains the transport's responsibility.

The const TBytes buffers may be retained by ordinary assignment. Shared elements
must remain read-only through every alias. TrafficSecret supplies an independent
copy because the TLS engine wipes its temporary secrets. Flow control, consumed
CRYPTO offsets and retransmission retention belong to QUIC, independently of
managed-array lifetime. Factory/session reference counting is unchanged; release
the session through the existing content-layer lifecycle.

Alert reports a TLS alert description for a QUIC CRYPTO_ERROR (0x100 + alert).
Existing TLS alert events still run. No TLS record is created for an alert.
The entry-point result follows the existing TLS convention: a non-negative
value counts generated handshake bytes; consult Active/LastAlertCode and the
alert callback for protocol failure. A negative value rejects an inapplicable
entry point. The record APIs Connect/Accept/EncodeData/DecodeData and KeyUpdate
are inapplicable to a QUIC session. QUIC application bytes use QUIC streams.

Tickets are bound to the transport mode; QUIC tickets also bind the selected
ALPN. Custom ticket stores must preserve the QUIC, ApplicationProtocol and
QUICEarlyDataContext metadata. Normal PSK resumption is supported.

QUIC early data is off by default. TTLS_ContentLayer.EnableQUICEarlyData(True),
called before StartQUIC, enables it for that session; the library's QUIC
transport calls it from tQuicTLSConnection.ConfigureEarlyData, and TsmHTTPSv3
exposes it as EnableEarlyData (QUICServer.txt). A server session also needs
TLSOptions.EarlyData = edmAccept and a handler that implements
iQUICTLSEarlyDataHandler. Only then do its tickets advertise early data, with
max_early_data_size 0xffffffff as QUIC requires, carrying the context that
CaptureEarlyDataContext returns; an empty or oversized context (over 65535
bytes) refuses early data. On resumption the server accepts early data only
for the first PSK identity, with the ticket's cipher suite and no
HelloRetryRequest, after the single-use claim and OnTLSCheckEarlyDataReplay,
and when AcceptEarlyDataContext approves the remembered context; otherwise the
handshake continues without it. A client offers early data only from a ticket
that advertised it, while that ticket's cipher suite is still offered and
before any HelloRetryRequest. TrafficSecret reports the 0-RTT secret at
qtlEarlyData; CRYPTO data is never accepted at that level. The existing TLS
record early-data implementation remains available to TLS record sessions.

No compatibility ChangeCipherSpec or EndOfEarlyData is emitted. EndOfEarlyData,
TLS KeyUpdate and post-handshake client authentication are rejected on QUIC.
QUIC packets, streams, HTTP/3 framing and QPACK are separate transport and
application layers; these entry points supply the TLS handshake integration.

The tQuicTLSConnection bridge owns the record-free session, connection state
and packet ciphers. Configure its TLS session before Start. AuthenticatePacket
opens an authenticated packet without committing packet-number receipt. Pass
the plaintext to the frame dispatcher, then call ProcessCryptoInput after the
complete frame batch has returned. This keeps a TLS key-level transition from
changing the state underneath another frame in the same packet. SynchronizeKeys
releases ciphers after dispatcher send, receive or key-discard notifications.
ProtectPacket only protects bytes; the caller reports actual UDP transmission
to the dispatcher after a successful send. The older OpenPacket and PacketSent
entry points retain their direct connection-state notification behavior.

Under FPC, legacy DES imports and dependent code paths are conditionally
excluded. The remaining TLS provider implementation units stay intentionally
linked. Record-free TLS 1.3 and the QUIC packet/TLS bridge have been qualified
with FPC 3.3.1 on native Linux64 and big-endian MIPS/o32 under QEMU in WSL.
Full public QUIC/HTTP/3 endpoint qualification remains incomplete because of
separate backend and runtime limitations. DES/3DES is not required by TLS 1.3
or QUIC; FPC stDES compatibility for legacy encrypted files remains an
independent backlog item.

HOT REPLACEMENT OF SERVER CERTIFICATES
--------------------------------------

Initial PFX provisioning remains ImportFromPFX followed by TLSSetupServer. For
a running TsmCustomTLSInternalServer, first import keys and certificates, then
ReplaceTLSServerCertificate(leaf,key) to update its serving cache.
ImportFromPFX also accepts snapshot bytes; parsing and PKCS#12 decryption
finish before the store mutation is locked. Import and serving-cache
replacement are separate operations: a later refusal can leave keys,
certificates, CAs, CRLs and key-pair/cipher-suite option changes in the
engine. Only the serving rows publish atomically within one engine. See
CertificateReload.txt for runtime PFX following.

Replacement prepares all name/algorithm slots before publication within one
engine. A later-slot preparation failure leaves that engine's prior serving
cache intact. EC signing leaves with digitalSignature and keyAgreement, or no
keyUsage extension, receive the same ECDHE/TLS 1.3 placement as
TLSSetupServer. Replacement follows the existing name/algorithm rules and has
no retirement list. In-progress handshakes and established sessions retain
references to their selected certificate/key. Async replacement visits one
shard at a time; no TLSLock spans shards, and a later failure can leave
earlier shards updated. Use one certificate writer per target or serialize
application, ACME and reloader writes externally; concurrent writers can leave
shards on different identities even when each call succeeds.

Chain and revocation checking, including CRL and AIA fetching and stapled OCSP
validation, follow the same engine policy as startup and ordinary handshakes.
Per-engine preparation files the leaf under that engine's TLSLock. Fetches may
block other handshakes on that engine. Add CA certificates before replacing a
leaf, using the engine's LocalExplicitTrustByDefault as at startup. OCSP
warming starts after publication; ordinary warm-up failures are reported
through OnWorkerError with the component as Sender and do not turn a committed
replacement into a failure. Warm-up requests are serialized on one worker,
which exits after its queued passes. Publication does not join an earlier
fetch. Warming uses the assigned Ocsp instance, preserving descendant state,
TrustedCertificates, store links and hooks. Changing or detaching Ocsp, or
receiving its destruction notification, waits for the in-flight warm-up fetch.
The component's Timeout bounds each read, not the total exchange; slow-drip
peers and custom descendants can extend this wait without a finite total
bound. Custom descendants must detach Ocsp before destroying state used by
CheckCertificate. Engine destruction joins before certificate stores are
freed. Ordinary scheduling errors after publication are contained without
application callbacks. A process-state scheduling fault propagates on the
publishing caller without worker reporting or automatic exit; publication
remains committed. OnWorkerError also observes the fatal LOG phase. Only
process-state faults reaching the OCSP warm-up worker or reloader polling
worker invoke bounded reporting with exit code 70. Ordinary handshake staple
fetches retain their exception-swallowing behavior without worker callbacks;
component certificate filing and destructor wrappers retain caller behavior.
See stWorkerFatal and CertificateReload.txt.

================================================================================
 TLS 1.2 CLIENT CERTIFICATE SELECTION
================================================================================

A server's CertificateRequest lists alternatives for the client's certificate.
An ECDHE/RSA server may authenticate an ECDSA client, and the reverse. RSA,
DSA and ECDSA signing certificates use certificate types 1, 2 and 64. A client
selects an actual local certificate with suitable validity, digitalSignature
and clientAuth usage, acceptable issuer names and a matching usable private key.
The key's intrinsic algorithm restrictions also apply: a PSS-restricted private
key cannot produce PKCS1 authentication merely because its public numbers match
an ordinary RSA certificate. Mutable preferences on ordinary RSA are distinct.
An empty authority-name list permits any otherwise eligible issuer. If a local
candidate cannot satisfy the request, the client tries another configured one.

The TLS 1.2 signature/hash pairs constrain both the chosen CertificateVerify
and certificate signatures. A certificate's subject key and its issuer's
signature are separate algorithms: an ordinary RSA key can belong to a
certificate signed using RSA-PSS. That issuer signature must be offered too.
An omitted trust anchor does not remove issuer-key metadata needed to check
the last transmitted certificate. Local issuer traversal is cycle-safe and
limited to 32 certificates; IncludeRootInTLSChain controls wire root omission.

The selected CertificateVerify hash must be offered and permitted locally.
There is no unoffered hash fallback. MD5 is not selected. SHA-1/SHA-224 require
the existing explicit legacy HashAlgorithmSHA1 policy; hardened defaults stay
unchanged. Unsupported/PQ pairs never become permissive hash defaults. This
change adds no TLS 1.2 PQ, EdDSA or intrinsic RSA-PSS subject-key signing support.
Explicit legacy TLS versions and fixed DH/ECDH agreement retain their existing
separate paths; their deprecated mechanisms are not enabled by this correction.

Without a usable identity the client sends an empty Certificate and no
CertificateVerify. A peer requiring client authentication rejects that result.
A full new request clears the previous selected key, hash and pending message;
it cannot reuse an identity from an incompatible earlier request. Existing
server policy that requires an authenticated renegotiation is preserved.

Programmatically created components must complete CheckLoaded initialization
and call TLSSetupClient after configuring trust and options, before connecting.
Changing preferences is not a replacement for those consumer setup calls.
Derived local cipher lists are computed even when copied preferences equal
their defaults, including when a loaded component changes to client mode.

Server requests use configured peer families independently of the server's
local key. Explicit simple-component SignatureRSA/SignatureDSS/SignatureECDSA
refusals remain effective across option changes. Available local credentials
still restrict the legacy server cipher list. Servers validate incoming signing
types and nonempty, exactly framed CertificateVerify pairs against the actual
sent request. Issuer pairs in a request do not alone enable that client key type.

The signature options therefore do not restrict what a server signs with.
Turning every signature scheme off does not make an RSA certificate
key-transport only, and no signature option can forbid the server's PKCS#1 v1.5
signatures while allowing RSA-PSS. Key transport only follows from the
certificate: an RSA leaf without digitalSignature in its keyUsage is not used
for the signing suites. Signing only with RSA-PSS also follows from the
certificate: one whose subject public key is id-RSASSA-PSS. The private key
does not record the difference; the certificate carries it.

For consumers of the wire/model API:
  * TInternalCertificateRequest.supported_sign_schemes keeps the exact ordered
    wire pairs, including unknown ones. supported_sign_algs contains only known
    pairs. Leave the raw vector empty to construct a request from those sets.
  * TLS12_EncodeCertificateVerify has RSA, DSA and EC overloads taking an explicit
    hash and always using TLS 1.2 framing. Existing TLS_EncodeCertificateVerify
    overloads keep their previous legacy framing contract.
  * TsmX509TrustedCertificates.ExportClientChainToTLS validates signing candidates
    and calls TTLSClientCertificateCheck with the full available issuer path,
    including a root omitted from the wire. The callback must check matching key
    possession and offered/permitted signature policy. Failure returns no
    selected certificate and length zero; the caller encodes the empty message.

================================================================================
 PEER CERTIFICATE DIAGNOSTICS
================================================================================

TCustomTLS_ContentLayer.PeerCertificateList returns an independent copy of the
current handshake's raw peer certificate entries: a uint24 DER length followed
by DER for each entry. This is captured before import, preserving wire order,
duplicates and unrelated certificates. TLS 1.3 entry extensions and request
context are stripped by the existing normalizer. Treat the bytes as unverified
peer input; the list is not a validated or constructed certification path.

Read PeerCertificateValidationAttempted before interpreting
PeerCertificateChainAccepted and PeerCertificateStatus. They report certificate
chain import only, not later identity-name, EKU or proof-of-possession checks.
An unattempted empty status is not successful authentication.

All four diagnostics reset when a new handshake starts. Before a Certificate
message, and for PSK-only resumed handshakes, there is no fresh certificate or
chain-import verdict. The completed snapshot survives Close and TLS 1.3
KeyUpdate. These reporting APIs do not relax authentication or trust policy.

================================================================================
 END OF FILE
================================================================================