API Reference
StreamSec.Mobile.TlsClass
TLSClass Unit
Feature notes: TLS implementation notes (RFC map)
Classes, interfaces and records
interfaceiQUICTLSHandler
procedure HandshakeData(aLevel: tQUICTLSLevel; const aData: TBytes);
procedure TrafficSecret(aLevel: tQUICTLSLevel; aIncoming: Boolean; const aCipherSuite: TCipherSuite; aHash: THashAlgorithm; const aSecret: TBytes);
function TransportParameters(const aData: TBytes): Boolean;
procedure Alert(aDescription: Byte);
interfaceiQUICTLSProtocolErrorHandler
Optional transport errors whose QUIC code cannot be represented by a TLS alert. Implementations close the transport before returning or raising.
procedure ProtocolError(aCode: UInt64);
interfaceiQUICTLSEarlyDataHandler
Optional record-free early-data policy. Capture runs only when issuing a server ticket after authentication; Accept runs after binder verification and the atomic single-use claim. These methods inspect stable transport metadata only, never create plugins or invoke application operations. Missing/empty context refuses early data. Published context is read-only; the TLS ticket store retains an independent copy, bounded to 65535 bytes.
function CaptureEarlyDataContext: TBytes;
function AcceptEarlyDataContext(const aContext: TBytes): Boolean;
classTTls13ClientTicket
TLS 1.3 (NEW, task 10): a client-side resumption ticket. Produced after a 1.3 handshake when the server sends a NewSessionTicket, and consumed on a later connection to offer PSK resumption and (optionally) send 0-RTT early data. Holds the already-derived resumption PSK (not the master secret) plus the metadata needed to build the pre_shared_key extension.
destructor Destroy; override;
An app rarely calls this directly: it wipes the resumption PSK from memory when the ticket is freed. Free a ticket you have Clone'd and kept once it has expired or been consumed so the secret does not linger.
function Clone: TTls13ClientTicket;
Call from an OnNewSessionTicket handler to keep a ticket past the handler return: the ticket passed in is owned by the content layer and freed once the handler exits, so Clone it and store the copy to reuse later by assigning it to a client's ResumptionTicket for PSK resumption / 0-RTT.
classTCustomTLS_ContentLayer
constructor Create;
Creates a reference-counted content-layer instance with FRefCount = 1 and OfferTLS13 defaulting to True. Applications normally do not call this directly: TsmStreamSecII builds the concrete TTLS_ContentLayer through TLSAddClientSession / TLSAddServerSession and hands it back.
destructor Destroy; override;
Reference-counted teardown - triggered by _Release reaching zero, not called directly by applications. Use Release to relinquish a session you hold.
function Accept(Src, Response: TStream): Integer; overload; virtual; abstract;
Server entry point: feed the received ClientHello bytes in Src, collect the server's handshake reply (ServerHello ... Finished, alerts) from Response. This 2-argument form cannot separate 0-RTT, so the server refuses TLS 1.3 early data with it; use the 3-argument overload to accept 0-RTT. Returns -1 and writes nothing, leaving LastAlertCode as it is, on a client session, on a Closed one, and after either side's close_notify. Abstract here; implemented by the concrete TTLS_ContentLayer.
function Accept(Src, EarlyData, Response: TStream): Integer; overload; virtual; abstract;
TLS 1.3 (NEW, task 11): accept with a dedicated 0-RTT destination. Any early (0-RTT) application data that trails the ClientHello in Src is written to EarlyData; ordinary data goes to Data on later DecodeData calls. Passing EarlyData = nil (or the 2-arg form) means the consumer cannot separate 0-RTT, so the server refuses early data and the client replays 1-RTT.
function Close(Response: TStream): Integer; virtual; abstract;
Initiates an orderly TLS shutdown: emits the close_notify alert into Response so the caller can flush it to the peer before closing the socket. Called by either side when it wants to end the secure channel cleanly. The close_notify goes out at warning level: it is a closure alert, not an error (RFC 8446 sec.6: in TLS 1.3 "the severity is implicit in the type of alert being sent"; in TLS 1.2 a fatal level would invalidate the session, RFC 5246 sec.7.2). It ends this side's sending only; the peer's remaining records are still read (see Closed for the close state machine). Returns -1 and writes nothing on a Closed session: no close_notify follows a fatal alert (RFC 8446 sec.6.1). A second Close returns 0 and writes nothing. Abstract here; implemented by TTLS_ContentLayer.
function Connect(Response: TStream): Integer; virtual; abstract;
Client entry point: starts the handshake by producing the ClientHello into Response. Call it once per session, then pump the server's bytes back through DecodeData. A later call returns -1 and writes nothing while a handshake is in progress (a TLS 1.2 renegotiation included) or after the session ended (a fatal alert, this side's Close or the peer's close_notify); it returns 0 and does nothing on an established TLS 1.3 session, and starts a renegotiation on an established TLS 1.2 session. A first Connect that raised without ending the session can be retried on the same session; one that raised on a fatal alert cannot. Abstract here; implemented by TTLS_ContentLayer.
function DecodeData(Src, Data, Response: TStream): Integer; overload; virtual; abstract;
The main data pump once (and while) a session is live: consumes inbound record bytes from Src, writes recovered application plaintext to Data, and any protocol bytes that must go back to the peer (handshake continuation, alerts, ChangeCipherSpec) to Response. This 3-argument form routes any TLS 1.3 0-RTT early data into Data together with 1-RTT data; use the 4-argument overload to keep them separate. On a Closed session it discards Src, writes nothing and returns -1; see Closed for what the consumer does after a fatal alert. After this side's Close it keeps reading the peer's records - data, alerts, a TLS 1.3 KeyUpdate or NewSessionTicket; a new handshake from the peer is ignored. The peer's close_notify ends reading: records after it are ignored, and later calls discard Src and return 0 (RFC 8446 sec.6.1). Data that came before the close_notify in the same Src is still written to Data. Abstract here; implemented by TTLS_ContentLayer.
function DecodeData(Src, Data, EarlyData, Response: TStream): Integer; overload; virtual; abstract;
TLS 1.3 (NEW, task 11): decode with a dedicated 0-RTT destination. While accepted early data is arriving it is written to EarlyData; 1-RTT data goes to Data. The consumer tells them apart by which stream the bytes land in.
function DecodeData(const Src: TTLSEncrypted; var Data: TPlainTextFragment; var Response: TTLSEncrypted): Integer; overload;
Fixed-buffer convenience overload of DecodeData that wraps the encrypted record, plaintext fragment and response buffers in temporary streams and calls the 3-argument stream form. Handy for callers that already work with the TTLSEncrypted / TPlainTextFragment record types rather than streams.
function EncodeData(Src, Response: TStream): Integer; overload; virtual; abstract;
Outbound counterpart to DecodeData: takes application plaintext from Src and writes the encrypted TLS records to Response for transmission. Call this to send data on an established session. It returns -1 and writes nothing - nothing is encrypted under any key - on a Closed session, after this side's Close, after the peer's close_notify on TLS 1.2 (RFC 5246 sec.7.2.1), and before the FIRST handshake completes (RFC 8446 sec.2, RFC 5246 sec.7.3; a TLS 1.2 renegotiation does not stop it); the TLS 1.3 server's 0.5-RTT window is the one exception, and client 0-RTT data goes through EarlyData, not this call. Abstract here; implemented by TTLS_ContentLayer.
procedure Release;
Relinquishes the caller's hold on this session: fires OnDestroy once and drops one reference (freeing the object when the last reference goes). This is how an application disposes of a content layer it obtained from TsmStreamSecII; safe to call on a nil reference.
procedure ConnRandomBuf(var aBuf; aCount: Cardinal);
Fills aCount bytes of aBuf from THIS CONNECTION'S secondary generator (see the ConnRandom property). Use it for every random field that is written to the wire as-is; use the global stRandom.RawRandom (the primary generator) for anything that stays secret, e.g. an ephemeral private key.
function ConnRandomBytes(aCount: Integer): tBytes;
As ConnRandomBuf, returning a fresh tBytes of aCount random bytes.
property ConnRandom: iRawRandom read GetConnRandom;
This connection's own SECONDARY random generator (stRandom.GetRawRandom(True) -> a fresh, uncached tDrbgAesCtrSecondary seeded FROM the primary generator).
Rationale: random fields fall into two classes. Values that go on the wire as-is (the hello randoms, the TLS 1.2 session_id, a CBC explicit record IV, a ticket identity) hand the peer - and any observer - raw generator output. Values used as key-generation input (an ECDHE/DHE private exponent, an ML-KEM coin, an RSA pre_master_secret) must stay secret; only a one-way function of them is ever transmitted. Drawing both classes from one generator means the attacker is handed a long, directly-observed output stream from the same instance that produces the connection's private keys. Splitting them keeps the primary generator's output off the wire entirely: the secondary is seeded from the primary through a one-way DRBG instantiate, so observing its output says nothing about the primary's state, and each connection's secondary is independent of every other's.
It is per connection and NOT internally locked (tDrbgAesCtrSecondary.Lock/ Unlock are deliberately no-ops), so only the thread that owns the connection may draw from it - the same contract SSH already relies on for its per-direction iSSHParameters.PRNG. Falls back to the primary generator if a secondary cannot be created, so behaviour is never worse than before.
property Active: Boolean read FActive;
True while the session can process handshake or application traffic: Connect / Accept set it before the handshake completes. A fatal incoming or outgoing alert sets it False for good (see Closed). A close_notify ends one direction only, so Active stays True after this side's Close or after the peer's close_notify, and becomes False once both close_notify alerts - this side's and the peer's, in either order - have been processed. Connect or Accept on an ended session returns -1 and leaves Active as it is. Read Encrypted for installed encryption; Active alone does not establish that a handshake has completed. A consumer detects the peer's close by CloseNotifyReceived, not by Active.
property CloseNotifySent: Boolean read fCloseNotifySent;
True once this side sent its close_notify (Close). From then on this side sends nothing more; the peer's records are still read.
property CloseNotifyReceived: Boolean read fCloseNotifyRcvd;
True once the peer's close_notify arrived, at either alert level. From then on nothing more is read (RFC 8446 sec.6.1: "Any data received after a closure alert has been received MUST be ignored"); this side answers with its own Close. This, not Active, is how a consumer learns of the peer's close: it hands over the data DecodeData delivered before the close_notify, on TLS 1.3 may still send its reply, and then calls Close and closes the transport once Active is False. TsmAsyncTLSServer, the mail transport, TAbstractTLSSocket and the snip TLS octet connection do so. TsmCustomTLSClient, the snip TLS client and tHttpTransport end a handshake on it; after the handshake they learn of the peer's close from the transport only.
property Closed: Boolean read fClosed;
True once this session sent or received a fatal error alert; it never becomes False again. A close_notify is not an error and never sets it. THE CLOSE STATE MACHINE: close_notify is tracked per direction, like ChangeCipherSpec in TLS 1.2 - one flag for each direction and one handler for both, used by Close (sending) and by the received alert. After this side's close_notify (CloseNotifySent) 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 (CloseNotifyReceived) it reads nothing more: DecodeData discards Src and returns 0. TLS 1.3 may still send data and then its own close_notify (RFC 8446 sec.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 - EncodeData returns -1 (RFC 5246 sec.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"). Once both directions are closed Active is False and the consumer closes the transport. THE CLOSE CONTRACT: the call that produced or read the fatal alert returns normally unless an alert handler raised (its result counts the bytes written), and the alert record it sent, if any, is the LAST thing in its Response - also when a handler raised. The consumer then writes those Response bytes to the transport, writes nothing else - it discards any application data or records it still had queued for the peer - and closes the transport. From then on the session refuses all input and output: DecodeData discards Src and returns -1, EncodeData, Close, KeyUpdate, Connect and Accept return -1, and none of them writes a byte or calls an alert event (RFC 8446 sec.6.2: "MUST close the connection without sending or receiving any additional data"; RFC 5246 sec.7.2.2). An alert that an OnOutgoingAlert handler downgrades to a warning (testing only) does not close the session.
property LastAlertCode: Integer read FLastAlertCode;
The code of the last TLS alert seen on this session; 0 means none, or close_notify (code 0). Inspect it after a failed handshake or a dropped session to learn why the peer aborted; the OnIncomingAlert / OnOutgoingAlert events give the same information live. Connect on an ended client session sets it to unexpected_message only when no alert at all was recorded (a recorded close_notify is kept), sends no alert and fires no event.
property Unmanaged: Boolean read FUnmanaged write FUnmanaged;
When True the owning component treats this session as externally managed and skips its normal lifetime bookkeeping. TsmStreamSecII sets it on sessions it spins up internally (e.g. the transient client used for background fetches); applications rarely set it themselves.
property AcceptedCiphers: TCipherSuites read FAcceptedCiphers write SetAcceptedCiphers;
Server-side allow-list of cipher suites the peer may pick when the server lets the CLIENT choose (ServerSelectsCipherSuite = False). On a resumed session it is pinned to the resumed suite. Ignored when CipherPreference drives selection. Mapped from TLSOptions.CipherSuites by TsmStreamSecII.
property AcceptHelloRequest: Boolean read FAcceptHelloRequest write SetAcceptHelloRequest;
Server: whether this session honours a client-initiated renegotiation (HelloRequest / new ClientHello on the live channel). TsmStreamSecII derives it from TLSOptions.AllowDualSockets. Leave False to refuse renegotiation.
property CipherPreference: TCipherSuites read FCipherPreference write SetCipherPreference;
The ordered cipher-suite preference list. On the CLIENT it is the suites offered in the ClientHello (highest preference first). On the SERVER it is the server's own preference order used when the server selects the suite; after negotiation it is narrowed to the single agreed suite.
property ClientCertificate: iCertificate read GetClientCertificate;
The peer client's certificate on a server session (or the local client cert once selected). Read it after the handshake for mTLS: identify the authenticated client. Base returns nil; TTLS_ContentLayer supplies it.
property CompressionPreference: TCompressionMethods read FCompressionPreference write SetCompressionPreference;
Offered/negotiated record compression methods. Effectively always the null method (0) on modern sessions - TLS compression is disabled for security - so applications leave this at its default.
property Context: PTLSSecurityParams read GetContext;
Pointer to the live TLS security parameters (negotiated keys, algorithms, state) for advanced inspection. Base returns nil; TTLS_ContentLayer exposes the real block. Internal/diagnostic - most applications never touch it.
property DHEphemeralKeySize: Integer read FDHEphemeralKeySize write SetDHEphemeralKeySize;
Bit-size of the ephemeral finite-field Diffie-Hellman group (the classic DHE key exchange) this SERVER generates for its ServerKeyExchange. Larger = more secure but slower. Mapped from TLSOptions.EphemeralDHKeySize. Irrelevant to the ECDHE-only TLS 1.3 path, which uses SupportedGroups instead.
property DHEphemeralQSize: Integer read FDHEphemeralQSize write SetDHEphemeralQSize;
Bit-size of the DHE subgroup order Q that pairs with DHEphemeralKeySize (server-side, from TLSOptions.EphemeralDHQSize). Advanced tuning of the finite-field DHE parameters; leave at the component default unless you know you need a specific safe-prime group sizing.
property SupportedGroups: TECKeySizes read FSupportedGroups write SetSupportedGroups;
The enabled (EC)DHE named groups / curves for key exchange, in preference order (P-256/384/521, X25519, X448, and the post-quantum ML-KEM hybrids). CLIENT offers key_share for these; SERVER uses the set to pick a group (and to decide when to send a HelloRetryRequest). From TLSOptions.SupportedGroups.
property PeerServerName: string read FPeerServerName write FPeerServerName;
SERVER-SIDE SNI: the host name the client asked for in its ClientHello server_name extension (RFC 6066), or '' when it sent none. Recorded from the ClientHello on both TLS 1.2 and 1.3, so it is available from the moment the hello has been processed - including inside certificate selection. IT IS ATTACKER-SUPPLIED AND UNAUTHENTICATED. The client chooses it; nothing about the handshake proves the name belongs to the client, and a name that matched no certificate would not have stopped the handshake. Use it to choose which virtual host answers, not to decide who the peer is. On a CLIENT session this is '' - the name the client SENT comes from DNSNameToCheck, which is also what the certificate is verified against.
property NegotiatedGroup: Word read FNegotiatedGroup write FNegotiatedGroup;
The NamedGroup actually used for key exchange, as the IANA code point - grp_x25519, grp_secp256r1, grp_x25519mlkem768 and the rest of the grp_* constants in StreamSec.Mobile.Tls13Handshake. TlsNamedGroupName turns it into a string. TLS 1.3 ONLY, and 0 before the key exchange has happened. It is NOT set for a TLS 1.2 session: the 1.2 handshake carries the curve inside the ServerKeyExchange rather than as a negotiated group, and there is no single field that means the same thing across both versions. Read Version first if you intend to report it. After a HelloRetryRequest it holds the group that was finally used, not the one first offered.
property Tls13SigSchemes: tBytes read FTls13SigSchemes write FTls13SigSchemes;
The enabled non-classical TLS 1.3 signature schemes (EdDSA / ML-DSA / Composite ML-DSA), two bytes big-endian each in descending preference. Both sides use it to extend the offered signature_algorithms and to gate which schemes are accepted for the peer's CertificateVerify. Empty = classical only. Computed from TLSOptions by TsmStreamSecII; rarely set by hand.
property PeerCertificateVerifyScheme: Word read fPeerCertificateVerifyScheme;
The scheme in the peer's most recently parsed CertificateVerify in this handshake. TLS 1.3 uses its SignatureScheme codepoint; TLS 1.2 uses the two wire octets (HashAlgorithm shl 8) or SignatureAlgorithm. On a client this describes the SERVER's TLS 1.3 CertificateVerify, on a server the CLIENT's TLS 1.2/1.3 CertificateVerify. A TLS 1.2 server signs its ServerKeyExchange instead, so that is not reported by this accessor. Available is False, with Scheme = 0, before a complete CertificateVerify is parsed, after a new handshake starts, for TLS 1.0/1.1 (no explicit scheme), and for a PSK/session-ID resumed handshake with no such message. A complete but rejected scheme/signature remains available for diagnosis. Truncated vectors do not set it. Availability records an observation, NOT successful signature verification, peer authentication or completion. Fatal close retains the observation until the layer is released.
property PeerCertificateVerifySchemeAvailable: Boolean read fPeerCertificateVerifySchemeAvailable;
True only after a complete peer CertificateVerify has been parsed. Read PeerCertificateVerifyScheme for its version/direction semantics; this does not establish that its signature was accepted.
property Encrypted: Boolean read GetEncrypted;
True once record-layer encryption is in force. On a server session it also gates encrypted client authentication (see RequireEncryptedClientAuth). Base returns False; TTLS_ContentLayer reports the real state.
property CACerts: TsmX509TrustedCertificates read FCACerts write SetCACerts;
The trust anchors (root/intermediate CAs) used to validate the peer's certificate chain during the handshake. Populated from the component's CACertificates. Set it (via the component) to control which issuers you trust for the peer - the CLIENT validating the server, or the SERVER validating a client cert under mTLS.
property CollectedCerts: TsmX509TrustedCertificates read FCollectedCerts write SetCollectedCerts;
The store into which certificates received from the peer during the handshake are imported (ImportChainFromTLS), so the application can inspect or cache the peer's chain afterwards. Shared with the component's CollectedCertificates. DEPRECATED / UNUSED: peer certificate chains received during a handshake are no longer imported into this per-layer store - the import is routed to the engine's own CollectedCertificates via TsmStreamSecII.DoTLSHandleCert (under TLSLock). Retained only for source/binary compatibility.
property MyCerts: TsmX509TrustedCertificates read FMyCerts write SetMyCerts;
The local identity store: the SERVER's own certificate(s)+keys used to answer a ClientHello, or the CLIENT's own cert(s) for mTLS. Populated from the component's MyCertificates; if empty on a server the handshake fails with no_common_cipher_suite.
property RequestClientAuth: Boolean read FRequestClientAuth write SetRequestClientAuth;
SERVER-side: when True the server asks the client for a certificate (CertificateRequest) but still proceeds if none is supplied - opportunistic mTLS. Mapped from TLSOptions.RequestClientCertificate. No effect on a client session.
property RequireClientAuth: Boolean read FRequireClientAuth write SetRequireClientAuth;
SERVER-side: when True the server requires a valid client certificate and aborts the handshake if the client sends none - enforced mTLS. The abort alert is version-specific (certificate_required under TLS 1.3, handshake_failure under TLS 1.2). Mapped from TLSOptions.RequireClientCertificate.
property RequireEncryptedClientAuth: Boolean read FRequireEncryptedClientAuth write SetRequireEncryptedClientAuth;
SERVER-side hardening: when True the client's certificate/verify must arrive under record-layer encryption (i.e. its identity is not exposed on the wire); a client cert offered while Encrypted is False is rejected. From TLSOptions.RequireEncryptedClientCertificate.
property SecureRenegotiation: Boolean read FSecureRenegotiation write SetSecureRenegotiation;
Nominally the RFC 5746 secure-renegotiation (renegotiation_info) policy flag, mapped from TLSOptions.SecureRenegotiation. Note: the concrete TTLS record layer keeps its OWN renegotiation state (seeded from the connection role and the peer's renegotiation_info extension) and never reads this stored value, so writing this property currently has no effect on the handshake.
property ServerCertificate: iCertificate read GetServerCertificate;
CLIENT: the leaf of the server's Certificate message, set once its chain validates. The leaf stays readable when later certificate checks reject it. A non-nil value does not mean it was accepted: read ServerCertificateAccepted for that. It is nil before the first Certificate message, when chain validation returns no leaf, and on a fresh session using an anonymous TLS 1.2 suite or TLS 1.3 PSK resumption. A renegotiation that fails before replacing the leaf can leave the previous certificate here, with ServerCertificateAccepted False. On a SERVER session this is the certificate the server sent; nil when it sent none (TLS 1.3 PSK resumption, anonymous TLS 1.2 suite). Base returns nil; TTLS_ContentLayer supplies the real certificate. Its availability follows the session's lifetime.
property PeerCertificateList: tBytes read GetPeerCertificateList;
Diagnostic snapshot of the current handshake's peer Certificate list, BEFORE trust validation. Contains each uint24 DER length followed by DER, in wire order, including duplicates and unrelated certificates. TLS 1.3 entry extensions and request context are stripped by the handshake driver. Reset at each handshake start; empty until a Certificate message, including PSK-only resumption. This is peer-supplied, unverified data, NOT a constructed or validated path. The getter returns an independent copy, valid after layer destruction.
property PeerCertificateValidationAttempted: Boolean read FPeerCertificateValidationAttempted;
Chain-import verdict for the last peer Certificate message. These do not include later TLS identity/EKU/proof-of-possession checks. Read Attempted first: an empty status set before validation is NOT a successful verdict.
property PeerCertificateChainAccepted: Boolean read FPeerCertificateChainAccepted;
property PeerCertificateStatus: TCertStatusCodes read FPeerCertificateStatus;
property ServerCertificateAccepted: Boolean read fServerCertificateAccepted;
CLIENT: True when the certificate in ServerCertificate passed this handshake's chain, configured name / IP / URI, extended key usage, Netscape certificate type and key usage checks. Name / IP / URI and usage mismatches are fatal on both versions; only an outgoing alert handler that downgrades the alert (Fatal := False, testing only) makes such a check count as passed. A chain failure never does. False when a client handshake starts, while certificate checks run, after certificate rejection, and whenever ServerCertificate is nil. A raising handler leaves this False. Set False again by a later rejection of the certificate's key type: the TLS 1.2 ServerKeyExchange key-type check and the TLS 1.3 CertificateVerify scheme check for EdDSA / ML-DSA keys; a failed CertificateVerify signature leaves it set (the handshake fails). Code that tested ServerCertificate for nil to learn whether the client accepted the certificate tests this instead. It also detects a name / IP / URI mismatch or a rejection under a raising handler, where the leaf stays assigned. It does not mean the remaining handshake succeeded or prove possession of the key. A resumed session sends no certificate: a TLS 1.3 PSK resumption and a TLS 1.2 session-ID resumption have this False and ServerCertificate nil, with Encrypted and IsResumedSession True. Always False on a SERVER session.
property URIToCheck: string read FURIToCheck write SetURIToCheck;
CLIENT-side certificate-identity check: if set, it is one of the identities the server certificate may match (CheckURI). Leave empty to skip the URI check. It is matched against URI subjectAltNames only (scheme and host), never against the subject CN or dNSName subjectAltNames: a host name belongs in DNSNameToCheck. When several of DNSNameToCheck, IPToCheck and URIToCheck are set, a match on any one of them is enough; a certificate that matches none is refused with one fatal alert, on both versions.
property IPToCheck: string read FIPToCheck write SetIPToCheck;
CLIENT-side certificate-identity check: if set, it is one of the identities the server certificate may match, among its subjectAltName IP addresses (CheckIP). Set it when connecting to a host by IP rather than name. A match on any one of the configured DNSNameToCheck, IPToCheck and URIToCheck is enough.
property DNSNameToCheck: string read FDNSNameToCheck write SetDNSNameToCheck;
The host name for name-based validation and SNI. On the CLIENT set this to the expected server name: it is sent as the SNI server_name in the ClientHello and the server certificate must match it (CheckDNSName), or match another configured IPToCheck / URIToCheck: one match is enough. On the SERVER it is populated from the SNI the client sent, so a handler can select the matching certificate.
property SessionID: TSessionID read FSessionID write FSessionID;
The TLS 1.2/1.0 session identifier used for stateful session resumption. The CLIENT may set a cached id to request resumption; the SERVER echoes/issues it. TLS 1.3 uses ResumptionTicket/PSK instead of this field.
property IsResumedSession: Boolean read FIsResumedSession write FIsResumedSession;
True if this handshake resumed a previous session (abbreviated handshake / PSK) rather than doing a full key exchange. Read it after the handshake to know whether a fresh certificate exchange occurred.
property ApplicationProtocols: TApplicationProtocols read FApplicationProtocols write SetApplicationProtocols;
The ALPN protocol list (RFC 7301). The CLIENT offers these in preference order; the SERVER supplies its supported set and PickProtocol narrows it to the single agreed protocol. Read it after the handshake to learn the negotiated protocol (e.g. h2, http/1.1, acme-tls/1).
property SelectedProtocol: OctetString read FSelectedProtocol;
The protocol ALPN NEGOTIATED for this session, or the empty OctetString when the peer offered/selected none. Read it after the handshake instead of ApplicationProtocols[0]: the two agree whenever a protocol was actually agreed, and differ in exactly the case that matters - a peer that sent no ALPN at all, where the offer list survives intact and its first entry is whatever we asked for rather than anything the peer consented to. A client that picks its wire from the offer list therefore speaks h2 to an HTTP/1.1 server, and the failure is a hang rather than an error. Valid on both roles; set only by PickProtocol, cleared whenever the offer changes.
property ServedProtocol: OctetString read GetServedProtocol;
WHAT TO SERVE THIS CONNECTION - SelectedProtocol when ALPN agreed on something, and otherwise whatever AlpnFallbackPolicy says. Read this rather than ApplicationProtocols[0]: the two agree whenever a protocol was agreed AND under the default policy, but only this one distinguishes "the peer chose h2" from "the peer chose nothing and h2 is merely what we asked for first". Empty means serve nothing - under afpStrict that is the honest answer to a peer that never negotiated, and the caller decides.
property AlpnFallbackPolicy: TAlpnFallbackPolicy read FAlpnFallbackPolicy write FAlpnFallbackPolicy;
Defaults to afpFirstOffered, which is what every caller reading ApplicationProtocols[0] has always got. Set afpStrict when the CALLER owns the no-ALPN decision.
property CipherSuite: TCipherSuite read FCipherSuite;
The cipher suite actually negotiated for this session (valid once Active). Read it for logging or policy decisions on both sides.
property Version: TProtocolVersion read GetVersion;
The negotiated protocol version. Base returns the compiled-in maximum minor; TTLS_ContentLayer reports the version actually agreed (e.g. TLS 1.2 vs 1.3). Read it to confirm which protocol version a live session is running.
property UserData: Pointer read FUserData write SetUserData;
An opaque application pointer carried on the session - use it to associate your own per-connection context (e.g. a socket or session object) with this content layer, retrievable in the component's TLS event handlers.
property EarlyDataStatus: TTLSEarlyDataStatus read FEarlyDataStatus;
EARLY DATA (NEW): pull API - usable without subscribing to component events. EarlyDataStatus reflects the 0-RTT phase; TakeEarlyDataDelivered returns (and resets) the count of early-data bytes delivered into the consumer's Data stream since the previous call, letting a pull consumer such as TAbstractTLSSocket mark exactly which received bytes are 0-RTT.
function TakeEarlyDataDelivered: Integer;
Returns the number of accepted 0-RTT early-data bytes delivered into the consumer's Data stream since the previous call, then resets the counter to zero. A SERVER-side pull consumer (e.g. TAbstractTLSSocket) calls this right after DecodeData to mark which freshly received bytes were 0-RTT versus 1-RTT; on a client, or a server that refused early data, it stays zero.
function ExportKeyingMaterial(const aLabel : AnsiString; const aContext: tBytes; aLen : Integer): tBytes; virtual;
RFC 8446 sec.7.5 keying-material exporter (the TLS 1.3 form of the RFC 5705 exporter): derives aLen bytes that BOTH ends of THIS connection - and only this connection - can compute, from the exporter_master_secret:
TLS-Exporter(label, context, len) = HKDF-Expand-Label(Derive-Secret(exporter_master_secret, label, ""), "exporter", Hash(context), len)
This is the "secure TLS connection identifier" an authentication layer running INSIDE the tunnel binds itself to, so that a man in the middle who terminates TLS cannot relay an authentication exchange across a different channel: the two channels have different exporter secrets and therefore different exported values. StreamSec.Snip.TLSOctetConnection uses it for the RFC 9266 'EXPORTER-Channel-Binding' token that the Snif KAPA folds into its transcript.
Returns an EMPTY result unless a TLS 1.3 handshake has completed on this session: TLS 1.2's exporter needs the extended_master_secret extension (RFC 7627) to be safe, which this layer does not negotiate, so exporting under 1.2 is refused rather than answered with a value a triple-handshake attacker could match. Every security-bearing consumer therefore FAILS CLOSED on an empty result. Base returns nil; TTLS_ContentLayer implements it.
property OfferTLS13: Boolean read FOfferTLS13 write FOfferTLS13;
TLS 1.3 offer/accept switch, defaulting to True (see field above): a client session advertises TLS 1.3 and a server session accepts it. Set False to force a 1.2-only session.
property OcspStaple: tBytes read FOcspStaple write FOcspStaple;
OCSP stapling: server staple to send / client staple received (see field).
property FallbackSCSV: Boolean read FFallbackSCSV write FFallbackSCSV;
RFC 7507: client downgrade-retry signalling (see field above).
property ResumptionTicket: TTls13ClientTicket read FResumptionTicket write FResumptionTicket;
TLS 1.3 (NEW, task 10): 0-RTT / PSK resumption surface.
- ResumptionTicket: a ticket from a previous connection to offer in the next ClientHello (set before Connect; remains consumer-owned).
- EarlyData: optional 0-RTT payload sent immediately after the ClientHello under the early-traffic key (only if the ticket allows it).
- OnNewSessionTicket: fired for each server NewSessionTicket.
procedure AddResumptionTicket(const aTicket: TTls13ClientTicket);
CLIENT-side: offer ADDITIONAL resumption tickets alongside ResumptionTicket in the next ClientHello (as PSK identities 1..N). Because the server's tickets are single-use, presenting several lets the server pick one that has not yet been consumed. The primary (ResumptionTicket, index 0) is the only 0-RTT-capable identity; extras must share its PRF hash (others are silently dropped) and are consumer-owned (not freed here). Call before Connect.
property EarlyData: tBytes read FEarlyData write FEarlyData;
CLIENT-side 0-RTT payload: set (together with a ResumptionTicket that permits it) before Connect and it is sent immediately after the ClientHello under the early-traffic key, saving a round-trip. Ignored on a server session, and on a client with no resumption ticket. Leave empty for an ordinary 1-RTT handshake.
property OnNewSessionTicket: TTls13NewTicketEvent read FOnNewSessionTicket write FOnNewSessionTicket;
CLIENT-side: fired for each NewSessionTicket the server issues after a TLS 1.3 handshake. Handle it to capture the delivered ticket (Clone it, since the one passed in is freed when the handler returns) for later PSK resumption / 0-RTT. Does not fire on a server session.
property OnChangeCipherSpec: TNotifyEvent read FOnChangeCipherSpec write FOnChangeCipherSpec;
Fired when a ChangeCipherSpec is processed, i.e. the point where the session switches to the newly negotiated keys. Internal wiring TsmStreamSecII hooks to track state; applications rarely handle it directly.
property OnCompress: TCompressEvent read FOnCompress write FOnCompress;
Hook to supply a custom record-compression implementation. Since TLS compression is disabled by default this is effectively unused; leave unset.
property OnDecompress: TDecompressEvent read FOnDecompress write FOnDecompress;
Hook to supply a custom record-decompression implementation, paired with OnCompress. Effectively unused because compression is off by default.
property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy;
Fired once when the session is being released/destroyed (see Release/DoDestroy). Handle it to clean up any per-session state you attached via UserData.
property OnGetCertificate: TGetCertificateEvent read FOnGetCertificate write SetOnGetCertificate;
Called during the handshake to obtain the local certificate to present, keyed by requested host name, ALPN, key-exchange and signature algorithm. Used to select the SERVER's leaf for a given SNI, or the CLIENT's cert for mTLS. TsmStreamSecII wires this to its own certificate cache.
property OnGetCertReq: TGetCertReqEvent read FOnGetCertReq write SetOnGetCertReq;
SERVER-side hook to build/customise the CertificateRequest sent under client authentication (which CA names / signature algorithms to advertise).
property OnIncomingAlert: TAlertEvent read FOnIncomingAlert write SetOnIncomingAlert;
Fired when an alert is received from the peer, with its code and whether it is fatal. Handle it to log or react to why a peer warned or aborted the session. The layer has already acted on a fatal incoming alert; changing Fatal has no effect. After a fatal one the session is Closed: see Closed for what the consumer must do. A received close_notify is reported with Fatal = False at either level (see CloseNotifyReceived). On TLS 1.3 a received error alert ends the session whatever its level (RFC 8446 sec.6: error alerts "MUST be treated as error alerts when received regardless of the AlertLevel in the message"); user_canceled is reported 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.
property OnOutgoingAlert: TAlertEvent read FOnOutgoingAlert write SetOnOutgoingAlert;
Fired when this side emits an alert to the peer, before the record is written. After a fatal alert the session is Closed and the alert record is the last bytes of the call's Response (see Closed for the consumer's part); if the handler raises, the record is still written, the session is still Closed, and the exception reaches the caller of the TLS call. This is the place to observe that the local side is aborting the handshake/connection. DOWNGRADE (TESTING ONLY - DO NOT USE IN PRODUCTION): setting 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 alert lets the handshake go on with the certificate the client refused, which then counts as accepted; a downgraded chain-validation alert leaves no certificate accepted (ServerCertificate nil): TLS 1.3 then ends the handshake 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 is nil. (user_canceled is a closure alert in TLS 1.3, and no_renegotiation does not exist there.) Every other code is always fatal. close_notify is reported with Fatal = False and always goes out at warning level, whatever the handler sets.
property OnRenegotiate: TRenegotiateEvent read FOnRenegotiate write SetOnRenegotiate;
SERVER-side: fired when the peer initiates a renegotiation, giving the requested SessionID so the handler can supply the matching cached session (or decline). Part of the TLS 1.2 renegotiation path.
property OnSelectCompression: TSelectCompressionEvent read FOnSelectCompression write SetOnSelectCompression;
Hook to choose the record-compression method from the offered list. Unused in practice since compression is disabled.
property OnHandshakeDone: TNotifyEvent read FOnHandshakeDone write SetOnHandshakeDone;
Fired once the handshake has fully completed and the channel is ready for application data (both sides). Handle it to start sending, or - on the client - to trigger ticket caching for later resumption.
Types (enumerations, sets, aliases)
enumtQUICTLSLevel
The trailing ecsMLKEM* members are TLS 1.3 post-quantum key_share groups (pure ML-KEM, draft-ietf-tls-mlkem); appended so the existing EC ordinals and the ordinal-based curve-strength comparisons are unchanged. QUIC carries ordered TLS handshake bytes at explicit encryption levels. Calls are serialized by the transport; callbacks must not reenter the same session. Published arrays are shared read-only and may be retained. Traffic secrets are independent of the TLS engine's subsequently wiped storage. TransportParameters validates tentative peer parameters; False aborts with illegal_parameter. Their authentication is complete only after the handshake succeeds. QUIC packet protection and key discard belong to the transport. Early data requires explicit transport opt-in and the optional context companion below; it never uses TLS application records.
tQUICTLSLevel = (qtlInitial, qtlEarlyData, qtlHandshake, qtlApplication);
enumTECKeySize
TECKeySize = (ecsAuto,ecs192,ecs224,ecs256,ecs384,ecs521,ecsx25519,ecsx448,
ecsMLKEM512,ecsMLKEM768,ecsMLKEM1024,
ecsX25519MLKEM768,ecsSecP256r1MLKEM768,ecsSecP384r1MLKEM1024);
setTECKeySizes
TECKeySizes = set of TECKeySize;
procTAlertEvent
TAlertEvent = procedure (Sender: TObject;
var Fatal: Boolean;
AlertCode: Integer) of object;
procTSelectCompressionEvent
TSelectCompressionEvent = procedure (Sender: TObject;
const CompMethods: array of TCompressionMethod;
var CompMethod: TCompressionMethod) of object;
procTRenegotiateEvent
TRenegotiateEvent = procedure (Sender: TObject;
const SessionID: TSessionID;
var Session: TCustomTLSSession) of object;
enumTRecordType
TRecordType = (rtUnknown,rtChangeCipherSpec,rtAlert,rtHandshake,rtData);
enumTTLSEarlyDataStatus
EARLY DATA (NEW): TLS 1.3 0-RTT status, exposed on the content layer so it reaches EVERY consumer through the pull API (TAbstractTLSSocket reads it from its TCustomTLS_ContentLayer peer), not only the TsmStreamSecII component events. A consumer that pulls plaintext from DecodeData must be able to tell early (replayable) bytes from ordinary 1-RTT data and find the boundary.
TTLSEarlyDataStatus = (edsNone, // not a 1.3 0-RTT connection / none yet
edsReceiving, // accepted early data is arriving
edsRejected, // server refused 0-RTT (client must replay)
edsEnded); // EndOfEarlyData reached; 1-RTT from here
procTTls13NewTicketEvent
Fired when a NewSessionTicket arrives. The Ticket is owned by the content layer and freed after the handler returns; a consumer that wants to keep it for a later resumption must Clone it.
TTls13NewTicketEvent = procedure (Sender: TObject;
Ticket: TTls13ClientTicket) of object;
procTCompressEvent
TCompressEvent = procedure (Sender: TObject;
Src: PTLSPlainText; PTLen: Integer;
Method: Byte;
var Dst: PTLSCompressed; var CLen: Integer;
var Error: Integer) of object;
procTDecompressEvent
TDecompressEvent = procedure (Sender: TObject;
Src: PTLSCompressed; CLen: Integer;
Method: Byte;
var Dst: PTLSPlainText; var PTLen: Integer;
var Error: Integer) of object;
procTGetCertificateEvent
TGetCertificateEvent = procedure (Sender: TObject;
const HostName: string;
const ALPN: OctetString;
KEA: TKeyExchangeAlgorithm;
{ TLS 1.3 (NEW): widened to the extended cache
index so the server can request EdDSA / ML-DSA
leaves as well as the classical ones. }
SignAlg: TSignatureAlgorithm13;
var H: PTLSHandshake;
var Len: Integer;
var C: iCertificate;
var Found: Boolean) of object;
procTGetCertReqEvent
TGetCertReqEvent = procedure (Sender: TObject;
KEA: TKeyExchangeAlgorithm;
const Version: TProtocolVersion;
var H: PTLSHandshake;
var Len: Integer;
var Found: Boolean) of object;
enumTAlpnFallbackPolicy
What ServedProtocol answers when ALPN settled on NOTHING - either because the peer sent no ALPN extension at all, or because no offer of ours matched.
afpFirstOffered is the DEFAULT, and it is the historical behaviour: callers have always read ApplicationProtocols[0], which after a failed negotiation is still the first entry of the OFFER. Keeping it as the default means a consumer that has always served its own first choice to a silent peer goes on doing so.
afpStrict answers empty instead, leaving the decision to the caller. That is what a server with its own fallback policy wants - it cannot apply a "refuse" rule if the layer has already told it a protocol was chosen. The async TLS server reads SelectedProtocol directly for the same reason, so its own FallbackPolicy governs.
TAlpnFallbackPolicy = (afpFirstOffered, afpStrict);
Routines