tls API reference Changelog View on GitHub

API reference

TLS 1.3 in Zig: a sans-I/O engine over caller-owned buffers, with blocking, nonblocking, and kTLS integrations.

module aead

src

AEAD cipher wrapper for TLS 1.3.

more

TLS 1.3 mandates three AEAD cipher suites (RFC 8446 §9.1):

  • TLS_AES_128_GCM_SHA256
  • TLS_AES_256_GCM_SHA384
  • TLS_CHACHA20_POLY1305_SHA256

All three share the same tag length (16 bytes) and nonce length (12 bytes). Keys are derived during the handshake and held for the connection lifetime.

Constants

pub const nonce_len = 12

src

pub const Nonce = stdx.mem.Array(nonce_len)

src

pub const Iv = stdx.mem.Array(nonce_len)

src

pub const tag_len = 16

src

Authentication tag — 16 bytes for all TLS 1.3 ciphers.

pub const Tag = stdx.mem.Array(tag_len)

src

pub const Aes128GcmKey = stdx.mem.Array(16)

src

pub const Aes256GcmKey = stdx.mem.Array(32)

src

pub const ChaCha20Poly1305Key = stdx.mem.Array(32)

src

pub const Error = …

src
value
error{
    AuthenticationFailed,
    AeadSetupFailed,
    AeadEncryptFailed,
    InputAliasesOutput,
    SliceLengthMismatch,
}

Functions

pub fn construct(iv: *const Iv, seq: u64) Nonce

src

Construct the per-record nonce by XORing the IV with the sequence number.

The sequence number is right-aligned as a big-endian u64 in a 12-byte buffer (zero-padded on the left), then XORed with the IV.

RFC 8446 §5.3

Types

union Aead

src
pub const Aead = union(CipherSuite)

A cipher context holding the key for one direction of a TLS connection.

Fields

aes_128_gcm_sha256: Aes128GcmKey
chacha20_poly1305_sha256: ChaCha20Poly1305Key
aes_256_gcm_sha384: Aes256GcmKey

Functions

pub fn suite(self: Aead) CipherSuite

src

pub fn keyUsageLimit(self: Aead) u64

src

pub fn secureZero(self: *Aead) void

src

pub fn encrypt( self: Aead, ctx: *Context, ciphertext: []u8, tag: *Tag, plaintext: []const u8, ad: []const u8, npub: *const Nonce, ) Error!void

src

Encrypt plaintext into ciphertext and write the authentication tag. ciphertext must be the same length as plaintext. ad is authenticated but not encrypted (the TLS record header).

pub fn decrypt( self: Aead, ctx: *Context, plaintext: []u8, ciphertext: []const u8, tag: *const Tag, ad: []const u8, npub: *const Nonce, ) Error!void

src

Decrypt ciphertext into plaintext and verify the authentication tag. plaintext must be the same length as ciphertext.

more

Returns error.AuthenticationFailed if the tag does not verify. Exact in-place decryption is supported. Any other input/output overlap returns error.InputAliasesOutput. On authentication failure, the whole plaintext output slice is securely zeroed. Argument errors leave it unchanged.

struct Context

src

Fields

suite: CipherSuite
inner: backend.aead.Context

Functions

pub fn init(aead: Aead) Error!Context

src

pub fn deinit(self: *Context) void

src

module alert

src

TLS Alert protocol.

RFC 8446 §6

Constants

pub const ParseError = error{ UnexpectedEof, InvalidAlertLength }

src

Functions

pub fn parse(msg: []const u8) ParseError!Alert

src

pub fn encode(out: []u8, level: Level, description: Description) error{BufferTooShort}![]u8

src

pub fn plaintextRecord(msg: *const [2]u8, out: []u8) error{BufferTooShort}![]u8

src

pub fn alertForError(err: anyerror) ?Description

src

Map any error to the alert to send the peer, or null when nothing should be sent. Errors outside the engine's own set carry no protocol meaning, so they answer internal_error, which is what this returned for them before the closed-set mapping existed.

Prefer alertForHandshakeError where the type is already the engine's: the scan below is only here for callers holding anyerror.

pub fn alertForHandshakeError(err: HandshakeError) ?Description

src

Map a TLS engine error to the alert to send the peer, or null when nothing should be sent. RFC 8446 §6.2 — error alerts should be as specific as the protocol defines.

more

The switch is exhaustive over HandshakeError, with no else arm: a new engine error is a compile error here until someone decides what the peer is told about it. A silent fall-through to internal_error is exactly what this shape prevents (#171).

error.PeerAlert is null: the peer already sent its own alert, and answering it with a second alert, let alone internal_error, blames the wrong side. RFC 8446 §6.2 says close without more data in that case.

Types

enum Level

src
pub const Level = enum(u8)

Fields

warning warning = 1
fatal fatal = 2
_ _

enum Description

src
pub const Description = enum(u8)

Fields

close_notify close_notify = 0
unexpected_message unexpected_message = 10
bad_record_mac bad_record_mac = 20
record_overflow record_overflow = 22
handshake_failure handshake_failure = 40
bad_certificate bad_certificate = 42
unsupported_certificate unsupported_certificate = 43
certificate_revoked certificate_revoked = 44
certificate_expired certificate_expired = 45
certificate_unknown certificate_unknown = 46
illegal_parameter illegal_parameter = 47
unknown_ca unknown_ca = 48
access_denied access_denied = 49
decode_error decode_error = 50
decrypt_error decrypt_error = 51
protocol_version protocol_version = 70
insufficient_security insufficient_security = 71
internal_error internal_error = 80
inappropriate_fallback inappropriate_fallback = 86
user_canceled user_canceled = 90
missing_extension missing_extension = 109
unsupported_extension unsupported_extension = 110
unrecognized_name unrecognized_name = 112
bad_certificate_status_response bad_certificate_status_response = 113
unknown_psk_identity unknown_psk_identity = 115
certificate_required certificate_required = 116
no_application_protocol no_application_protocol = 120
_ _

struct Alert

src

Fields

level: Level
description: Description

Functions

pub inline fn isCloseNotify(self: Alert) bool

src

pub inline fn isFatal(self: Alert) bool

src

pub const AlpnError = @import("alpn.zig").Error

src

pub const AlpnProtocols = @import("alpn.zig").Protocols

src

module certificate

src

TLS 1.3 Certificate and CertificateVerify handshake message handling.

RFC 8446 §4.4.2, §4.4.3

Constants

pub const PolicyError = certificate_policy.PolicyError

src

pub const ParseError = …

src
value
error{
    UnexpectedEof,
    InvalidHandshakeType,
    InvalidHandshakeLength,
    UnexpectedCertificateRequestContext,
    EmptyCertificateList,
    InvalidExtensionLength,
    DuplicateExtension,
    UnsupportedExtension,
    UnexpectedExtension,
    CertificateIssuerNotFound,
    MissingTrustAnchor,
    CertificateChainTooLong,
} || PolicyError ||
    Certificate.ParseError ||
    Certificate.Parsed.VerifyError ||
    Certificate.Parsed.VerifyHostNameError ||
    Certificate.Parsed.NameConstraintError

pub const EncodeError = error{ BufferTooShort, RequestContextTooLong }

src
value
error{
    EmptyCertificateChain,
    InvalidCertificate,
    UnsupportedCertificateSignatureAlgorithm,
}

pub const server_certificate_verify_context = @as([64]u8, @splat(' ')) ++ "TLS 1.3, server CertificateVerify\x00"

src

pub const client_certificate_verify_context = @as([64]u8, @splat(' ')) ++ "TLS 1.3, client CertificateVerify\x00"

src

pub const VerifyError = …

src
value
error{
    BufferTooShort,
    InvalidEncoding,
    InvalidEnumTag,
    InvalidHandshakeType,
    SignatureVerificationFailed,
    UnexpectedEof,
    UnsupportedSignatureScheme,
}

Functions

pub fn encodedLen(request_context: []const u8, certs_der: []const []const u8) usize

src

Encoded size of a TLS 1.3 Certificate message carrying certs_der and the request_context that encode will echo. Both functions take the context in the same position so a caller cannot size a frame with a different context than the one it encodes. RFC 8446 §4.4.2.

pub fn encode( out: []u8, request_context: []const u8, certs_der: []const []const u8, ) EncodeError![]const u8

src

Encode a TLS 1.3 Certificate handshake message with empty per-certificate extensions. request_context is empty for a server Certificate and echoes the CertificateRequest context for a client Certificate. RFC 8446 §4.4.2.

pub fn parseClientCertificate( msg: []const u8, expected_request_context: []const u8, ) ParseError!ClientCertificateStatus

src

Parse a client Certificate message enough for server-side client-auth state machine decisions. Full client certificate validation is intentionally left to the later #4 verification slice; this helper validates framing, request_context echo, list bounds, and per-entry extension syntax.

RFC 8446 §4.4.2

pub fn parseClientChain( msg: []const u8, expected_request_context: []const u8, policy: Policy, ) ParseError!VerifiedClientChain

src

Parse a client Certificate handshake message (echoing the CertificateRequest request_context), return the verified leaf public key and DER as slices into msg, and run chain validation per policy. Mirrors parse but accepts the non-empty client request_context and uses the client-auth leaf policy. The caller must keep msg alive until the returned slices have been consumed. RFC 8446 §4.4.2 (client Certificate), §4.4.3 (client CertificateVerify).

pub fn parse(msg: []const u8, policy: Policy) ParseError![]const u8

src

Parse a Certificate handshake message and extract the leaf certificate public key as a slice into msg. The caller must keep msg alive until verifySignature has been called. Chain anchoring requires a trust bundle or the explicit insecure_no_chain_anchor test/demo opt-in.

RFC 8446 §4.4.2

pub fn chainRequiredSignatureSchemes( certs_der: []const []const u8, ) ChainSignatureSchemesError!OfferedCertificateSchemes

src

RFC 8446 §4.2.3, §4.4.2.2 — parse a configured certificate chain and return the set of signature schemes the peer must accept to verify it. The leaf (index 0) is always included, matching parse; subsequent self-signed certificates (presented trust anchors) are exempt. Malformed DER or unsupported signature algorithms fail loudly so callers surface bad credentials at configuration time rather than failing every handshake.

pub fn chainMatchesSignatureSchemes( certs_der: []const []const u8, offered: OfferedCertificateSchemes, ) bool

src

RFC 8446 §4.2.3, §4.4.2.2 — return true when every validated certificate in certs_der uses a signature algorithm offered in offered.

pub fn certificateVerifyEncodedLen(signature: []const u8) usize

src

pub fn encodeCertificateVerify( out: []u8, scheme: SignatureScheme, signature: []const u8, ) EncodeError![]const u8

src

Encode a CertificateVerify handshake message from a caller-provided signature. tls does not own private keys; server-side code signs server_context || transcript_hash outside this helper, then wraps the signature here. RFC 8446 §4.4.3.

pub fn verifyCertificateVerify( role: Role, msg: []const u8, pub_key: []const u8, transcript_hash: []const u8, offered_schemes: ?[]const SignatureScheme, ) VerifyError!void

src

Verify a CertificateVerify handshake message sent by role.

more

pub_key is a slice into the caller's Certificate message buffer. transcript_hash covers all messages up to and including Certificate. A non-null offered_schemes requires the message's scheme to be one the peer offered (RFC 8446 §4.4.3); null skips that filter for callers that verify a raw frame against a key they already trust.

RFC 8446 §4.4.3

Types

enum LeafUsage

src
pub const LeafUsage = certificate_policy.LeafUsage

Fields

none none
server_auth server_auth
client_auth client_auth

Client-auth leaf policy: EKU clientAuth and KeyUsage.digitalSignature enforced when present, plus X.509v3 and signature-algorithm checks.

struct Policy

src
pub const Policy = certificate_policy.Policy

Certificate validation policy.

Fields

bundle: ?*const Certificate.Bundle

Trust anchors for chain validation. If null, certificate parsing fails unless insecure_no_chain_anchor is set. That opt-in still extracts the leaf public key and lets CertificateVerify prove key possession, but it does not authenticate the chain to any trust root.

insecure_no_chain_anchor: bool

Explicit test/demo escape hatch for self-signed fixtures. Production clients should leave this false and provide bundle.

now_sec: i64

Current time in seconds since the Unix epoch, for validity checks.

host_name: ?[]const u8

This ASCII reference identifies the expected subjectAltName entry: a DNS name matches DNS-ID, and an IPv4 or IPv6 literal matches iPAddress (RFC 9525 §6.2.1). The caller owns IDNA conversion to A-labels. null disables the check. ClientHandshake.Config.host_name supplies the default value.

leaf_usage: LeafUsage

Enforce TLS 1.3 certificate residual policy for the leaf's intended use. .server_auth requires KeyUsage.digitalSignature when KeyUsage is present, EKU serverAuth when EKU is present, and a TLS 1.3-compatible certificate signature algorithm. .client_auth mirrors that with EKU clientAuth. .none skips all leaf policy checks.

certificate_signature_schemes: []const SignatureScheme

Algorithms accepted for signatures appearing in certificates. This is the signature_algorithms_cert policy; when that extension is omitted, RFC 8446 §4.2.3 says signature_algorithms applies to certificates too.

Constants

pub const init: Policy = …

src
value
.{
        .bundle = null,
        .insecure_no_chain_anchor = false,
        .now_sec = 0,
        .host_name = null,
        .leaf_usage = .server_auth,
        .certificate_signature_schemes = capabilities.current.certificate_signature_schemes,
    }

The default policy: no trust anchor, no insecure opt-in, no hostname check, epoch time, server-auth leaf usage, and the backend's certificate signature schemes.

enum SignatureScheme

src
pub const SignatureScheme = signature_scheme.SignatureScheme

RFC 8446 §4.2.3 signature schemes supported by tls.

Fields

rsa_pkcs1_sha256 rsa_pkcs1_sha256 = 0x0401
rsa_pkcs1_sha384 rsa_pkcs1_sha384 = 0x0501
rsa_pkcs1_sha512 rsa_pkcs1_sha512 = 0x0601
ecdsa_secp256r1_sha256 ecdsa_secp256r1_sha256 = 0x0403
ecdsa_secp384r1_sha384 ecdsa_secp384r1_sha384 = 0x0503
ecdsa_secp521r1_sha512 ecdsa_secp521r1_sha512 = 0x0603
rsa_pss_rsae_sha256 rsa_pss_rsae_sha256 = 0x0804
rsa_pss_rsae_sha384 rsa_pss_rsae_sha384 = 0x0805
rsa_pss_rsae_sha512 rsa_pss_rsae_sha512 = 0x0806
ed25519 ed25519 = 0x0807
_ _

Constants

pub const supported_handshake: []const SignatureScheme = …

src
value
&.{
        .ecdsa_secp256r1_sha256,
        .ecdsa_secp384r1_sha384,
        .rsa_pss_rsae_sha256,
        .rsa_pss_rsae_sha384,
        .ed25519,
    }

pub const supported_certificate: []const SignatureScheme = …

src
value
&.{
        .rsa_pkcs1_sha256,
        .rsa_pkcs1_sha384,
        .rsa_pkcs1_sha512,
        .ecdsa_secp256r1_sha256,
        .ecdsa_secp384r1_sha384,
        .rsa_pss_rsae_sha256,
        .rsa_pss_rsae_sha384,
        .rsa_pss_rsae_sha512,
        .ed25519,
    }

Functions

pub fn supportsHandshake(self: SignatureScheme) bool

src

enum ClientCertificateStatus

src

Fields

empty empty
present present

struct VerifiedClientChain

src

Verified client leaf material borrowed from the Certificate message.

Fields

pub_key: []const u8
leaf_der: []const u8

enum Role

src
pub const Role = capabilities.Role

Handshake endpoint that sent the CertificateVerify message. The role picks the context string RFC 8446 §4.4.3 prepends to the transcript hash, so one signature can never satisfy both roles.

Fields

client client
server server

module Certificate

src

The bounds-checked X.509 parser used by the handshake.

Constants

pub const Bundle = std.crypto.Certificate.Bundle

src

OS trust-store loading stays std-owned; tls owns X.509 parse-and-verify.

pub const ParseError = …

src
value
der.Element.ParseError || ParseVersionError || ParseTimeError || ParseEnumError ||
    ParseBitStringError || error{
    CertificateUnsupportedCriticalExtension,
    CertificateHasDuplicateExtension,
}

Functions

pub fn parse(cert: Certificate) ParseError!Parsed

src

Types

enum Version

src

Fields

v1 v1
v2 v2
v3 v3

enum Algorithm

src

Fields

sha1WithRSAEncryption sha1WithRSAEncryption
sha224WithRSAEncryption sha224WithRSAEncryption
sha256WithRSAEncryption sha256WithRSAEncryption
sha384WithRSAEncryption sha384WithRSAEncryption
sha512WithRSAEncryption sha512WithRSAEncryption
ecdsa_with_SHA224 ecdsa_with_SHA224
ecdsa_with_SHA256 ecdsa_with_SHA256
ecdsa_with_SHA384 ecdsa_with_SHA384
ecdsa_with_SHA512 ecdsa_with_SHA512
md2WithRSAEncryption md2WithRSAEncryption
md5WithRSAEncryption md5WithRSAEncryption
curveEd25519 curveEd25519
rsassaPss_with_SHA256 rsassaPss_with_SHA256
rsassaPss_with_SHA384 rsassaPss_with_SHA384
rsassaPss_with_SHA512 rsassaPss_with_SHA512

Constants

pub const map = …

src
value
std.StaticStringMap(Algorithm).initComptime(.{
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05 }, .sha1WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B }, .sha256WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C }, .sha384WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D }, .sha512WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0E }, .sha224WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x01 }, .ecdsa_with_SHA224 },
        .{ &.{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02 }, .ecdsa_with_SHA256 },
        .{ &.{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03 }, .ecdsa_with_SHA384 },
        .{ &.{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04 }, .ecdsa_with_SHA512 },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02 }, .md2WithRSAEncryption },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04 }, .md5WithRSAEncryption },
        .{ &.{ 0x2B, 0x65, 0x70 }, .curveEd25519 },
    })

Types

type fn Hash

src
pub fn Hash(comptime algorithm: Algorithm) type

enum Attribute

src

Fields

commonName commonName
serialNumber serialNumber
countryName countryName
localityName localityName
stateOrProvinceName stateOrProvinceName
streetAddress streetAddress
organizationName organizationName
organizationalUnitName organizationalUnitName
postalCode postalCode
organizationIdentifier organizationIdentifier
pkcs9_emailAddress pkcs9_emailAddress
domainComponent domainComponent

Constants

pub const map = …

src
value
std.StaticStringMap(Attribute).initComptime(.{
        .{ &.{ 0x55, 0x04, 0x03 }, .commonName },
        .{ &.{ 0x55, 0x04, 0x05 }, .serialNumber },
        .{ &.{ 0x55, 0x04, 0x06 }, .countryName },
        .{ &.{ 0x55, 0x04, 0x07 }, .localityName },
        .{ &.{ 0x55, 0x04, 0x08 }, .stateOrProvinceName },
        .{ &.{ 0x55, 0x04, 0x09 }, .streetAddress },
        .{ &.{ 0x55, 0x04, 0x0A }, .organizationName },
        .{ &.{ 0x55, 0x04, 0x0B }, .organizationalUnitName },
        .{ &.{ 0x55, 0x04, 0x11 }, .postalCode },
        .{ &.{ 0x55, 0x04, 0x61 }, .organizationIdentifier },
        .{ &.{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01 }, .pkcs9_emailAddress },
        .{ &.{ 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x19 }, .domainComponent },
    })

enum GeneralNameTag

src
pub const GeneralNameTag = enum(u5)

Fields

otherName otherName = 0
rfc822Name rfc822Name = 1
dNSName dNSName = 2
x400Address x400Address = 3
directoryName directoryName = 4
ediPartyName ediPartyName = 5
uniformResourceIdentifier uniformResourceIdentifier = 6
iPAddress iPAddress = 7
registeredID registeredID = 8
_ _

struct DirectoryString

src

A string value from a certificate, with the ASN.1 type that encoded it.

more

The bytes are borrowed from the certificate buffer and are not decoded text: call write to render them. Certificate text comes from whoever the peer's chain says it is, so it is untrusted input. write escapes every byte that could forge terminal or log output (C0 controls including newline and ESC, DEL, and bytes that are not valid UTF-8), and renders an encoding it cannot decode as \xNN escapes rather than guessing.

RFC 5280 §4.1.2.4.

Fields

encoding: Encoding
bytes: []const u8

Functions

pub fn write(self: DirectoryString, w: *Io.Writer) Io.Writer.Error!void

src

Write this value as UTF-8, with hostile bytes escaped.

Not a round-trip format: the output is for a person or a log line, not for parsing back. A backslash is written as-is; what is escaped is only what could forge output.

Types

enum Encoding

src

The ASN.1 string types a certificate's text fields can use.

Fields

utf8_string utf8_string
printable_string printable_string
ia5_string ia5_string

RFC 5280 requires this one of conforming CAs, but old ones emit it.

teletex_string teletex_string

T.61, whose mapping is a national variant minefield. Never guessed.

bmp_string bmp_string

UCS-2 in practice: two-byte big-endian code units.

universal_string universal_string

Four-byte big-endian code units.

numeric_string numeric_string

Still legal in DirectoryString, still seen in old chains.

visible_string visible_string
unrecognized unrecognized

Any other tag, rendered as hex rather than as text.

struct NameEntry

src

One AttributeTypeAndValue from a distinguished name (RFC 5280 §4.1.2.4).

more

oid is the attribute's object identifier as raw DER content bytes, kept so an attribute this parser does not model is still reportable. attribute is the modeled name, or null when the identifier is unknown.

A RelativeDistinguishedName that holds more than one attribute yields them one after another with no grouping marker. That is deliberate: the only thing a display needs is the values, and multi-valued RDNs are rare.

Fields

oid: []const u8
attribute: ?Attribute
value: DirectoryString

struct NameIterator

src

Walks the AttributeTypeAndValues of a distinguished name, in wire order.

Fields

bytes: []const u8
next_rdn: u32

The next RelativeDistinguishedName to enter, and the end of the Name.

name_end: u32
atav: u32

The next AttributeTypeAndValue in the current RDN, and where it ends.

rdn_end: u32

Constants

pub const Error = der.Element.ParseError || ParseEnumError

src

Functions

pub fn init(bytes: []const u8) NameIterator

src

pub fn next(self: *NameIterator) Error!?NameEntry

src

struct GeneralName

src

One entry of a subjectAltName GeneralNames sequence (RFC 5280 §4.2.1.6).

Fields

kind: GeneralNameTag
value: []const u8

The value, still encoded as the certificate carried it. For iPAddress that is the address in network byte order, four octets for IPv4 and sixteen for IPv6. For dNSName it is the name. Nothing is decoded.

struct SanIterator

src

Walks the GeneralNames of a subjectAltName extension in wire order.

Fields

bytes: []const u8
index: u32
end: u32

Functions

pub fn next(self: *SanIterator) der.Element.ParseError!?GeneralName

src

struct Parsed

src

Fields

Constants

pub const SanIteratorError = …

src
value
der.Element.ParseError || error{
        CertificateFieldHasWrongDataType,
    }

pub const NameConstraintError = …

src
value
der.Element.ParseError || error{
        CertificateFieldHasWrongDataType,
        CertificateNameConstraintViolation,
        CertificateNameConstraintUnsupported,
    }

pub const VerifyError = …

src
value
error{
        CertificateIssuerMismatch,
        CertificateNotYetValid,
        CertificateExpired,
        CertificateSignatureAlgorithmUnsupported,
        CertificateSignatureAlgorithmMismatch,
        CertificateFieldHasInvalidLength,
        CertificateFieldHasWrongDataType,
        CertificatePublicKeyInvalid,
        CertificateSignatureInvalidLength,
        CertificateSignatureInvalid,
        CertificateSignatureUnsupportedBitCount,
        CertificateSignatureNamedCurveUnsupported,
    }

pub const VerifyHostNameError = …

src
value
error{
        CertificateHostMismatch,
        CertificateFieldHasInvalidLength,
        CertificateFieldHasWrongDataType,
    }

Functions

pub fn init( certificate: Certificate, issuer_slice: Slice, subject_slice: Slice, common_name_slice: Slice, signature_slice: Slice, signature_algorithm: Algorithm, pub_key_algo: PubKeyAlgo, pub_key_slice: Slice, message_slice: Slice, subject_alt_name_slice: Slice, key_usage_slice: Slice, ext_key_usage_slice: Slice, name_constraints_slice: Slice, name_constraints_critical: bool, validity: Validity, version: Version, ) Parsed

src

A parsed certificate with the policy fields at their defaults: not a CA and no basicConstraints path length.

pub fn issuer(p: Parsed) []const u8

src

pub fn subject(p: Parsed) []const u8

src

pub fn pubKey(p: Parsed) []const u8

src

pub fn subjectAttributes(p: Parsed) NameIterator

src

Every AttributeTypeAndValue in the subject, in wire order.

Values are borrowed and still encoded; render each with DirectoryString.write. See NameEntry for what a single entry holds.

pub fn issuerAttributes(p: Parsed) NameIterator

src

Every AttributeTypeAndValue in the issuer, in wire order.

pub fn subjectAltNames(p: Parsed) SanIteratorError!SanIterator

src

The subjectAltName entries as the certificate carries them, or an empty iterator when the extension is absent.

The extension's GeneralNames SEQUENCE is unwrapped here, so a caller never handles the container. Values are not decoded: a dNSName is its bytes and an iPAddress is its address bytes, four for IPv4 and sixteen for IPv6 (RFC 5280 §4.2.1.6).

pub fn nameConstraints(p: Parsed) []const u8

src

pub fn verifyNameConstraints(ca: Parsed, subordinate: Parsed) NameConstraintError!void

src

RFC 5280 §4.2.1.10 — a CA's Name Constraints extension restricts all supported GeneralName values in subordinate certificates.

pub fn allowsKeyUsage(p: Parsed, bit_index: u4) ParseError!bool

src

RFC 5280 §4.2.1.3 — KeyUsage is a BIT STRING. Missing extension means no key-usage restriction; present extension must contain the requested bit.

pub fn allowsExtKeyUsage(p: Parsed, oid: []const u8) ParseError!bool

src

RFC 5280 §4.2.1.12 — ExtendedKeyUsage is a sequence of OIDs. Missing extension means no EKU restriction; present extension must include OID.

pub fn verify(parsed_subject: Parsed, parsed_issuer: Parsed, now_sec: i64) VerifyError!void

src

This function verifies:

  • That the subject's issuer is indeed the provided issuer.
  • The time validity of the subject.
  • The signature.

pub fn verifyHostName(parsed_subject: Parsed, host_name: []const u8) VerifyHostNameError!void

src

The verifier compares an ASCII reference identity against the subject alternate names: a DNS name against DNS-ID entries, and an address literal against iPAddress entries. Internationalized labels use caller-produced A-labels. Non-ASCII reference names return CertificateHostMismatch. Non-ASCII DNS-ID entries do not match.

Callers own IDNA conversion and syntax checks for reference names. This function does not validate Punycode.

RFC 6125 §6.4.4, RFC 9525 §6.1, RFC 9525 §6.2.1.

pub fn isAddressLiteral(host: []const u8) bool

src

Whether host is an IPv4 or IPv6 literal rather than a DNS name. An address verifies against iPAddress SANs and must not be sent as a HostName in SNI (RFC 6066 §3).

Types

union PubKeyAlgo

src
pub const PubKeyAlgo = union(AlgorithmCategory)

Fields

rsassa_pss: ?PssParameters
X9_62_id_ecPublicKey: NamedCurve
curveEd25519: void

struct Validity

src

Fields

not_before: u64
not_after: u64

struct Slice

src
pub const Slice = der.Element.Slice

Fields

start: u32
end: u32

Constants

pub const empty: Slice = .{ .start = 0, .end = 0 }

src

enum PssHash

src

Fields

sha256 sha256
sha384 sha384
sha512 sha512

Functions

pub fn digestLen(self: PssHash) u32

src

pub fn algorithm(self: PssHash) Algorithm

src

struct PssParameters

src

RSASSA-PSS-params from an AlgorithmIdentifier (RFC 4055 §3.1, §4.1). The parser retains every field so key and signature constraints cannot be discarded before verification.

Fields

hash: PssHash
mgf1_hash: PssHash

Functions

pub fn forTls(comptime Hash: type) PssParameters

src

The parameters a TLS 1.3 RSA-PSS scheme carries implicitly. Unlike a certificate AlgorithmIdentifier, CertificateVerify has no DER to parse.

pub fn matchesTls(self: PssParameters, comptime Hash: type) bool

src

TLS 1.3 RSA-PSS uses MGF1 with the scheme hash, salt length equal to the digest length, and trailerField 1 (RFC 8446 §4.2.3).

struct der

src

Types

enum Class

src
pub const Class = enum(u2)

Fields

universal universal
application application
context_specific context_specific
private private

enum PC

src
pub const PC = enum(u1)

Fields

primitive primitive
constructed constructed

struct Identifier

src
pub const Identifier = packed struct(u8)

Fields

tag: Tag
pc: PC
class: Class

enum Tag

src
pub const Tag = enum(u5)

Fields

boolean boolean = 1
integer integer = 2
bitstring bitstring = 3
octetstring octetstring = 4
null null = 5
object_identifier object_identifier = 6
sequence sequence = 16
sequence_of sequence_of = 17
utc_time utc_time = 23
generalized_time generalized_time = 24
_ _

struct Element

src

Fields

identifier: Identifier
slice: Slice

Constants

pub const ParseError = error{CertificateFieldHasInvalidLength}

src

Functions

pub fn parse(bytes: []const u8, index: u32) Element.ParseError!Element

src

Types

struct Slice

src

Fields

start: u32
end: u32

Constants

pub const empty: Slice = .{ .start = 0, .end = 0 }

src

struct rsa

src

RSA verification primitives. Every input is public, so variable-time modular exponentiation and padding comparisons are acceptable here. No function accepts a private key or produces a signature. A future signing implementation needs a separate private-key type and constant-time, blinded private operations; it cannot inherit this verification path.

Types

struct PSSSignature

src

RFC 3447 8.1 RSASSA-PSS, verification only. CertificateVerify and PSS-signed certificate chains share this path with their own key floors.

Constants

pub const VerifyError = EncryptError || error{InvalidSignature}

src

pub const VerifyDerError = …

src
value
der.Element.ParseError || error{
            CertificateFieldHasWrongDataType,
            CertificatePublicKeyInvalid,
            CertificateSignatureAlgorithmMismatch,
            CertificateSignatureInvalidLength,
            CertificateSignatureInvalid,
            CertificateSignatureUnsupportedBitCount,
        }

Functions

pub fn verifyDer( comptime Hash: type, msg: []const u8, sig: []const u8, pub_key: []const u8, comptime min_modulus_bits: u32, params: PssParameters, ) VerifyDerError!void

src

Verify PSS against an RSAPublicKey DER slice and explicit TLS parameters. Certificate chains supply parsed SPKI parameters; CertificateVerify supplies PssParameters.forTls(Hash).

pub fn verify( comptime modulus_len: usize, sig: [modulus_len]u8, msg: []const u8, public_key: PublicKey, comptime Hash: type, ) VerifyError!void

src

pub fn concatVerify( comptime modulus_len: usize, sig: [modulus_len]u8, msg: []const []const u8, public_key: PublicKey, comptime Hash: type, ) VerifyError!void

src

struct PKCS1v1_5Signature

src

RFC 3447 8.2 RSASSA-PKCS1-v1_5, verification only.

Constants

pub const VerifyError = EncryptError || error{InvalidSignature}

src

pub const VerifyDerError = …

src
value
der.Element.ParseError || error{
            CertificateFieldHasWrongDataType,
            CertificatePublicKeyInvalid,
            CertificateSignatureInvalidLength,
            CertificateSignatureInvalid,
            CertificateSignatureUnsupportedBitCount,
        }

Functions

pub fn verifyDer( comptime Hash: type, msg: []const u8, sig: []const u8, pub_key: []const u8, ) VerifyDerError!void

src

Verify a signature over msg against an RSAPublicKey DER slice. The signature length must equal the modulus length before the fixed-size public operation. A short or long input never gets zero-padded into a plausible signature.

pub fn verify( comptime modulus_len: usize, sig: [modulus_len]u8, msg: []const u8, public_key: PublicKey, comptime Hash: type, ) VerifyError!void

src

pub fn concatVerify( comptime modulus_len: usize, sig: [modulus_len]u8, msg: []const []const u8, public_key: PublicKey, comptime Hash: type, ) VerifyError!void

src

struct PublicKey

src

Fields

n: Modulus
e: Fe

Constants

pub const FromBytesError = error{CertificatePublicKeyInvalid}

src

pub const ParseDerError = der.Element.ParseError || error{CertificateFieldHasWrongDataType}

src

Functions

pub fn fromBytes(pub_bytes: []const u8, modulus_bytes: []const u8) FromBytesError!PublicKey

src

pub fn parseDer(pub_key: []const u8) ParseDerError!struct { modulus: []const u8, exponent: []const u8 }

src

module certificate_chain

src

Constants

pub const PemDecodeError = …

src
value
error{
    NoCertificate,
    MissingCertificateEnd,
    InvalidCertificateEncoding,
    CertificateBufferTooShort,
    CertificateChainTooLong,
}

Types

union CertificateChain

src
pub const CertificateChain = union(enum)

Fields

slice: []const []const u8
single: []const u8

Constants

pub const empty: CertificateChain = .{ .slice = &.{} }

src

Functions

pub fn init(certs_der: []const []const u8) CertificateChain

src

pub fn singleCert(cert_der: []const u8) CertificateChain

src

pub fn fromPem( pem: []const u8, der_storage: []u8, chain_storage: [][]const u8, ) PemDecodeError!CertificateChain

src

Decode RFC 7468 CERTIFICATE blocks into caller-owned storage.

more

The returned chain borrows both output buffers. They must outlive every handshake that uses the chain and must not overlap pem. One chain slot is required per block; pem.len bytes always suffice for DER storage. Non-whitespace outside the Base64 alphabet is rejected, and output storage may contain partial data after an error.

pub fn requiredSignatureSchemes( self: CertificateChain, ) certificate.ChainSignatureSchemesError!OfferedCertificateSchemes

src

RFC 8446 §4.2.3, §4.4.2.2 — parse this chain and return the set of signature schemes a peer must accept to verify it.

pub fn matchesSignatureSchemes( self: CertificateChain, offered: OfferedCertificateSchemes, ) bool

src

RFC 8446 §4.2.3, §4.4.2.2 — return true when every validated certificate in this chain carries a signature algorithm present in offered.

pub fn encodedLen(self: CertificateChain, request_context: []const u8) usize

src

Encoded size of this chain's Certificate message. request_context is the value encode will echo, so the size and the frame cannot drift apart. RFC 8446 §4.4.2.

pub fn encode( self: CertificateChain, out: []u8, request_context: []const u8, ) certificate.EncodeError![]const u8

src

Encode this chain as a Certificate message. request_context is empty for a server Certificate and echoes the CertificateRequest context for a client Certificate. RFC 8446 §4.4.2.

union CertificateChain

src
pub const CertificateChain = certificate_chain.CertificateChain

Fields

slice: []const []const u8
single: []const u8

Constants

pub const empty: CertificateChain = .{ .slice = &.{} }

src

Functions

pub fn init(certs_der: []const []const u8) CertificateChain

src

pub fn singleCert(cert_der: []const u8) CertificateChain

src

pub fn fromPem( pem: []const u8, der_storage: []u8, chain_storage: [][]const u8, ) PemDecodeError!CertificateChain

src

Decode RFC 7468 CERTIFICATE blocks into caller-owned storage.

more

The returned chain borrows both output buffers. They must outlive every handshake that uses the chain and must not overlap pem. One chain slot is required per block; pem.len bytes always suffice for DER storage. Non-whitespace outside the Base64 alphabet is rejected, and output storage may contain partial data after an error.

pub fn requiredSignatureSchemes( self: CertificateChain, ) certificate.ChainSignatureSchemesError!OfferedCertificateSchemes

src

RFC 8446 §4.2.3, §4.4.2.2 — parse this chain and return the set of signature schemes a peer must accept to verify it.

pub fn matchesSignatureSchemes( self: CertificateChain, offered: OfferedCertificateSchemes, ) bool

src

RFC 8446 §4.2.3, §4.4.2.2 — return true when every validated certificate in this chain carries a signature algorithm present in offered.

pub fn encodedLen(self: CertificateChain, request_context: []const u8) usize

src

Encoded size of this chain's Certificate message. request_context is the value encode will echo, so the size and the frame cannot drift apart. RFC 8446 §4.4.2.

pub fn encode( self: CertificateChain, out: []u8, request_context: []const u8, ) certificate.EncodeError![]const u8

src

Encode this chain as a Certificate message. request_context is empty for a server Certificate and echoes the CertificateRequest context for a client Certificate. RFC 8446 §4.4.2.

module der

src

Bounds-checked DER envelope validation, for callers that hand certificates to std's Certificate.Bundle.

Functions

pub fn validCertificate(der: []const u8) bool

src

Whether der holds exactly one well-formed DER certificate.

more

A certificate is a single SEQUENCE that fills the whole buffer, containing a tbsCertificate, a signatureAlgorithm, and a signatureValue, in that order. The tbsCertificate carries the six mandatory fields, or seven when an explicit version precedes them.

This is the envelope, not the contents: fields are not decoded and the signature is not checked. It is the weaker claim that std's parser cannot walk off the end of the buffer.

module capabilities

src

Public compile-time capability discovery for the selected crypto backend.

Every table here is comptime data held in .rodata: a query scans at most six entries and allocates nothing.

Constants

pub const Backend = backend.Backend

src

pub const active_backend: Backend = backend.active

src

Backend identity inferred from the selected libcrypto headers and FIPS policy.

pub const approved_only: bool = backend.approved_only

src

Selects the NIST-approved row over the full one.

pub const current: Profile = …

src
value
switch (active_backend) {
    .native => native,
    .openssl => openssl,
    .@"openssl-approved" => openssl_approved,
    .@"aws-lc" => aws_lc,
    .@"aws-lc-approved" => aws_lc_approved,
    .boringssl => boringssl,
}

The row the selected crypto backend and approval policy resolve to.

pub const cipher_suites = current.cipher_suites

src

TLS 1.3 cipher suites this build advertises. An approved-only build advertises AES-GCM only.

pub const hybrid_groups = …

src
value
[_]NamedGroup{
    .x25519_mlkem768,
    .secp256r1_mlkem768,
    .secp384r1_mlkem1024,
}

RFC 10024 groups that tls implements. Backend support remains selectable.

pub const HybridPolicyError = …

src
value
error{
    /// The group list or initial-share relation is malformed.
    InvalidHybridPolicy,
    /// The selected backend identity prohibits a known hybrid group.
    HybridGroupUnavailable,
}

pub const recommended_server_groups: []const NamedGroup = if (supportsHybridGroup(.server, .x25519_mlkem768) and supportsHybridGroup(.server, .secp256r1_mlkem768)) &.{ .x25519_mlkem768, .secp256r1_mlkem768 } else if (supportsHybridGroup(.server, .x25519_mlkem768)) &.{.x25519_mlkem768} else if (supportsHybridGroup(.server, .secp256r1_mlkem768)) &.{.secp256r1_mlkem768} else &.{}

src

Hybrid groups a server of this build accepts by default, in server preference order. A server needs no extra keypair for any of them: it encapsulates to whatever share the client sent, so listing every group the backend implements can only turn a classical connection post-quantum. The order puts X25519MLKEM768 first because that is the group peers deploy.

Functions

pub fn supportsCipherSuite(suite: CipherSuite) bool

src

Report whether this build advertises suite.

pub fn supportsCertificateVerifyScheme(scheme: SignatureScheme) bool

src

Report whether this build advertises scheme for CertificateVerify.

pub fn supportsCertificateSignatureScheme(scheme: SignatureScheme) bool

src

Report whether this build accepts scheme in a certificate chain.

pub fn supportsGroup(role: Role, group: NamedGroup) bool

src

Report whether one role can use group with the active backend. An approved-only build answers false for X25519 and every hybrid group.

pub fn supportsHybridGroup(role: Role, group: NamedGroup) bool

src

Report whether one role can use an RFC 10024 group with the active backend. A classical or unknown group is never a hybrid answer.

pub fn validateHybridGroups( role: Role, groups: []const NamedGroup, ) HybridPolicyError!void

src

Validate a borrowed RFC 10024 group list before key generation or wire I/O.

pub fn requiresP384(groups: []const NamedGroup) bool

src

Report whether a group list requires a P-384 keypair.

Types

enum Role

src

Handshake endpoint a capability question applies to. Roles are queried separately because a backend can implement one direction of a group before the other, and a server additionally needs a configured keypair.

Fields

client client
server server

struct Profile

src

One backend's capability table.

Groups are slices, not std.EnumSet(NamedGroup): that enum is non-exhaustive enum(u16), so a set over it would be 8 KiB and would index out of range for a peer group the engine has never heard of. A slice turns an unknown group into a miss, which is the answer negotiation needs.

Fields

cipher_suites: []const CipherSuite

Cipher suites offered in ClientHello (RFC 8446 §4.1.2).

client_groups: []const NamedGroup

Groups usable in a client key share (RFC 8446 §4.2.7, §4.2.8).

server_groups: []const NamedGroup

Groups usable in a server key share (RFC 8446 §4.2.7, §4.2.8).

certificate_verify_schemes: []const SignatureScheme

CertificateVerify schemes (RFC 8446 §4.4.3).

certificate_signature_schemes: []const SignatureScheme

Certificate-chain signature schemes (RFC 8446 §4.4.2.2).

struct HybridPolicy

src

RFC 10024 hybrid negotiation policy for one handshake role.

Fields

supported_groups: []const NamedGroup

Hybrid groups advertised in supported_groups. Caller-owned; the slice must outlive the handshake because HRR reuses it verbatim.

initial_key_share: ?NamedGroup

Optional hybrid key_share sent in ClientHello1. It must also appear in supported_groups. null advertises support without an initial share, allowing a server to select the group through HelloRetryRequest.

Constants

pub const empty: HybridPolicy = .{ .supported_groups = &.{}, .initial_key_share = null }

src

Hybrid negotiation disabled: no advertised groups and no initial share.

pub const recommended: HybridPolicy = …

src
value
if (supportsHybridGroup(.client, .x25519_mlkem768))
        .{ .supported_groups = &.{.x25519_mlkem768}, .initial_key_share = .x25519_mlkem768 }
    else if (supportsHybridGroup(.client, .secp256r1_mlkem768))
        .{ .supported_groups = &.{.secp256r1_mlkem768}, .initial_key_share = .secp256r1_mlkem768 }
    else
        .empty

The default policy: advertise and share the one hybrid group this build implements best. X25519MLKEM768 is the group every deployed stack offers first (RFC 10024 §2), so a client that shares it costs a server nothing to answer. Resolves to .empty only when the backend has no hybrid group at all, which keeps an approved-only build's classical first flight. A caller that wants classical-only key exchange writes .hybrid = .empty explicitly.

Functions

pub fn validate(self: HybridPolicy) HybridPolicyError!void

src

Validate the compiled support, group list, and initial-share relation.

pub fn requiresP384(self: HybridPolicy) bool

src

Report whether this policy requires a P-384 keypair.

enum CipherSuite

src
pub const CipherSuite = @import("cipher_suite.zig").CipherSuite

RFC 8446 Appendix B.4

Fields

aes_128_gcm_sha256 aes_128_gcm_sha256 = 0x1301
chacha20_poly1305_sha256 chacha20_poly1305_sha256 = 0x1303
aes_256_gcm_sha384 aes_256_gcm_sha384 = 0x1302

Functions

pub fn fromWire(value: u16) ?CipherSuite

src

pub fn hash(self: CipherSuite) Hash

src

module client_hello

src

TLS 1.3 ClientHello handshake message encoding.

RFC 8446 §4.1.2

RFC 6066 §3 permits opaque inbound names. tls instead applies one 1–253-octet HostName length policy to encoding, length preflight, and parsing. A null server_name omits SNI. A present empty name is invalid. Callers own DNS label validation and IDNA conversion.

Constants

pub const max_server_name_len: usize = 253

src

RFC 1035 §2.3.4 — a 255-octet DNS wire name permits 253 presentation octets.

pub const Protocols = AlpnProtocols

src

pub const EncodeError = …

src
value
error{
    BufferTooShort,
    /// Server name policy (RFC 6066 §3, RFC 1035 §2.3.4).
    InvalidServerName,
    ServerNameTooLong,
    ExtensionTooLong,
    /// Caller-supplied extension policy (RFC 8446 §4.2).
    ReservedExtension,
    DuplicateExtension,
    /// ALPN ProtocolNameList policy (RFC 7301 §3.1).
    TooManyAlpnBytes,
    EmptyAlpnProtocol,
    AlpnProtocolTooLong,
    /// RFC 10024 hybrid policy, or a group this backend identity prohibits.
    InvalidHybridPolicy,
    HybridGroupUnavailable,
    /// RFC 8449 §4 — RecordSizeLimit is at least 64.
    RecordSizeLimitTooSmall,
}

Errors from encodedLen and encode. Enumerated rather than composed from the contributing modules so a new backend or extension error is a compile error here instead of a silent widening of the public surface.

pub const RetryEncodeError = …

src
value
error{
    BufferTooShort,
    InvalidServerName,
    ServerNameTooLong,
    IdentityTooLong,
    InvalidBinderLength,
    ExtensionTooLong,
    /// `selected_group` is one the caller gave no key for, or the hybrid
    /// policy does not carry a share for it.
    UnsupportedGroup,
    TooManyAlpnBytes,
    EmptyAlpnProtocol,
    AlpnProtocolTooLong,
    InvalidHybridPolicy,
    HybridGroupUnavailable,
    RecordSizeLimitTooSmall,
}

Errors from encodeRetry.

pub const PskEncodeError = …

src
value
error{
    BufferTooShort,
    InvalidServerName,
    ServerNameTooLong,
    IdentityTooLong,
    InvalidBinderLength,
    ExtensionTooLong,
    ReservedExtension,
    DuplicateExtension,
    TooManyAlpnBytes,
    EmptyAlpnProtocol,
    AlpnProtocolTooLong,
    InvalidHybridPolicy,
    HybridGroupUnavailable,
    RecordSizeLimitTooSmall,
}

Errors from encodeWithPsk.

pub const ParseError = …

src
value
error{
    UnexpectedEof,
    InvalidHandshakeType,
    InvalidHandshakeLength,
    InvalidVectorLength,
    InvalidExtensionLength,
    InvalidEnumTag,
    InvalidCompressionMethod,
    DuplicateExtension,
    DuplicateKeyShare,
    MissingExtension,
    UnsupportedTlsVersion,
    UnsupportedKeyShare,
    MalformedKeyShare,
    /// No offered CertificateVerify scheme overlaps this build. RFC 8446
    /// §4.2.3 negotiation failure, distinct from a forbidden peer selection.
    NoCommonSignatureScheme,
    IllegalParameter,
    /// RFC 8449 §4 — RecordSizeLimit is at least 64.
    RecordSizeLimitTooSmall,
    /// `ParseOptions.received` had no slot left.
    ExtensionSinkFull,
}

Errors from parse.

Functions

pub fn encodedLen(params: EncodeParams) EncodeError!usize

src

Wire size of the ClientHello encode produces for params. Preflight with this rather than trusting a buffer size: every rejection encode reports for the same params is reported here first.

pub fn encode(out: []u8, params: EncodeParams) EncodeError![]u8

src

Encode a ClientHello handshake message into out.

Returns the written slice. Feed it into the transcript hash before wrapping it in a TLS record: the transcript covers the handshake header plus body, not the outer record header.

RFC 8446 §4.1.2

pub fn encodeRetry(out: []u8, params: RetryParams) RetryEncodeError!PskEncodeResult

src

Encode ClientHello2 in response to a HelloRetryRequest.

RFC 8446 §4.1.2: the second ClientHello is identical to the first except that key_share carries only a KeyShareEntry for the selected group, and a cookie is echoed when the HelloRetryRequest provided one.

pub fn encodeWithPsk( out: []u8, params: EncodeParams, psk: PskParams, ) PskEncodeError!PskEncodeResult

src

Encode a ClientHello offering a PSK for session resumption. Builds the full message with psk_key_exchange_modes and a pre_shared_key extension (the LAST extension, RFC 8446 §4.2.11) carrying one identity. The binder is left zero-filled: the caller computes it over msg[0..prefix_len] and writes it at msg[binder_offset..][0..binder_len].

RFC 8446 §4.1.3, §4.2.11

pub fn parse(msg: []const u8, opts: ParseOptions) ParseError!Parsed

src

Parse a ClientHello handshake message (RFC 8446 §4.1.2).

Every extension the engine does not handle itself is ignored, as §4.1.2 requires. A protocol built on TLS reads its own extension through opts.allowed_extensions and opts.received instead (QUIC's transport parameters, RFC 9001 §8.2).

pub fn extensionOffset(msg: []const u8, wanted: u16) ?usize

src

Byte offset of the extension entry (type field) for wanted, or null. The PSK binder is computed over everything before the binders vector, so a verifier needs the entry's position, not just its data.

pub fn extension(msg: []const u8, wanted: u16) ?[]const u8

src

The raw extension_data for wanted, or null when the ClientHello does not carry it. The slice borrows msg. Used by callers that require an extension to be present (RFC 8446 §4.2: a server that requires one aborts with missing_extension).

Types

enum EarlyDataOffer

src

P-256 key the layout tests use when P-256 carries the first flight. Whether the ClientHello offers 0-RTT early data (RFC 8446 §4.2.10). An offering ClientHello carries an empty early_data extension and is only valid alongside pre_shared_key.

Fields

none none
offer offer

enum PskKeyExchangeMode

src
pub const PskKeyExchangeMode = enum(u8)

PskKeyExchangeMode (RFC 8446 §4.2.9).

Fields

psk_ke psk_ke = 0
psk_dhe_ke psk_dhe_ke = 1

struct KemShare

src

Optional RFC 10024 §4.1 hybrid key_share for the ClientHello.

Fields

group: NamedGroup
data: []const u8

struct EncodeParams

src

Everything encodedLen, encode, and encodeWithPsk read. The defaults describe the smallest first flight: one X25519 key share, no SNI, no ALPN, no hybrid group, and no caller-supplied extension.

Fields

random: Random
public_key: x25519.PublicKey

The X25519 share. Emitted only when this build advertises X25519, so an approved-only build needs public_key_p256 to carry the first flight.

public_key_p256: ?p256.PublicKey = null
public_key_p384: ?p384.PublicKey = null
server_name: ?[]const u8 = null

Absent omits the server_name extension; a present but empty or over-long name is an error (RFC 6066 §3, RFC 1035 §2.3.4).

alpn_protocols: AlpnProtocols = &.{}
hybrid_groups: []const NamedGroup = &.{}

RFC 10024 §4.1 groups advertised in supported_groups. A group listed without a matching hybrid_share is advertised but not keyed, which is how a HelloRetryRequest is provoked.

hybrid_share: ?KemShare = null
record_size_limit: ?u16 = null

RFC 8449 §4 — the largest TLSInnerPlaintext this client can receive.

extra_extensions: []const extension_type.ExtraExtension = &.{}

Extensions the engine frames verbatim after its own. pre_shared_key stays reserved so a PSK handshake can still append it last (RFC 8446 §4.2.11).

struct RetryPsk

src

PSK fields retained when constructing ClientHello2 after HRR. The binder is emitted as zeroes for the caller to patch through PskEncodeResult.

Fields

identity: []const u8
mode: PskKeyExchangeMode

struct RetryParams

src

Everything encodeRetry reads. selected_group's key from this struct is the one emitted in key_share; the other keys stay out of ClientHello2.

Fields

random: Random
x25519_public_key: x25519.PublicKey

The client's existing ephemeral keys. RFC 8446 §4.1.4 does not require a fresh key for the selected group, so the matching one is reused.

p256_public_key: p256.PublicKey
p384_public_key: ?p384.PublicKey = null
selected_group: NamedGroup
cookie: ?[]const u8 = null

Echoed verbatim from the HelloRetryRequest (RFC 8446 §4.2.2).

server_name: ?[]const u8 = null
alpn_protocols: AlpnProtocols = &.{}
hybrid_groups: []const NamedGroup = &.{}

Must still list the selected group, per RFC 8446 §4.1.2 continuity.

hybrid_share: ?KemShare = null
record_size_limit: ?u16 = null

RFC 8446 §4.1.2 requires the RFC 8449 offer to survive a retry.

psk: ?RetryPsk = null

A compatible PSK stays in ClientHello2 with a recomputed binder. RFC 8446 §4.2.11.2.

struct PskEncodeResult

src

Encoded ClientHello plus the offsets needed to patch its PSK binder. prefix_len covers the message through the identities and excludes the binders list. RFC 8446 §4.2.11.2.

Fields

msg: []u8
prefix_len: usize
binder_offset: usize

struct PskOffer

src

One pre_shared_key offer: the identity's opaque bytes, its obfuscated ticket age, and its binder entry. RFC 8446 §4.2.11: the binders list carries exactly one binder per identity, in offer order. binder.len is the hash output of the PSK's cipher suite (§4.2.11.2: the binder is an HMAC over the transcript hash, Finished-style), so 32 bytes claim SHA-256 and 48 claim SHA-384.

Fields

identity: []const u8
binder: []const u8

struct PskOfferIter

src

Iterator over the parallel (PskIdentity, binder) pairs of a pre_shared_key ext_data (identities list + binders list, RFC 8446 §4.2.11). Yields each offer in offer order.

more

Both readers are bounded to their own vectors: an entry-header read can never consume bytes past the identities-vector end into the binders region. Without that bound, a one-byte-short identities vector let the u16 entry-length read cross into the binders bytes and the vector_end - pos bounds check underflowed usize (#103 review P0/P1).

Fields

identities: wire.Reader
binders: wire.Reader

Constants

pub const Error = …

src
value
error{
        InvalidExtensionLength,
        InvalidVectorLength,
        UnexpectedEof,
    }

Functions

pub fn init(psk_ext: []const u8) Error!PskOfferIter

src

pub fn next(self: *PskOfferIter) Error!?PskOffer

src

struct PskParams

src

The single pre_shared_key offer encodeWithPsk frames.

Fields

mode: PskKeyExchangeMode
identity: []const u8

The ticket bytes of a resumption PSK, or the identity of an external one (RFC 8446 §4.2.11.1, RFC 9257 §4).

obfuscated_ticket_age: u32

(ticket_age + ticket_age_add) mod 2^32 for a resumption PSK.

binder_len: u8

Hash length of the PSK's cipher suite: 32 for SHA-256, 48 for SHA-384.

early_data: EarlyDataOffer = .none

struct ParseOptions

src

What parse keeps beyond the extensions the engine understands itself.

Fields

allowed_extensions: []const extension_type.ExtraExtension = &.{}

Extension types the caller wants the bytes for. The engine ignores any other type it does not handle, as RFC 8446 §4.1.2 requires; only the types listed here are kept. Only .extension_type is read.

received: ?*extension_type.ExtensionSink = null

Caller storage for the allowed extensions the client sent. Slices in the result borrow the input message.

struct Parsed

src

Fields

cipher_suites: []const u8
legacy_session_id: []const u8
signature_schemes: []const u8
signature_schemes_cert: ?[]const u8

RFC 8446 §4.2.3 — signature_algorithms_cert list when sent by the client, or null when omitted (callers fall back to signature_schemes).

server_name: ?[]const u8
alpn_protocols: []const u8
groups: SupportedGroups
public_key: ?x25519.PublicKey
public_key_p256: ?p256.PublicKey
public_key_p384: ?p384.PublicKey
hybrid_key_shares: buffer.Array(ParsedKemKeyShare, 3)

RFC 10024 hybrid key_share values borrowed from the ClientHello.

record_size_limit: ?u16

RFC 8449 §4 — the offered TLSInnerPlaintext receive limit.

offered_extensions: OfferedExtensions

Offered ClientHello extensions tracked for validating server responses.

psk_ext: ?[]const u8

pre_shared_key extension (RFC 8446 §4.2.11), if present. psk_ext points at the full extension ext_data (identities + binders) in the ClientHello buffer; binders_offset is the byte offset within the ClientHello message where the binders list begins (the binder hash covers msg[0..binders_offset]). Null when the client did not offer PSK.

psk_key_exchange_modes: ?[]const u8

psk_key_exchange_modes (RFC 8446 §4.2.9), if present. Slice into the ClientHello buffer (the modes list, after the list-length byte).

offered_early_data: bool

Whether the client offered the early_data extension (0-RTT). RFC 8446 §4.2.10.

extensions: []const extension_type.ExtraExtension

The allowed extensions the client sent, in wire order, borrowed from the ClientHello. Empty unless ParseOptions.received was supplied.

Functions

pub fn init(cipher_suites: []const u8) Parsed

src

A ClientHello with the given cipher-suite vector and every optional extension absent.

pub fn certificateSignatureSchemes(self: Parsed) []const u8

src

RFC 8446 §4.2.3 — effective certificate signature-scheme vector: signature_algorithms_cert when present, else signature_algorithms.

pub fn offersSuite(self: Parsed, suite: CipherSuite) bool

src

pub fn selectAlpn(self: Parsed, server_protocols: []const []const u8) ?[]const u8

src

Return the first server-preferred protocol also present in the client's ALPN ProtocolNameList. Returned slice points at server_protocols, not the ClientHello buffer, so it is stable for server flight encoding.

struct SupportedGroups

src

Fields

set: std.EnumSet(KnownGroup)

Constants

pub const empty: SupportedGroups = .{ .set = .empty }

src

No groups supported.

Functions

pub fn contains(self: SupportedGroups, group: NamedGroup) bool

src

pub fn insert(self: *SupportedGroups, group: NamedGroup) void

src

struct ParsedKemKeyShare

src

RFC 10024 hybrid key_share stored in both ParsedKeyShares and Parsed.

Fields

group: NamedGroup
data: []const u8

module ClientHandshake

src

TLS 1.3 client handshake state machine.

Owns the running transcript hash and drives the handshake message sequence. Does no I/O: the caller feeds in decrypted record bytes and receives bytes to send. RFC 8446 §4, Appendix A.

Constants

pub const max_out_len = frame.max_wire_record_len

src

Largest a single record can be on the wire: header + maximum ciphertext. An output buffer of this size always holds any one record we emit.

pub const OutBuffer = frame.OutBuffer

src

pub const recommended_handshake_storage = 4 * frame.max_plaintext_len

src

Comfortable default for handshake-message reassembly across records.

pub const Storage = buffer.Array(u8, recommended_handshake_storage)

src

pub const HybridPolicyError = capabilities.HybridPolicyError

src

pub const ConfigError = Config.ValidationError

src

pub const StartError = CoreError || error{TicketServerNameMismatch}

src

pub const ServerHelloError = CoreError

src

pub const HelloRetryRequestError = CoreError

src

pub const FlightError = CoreError

src

pub const HandleError = ProcessError || ReceiveError || SendError || error{PendingWrite}

src

pub const AlertError = handshake.AlertError

src

pub const SendError = …

src
value
RecordLayer.EncryptError || error{
    PendingWrite,
    PendingKeyUpdateResponse,
    UnexpectedMessage,
}

pub const ProcessError = …

src
value
frame.ParseError || RecordLayer.DecryptError || CoreError ||
    SendError || ClientFinishedError || alert.ParseError ||
    error{ IncompleteRecord, UnexpectedRecord, UnexpectedMessage, PeerAlert }

pub const ClientFinishedError = …

src
value
SendError || CoreError || error{
    EarlyDataUnsupported,
    SignatureSchemeNotOffered,
}

pub const ReceiveError = …

src
value
RecordLayer.DecryptError || CoreError || alert.ParseError ||
    error{ UnexpectedRecord, PeerAlert }

Functions

pub fn init(config: Config) ClientHandshake

src

pub fn bindStorage(self: *ClientHandshake, storage: StorageBinding) void

src

Bind storage only after a self-referential wrapper reaches its final address.

pub fn deinit(self: *ClientHandshake) void

src

pub fn completeWrite(self: *ClientHandshake) void

src

pub fn state(self: *const ClientHandshake) State

src

pub fn isConnected(self: *const ClientHandshake) bool

src

pub fn isResumed(self: *const ClientHandshake) bool

src

True when the completed handshake resumed via a session ticket PSK (false for full certificate handshakes and external PSK handshakes).

pub fn hasPendingWrite(self: *const ClientHandshake) bool

src

pub fn hasPendingKeyUpdateResponse(self: *const ClientHandshake) bool

src

pub fn lastPeerAlert(self: *const ClientHandshake) ?alert.Alert

src

pub fn trafficSecrets( self: *const ClientHandshake, ) error{NotRetained}!*const traffic_secrets.TrafficSecrets

src

pub fn missingExtension(self: *const ClientHandshake) u16

src

pub fn peerCertificateChain(self: *const ClientHandshake) []const []const u8

src

pub fn selectedAlpnProtocol(self: *const ClientHandshake) ?[]const u8

src

pub fn cipherSuite(self: *const ClientHandshake) CipherSuite

src

pub fn start(self: *ClientHandshake, out: []u8) StartError![]const u8

src

pub fn startWithPsk( self: *ClientHandshake, out: []u8, offer: PskStart, ) StartError![]const u8

src

pub fn processServerHello(self: *ClientHandshake, msg: []const u8) ServerHelloError!void

src

pub fn processHelloRetryRequest( self: *ClientHandshake, msg: []const u8, out: []u8, ) HelloRetryRequestError!?[]const u8

src

pub fn handleRecord(self: *ClientHandshake, record: []u8, out: []u8) HandleError!Event

src

pub fn sendAlert( self: *ClientHandshake, description: alert.Description, out: []u8, ) AlertError![]const u8

src

pub fn maxOutboundPlaintext(self: *const ClientHandshake) usize

src

RFC 8449 §4 — largest application fragment the current TX epoch accepts.

pub fn maxInboundPlaintext(self: *const ClientHandshake) usize

src

RFC 8449 §4 — largest application fragment the current RX epoch accepts.

pub fn sendApplicationData( self: *ClientHandshake, plaintext: []const u8, out: []u8, ) SendError![]const u8

src

pub fn sendPreparedApplicationData( self: *ClientHandshake, plaintext_len: usize, out: []u8, ) SendError![]const u8

src

pub fn sendEarlyData( self: *ClientHandshake, plaintext: []const u8, out: []u8, ) SendError![]const u8

src

pub fn txKtlsInfo(self: *const ClientHandshake) RecordLayer.KtlsInfo

src

pub fn rxKtlsInfo(self: *const ClientHandshake) RecordLayer.KtlsInfo

src

pub fn deriveSessionTicket( self: *const ClientHandshake, nst: NewSessionTicket, ) error{ NoResumptionSecret, TicketIdentityTooLong }!SessionTicket

src

pub fn processFlight( self: *ClientHandshake, payload: []const u8, policy: certificate.Policy, ) FlightError!void

src

pub fn clientFinished(self: *ClientHandshake, out: []u8) ClientFinishedError![]const u8

src

pub fn clientFinishedMessage( self: *ClientHandshake, out: []u8, ) ClientFinishedError![]const u8

src

pub fn receiveRecord(self: *ClientHandshake, record: []u8) ReceiveError!ReceiveEvent

src

pub fn receiveKtlsRecord( self: *ClientHandshake, content_type: frame.ContentType, content: []u8, ) ReceiveError!ReceiveEvent

src

pub fn sendKeyUpdate( self: *ClientHandshake, out: []u8, request: KeyUpdateRequest, ) SendError![]const u8

src

pub fn ratchetKtlsTx( self: *ClientHandshake, request: KeyUpdateRequest, ) SendError!void

src

Types

struct HandshakeReader

src
pub const HandshakeReader = handshake.Reader

Iterates handshake messages packed into one decrypted record payload.

Fields

r: wire.Reader

Functions

pub fn init(buf: []const u8) Reader

src

pub fn next(self: *Reader) error{UnexpectedEof}!?Message

src

Return the next complete handshake message, or null when the payload is drained. On UnexpectedEof, r.end is restored to the start of the partial message so the caller can retain exactly the unfinished suffix for cross-record reassembly.

Types

struct Message

src

Fields

type: Type
raw: []const u8

Full message including the 4-byte handshake header. This is what feeds the transcript hash.

enum HandshakeType

src
pub const HandshakeType = handshake.Type

RFC 8446 §4 — handshake message type. Open enum: unrecognized values pass through the reader untouched; the state machine decides what is unexpected.

Fields

client_hello client_hello = 0x01
server_hello server_hello = 0x02
end_of_early_data end_of_early_data = 0x05
new_session_ticket new_session_ticket = 0x04
encrypted_extensions encrypted_extensions = 0x08
certificate_request certificate_request = 0x0d
certificate certificate = 0x0b
certificate_verify certificate_verify = 0x0f
finished finished = 0x14
key_update key_update = 0x18
message_hash message_hash = 0xfe
_ _

enum KeyUpdateRequest

src
pub const KeyUpdateRequest = handshake.KeyUpdateRequest

RFC 8446 §4.6.3 — whether the KeyUpdate recipient must respond with its own.

Fields

update_not_requested update_not_requested = 0
update_requested update_requested = 1

module NewSessionTicket

src

Named so a caller can spell the type its Event.new_session_ticket arm carries. RFC 8446 §4.6.1. Defined with the event shapes in handshake.zig, because both roles' event types name it.

Constants

pub const max_ticket_lifetime_sec = 7 * 24 * 60 * 60

src

pub const max_nonce_len = std.math.maxInt(u8)

src

pub const EncodeError = …

src
value
error{
    BufferTooShort,
    TicketLifetimeTooLong,
    TicketNonceTooLong,
    EmptyTicket,
    TicketTooLong,
    TicketTooLarge,
    InputAliasesOutput,
}

pub const ParseError = …

src
value
error{
    UnexpectedEof,
    InvalidHandshakeType,
    InvalidHandshakeLength,
    EmptyTicket,
    InvalidExtensionLength,
    DuplicateExtension,
}

Functions

pub fn encode(out: []u8, ticket: NewSessionTicket) EncodeError![]const u8

src

Encode a complete NewSessionTicket handshake message into caller-owned storage. ticket_age_add must be freshly generated for each ticket, and ticket_nonce must be unique across all tickets issued on one connection. The caller owns both inputs.

pub fn parse(msg: []const u8) ParseError!NewSessionTicket

src

Parse a complete NewSessionTicket handshake message including its 4-byte Handshake header. Returned slices borrow msg and are for inspection only.

struct Signer

src
pub const Signer = signature.Signer

Fields

scheme: SignatureScheme
context: *anyopaque
sign: *const fn (context: *anyopaque, msg: []const u8, out: []u8) SignError![]const u8

union CertificateChain

src
pub const CertificateChain = certificate_chain.CertificateChain

Fields

slice: []const []const u8
single: []const u8

Constants

pub const empty: CertificateChain = .{ .slice = &.{} }

src

Functions

pub fn init(certs_der: []const []const u8) CertificateChain

src

pub fn singleCert(cert_der: []const u8) CertificateChain

src

pub fn fromPem( pem: []const u8, der_storage: []u8, chain_storage: [][]const u8, ) PemDecodeError!CertificateChain

src

Decode RFC 7468 CERTIFICATE blocks into caller-owned storage.

more

The returned chain borrows both output buffers. They must outlive every handshake that uses the chain and must not overlap pem. One chain slot is required per block; pem.len bytes always suffice for DER storage. Non-whitespace outside the Base64 alphabet is rejected, and output storage may contain partial data after an error.

pub fn requiredSignatureSchemes( self: CertificateChain, ) certificate.ChainSignatureSchemesError!OfferedCertificateSchemes

src

RFC 8446 §4.2.3, §4.4.2.2 — parse this chain and return the set of signature schemes a peer must accept to verify it.

pub fn matchesSignatureSchemes( self: CertificateChain, offered: OfferedCertificateSchemes, ) bool

src

RFC 8446 §4.2.3, §4.4.2.2 — return true when every validated certificate in this chain carries a signature algorithm present in offered.

pub fn encodedLen(self: CertificateChain, request_context: []const u8) usize

src

Encoded size of this chain's Certificate message. request_context is the value encode will echo, so the size and the frame cannot drift apart. RFC 8446 §4.4.2.

pub fn encode( self: CertificateChain, out: []u8, request_context: []const u8, ) certificate.EncodeError![]const u8

src

Encode this chain as a Certificate message. request_context is empty for a server Certificate and echoes the CertificateRequest context for a client Certificate. RFC 8446 §4.4.2.

struct SessionTicket

src

Caller-owned resumption ticket material derived from a NewSessionTicket. The caller stores these and offers them later in a pre_shared_key extension to resume a session. RFC 8446 §4.6.1, §4.2.11.

Fields

identity: buffer.Array(u8, max_identity_len)

Opaque ticket identity bytes (copied from the NewSessionTicket). The caller owns this storage; tls copies into the fixed-capacity buffer.

psk: buffer.Array(u8, 48)

PSK derived from the resumption_master_secret and the ticket nonce (HKDF-Expand-Label(resumption_master_secret, "resumption", nonce, Hash.length)). RFC 8446 §4.6.1, §7.4/§7.5. Capacity covers SHA-384.

ticket_age_add: u32

RFC 8446 §4.6.1 — ticket_age_add added to the client's view of ticket age to obfuscate it in the pre_shared_key extension.

ticket_lifetime: u32

RFC 8446 §4.6.1 — ticket lifetime in seconds.

max_early_data_size: ?u32

RFC 8446 §4.6.1, §4.2.10 — max_early_data_size from the early_data extension, if present (for 0-RTT policy; #3).

cipher_suite: CipherSuite

Cipher suite of the session that issued this ticket. The PSK binder is computed with this suite's hash (the hash under which the PSK was derived), so the offering client must use the same hash even before the new handshake negotiates a suite. RFC 8446 §4.2.11.2, §7.1.

alpn_protocol: buffer.Array(u8, 255)

ALPN protocol selected in the session that issued this ticket. RFC 8446 §4.2.10 binds 0-RTT acceptance to the ticket's ALPN: when the server accepts early_data, the negotiated ALPN must equal this value. Empty means the issuing session negotiated no ALPN (ALPN protocols are never empty, so empty is unambiguous).

server_name: buffer.Array(u8, 255)

SNI host name authenticated on the issuing connection (RFC 8446 §4.6.1). Empty when the issuing connection sent no SNI.

Constants

pub const max_identity_len = 512

src

Maximum ticket identity accepted from a server. Foreign servers (such as OpenSSL) can emit tickets larger than this library's own 256-byte server issuance cap.

Functions

pub fn init( ticket_age_add: u32, ticket_lifetime: u32, cipher_suite: CipherSuite, max_early_data_size: ?u32, ) SessionTicket

src

A ticket with empty identity, PSK, ALPN, and server_name storage and the given resumption metadata.

pub fn isExpired(self: *const SessionTicket, age_ms: u32) bool

src

True once age_ms reaches the ticket's RFC 8446 §4.6.1 lifetime (clamped to seven days). A zero-lifetime ticket is immediately expired.

pub fn matchesServerName(self: *const SessionTicket, server_name: ?[]const u8) bool

src

RFC 8446 §4.6.1 — a ticket must only be offered to the server identity that issued it. DNS names compare ASCII case-insensitively.

pub fn secureZero(self: *SessionTicket) void

src

Erase the ticket identity, PSK capacity, and metadata. The ticket is invalid after this call.

struct ClientCredentials

src
pub const ClientCredentials = handshake_core.Credentials

Caller-owned client certificate chain and signer for client authentication.

Fields

chain: CertificateChain
signer: signature.Signer
required: signature.OfferedCertificateSchemes

Constants

pub const InitError = certificate.ChainSignatureSchemesError

src

Functions

pub fn init(chain: CertificateChain, signer: signature.Signer) InitError!Credentials

src

RFC 8446 §4.2.3, §4.4.2.2 — validate the configured chain at load or rotation time rather than reparsing its DER for every connection.

struct KeyPairs

src
pub const KeyPairs = handshake_key_pairs.KeyPairs

Fields

x25519: x25519.KeyPair

Only secret_key is meaningful until derived contains .x25519.

p256: p256.KeyPair

Only secret_key is meaningful until derived contains .p256.

p384: ?p384.KeyPair
derived: std.EnumSet(Public)

The public keys that hold their scalar's point. A server can defer one: it stays all zero until deriveFor fills it. Every byte zero reads as nothing derived, so a wiped keypair cannot pass for one whose all-zero keys are real. P-384 is never deferred.

Constants

pub const DeriveError = x25519.Error || p256.Error

src

Functions

pub fn init(x25519_keypair: x25519.KeyPair) p256.Error!KeyPairs

src

Fallible because generating the P-256 half is: the backend can refuse, and a refusal it would repeat is the caller's to handle (shed this handshake), not this function's to hide behind a retry (#88).

pub fn initWithP256( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, ) KeyPairs

src

pub fn initDeferredP256( x25519_keypair: x25519.KeyPair, p256_secret: p256.SecretKey, ) KeyPairs

src

Server only: defer the P-256 public key. It is a fixed-base scalar multiplication (plus the backend's key check), wasted on every client that picks X25519. ServerHandshake derives it when a ClientHello selects a P-256 group. A client must send its shares up front, so ClientHandshake rejects deferred keypairs.

pub fn initDeferred(x25519_secret: x25519.SecretKey, p256_secret: p256.SecretKey) KeyPairs

src

Server only: defer both public keys. The server then pays one fixed-base multiplication, for the group the ClientHello selects, instead of one per group (#136). Same client rule as initDeferredP256.

pub fn deriveFor(self: *KeyPairs, group: NamedGroup) DeriveError!void

src

Derive the deferred public key that group puts on the wire: its own for a classical group, its classical component's for a hybrid. No-op for a key that was never deferred or is derived already.

pub fn initWithP256P384( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, p384_keypair: p384.KeyPair, ) KeyPairs

src

pub fn secureZero(self: *KeyPairs) void

src

Types

enum Public

src

Fields

x25519 x25519
p256 p256

struct HybridPolicy

src
pub const HybridPolicy = capabilities.HybridPolicy

RFC 10024 hybrid negotiation policy for one handshake role.

Fields

supported_groups: []const NamedGroup

Hybrid groups advertised in supported_groups. Caller-owned; the slice must outlive the handshake because HRR reuses it verbatim.

initial_key_share: ?NamedGroup

Optional hybrid key_share sent in ClientHello1. It must also appear in supported_groups. null advertises support without an initial share, allowing a server to select the group through HelloRetryRequest.

Constants

pub const empty: HybridPolicy = .{ .supported_groups = &.{}, .initial_key_share = null }

src

Hybrid negotiation disabled: no advertised groups and no initial share.

pub const recommended: HybridPolicy = …

src
value
if (supportsHybridGroup(.client, .x25519_mlkem768))
        .{ .supported_groups = &.{.x25519_mlkem768}, .initial_key_share = .x25519_mlkem768 }
    else if (supportsHybridGroup(.client, .secp256r1_mlkem768))
        .{ .supported_groups = &.{.secp256r1_mlkem768}, .initial_key_share = .secp256r1_mlkem768 }
    else
        .empty

The default policy: advertise and share the one hybrid group this build implements best. X25519MLKEM768 is the group every deployed stack offers first (RFC 10024 §2), so a client that shares it costs a server nothing to answer. Resolves to .empty only when the backend has no hybrid group at all, which keeps an approved-only build's classical first flight. A caller that wants classical-only key exchange writes .hybrid = .empty explicitly.

Functions

pub fn validate(self: HybridPolicy) HybridPolicyError!void

src

Validate the compiled support, group list, and initial-share relation.

pub fn requiresP384(self: HybridPolicy) bool

src

Report whether this policy requires a P-384 keypair.

struct Config

src

Fields

keypairs: KeyPairs

Fresh ephemeral shares for ClientHello and any hybrid retry.

host_name: ?[]const u8

One source for SNI and the certificate reference identity.

now_sec: i64

Unix time used for certificate validity checks.

random: Random

ClientHello random supplied by the caller.

bundle: ?*const crypto.Certificate.Bundle = null
insecure_no_chain_anchor: bool = false
alpn_protocols: AlpnProtocols = &.{}

Caller-owned ALPN names, retained through a possible retry.

record_size_limit: ?u16 = null

RFC 8449 §4 — offer the largest TLSInnerPlaintext this client can receive.

hybrid: HybridPolicy = .recommended

RFC 10024 hybrid key exchange. .recommended advertises and shares X25519MLKEM768, or .empty for a classical first flight.

reassembly: ?[]u8 = null

Caller-owned storage for handshake messages spanning records.

peer_cert_buffer: ?[]u8 = null

Optional retention of the verified peer chain, leaf first.

credentials: ?ClientCredentials = null

Chain and signer used only when the server requests client authentication.

extra_extensions: []const extension_type.ExtraExtension = &.{}
required_extensions: []const u16 = &.{}
peer_extensions: ?*encrypted_extensions.ExtensionSink = null
traffic_secrets: ?*traffic_secrets.TrafficSecrets = null

Constants

pub const ValidationError = …

src
value
HybridPolicyError ||
        error{ MissingP384KeyPair, RecordSizeLimitTooSmall, RecordSizeLimitTooLarge }

Functions

pub fn validate(self: *const Config) ValidationError!void

src

union PskStart

src
pub const PskStart = union(enum)

A resumption ticket or an externally provisioned PSK. The tag replaces the former early-data boolean and makes the two binder labels unambiguous.

Fields

resumption: Resumption
external: External

Types

struct Resumption

src

Fields

ticket: *const SessionTicket

Borrowed until the handshake reaches .connected or fails: the engine retains slices into ticket for ServerHello and HRR retries.

age_ms: u32

Elapsed milliseconds since this ticket was received (RFC 8446 §4.2.11.1).

early_data: client_hello.EarlyDataOffer = .none

Early data remains opt-in even when the ticket permits it.

struct External

src

Fields

identity: []const u8
psk: []const u8

RFC 9257 §6 requires at least 128 bits.

cipher_suite: CipherSuite

The suite provisions the binder hash.

struct StorageBinding

src

Buffers whose addresses are stable only after an enclosing wrapper is pinned.

Fields

reassembly: ?[]u8 = null
peer_certificate: ?[]u8 = null

enum State

src

Record-adapter view of the core's phase-tagged client state.

Fields

start start
wait_sh wait_sh
wait_ee wait_ee
wait_cert_or_cr wait_cert_or_cr
wait_cert wait_cert
wait_cv wait_cv
wait_finished wait_finished
send_finished send_finished
connected connected

union Event

src
pub const Event = handshake.Event

What a handled inbound record yielded. One shape covers both the handshake and connected phases, for both roles. new_session_ticket is client-role only, because tickets are server-issued. A connected engine returns neither write nor new_session_ticket.

Fields

application_data: []const u8

Decrypted application data (a slice into the caller's record buffer).

write: []const u8

A record that MUST be written to the transport before the engine may be called again — the server's ServerHello, the client's Finished, or a KeyUpdate response from either role. Written into out.

key_update: KeyUpdateEvent

The peer's KeyUpdate ratcheted one or both traffic keys. See KeyUpdateEvent for details. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: the server sent a NewSessionTicket post-handshake. The caller may call deriveSessionTicket to obtain a storable SessionTicket (identity + PSK + age/lifetime). The parsed fields borrow the caller's record buffer; copy what you need before the next handleRecord. RFC 8446 §4.6.1.

none none

Handled internally; nothing for the caller to do.

closed closed

The peer sent close_notify.

union ReceiveEvent

src
pub const ReceiveEvent = handshake.ReceiveEvent

Connected-state receive result. This path owns only RX state, so callers can process inbound records while an unrelated TX record remains in flight.

Fields

application_data: []const u8
key_update: KeyUpdateRequest

The RX key is already ratcheted. For update_requested, the caller MUST send update_not_requested before its next application-data record. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: see Event.new_session_ticket. A server never receives one, because tickets are issued by the server.

none none
closed closed

struct KeyUpdateEvent

src
pub const KeyUpdateEvent = handshake.KeyUpdateEvent

Surfaced when a peer KeyUpdate changes one or both traffic-key epochs. RFC 8446 §4.6.3. For kTLS callers: rx means the kernel RX path is paused (EKEYEXPIRED) until the new key is installed via setsockopt(TLS_RX); tx means the caller must reinstall TLS_TX after writing response and calling completeWrite().

Fields

response: ?[]const u8

Record to send first (the KeyUpdate response), or null if the peer sent update_not_requested and no response is needed. The caller MUST write this to the transport and call completeWrite() before reinstalling TLS_TX. The response is encrypted under the OLD TX key — the engine ratchets TX inside sendKeyUpdate after encryption.

rx: bool

RX traffic key was ratcheted — caller must reinstall TLS_RX.

tx: bool

TX traffic key was ratcheted (we are sending a KeyUpdate response) — caller must reinstall TLS_TX after writing response and calling completeWrite().

enum CompressionMethod

src
pub const CompressionMethod = @import("compression_method.zig").CompressionMethod

Fields

no_compression no_compression = 0
_ _

module errors

src

Coarse classification of the handshake error sets, shared by every integration so there is one exhaustive table rather than one per wrapper.

Constants

pub const HandshakeError = …

src
value
ClientHandshake.StartError ||
    ClientHandshake.HandleError ||
    ServerHandshake.HandleError ||
    ServerFlightError

Every error either handshake role can produce. Used as one classification domain so the table below is written once instead of per role.

pub const ServerFlightError = …

src
value
switch (@typeInfo(
    @typeInfo(@TypeOf(ServerHandshake.sendServerFlightBuffered)).@"fn".return_type.?,
)) {
    .error_union => |u| u.error_set,
    else => @compileError("sendServerFlightBuffered no longer returns an error union"),
}

Functions

pub fn classify(err: HandshakeError) Class

src

Classify one core handshake error.

more

Deliberately exhaustive: no else. Adding a variant to any core handshake error set is a compile error here until someone decides which coarse class the new failure belongs to. That decision is security-relevant — silently reporting a certificate failure as a generic protocol error is exactly the bug this shape prevents — so it does not get a default.

Types

enum Class

src

Coarse failure class. Public error sets are thin projections of this.

Fields

certificate certificate

Peer certificate chain / hostname / signature did not authenticate.

decrypt decrypt

AEAD tag, Finished MAC, or PSK binder mismatch.

alert alert

Peer sent a fatal alert.

protocol protocol

Peer sent something malformed, unexpected, or forbidden.

record_overflow record_overflow

Peer record exceeded the RFC 8446 §5.1 limit.

buffer buffer

Our configured buffers were too small — including undersized client-certificate retention storage (ClientCertificateTooLarge: the leaf DER was verified fine, only the caller's buffer cannot hold it).

options options

Caller-supplied options were unusable.

internal internal

Our fault: backend failure, counter overflow, broken invariant.

no_alpn no_alpn

ALPN offered by both sides with no overlap (server only).

unsupported_suite unsupported_suite

No cipher suite overlap (server only).

missing_credentials missing_credentials

Server credentials missing or unusable (server only).

client_certificate client_certificate

Client certificate required or unsupported by policy (server only). An oversized-but-verified leaf is .buffer, not here: the failure is the caller's retention storage, not the peer's certificate.

module EstablishedSession

src

The compact post-handshake server engine, constructed only by ServerHandshake.extractEstablished (#115).

Constants

pub const ReceiveError = handshake.ReceiveError

src

pub const SendError = handshake.SendError

src

pub const AlertError = handshake.AlertError

src

pub const HandleError = ReceiveError || SendError

src

Functions

pub fn init(rx: RecordLayer, tx: RecordLayer, suite: Suite) EstablishedSession

src

A connected session over the given record layers and traffic-secret suite, with no KeyUpdate in flight and nothing pending. ServerHandshake calls this only from extractEstablished; construct one that way, not directly.

pub fn deinit(self: *EstablishedSession) void

src

Release the backend AEAD contexts and zero every secret this engine owns.

pub fn hasPendingWrite(self: *const EstablishedSession) bool

src

pub fn completeWrite(self: *EstablishedSession) void

src

pub fn hasPendingKeyUpdateResponse(self: *const EstablishedSession) bool

src

RFC 8446 §4.6.3 — true after receiving update_requested until the required update_not_requested response has been generated.

pub fn lastPeerAlert(self: *const EstablishedSession) ?alert.Alert

src

Most recent non-close_notify peer alert, or null.

pub fn handle(self: *EstablishedSession, record: []u8, out: []u8) HandleError!Event

src

Process one complete encrypted record: decrypt, classify, and — for an inbound update_requested KeyUpdate — produce the response record in out encrypted under the old TX key (RFC 8446 §4.6.3). The same connected handleRecord path the handshake engine runs.

pub fn receive(self: *EstablishedSession, record: []u8) ReceiveError!ReceiveEvent

src

Decrypt and classify one complete record. RX-only: safe while an unrelated TX record is in flight. A received update_requested KeyUpdate sets the response obligation (hasPendingKeyUpdateResponse) without producing the response — the caller serializes it against its own TX.

pub fn maxOutboundPlaintext(self: *const EstablishedSession) usize

src

RFC 8449 §4 — largest application fragment the current TX epoch accepts.

pub fn maxInboundPlaintext(self: *const EstablishedSession) usize

src

RFC 8449 §4 — largest application fragment the current RX epoch accepts.

pub fn sendApplicationData( self: *EstablishedSession, plaintext: []const u8, out: []u8, ) SendError![]u8

src

Serialize and encrypt one application-data record under the current TX key. Refuses while a KeyUpdate response is owed (RFC 8446 §4.6.3).

pub fn sendAlert( self: *EstablishedSession, description: alert.Description, out: []u8, ) AlertError![]const u8

src

Send an alert through the established record path (encrypted). close_notify is a warning-level alert; everything else is fatal (RFC 8446 §6.1, §6.2).

pub fn sendKeyUpdate( self: *EstablishedSession, out: []u8, request: KeyUpdateRequest, ) SendError![]const u8

src

Serialize, encrypt, and send a KeyUpdate; then ratchet the TX key so the update takes effect for subsequent records (RFC 8446 §4.6.3).

pub fn ratchetTx(self: *EstablishedSession, request: KeyUpdateRequest) SendError!void

src

Derive and install the next TX traffic key after an external record layer has sent a KeyUpdate under the old key. request must match that record; update_not_requested also satisfies any owed response.

Types

union Event

src
pub const Event = handshake.Event

Connected-state event shapes shared with the handshake engines.

Fields

application_data: []const u8

Decrypted application data (a slice into the caller's record buffer).

write: []const u8

A record that MUST be written to the transport before the engine may be called again — the server's ServerHello, the client's Finished, or a KeyUpdate response from either role. Written into out.

key_update: KeyUpdateEvent

The peer's KeyUpdate ratcheted one or both traffic keys. See KeyUpdateEvent for details. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: the server sent a NewSessionTicket post-handshake. The caller may call deriveSessionTicket to obtain a storable SessionTicket (identity + PSK + age/lifetime). The parsed fields borrow the caller's record buffer; copy what you need before the next handleRecord. RFC 8446 §4.6.1.

none none

Handled internally; nothing for the caller to do.

closed closed

The peer sent close_notify.

union ReceiveEvent

src
pub const ReceiveEvent = handshake.ReceiveEvent

Connected-state receive result. This path owns only RX state, so callers can process inbound records while an unrelated TX record remains in flight.

Fields

application_data: []const u8
key_update: KeyUpdateRequest

The RX key is already ratcheted. For update_requested, the caller MUST send update_not_requested before its next application-data record. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: see Event.new_session_ticket. A server never receives one, because tickets are issued by the server.

none none
closed closed

enum KeyUpdateRequest

src
pub const KeyUpdateRequest = handshake.KeyUpdateRequest

RFC 8446 §4.6.3 — whether the KeyUpdate recipient must respond with its own.

Fields

update_not_requested update_not_requested = 0
update_requested update_requested = 1

module extension_type

src

TLS extension type registry values.

RFC 8446 §4.2 and related extension RFCs.

Constants

pub const ExtraExtensionError = …

src
value
error{
    /// The caller supplied a type the engine emits itself.
    ReservedExtension,
    /// The caller supplied the same type twice.
    DuplicateExtension,
    /// extension_data longer than the u16 length field allows.
    ExtensionTooLong,
}

pub const OfferedExtensions = std.EnumSet(OfferedExtension)

src

pub const DuplicateExtensionError = error{ InvalidExtensionLength, DuplicateExtension }

src

Functions

pub fn validateExtraExtensions( extras: []const ExtraExtension, ) ExtraExtensionError!void

src

pub fn extraExtensionsLen(extras: []const ExtraExtension) ExtraExtensionError!usize

src

Wire size of the supplied extensions: type, length, and data each time.

pub fn rejectDuplicateExtensions(extensions: []const u8) DuplicateExtensionError!void

src

Types

struct ExtraExtension

src

An extension the caller supplies verbatim. The engine frames it, rejects a duplicate or reserved type, and otherwise treats data as opaque bytes: a protocol built on TLS (QUIC's transport parameters, for instance) owns the meaning. RFC 8446 §4.2.

Fields

data: []const u8

struct ExtensionSink

src

Caller-owned slots for the extensions a peer sent. A parser appends what the caller allowed, in wire order; the data slices borrow the parsed message.

Fields

items: []ExtraExtension
len: usize

Functions

pub fn init(items: []ExtraExtension) ExtensionSink

src

pub fn append(self: *ExtensionSink, extra: ExtraExtension) bool

src

pub fn slice(self: *const ExtensionSink) []const ExtraExtension

src

enum OfferedExtension

src

Fields

server_name server_name
record_size_limit record_size_limit
early_data early_data

enum ExtensionType

src
pub const ExtensionType = enum(u16)

Fields

server_name server_name = 0x0000
status_request status_request = 0x0005
supported_groups supported_groups = 0x000a
signature_algorithms signature_algorithms = 0x000d
heartbeat heartbeat = 0x000f
alpn alpn = 0x0010
status_request_v2 status_request_v2 = 0x0011
signed_certificate_timestamp signed_certificate_timestamp = 0x0012
padding padding = 0x0015
record_size_limit record_size_limit = 0x001c
pre_shared_key pre_shared_key = 0x0029
early_data early_data = 0x002a
supported_versions supported_versions = 0x002b
cookie cookie = 0x002c
psk_key_exchange_modes psk_key_exchange_modes = 0x002d
certificate_authorities certificate_authorities = 0x002f
oid_filters oid_filters = 0x0030
post_handshake_auth post_handshake_auth = 0x0031
signature_algorithms_cert signature_algorithms_cert = 0x0032
key_share key_share = 0x0033
_ _

Functions

pub fn isGrease(self: ExtensionType) bool

src

enum ExtensionType

src
pub const ExtensionType = @import("extension_type.zig").ExtensionType

Fields

server_name server_name = 0x0000
status_request status_request = 0x0005
supported_groups supported_groups = 0x000a
signature_algorithms signature_algorithms = 0x000d
heartbeat heartbeat = 0x000f
alpn alpn = 0x0010
status_request_v2 status_request_v2 = 0x0011
signed_certificate_timestamp signed_certificate_timestamp = 0x0012
padding padding = 0x0015
record_size_limit record_size_limit = 0x001c
pre_shared_key pre_shared_key = 0x0029
early_data early_data = 0x002a
supported_versions supported_versions = 0x002b
cookie cookie = 0x002c
psk_key_exchange_modes psk_key_exchange_modes = 0x002d
certificate_authorities certificate_authorities = 0x002f
oid_filters oid_filters = 0x0030
post_handshake_auth post_handshake_auth = 0x0031
signature_algorithms_cert signature_algorithms_cert = 0x0032
key_share key_share = 0x0033
_ _

Functions

pub fn isGrease(self: ExtensionType) bool

src

module frame

src

TLS 1.3 record layer.

more

Implements wire format parsing and encoding for TLS records per RFC 8446 §5. No crypto here — just framing. AEAD encrypt/decrypt is a separate layer.

Record layout on the wire:

ContentType (1 byte) ProtocolVersion (2 bytes, always 0x0303 in TLS 1.3) length (2 bytes, big-endian) fragment (length bytes)

After the handshake, all records are TLSCiphertext: the ContentType byte is always application_data (23), and the real type is smuggled inside the AEAD plaintext as TLSInnerPlaintext.

Constants

pub const max_plaintext_len = 1 << 14

src

RFC 8446 §5.1 — maximum plaintext fragment length.

pub const max_ciphertext_len = max_plaintext_len + 256

src

RFC 8446 §5.2 — maximum ciphertext length (plaintext + AEAD overhead). "MUST NOT exceed 2^14 + 256 bytes."

pub const header_len = 5

src

Wire size of a record header.

pub const max_wire_record_len = header_len + max_ciphertext_len

src

Largest a single record can be on the wire: header + maximum ciphertext. An output buffer of this size always holds any one record we emit.

pub const OutBuffer = buffer.Array(u8, max_wire_record_len)

src

pub const ParseError = …

src
value
error{
    /// Fewer than 5 bytes available.
    BufferTooShort,
    /// length field exceeds the RFC 8446 §5.2 maximum.
    RecordTooLarge,
}

Functions

pub fn parseHeader(buf: []const u8) ParseError!Header

src

Parse the 5-byte record header from the front of buf.

Returns the parsed header value. The fragment begins at buf[header_len..] and is header.length() bytes long — caller ensures that many bytes are available.

RFC 8446 §5.1, §5.2

Types

enum ContentType

src
pub const ContentType = enum(u8)

RFC 8446 Appendix B.1

Fields

invalid invalid = 0
change_cipher_spec change_cipher_spec = 20
alert alert = 21
handshake handshake = 22
application_data application_data = 23
_ _

Unknown values are valid on the wire; ignore or alert as appropriate.

struct Header

src
pub const Header = extern struct

A TLS record header — exactly the 5-byte wire layout.

Uses extern struct with [2]u8 for big-endian u16 fields so the in-memory layout matches the wire byte-for-byte. Use legacyVersion() and length() to read the u16 fields in native byte order.

Fields

content_type: ContentType
legacy_version_be: [2]u8

Always 0x0303 on the wire for TLS 1.3. Frozen for middlebox compatibility; actual version negotiation happens in the supported_versions extension. Not exposed — no caller should branch on this.

length_be: [2]u8

Big-endian payload length. Use length() to read as native u16.

Functions

pub inline fn length(self: Header) u16

src

pub inline fn write(self: Header, out: *[header_len]u8) void

src

pub fn init(content_type: ContentType, len: u16) Header

src

module handshake

src

The connected record-path core shared by both handshake roles and the extracted EstablishedSession: the connected event shapes (Event, ReceiveEvent, KeyUpdateEvent), the shared error sets, and the record/KeyUpdate/alert helpers behind every connected entry point.

Constants

pub const max_post_handshake_messages = max_post_handshake_key_updates

src

pub const SendError = …

src
value
RecordLayer.EncryptError || error{
    PendingWrite,
    PendingKeyUpdateResponse,
}

pub const key_update_body_len = 1

src

RFC 8446 §4.6.3 — KeyUpdate is a 4-byte handshake header plus a 1-byte request body, so a fixed 5-byte buffer reassembles one fragmented across records (§5.1).

pub const key_update_total_len = handshake_header_len + key_update_body_len

src

pub const ReceiveError = RecordLayer.DecryptError || alert.ParseError || error{ UnexpectedEof, UnexpectedRecord, UnexpectedMessage, IllegalParameter } || error{ TooManyKeyUpdates, PeerAlert }

src

pub const AlertError = RecordLayer.EncryptError || error{ BufferTooShort, PendingWrite }

src

Functions

pub fn validateChangeCipherSpec(fragment: []const u8) error{UnexpectedRecord}!void

src

pub fn decryptProtected( rx: *RecordLayer, record: []u8, ) (RecordLayer.DecryptError || error{UnexpectedMessage})!RecordLayer.DecryptedRecord

src

pub fn sendApplicationData(self: anytype, plaintext: []const u8, out: []u8) SendError![]u8

src

pub fn sendPreparedApplicationData( self: anytype, plaintext_len: usize, out: []u8, ) SendError![]u8

src

pub fn sendKeyUpdate( comptime sender: KeyUpdateSender, self: anytype, out: []u8, request: KeyUpdateRequest, ) SendError![]u8

src

pub fn ratchetKtlsTx( comptime sender: KeyUpdateSender, self: anytype, request: KeyUpdateRequest, ) SendError!void

src

Advance the send traffic secret after an external TLS record layer has sent a KeyUpdate under the old key. request describes the record already sent. The caller must serialize the send and subsequent key installation around this call. RFC 8446 §4.6.3.

pub fn serverReceivePlaintext( self: anytype, content_type: frame.ContentType, content: []u8, ) ReceiveError!ReceiveEvent

src

Classify one decrypted connected-state record payload. Server role: the connected receive path shared by ServerHandshake and the extracted EstablishedSession. Application data resets the consecutive-KeyUpdate counter (the flood cap); handshake content must be exactly one KeyUpdate aligned to the record boundary (§5.1); alerts either close (close_notify, §6.1) or surface as PeerAlert (§6.2).

pub fn serverReceiveRecord(self: anytype, record: []u8) ReceiveError!ReceiveEvent

src

Decrypt and classify one complete connected-state record. Server role; mutates RX only, so an unrelated TX record may still be in flight.

pub fn serverHandleConnected( self: anytype, record: []u8, out: []u8, ) (ReceiveError || SendError)!Event

src

The server's connected handleRecord path: receive one record and, for an inbound update_requested KeyUpdate, produce the response record in out (RFC 8446 §4.6.3), encrypted under the old TX key.

pub fn sendEstablishedAlert( self: anytype, description: alert.Description, out: []u8, ) AlertError![]const u8

src

Serialize and encrypt one alert under the current TX key. close_notify is warning-level; every other description is fatal (RFC 8446 §6.1, §6.2).

pub fn parseKeyUpdate(msg: []const u8) error{ UnexpectedEof, IllegalParameter }!KeyUpdateRequest

src

Parse a KeyUpdate handshake message (4-byte header + 1-byte request).

Types

module NewSessionTicket

src

One parsed NewSessionTicket post-handshake message. RFC 8446 §4.6.1. Named here because Event.new_session_ticket and ReceiveEvent.new_session_ticket carry it, and both shapes are defined here.

Constants

pub const max_ticket_lifetime_sec = 7 * 24 * 60 * 60

src

pub const max_nonce_len = std.math.maxInt(u8)

src

pub const EncodeError = …

src
value
error{
    BufferTooShort,
    TicketLifetimeTooLong,
    TicketNonceTooLong,
    EmptyTicket,
    TicketTooLong,
    TicketTooLarge,
    InputAliasesOutput,
}

pub const ParseError = …

src
value
error{
    UnexpectedEof,
    InvalidHandshakeType,
    InvalidHandshakeLength,
    EmptyTicket,
    InvalidExtensionLength,
    DuplicateExtension,
}

Functions

pub fn encode(out: []u8, ticket: NewSessionTicket) EncodeError![]const u8

src

Encode a complete NewSessionTicket handshake message into caller-owned storage. ticket_age_add must be freshly generated for each ticket, and ticket_nonce must be unique across all tickets issued on one connection. The caller owns both inputs.

pub fn parse(msg: []const u8) ParseError!NewSessionTicket

src

Parse a complete NewSessionTicket handshake message including its 4-byte Handshake header. Returned slices borrow msg and are for inspection only.

enum KeyUpdateSender

src

Fields

client client
server server

union Event

src
pub const Event = union(enum)

What a handled inbound record yielded. One shape covers both the handshake and connected phases, for both roles. new_session_ticket is client-role only, because tickets are server-issued. A connected engine returns neither write nor new_session_ticket.

Fields

application_data: []const u8

Decrypted application data (a slice into the caller's record buffer).

write: []const u8

A record that MUST be written to the transport before the engine may be called again — the server's ServerHello, the client's Finished, or a KeyUpdate response from either role. Written into out.

key_update: KeyUpdateEvent

The peer's KeyUpdate ratcheted one or both traffic keys. See KeyUpdateEvent for details. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: the server sent a NewSessionTicket post-handshake. The caller may call deriveSessionTicket to obtain a storable SessionTicket (identity + PSK + age/lifetime). The parsed fields borrow the caller's record buffer; copy what you need before the next handleRecord. RFC 8446 §4.6.1.

none none

Handled internally; nothing for the caller to do.

closed closed

The peer sent close_notify.

union ReceiveEvent

src
pub const ReceiveEvent = union(enum)

Connected-state receive result. This path owns only RX state, so callers can process inbound records while an unrelated TX record remains in flight.

Fields

application_data: []const u8
key_update: KeyUpdateRequest

The RX key is already ratcheted. For update_requested, the caller MUST send update_not_requested before its next application-data record. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: see Event.new_session_ticket. A server never receives one, because tickets are issued by the server.

none none
closed closed

struct KeyUpdateEvent

src

Surfaced when a peer KeyUpdate changes one or both traffic-key epochs. RFC 8446 §4.6.3. For kTLS callers: rx means the kernel RX path is paused (EKEYEXPIRED) until the new key is installed via setsockopt(TLS_RX); tx means the caller must reinstall TLS_TX after writing response and calling completeWrite().

Fields

response: ?[]const u8

Record to send first (the KeyUpdate response), or null if the peer sent update_not_requested and no response is needed. The caller MUST write this to the transport and call completeWrite() before reinstalling TLS_TX. The response is encrypted under the OLD TX key — the engine ratchets TX inside sendKeyUpdate after encryption.

rx: bool

RX traffic key was ratcheted — caller must reinstall TLS_RX.

tx: bool

TX traffic key was ratcheted (we are sending a KeyUpdate response) — caller must reinstall TLS_TX after writing response and calling completeWrite().

enum Type

src
pub const Type = enum(u8)

RFC 8446 §4 — handshake message type. Open enum: unrecognized values pass through the reader untouched; the state machine decides what is unexpected.

Fields

client_hello client_hello = 0x01
server_hello server_hello = 0x02
end_of_early_data end_of_early_data = 0x05
new_session_ticket new_session_ticket = 0x04
encrypted_extensions encrypted_extensions = 0x08
certificate_request certificate_request = 0x0d
certificate certificate = 0x0b
certificate_verify certificate_verify = 0x0f
finished finished = 0x14
key_update key_update = 0x18
message_hash message_hash = 0xfe
_ _

enum KeyUpdateRequest

src
pub const KeyUpdateRequest = enum(u8)

RFC 8446 §4.6.3 — whether the KeyUpdate recipient must respond with its own.

Fields

update_not_requested update_not_requested = 0
update_requested update_requested = 1

enum KeyUpdateObligation

src
pub const KeyUpdateObligation = enum(u8)

Fields

none none
response_owed response_owed

struct Reader

src

Iterates handshake messages packed into one decrypted record payload.

Fields

r: wire.Reader

Functions

pub fn init(buf: []const u8) Reader

src

pub fn next(self: *Reader) error{UnexpectedEof}!?Message

src

Return the next complete handshake message, or null when the payload is drained. On UnexpectedEof, r.end is restored to the start of the partial message so the caller can retain exactly the unfinished suffix for cross-record reassembly.

Types

struct Message

src

Fields

type: Type
raw: []const u8

Full message including the 4-byte handshake header. This is what feeds the transcript hash.

module hkdf

src

TLS 1.3 HKDF key derivation.

HKDF (RFC 5869) over hmac.zig and the libcrypto-backed SHA-2 types in crypto/sha2.zig (#138), with TLS 1.3-specific label expansion per RFC 8446 §7.1 and §7.3.

Constants

pub const HkdfSha256 = Hkdf(sha2.Sha256, crypto.hash.sha2.Sha256)

src

TLS_AES_128_GCM_SHA256 and TLS_CHACHA20_POLY1305_SHA256.

pub const HkdfSha384 = Hkdf(sha2.Sha384, crypto.hash.sha2.Sha384)

src

TLS_AES_256_GCM_SHA384.

Types

enum PskKind

src

The provision source that selects the binder label in RFC 8446 §7.1.

Fields

external external
resumption resumption

type fn Hkdf

src
pub fn Hkdf(comptime Hash: type, comptime ComptimeHash: type) type

Construct the TLS 1.3 schedule over a runtime and comptime hash pair. A libcrypto backend supplies its runtime hash (#138). Native supplies std's implementation. The comptime hash must match because libcrypto cannot run during compilation.

Constants

pub const prk_len = Hash.digest_length

src

Length of the pseudorandom key and all derived secrets.

pub const Prk = stdx.mem.Array(prk_len)

src

pub const TranscriptHash = stdx.mem.Array(prk_len)

src

pub const TrafficSecret = stdx.mem.Array(prk_len)

src

pub const FinishedKey = stdx.mem.Array(prk_len)

src

pub const Keyed = hmac.Hmac(Hash)

src

HMAC keyed by one secret. Every derivation below that takes a *const Keyed reuses its pad states (#138). A Keyed is a secret: stack only, wiped with secureZero in a defer.

pub const early_secret: Prk = …

src
value
blk: {
            @setEvalBranchQuota(100_000);
            var out: Prk = undefined;
            ComptimeHmac.create(&out.data, prk_zero, prk_zero);
            break :blk out;
        }

EarlySecret for a full handshake with no PSK. Salt and IKM are both zero — comptime constant per RFC 8446 §7.1.

Functions

pub fn extract(salt: []const u8, ikm: []const u8) Prk

src

RFC 8446 §7.1 — HKDF-Extract.

pub fn expandLabel( out: []u8, comptime label: []const u8, context: []const u8, prk: Prk, ) void

src

RFC 8446 §7.1 — HKDF-Expand-Label.

Derives out.len bytes from prk using a TLS 1.3 structured label. label must be a comptime string (all TLS 1.3 labels are literals). context is runtime — typically a transcript hash or empty.

pub fn expandLabelKeyed( out: []u8, comptime label: []const u8, context: []const u8, key: *const Keyed, ) void

src

HKDF-Expand-Label under a secret that is already keyed.

pub inline fn pskEarlySecret(psk: []const u8) Prk

src

RFC 8446 §7.1 — EarlySecret for a PSK or resumption handshake.

pub fn deriveSecret( secret: Prk, comptime label: []const u8, transcript_hash: *const TranscriptHash, ) Prk

src

RFC 8446 §7.1 — Derive-Secret.

Expands secret using label and a transcript hash as context. Output is always prk_len bytes (the hash output length).

pub fn deriveSecretKeyed( key: *const Keyed, comptime label: []const u8, transcript_hash: *const TranscriptHash, ) Prk

src

Derive-Secret under a secret that is already keyed.

pub fn handshakeSecret(early: Prk, dhe: []const u8) Prk

src

RFC 8446 §7.1 — HandshakeSecret.

Mixes the DHE shared secret into the key schedule. dhe is the raw ECDH output: 32 bytes for X25519/P-256, 48 for P-384. The key exchange layer owns the sizing; the key schedule just extracts over whatever bytes it is given.

pub fn handshakeSecretFor(psk: ?[]const u8, dhe: []const u8) Prk

src

RFC 8446 §7.1 — HandshakeSecret from the negotiated PSK, or from none. Without a PSK the "derived" salt is early_derived, so only the extract runs.

pub fn masterSecret(handshake: Prk) Prk

src

RFC 8446 §7.1 — MasterSecret.

No new key material at this stage; IKM is zero.

pub inline fn externalBinderKey(early: Prk) FinishedKey

src

pub inline fn resumptionBinderKey(early: Prk) FinishedKey

src

pub inline fn binderKey(early: Prk, kind: PskKind) FinishedKey

src

pub inline fn clientEarlyTrafficSecret( early: Prk, transcript_hash: *const TranscriptHash, ) TrafficSecret

src

pub inline fn earlyExporterMasterSecret( early: Prk, transcript_hash: *const TranscriptHash, ) Prk

src

pub inline fn clientHandshakeTrafficSecret( handshake: Prk, transcript_hash: *const TranscriptHash, ) TrafficSecret

src

pub inline fn serverHandshakeTrafficSecret( handshake: Prk, transcript_hash: *const TranscriptHash, ) TrafficSecret

src

pub inline fn clientApplicationTrafficSecret( master: Prk, transcript_hash: *const TranscriptHash, ) TrafficSecret

src

pub inline fn serverApplicationTrafficSecret( master: Prk, transcript_hash: *const TranscriptHash, ) TrafficSecret

src

pub inline fn resumptionMasterSecret( master: Prk, transcript_hash: *const TranscriptHash, ) Prk

src

pub fn resumptionPsk(resumption_master: Prk, ticket_nonce: []const u8) Prk

src

pub inline fn nextTrafficSecret(secret: TrafficSecret) TrafficSecret

src

RFC 8446 §7.2 — next-generation application traffic secret. application_traffic_secret_N+1 = HKDF-Expand-Label(secret_N, "traffic upd", "", Hash.length)

pub fn makeRecordLayer(key: CipherSuite, prk: TrafficSecret) aead.Error!RecordLayer

src

Derive both the write key and IV from a traffic secret and return a ready-to-use RecordLayer. key selects the AEAD at runtime (the negotiated cipher suite), so a single arm serves all suites of its hash (e.g. SHA-256 covers AES-128-GCM and ChaCha20-Poly1305).

pub fn makeRecordLayerAndFinishedKey( key: CipherSuite, prk: TrafficSecret, finished_key: *FinishedKey, ) aead.Error!RecordLayer

src

makeRecordLayer plus the RFC 8446 §4.4.4 finished key, for a handshake traffic secret: three expands under one keying.

pub inline fn finishedKey(prk: TrafficSecret) FinishedKey

src

RFC 8446 §4.4.4 — derive the finished key from a traffic secret.

pub fn binder( finished_key: FinishedKey, transcript_hash: *const TranscriptHash, ) [prk_len]u8

src

RFC 8446 §4.2.11.2 — compute a PSK binder: HMAC(finished_key, transcript_hash) over the truncated ClientHello prefix. The binder key is resumptionBinderKey(pskEarlySecret(psk)); the finished_key is finishedKey(binder_key). transcript_hash is Hash(prefix).

pub inline fn trafficKey( comptime key: CipherSuite, prk: TrafficSecret, ) @FieldType(aead.Aead, @tagName(key))

src

RFC 8446 §7.3 — derive the write key from a traffic secret.

pub inline fn trafficIv(prk: TrafficSecret) Iv

src

RFC 8446 §7.3 — derive the write IV from a traffic secret. Always 12 bytes for all TLS 1.3 cipher suites.

module io

src

Blocking socket adapter for the Sans-I/O drive loop.

more

The engine consumes and produces byte slices; the caller owns the transport. Every caller driving a TLS connection over a blocking TCP socket writes the same two loops, so they live here. The engine itself never names std.Io — this module is a leaf that consumers opt into, and Zig's lazy compilation keeps it out of builds that don't.

Reads go straight to the socket, not through Io.Reader: readSliceShort loops until the destination is full, and peek/take hand out slices of the Reader's internal buffer, which forces a copy into the caller-owned RecordBuffer. One read lands bytes directly in rb.writable() — zero copies, one syscall. Writes loop on short writev counts directly for the same reason: Io.Writer exists to batch small writes, and a TLS record should reach the socket immediately.

Functions

pub fn fill(io: Io, stream: Io.net.Stream, rb: *RecordBuffer) !usize

src

Read once into the buffer's writable region and report the bytes to it. Returns the byte count; 0 means the peer closed the transport.

pub fn writeAll(io: Io, stream: Io.net.Stream, bytes: []const u8) !void

src

Write all bytes, looping on short writes.

module kex

src

TLS 1.3 named group identifiers and fixed wire sizes.

RFC 8446 §4.2.7, §4.2.8 and RFC 10024 §4, §7.

Constants

pub const p256 = ec_kex.p256

src

The two NIST curves, instantiated once from the shared factory in ec_kex.zig. The registry below reads their wire sizes from here.

pub const p384 = ec_kex.p384

src

Types

enum ComponentOrder

src

Fields

mlkem_first mlkem_first
classical_first classical_first

struct HybridSpec

src

Fields

classical_group: NamedGroup
parameter_set: ParameterSet
component_order: ComponentOrder

enum NamedGroup

src
pub const NamedGroup = enum(u16)

Non-exhaustive so unknown peer groups parse without UB and are rejected by negotiation rather than crashing.

Fields

x25519 x25519 = 0x001d
secp256r1 secp256r1 = 0x0017
secp384r1 secp384r1 = 0x0018
secp256r1_mlkem768 secp256r1_mlkem768 = 0x11eb
x25519_mlkem768 x25519_mlkem768 = 0x11ec
secp384r1_mlkem1024 secp384r1_mlkem1024 = 0x11ed
_ _

Functions

pub fn publicKeyLen(self: NamedGroup) ?u16

src

Client KeyShareEntry key_exchange length for an implemented group.

pub fn serverKeyShareLen(self: NamedGroup) ?u16

src

Server KeyShareEntry key_exchange length for an implemented group.

pub fn sharedSecretLen(self: NamedGroup) ?u8

src

pub fn hybridSpec(self: NamedGroup) ?HybridSpec

src

struct KeyPairs

src
pub const KeyPairs = @import("handshake_key_pairs.zig").KeyPairs

Caller-owned ephemeral keypairs. handshake_core.Client.useKeypairs, startEncoded, and handshake_core.Server.useKeypairs take this type.

Fields

x25519: x25519.KeyPair

Only secret_key is meaningful until derived contains .x25519.

p256: p256.KeyPair

Only secret_key is meaningful until derived contains .p256.

p384: ?p384.KeyPair
derived: std.EnumSet(Public)

The public keys that hold their scalar's point. A server can defer one: it stays all zero until deriveFor fills it. Every byte zero reads as nothing derived, so a wiped keypair cannot pass for one whose all-zero keys are real. P-384 is never deferred.

Constants

pub const DeriveError = x25519.Error || p256.Error

src

Functions

pub fn init(x25519_keypair: x25519.KeyPair) p256.Error!KeyPairs

src

Fallible because generating the P-256 half is: the backend can refuse, and a refusal it would repeat is the caller's to handle (shed this handshake), not this function's to hide behind a retry (#88).

pub fn initWithP256( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, ) KeyPairs

src

pub fn initDeferredP256( x25519_keypair: x25519.KeyPair, p256_secret: p256.SecretKey, ) KeyPairs

src

Server only: defer the P-256 public key. It is a fixed-base scalar multiplication (plus the backend's key check), wasted on every client that picks X25519. ServerHandshake derives it when a ClientHello selects a P-256 group. A client must send its shares up front, so ClientHandshake rejects deferred keypairs.

pub fn initDeferred(x25519_secret: x25519.SecretKey, p256_secret: p256.SecretKey) KeyPairs

src

Server only: defer both public keys. The server then pays one fixed-base multiplication, for the group the ClientHello selects, instead of one per group (#136). Same client rule as initDeferredP256.

pub fn deriveFor(self: *KeyPairs, group: NamedGroup) DeriveError!void

src

Derive the deferred public key that group puts on the wire: its own for a classical group, its classical component's for a hybrid. No-op for a key that was never deferred or is derived already.

pub fn initWithP256P384( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, p384_keypair: p384.KeyPair, ) KeyPairs

src

pub fn secureZero(self: *KeyPairs) void

src

Types

enum Public

src

Fields

x25519 x25519
p256 p256

module ktls

src

Linux kernel TLS (kTLS) UAPI: the constants and struct layouts, the TCP_ULP/TLS_TX/TLS_RX installs, and the record-type cmsg framing that carries control records.

more

The constants and structs are pure data definitions from include/uapi/linux/tls.h, defined unconditionally (they're just bytes) so non-Linux callers can compile kTLS packing and framing code for key-logging/debug. The pack* helpers fold the salt/IV split and cipher layout into the library so callers never handle the kernel struct layout or the RFC 8446 §5.3 nonce split themselves; the cmsg encoder and parser are likewise pure buffer shaping.

The install helpers call linux.setsockopt, never std.posix.setsockopt: the posix wrapper maps EINVAL to unreachable, and EINVAL is a legitimate answer for this API (a tls_crypto_info.version or cipher_type the kernel does not know). In ReleaseFast that unreachable is UB; a typed error is not. Every errno decode here is total. The installs are meaningful only with Linux setsockopt(TLS_*); on other targets they compile but report error.Unavailable, the contract's "stay in userspace TLS" signal.

Install ordering is caller-owned: the kernel accepts TX and RX installs independently (either alone, in either order), so "TX after the server flight, RX after the client Finished, rekey on KeyUpdate" is policy this module does not enforce.

References:

  • https://docs.kernel.org/networking/tls.html
  • include/uapi/linux/tls.h
  • RFC 8446 §5.3 (per-record nonce / IV split), §7.1 (traffic key derivation)

Constants

pub const SOL_TCP: u32 = 6

src

SOL_TCP (IPPROTO_TCP) for setsockopt(fd, SOL_TCP, TCP_ULP, ...). Kernel UAPI name kept verbatim for grep-ability against include/uapi/linux/tls.h.

pub const TCP_ULP: u32 = 31

src

TCP_ULP socket option to install the TLS ULP. include/uapi/linux/tls.h.

pub const SOL_TLS: u32 = 282

src

SOL_TLS = IPPROTO_TCP + 256. include/uapi/linux/tls.h.

pub const TLS_TX: u32 = 1

src

TLS_TX direction: install the transmit traffic key.

pub const TLS_RX: u32 = 2

src

TLS_RX direction: install the receive traffic key.

pub const TLS_SET_RECORD_TYPE: u32 = 1

src

Ancillary-data type used to select a non-application TLS TX record.

pub const TLS_GET_RECORD_TYPE: u32 = 2

src

Ancillary-data type carrying the decrypted TLS RX record type.

pub const TLS_1_3_VERSION: u16 = 0x0304

src

TLS_1_3_VERSION (0x0304) for tls_crypto_info.version.

pub const TLS_CIPHER_AES_GCM_128: u16 = 51

src

tls_cipher_type values from include/uapi/linux/tls.h. These mirror RecordLayer.KtlsCipherType but are the raw kernel UAPI integers.

pub const TLS_CIPHER_AES_GCM_256: u16 = 52

src

pub const TLS_CIPHER_CHACHA20_POLY1305: u16 = 54

src

pub const PackError = error{CipherMismatch}

src

pub const RecordType = u8

src

A TLS content type (RFC 8446 §5.1): the byte a TLS_SET_RECORD_TYPE cmsg selects and a TLS_GET_RECORD_TYPE cmsg reports. Left as the raw byte because the content-type enum belongs to the TLS layer, not the UAPI.

pub const InstallError = …

src
value
error{
    /// This socket cannot do kTLS: no ULP named "tls" (ENOENT) or no TLS
    /// support at this level (ENOPROTOOPT / EPROTONOSUPPORT / EOPNOTSUPP).
    /// The caller's signal to stay in userspace TLS. ENOPROTOOPT is also
    /// what a TLS_TX/TLS_RX install reports when the ULP was never attached,
    /// since the socket then has no TLS level at all — and it is the answer
    /// on non-Linux targets, where no socket can do kTLS.
    Unavailable,
    /// kTLS is present but the socket forbids the install right now: EBUSY,
    /// which the kernel returns when a TLS_TX rekey races records in flight.
    Busy,
    /// Everything else, EINVAL included: a crypto-info the kernel cannot use
    /// (EINVAL), a socket that is not ESTABLISHED (ENOTCONN), a second ULP
    /// attach (EEXIST). A programming error or a dead socket — no fallback.
    Failed,
}

Outcome of a kTLS option install.

pub const control_space = mem.alignForward(usize, cmsg_len, @sizeOf(usize))

src

CMSG_SPACE(sizeof(u8)): the control buffer one record-type cmsg needs, padding included. kTLS reports controllen == 24 for such a cmsg, so the receive buffer must be at least this large even though the cmsg is 17 long.

pub const ParseError = error{InvalidControlMessage}

src

Functions

pub fn packAesGcm128(info: KtlsInfo) PackError!Tls12CryptoInfoAesGcm128

src

Pack a KtlsInfo into the AES-GCM-128 kernel struct. Returns an error if the info's cipher type is not AES-GCM-128.

pub fn packAesGcm256(info: KtlsInfo) PackError!Tls12CryptoInfoAesGcm256

src

Pack a KtlsInfo into the AES-GCM-256 kernel struct.

pub fn packChaCha20Poly1305(info: KtlsInfo) PackError!Tls12CryptoInfoChaCha20Poly1305

src

Pack a KtlsInfo into the ChaCha20-Poly1305 kernel struct. ChaCha20 uses the full 12-byte IV with no salt.

pub fn ulpInstall(fd: posix.socket_t) InstallError!void

src

Attach the "tls" ULP; every TLS_* option install requires it.

The kernel attaches only in TCP_ESTABLISHED and only once. Attach before the first userspace read: plaintext already pulled off the socket cannot be told apart from a TLS record afterwards (see parseRecordType).

pub fn txInstall(fd: posix.socket_t, info: *const Tls12CryptoInfoAesGcm128) InstallError!void

src

Install the transmit key (TLS_TX).

pub fn rxInstall(fd: posix.socket_t, info: *const Tls12CryptoInfoAesGcm128) InstallError!void

src

Install the receive key (TLS_RX).

pub fn installCryptoInfo( fd: posix.socket_t, direction: u32, crypto_info: []const u8, ) InstallError!void

src

Install a packed crypto-info struct for direction (TLS_TX or TLS_RX). The kernel selects the cipher layout from the option length, so crypto_info is the bytes of one of the Tls12CryptoInfo* structs; prefer the typed txInstall/rxInstall when the cipher is AES-GCM-128.

pub fn parseRecordType(control: []const u8, flags: u32) ParseError!?RecordType

src

Record type from the control buffer a kTLS recvmsg filled, or null when the kernel attached no cmsg at all.

more

kTLS reports the type of every record it decrypts, attaching the cmsg to the first bytes of the record; MSG_EOR is set only on the recv that consumes the record's final byte. A record larger than the caller's read buffer therefore legitimately yields cmsg-present + EOR-clear, so EOR is deliberately NOT required here — record completion is the caller's to track from msg_flags, and guarding split control records is caller policy. Control data that breaks the framing contract is an error, never a guess: bytes whose record type was never reported cannot be classified, and guessing desynchronizes the record layer. A null return with bytes received means the kernel attached no cmsg at all — plaintext that reached the socket buffer before the ULP attach.

Types

struct TlsCryptoInfo

src
pub const TlsCryptoInfo = extern struct

struct tls_crypto_info from include/uapi/linux/tls.h.

Fields

version: u16

struct Tls12CryptoInfoAesGcm128

src
pub const Tls12CryptoInfoAesGcm128 = extern struct

struct tls12_crypto_info_aes_gcm_128 from include/uapi/linux/tls.h. The 12-byte TLS 1.3 IV splits into salt[4] (first 4 bytes) and iv[8] (last 8 bytes); the kernel reconstructs the per-record nonce as salt || iv XOR seq (RFC 8446 §5.3).

Fields

info: TlsCryptoInfo
iv: [8]u8
key: [16]u8
salt: [4]u8
rec_seq: [8]u8

Functions

pub fn secureZero(self: *Tls12CryptoInfoAesGcm128) void

src

Erase the packed key material and invalidate this value.

struct Tls12CryptoInfoAesGcm256

src
pub const Tls12CryptoInfoAesGcm256 = extern struct

struct tls12_crypto_info_aes_gcm_256 from include/uapi/linux/tls.h.

Fields

info: TlsCryptoInfo
iv: [8]u8
key: [32]u8
salt: [4]u8
rec_seq: [8]u8

Functions

pub fn secureZero(self: *Tls12CryptoInfoAesGcm256) void

src

Erase the packed key material and invalidate this value.

struct Tls12CryptoInfoChaCha20Poly1305

src
pub const Tls12CryptoInfoChaCha20Poly1305 = extern struct

struct tls12_crypto_info_chacha20_poly1305 from include/uapi/linux/tls.h. ChaCha20-Poly1305 has no salt/IV split: the full 12-byte IV goes in iv, and salt is omitted (size 0).

Fields

info: TlsCryptoInfo
iv: [12]u8
key: [32]u8
rec_seq: [8]u8

ChaCha20-Poly1305 uses an 8-byte rec_seq in the kernel struct even though the TLS 1.3 IV is 12 bytes; the nonce is iv XOR seq over the last 8 bytes (RFC 8446 §5.3).

Functions

pub fn secureZero(self: *Tls12CryptoInfoChaCha20Poly1305) void

src

Erase the packed key material and invalidate this value.

struct cmsghdr

src
pub const cmsghdr = extern struct

struct cmsghdr (include/linux/socket.h): the ancillary-data header the record-type cmsgs ride in. Transcribed like the tls.h layouts above because std.os.linux.cmsghdr exists only on Zig >= 0.16 and the layout is kernel-frozen; the comptime block below cross-checks the transcription where std names the struct.

Fields

len: usize

The kernel and glibc use usize for this field; musl uses socklen_t.

level: i32
type: i32

struct ControlBuffer

src

A control buffer for one record-type cmsg. Wrapped in a struct because the buffer has to be as aligned as struct cmsghdr and Zig cannot express an alignment on an array type alias; bytes is the msghdr.control target.

Fields

bytes: [control_space]u8 align(@alignOf(cmsghdr))

Functions

pub fn init(content_type: RecordType) ControlBuffer

src

Encode a TLS_SET_RECORD_TYPE cmsg selecting content_type for the record sendmsg is about to write. The padding starts zeroed, so no stale stack bytes enter the kernel with the control message.

The kernel refuses any other cmsg on a kTLS socket with EINVAL, so there is deliberately no way to pass a different level or cmsg type.

pub fn encoded(self: *const ControlBuffer) []const u8

src

Borrow the encoded msghdr.control bytes from stable caller storage.

module level

src

Encryption levels for handshake messages, shared by both roles.

A TLS record hides the level in a sequence-number-selected key; a QUIC packet header states it. The handshake needs the second view to serve both, so the level becomes an explicit property of every message it hands out and accepts (RFC 8446 §5, RFC 9001 §4.1.3).

Constants

pub const MismatchError = error{WrongLevel}

src

Functions

pub fn of(msg_type: handshake.Type) ?Level

src

The level a handshake message is protected under, or null for a type this engine does not consume as a whole message.

RFC 8446 §4: ClientHello and ServerHello are plaintext. EndOfEarlyData and 0-RTT-bearing messages ride early. Everything between the server flight and the client Finished rides handshake. NewSessionTicket and KeyUpdate are post-handshake, so application.

pub fn check(msg_type: handshake.Type, provided: Level) MismatchError!void

src

Reject a message delivered at a level it cannot occupy. RFC 9001 §4.1.3 requires this check: CRYPTO data at the wrong level is a connection error, not something to hand to the parser and hope.

Types

enum Level

src

The four encryption levels a TLS 1.3 handshake uses. plaintext is the ClientHello and ServerHello exchange, which carries no protection at all.

Fields

plaintext plaintext
early early
handshake handshake
application application

union Output

src
pub const Output = union(enum)

One thing the handshake has for its caller, in order.

Fields

message: Message

A handshake message to protect at level and send. The bytes are the message exactly as it appears after the record protection is removed: handshake type and length included, nothing around them.

read_level: Level

Reads from now on use keys at this level.

write_level: Level

Writes from now on use keys at this level.

key_available: Level

Keys for level exist and may be used. The caller fetches the traffic secret and derives its own protection keys; the engine never derives record keys on this path.

done done

The handshake is complete for this role.

alert: Struct

An alert the caller must carry: a record for a TLS stream, a CONNECTION_CLOSE for QUIC. The core never frames or encrypts one.

Types

struct Message

src

Fields

level: Level
bytes: []const u8

struct Struct

src

Fields

level: alert.Level
description: alert.Description

struct Queue

src

A bounded FIFO of Outputs, over caller-owned storage. The handshake fills it and the caller drains it with next(); nothing here allocates, and the byte slices in message outputs borrow whatever buffer produced them.

Fields

slots: []Output
head: usize
tail: usize

Constants

pub const Error = error{QueueFull}

src

Functions

pub fn init(slots: []Output) Queue

src

pub fn isEmpty(self: *const Queue) bool

src

pub fn isFull(self: *const Queue) bool

src

pub fn push(self: *Queue, item: Output) Error!void

src

pub fn pop(self: *Queue) ?Output

src

pub fn clear(self: *Queue) void

src

Drop everything without freeing; used when a handshake fails.

module handshake_core

src

The step-driven handshake core: levels in, levels out.

more

This is the new type the record engines will become adapters over. It owns the transcript and the key schedule, accepts bare handshake messages tagged with an encryption level, and yields messages and level transitions for a caller that provides its own protection (QUIC CRYPTO frames, or a record adapter).

Nothing here encrypts, frames, or decrypts. RFC 8446 §5 puts that around the handshake; RFC 9001 §4.1.3 requires the level to be checked at this boundary, which is what level.check does.

Both roles now cover the full handshake, including client authentication, PSK offers and retries, early-data ordering, application-key derivation, and bounded post-handshake control messages. Callers may supply encoded messages or use the core's ClientHello encoders; record protection stays outside.

Constants

pub const Error = …

src
value
error{
    /// A message arrived at a level it cannot occupy. RFC 9001 §4.1.3.
    WrongLevel,
    /// The caller asked for an output the queue has no room for.
    QueueFull,
    /// A message arrived out of order, or before the handshake reached the
    /// point that accepts it.
    UnexpectedMessage,
    /// The peer's leaf public key does not fit the core's retention buffer.
    CertificateKeyTooLarge,
    /// The server asked for a client certificate and the client sent none.
    ClientCertificateRequired,
    /// A server configured with ALPN found no overlap with the client.
    NoApplicationProtocol,
} || capabilities.HybridPolicyError || hybrid_kex.Error ||
    error{
        MissingP384KeyPair,
        MissingKeyPairs,
        PeerShareStorageTooSmall,
        HybridServerUnsupported,
        GroupNotOffered,
        NoPeerSharesRetained,
        InvalidPskBinder,
        InvalidVectorLength,
        TooManyPskIdentities,
        MissingRequiredExtension,
        EarlyDataSkipLimitExceeded,
        ClientCertificateTooLarge,
        UnsupportedKeyShare,
    } ||
    server_hello.ParseError || certificate.VerifyError ||
    certificate.ParseError || certificate.EncodeError ||
    finished.VerifyError || encrypted_extensions.ParseError ||
    encrypted_extensions.EncodeError || certificate_request.ParseError ||
    signature.SignError || aead.Error ||
    server_hello.HrrParseError || client_hello.RetryEncodeError ||
    alert.ParseError || NewSessionTicket.ParseError ||
    NewSessionTicket.EncodeError || certificate.ChainSignatureSchemesError ||
    error{
        AlpnProtocolTooLong,
        InvalidServerName,
        ServerNameTooLong,
        TooManyAlpnBytes,
        EmptyAlpnProtocol,
        ExtensionTooLong,
        ReservedExtension,
        DuplicateExtension,
        IdentityTooLong,
        InvalidBinderLength,
        InvalidHybridPolicy,
        HybridGroupUnavailable,
    } ||
    error{
        TooManyKeyUpdates,
        TooManyNewSessionTickets,
        InvalidHandshakeType,
        NoCommonSignatureScheme,
        MissingServerCredentials,
        UnsupportedCipherSuite,
        ClientHelloTooLarge,
        HandshakeBufferTooShort,
        EmptyIdentity,
        PskTooShort,
        PskTooLong,
    }

pub const peer_share_storage_len = 32 + 65 + 97 + 3 * hybrid_kex.max_client_share_len + 12

src

The server's plaintext half: accept the ClientHello, queue the ServerHello, derive the same handshake traffic secrets the client derives. Storage for every classical and RFC 10024 hybrid share a ClientHello can carry. Two bytes retain the group tag so hybrid code points are not truncated.

Functions

pub fn pskBinderKey(comptime Hkdf: type, psk: []const u8) [Hkdf.prk_len]u8

src

pub fn binderFor( comptime Hkdf: type, binder_key: [Hkdf.prk_len]u8, binder_hash: []const u8, ) [Hkdf.prk_len]u8

src

Types

struct Credentials

src

What a role signs with when it authenticates. Construction parses the chain once so accepting a connection only intersects the retained two-byte bitset.

Fields

chain: CertificateChain
signer: signature.Signer
required: signature.OfferedCertificateSchemes

Constants

pub const InitError = certificate.ChainSignatureSchemesError

src

Functions

pub fn init(chain: CertificateChain, signer: signature.Signer) InitError!Credentials

src

RFC 8446 §4.2.3, §4.4.2.2 — validate the configured chain at load or rotation time rather than reparsing its DER for every connection.

struct HandshakeSecrets

src

Fields

len: u8
client: [48]u8
server: [48]u8

struct Client

src

Fields

suite: suite_state.Suite

Transcript and key schedule. The client starts buffering both candidate hashes because the suite is unknown until ServerHello (RFC 8446 §4.4.1).

policy: certificate.Policy

The caller's verification policy, applied when Certificate arrives.

alpn: []const []const u8

ALPN protocols offered, in preference order. Borrowed from the caller.

server_name: ?[]const u8

The SNI value to preserve across HelloRetryRequest.

offered: extension_type.OfferedExtensions

The extensions offered in ClientHello, used to validate the response.

record_size_limit: ?u16

RFC 8449 §4 — retained verbatim across HelloRetryRequest.

server_record_size_limit: ?u16

RFC 8449 §4 — the server's response limits every client TX epoch.

allowed_extensions: []const extension_type.ExtraExtension

Extension types the caller allows in EncryptedExtensions, borrowed.

extension_sink: extension_type.ExtensionSink

Caller-owned slots for allowed extensions. Their data borrows the input.

credentials: ?Credentials

Client credentials, used only after a CertificateRequest.

offered_client_signature_schemes: OfferedSignatureSchemesBuffer

CertificateVerify schemes offered in ClientHello.signature_algorithms.

offered_cert_signature_schemes: signature.OfferedCertificateSchemes

Effective certificate signature schemes from ClientHello.

queue: level.Queue
early: ?EarlySecret

The early traffic secret exists only after an early-data offer.

psk_suite: ?CipherSuite

Resumption ticket parameters supplied before the ClientHello is encoded.

psk_alpn: []const u8
keypairs: ?KeyPairs

The caller's ephemeral keypairs. Secret state is zeroized in deinit.

hybrid: capabilities.HybridPolicy
kem_key: ?hybrid_kex.ClientKeyPair
required_extensions: []const u16

EncryptedExtensions policy and its diagnostic, borrowed from the caller.

traffic_secret_storage: ?*traffic_secrets.TrafficSecrets

Optional caller-owned traffic-secret capture. The caller wipes it.

phase: Phase

Phase payloads make certificate, retry, and post-handshake state valid only in the phase that can consume it.

last_alert: ?alert.Alert

The most recent peer alert remains available during and after the handshake.

Functions

pub fn init(slots: []level.Output, policy: certificate.Policy) Client

src

pub fn deinit(self: *Client) void

src

pub fn state(self: *const Client) State

src

pub fn isConnected(self: *const Client) bool

src

pub fn selectedSuite(self: *const Client) ?CipherSuite

src

pub fn next(self: *Client) ?level.Output

src

pub fn receiveExtensions( self: *Client, allowed: []const extension_type.ExtraExtension, slots: []extension_type.ExtraExtension, ) void

src

pub fn requireExtensions(self: *Client, required: []const u16) void

src

pub fn missingExtension(self: *const Client) u16

src

pub fn useTrafficSecretStorage( self: *Client, storage: *traffic_secrets.TrafficSecrets, ) void

src

pub fn trafficSecrets( self: *const Client, ) error{NotRetained}!*const traffic_secrets.TrafficSecrets

src

pub fn peerExtensions(self: *const Client) []const extension_type.ExtraExtension

src

pub fn serverRecordSizeLimit(self: *const Client) ?u16

src

pub fn offerHybrid(self: *Client, policy: capabilities.HybridPolicy) void

src

pub fn useKeypairs(self: *Client, keypairs: KeyPairs) void

src

pub fn usePskTicketAlpn(self: *Client, protocol: []const u8) void

src

pub fn offerAlpn(self: *Client, protocols: []const []const u8) void

src

pub fn selectedAlpn(self: *const Client) ?[]const u8

src

pub fn serverSelectedPsk(self: *const Client) bool

src

pub fn isResumed(self: *const Client) bool

src

pub fn retryGroup(self: *const Client) ?kex.NamedGroup

src

pub fn earlyDataStatus(self: *const Client) ?EarlyData

src

pub fn earlyDataAccepted(self: *const Client) bool

src

pub fn offerEarlyData(self: *Client, psk: []const u8) Error!void

src

RFC 8446 §4.2.10, §7.1 — derive and announce the early traffic secret.

pub fn earlySecret(self: *const Client) ?[]const u8

src

pub fn start(self: *Client, client_hello_msg: []const u8) Error!void

src

Absorb a caller-encoded ClientHello and queue it at plaintext.

pub fn provide( self: *Client, provided: level.Level, server_hello_msg: []const u8, ) Error!void

src

Accept ServerHello and derive handshake keys transactionally.

pub fn provideHandshake( self: *Client, provided: level.Level, msg: []const u8, ) Error!void

src

Accept one encrypted server-flight message without changing the original phase or transcript when parsing or verification fails.

pub fn startEncoded( self: *Client, out: []u8, random: Random, keypairs: KeyPairs, host: ?[]const u8, alpn: []const []const u8, extras: []const extension_type.ExtraExtension, ) Error![]const u8

src

pub fn startEncodedWithPsk( self: *Client, out: []u8, random: Random, keypairs: KeyPairs, host: ?[]const u8, alpn: []const []const u8, psk: []const u8, identity: []const u8, obfuscated_ticket_age: u32, ) Error![]const u8

src

Encode a resumption offer and retain its PSK for ServerHello selection.

pub fn startEncodedWithPskEarlyData( self: *Client, out: []u8, random: Random, keypairs: KeyPairs, host: ?[]const u8, alpn: []const []const u8, psk: []const u8, identity: []const u8, obfuscated_ticket_age: u32, ) Error![]const u8

src

Encode a resumption offer that also carries RFC 8446 §4.2.10 early_data.

pub fn startEncodedWithExternalPsk( self: *Client, out: []u8, random: Random, keypairs: KeyPairs, host: ?[]const u8, alpn: []const []const u8, psk: []const u8, identity: []const u8, suite: CipherSuite, ) Error![]const u8

src

RFC 9257 §6 — external PSKs carry at least 128 bits and use the external binder label rather than the resumption label.

pub fn acceptHelloRetryRequest( self: *Client, provided: level.Level, hrr: []const u8, ) Error!kex.NamedGroup

src

Accept HRR and retain its cookie and compatible PSK in the retry phase.

pub fn sendClientHello2( self: *Client, group: kex.NamedGroup, random: Random, keypairs: KeyPairs, out: []u8, ) Error![]const u8

src

Encode ClientHello2 with the HRR cookie and a freshly rebound PSK.

pub fn sendEndOfEarlyData(self: *Client, out: []u8) Error![]const u8

src

Emit EndOfEarlyData before Finished whenever early keys were offered.

pub fn sendClientFinished(self: *Client, out: []u8) Error![]const u8

src

Assemble the client flight and commit only after every encoding, key derivation, and queue operation succeeds.

pub fn handshakeSecrets(self: *const Client) ?HandshakeSecrets

src

pub fn applicationSecrets(self: *const Client) ?HandshakeSecrets

src

pub fn resumptionMaster(self: *const Client) ?[48]u8

src

pub fn resumptionPsk(self: *const Client, nonce: []const u8, out: []u8) Error!void

src

pub fn sendKeyUpdate( self: *Client, request: handshake.KeyUpdateRequest, out: []u8, ) Error![]const u8

src

pub fn provideApplication( self: *Client, provided: level.Level, msg: []const u8, ) Error!void

src

Process one post-handshake control message with independent flood caps.

pub fn provideApplicationData(self: *Client, plaintext: []const u8) Error!void

src

Application data resets both burst budgets only when it carries a byte.

pub fn provideAlert(self: *Client, provided: level.Level, body: []const u8) Error!void

src

pub fn lastAlert(self: *const Client) ?alert.Alert

src

pub fn lastTicket(self: *const Client) ?NewSessionTicket

src

pub fn policyOf(self: *const Client) certificate.Policy

src

Types

enum EarlyData

src

Fields

not_accepted not_accepted
accepted accepted
end_sent end_sent

enum State

src

Fields

start start
wait_server_hello wait_server_hello
wait_encrypted_extensions wait_encrypted_extensions
wait_certificate wait_certificate
wait_certificate_verify wait_certificate_verify
wait_finished wait_finished
wait_client_hello2 wait_client_hello2
server_finished_verified server_finished_verified
connected connected

union Phase

src
pub const Phase = union(State)

Fields

start: void
wait_server_hello: WaitServerHello
wait_certificate: ServerFlight
wait_certificate_verify: CertificateVerify
wait_finished: ServerFlight
server_finished_verified: ServerFlight
connected: Connected

struct TranscriptHash

src

Fields

data: [48]u8
len: u8

Functions

pub fn init() TranscriptHash

src

pub fn slice(self: *const TranscriptHash) []const u8

src

struct PeerShare

src

Fields

group: kex.NamedGroup
bytes: []const u8

struct Server

src

Fields

suite: suite_state.Suite
queue: level.Queue
phase: Phase
alpn: []const []const u8
keypairs: ?KeyPairs
peer_shares: [6]PeerShare
allowed_extensions: []const extension_type.ExtraExtension
extension_sink: ?*extension_type.ExtensionSink
send_extensions: []const extension_type.ExtraExtension
advertised_record_size_limit: ?u16

RFC 8449 §4 — emitted only in response to a client's offer.

client_server_name: buffer.Array(u8, client_hello.max_server_name_len)

RFC 6066 §3 — owned storage keeps SNI independent of record reuse.

hybrid_groups: []const kex.NamedGroup
psk_lookup: ?PskLookup
client_auth: ClientAuthState
required_extensions: []const u16
traffic_secret_storage: ?*traffic_secrets.TrafficSecrets

Constants

pub const max_psk_len = 64

src

Maximum PSK byte length carried inline by PskEntry. Covers both TLS 1.3 resumption PSKs (32/48 bytes) and external PSKs up to 64 bytes.

pub const group_preference = [_]kex.NamedGroup{ .x25519, .secp256r1, .secp384r1 }

src

Functions

pub fn init(slots: []level.Output) Server

src

pub fn deinit(self: *Server) void

src

pub fn state(self: *const Server) State

src

pub fn isConnected(self: *const Server) bool

src

pub fn selectedSuite(self: *const Server) ?CipherSuite

src

pub fn next(self: *Server) ?level.Output

src

pub fn useKeypairs(self: *Server, keypairs: KeyPairs) void

src

pub fn usePeerShareStorage(self: *Server, storage: []u8) void

src

pub fn usePskLookup(self: *Server, lookup: PskLookup) void

src

pub fn setEarlyDataSkipLimit(self: *Server, limit: u32) void

src

pub fn supportHybrid(self: *Server, groups: []const kex.NamedGroup) Error!void

src

pub fn supportAlpn(self: *Server, protocols: []const []const u8) void

src

pub fn receiveExtensions( self: *Server, allowed: []const extension_type.ExtraExtension, sink: *extension_type.ExtensionSink, ) void

src

pub fn sendExtensions(self: *Server, extras: []const extension_type.ExtraExtension) void

src

pub fn requireExtensions(self: *Server, required: []const u16) void

src

pub fn missingExtension(self: *const Server) u16

src

pub fn useTrafficSecretStorage( self: *Server, storage: *traffic_secrets.TrafficSecrets, ) void

src

pub fn trafficSecrets( self: *const Server, ) error{NotRetained}!*const traffic_secrets.TrafficSecrets

src

pub fn setClientAuth( self: *Server, policy: ClientAuthPolicy, verification: certificate.Policy, ) void

src

pub fn requireClientCertificate(self: *Server, policy: certificate.Policy) void

src

pub fn requestClientCertificate(self: *Server, policy: certificate.Policy) void

src

pub fn useClientCertificateBuffer(self: *Server, storage: []u8) void

src

pub fn clientCertificateDer(self: *const Server) ?[]const u8

src

pub fn peerExtensions(self: *const Server) []const extension_type.ExtraExtension

src

pub fn selectedAlpn(self: *const Server) ?[]const u8

src

pub fn clientServerName(self: *const Server) ?[]const u8

src

pub fn ticketCompatibility(self: *const Server) TicketCompatibility

src

pub fn negotiatedGroup(self: *const Server) ?kex.NamedGroup

src

pub fn selectedPsk(self: *const Server) ?SelectedPsk

src

pub fn selectedPskIndex(self: *const Server) ?u16

src

pub fn isResumed(self: *const Server) bool

src

pub fn selectPsk( parsed: client_hello.Parsed, msg: []const u8, lookup: PskLookup, negotiated_suite: CipherSuite, ) Error!?PskSelection

src

Select and verify the first known hash-compatible PSK. A known identity with a bad binder is fatal rather than an invitation to try later ones.

pub fn provide( self: *Server, provided: level.Level, client_hello_msg: []const u8, cipher_suite: CipherSuite, server_hello_msg: []const u8, ) Error!void

src

pub fn provideClientHello( self: *Server, provided: level.Level, client_hello_msg: []const u8, cipher_suite: CipherSuite, ) Error!void

src

pub fn selectedGroup(self: *const Server) ?kex.NamedGroup

src

pub fn preferredRetryGroup(self: *const Server) ?kex.NamedGroup

src

RFC 8446 §4.2.8, RFC 10024 §4.1 — when no usable share exists, choose the server's preferred advertised group for HelloRetryRequest.

pub fn preferredHybridShare( self: *const Server, shares: []const client_hello.ParsedKemKeyShare, ) ?*const client_hello.ParsedKemKeyShare

src

pub fn sendHelloRetryRequest( self: *Server, selected_group: kex.NamedGroup, legacy_session_id: []const u8, out: []u8, ) Error![]const u8

src

pub fn sendServerHello( self: *Server, random: Random, legacy_session_id: []const u8, out: []u8, ) Error![]const u8

src

Encode ServerHello after selecting the server's preferred offered group. Hybrid encapsulation must precede encoding because its ciphertext is the server key_share; caller-encoded hybrid messages cannot reproduce it.

pub fn provideServerHello( self: *Server, provided: level.Level, server_hello_msg: []const u8, ) Error!void

src

pub fn admitEarlyData(self: *Server, psk: []const u8) Error!void

src

Manual admission remains useful to record-free tests and callers whose PSK policy is not represented by PskLookup. Automatic PSK selection uses the same derivation and accounting state.

pub fn earlySecret(self: *const Server) ?[]const u8

src

pub fn earlyDataSkipWindow(self: *const Server) EarlyDataSkip

src

pub fn endOfEarlyDataReceived(self: *const Server) bool

src

pub fn earlyDataLimit(self: *const Server) ?u32

src

pub fn earlyDataReceived(self: *const Server) u32

src

pub fn earlyDataSkipBytes(self: *const Server) u32

src

pub fn receiveEarlyData(self: *Server, content_len: u32) Error!void

src

pub fn closeEarlyDataSkipWindow(self: *Server) void

src

pub fn skipEarlyData(self: *Server, skipped: u32) Error!void

src

pub fn sendFlight( self: *Server, creds: ?Credentials, alpn: ?[]const u8, out: []u8, ) Error!void

src

pub fn provideClientFlight( self: *Server, provided: level.Level, msg: []const u8, ) Error!void

src

pub fn handshakeSecrets(self: *const Server) ?HandshakeSecrets

src

pub fn applicationSecrets(self: *const Server) ?HandshakeSecrets

src

pub fn selectCredentials( self: *const Server, candidates: []const Credentials, ) error{ EmptyCertificateChain, NoCommonSignatureScheme }!Credentials

src

pub fn flightBufferLen( self: *const Server, creds: Credentials, alpn: ?[]const u8, ) usize

src

pub fn sendNewSessionTicket( self: *Server, ticket: NewSessionTicket, out: []u8, ) Error![]const u8

src

pub fn resumptionPsk(self: *const Server, nonce: []const u8, out: []u8) Error![]const u8

src

Types

enum ClientAuthPolicy

src

Fields

none none
optional optional
required required

struct ClientAuthState

src

Client-authentication configuration is immutable; verified leaf keys and retained certificates live only in the phases that own them.

Fields

policy: ClientAuthPolicy
verification: certificate.Policy
certificate_storage: buffer.Slice(u8)

struct PskEntry

src

Fields

psk: buffer.Array(u8, max_psk_len)
cipher_suite: CipherSuite
kind: hkdf.PskKind
alpn: ?[]const u8

Constants

pub const empty: PskEntry = …

src
value
.{
            .psk = .empty,
            .cipher_suite = .aes_128_gcm_sha256,
            .kind = .resumption,
            .max_early_data_size = null,
            .alpn = null,
        }

Functions

pub fn init(psk: []const u8, cipher_suite: CipherSuite) PskEntry

src

pub fn pskSlice(self: *const PskEntry) []const u8

src

pub fn secureZero(self: *PskEntry) void

src

struct PskQuery

src

Context passed to PskLookup.lookup for each offered identity. server_name and selected_alpn come from the parsed ClientHello (ALPN selection runs before PSK lookup) so stateless ticket openers can authenticate both in AAD without storing them in the ticket payload.

Fields

identity: []const u8
server_name: ?[]const u8
selected_alpn: ?[]const u8

struct PskLookup

src

Pure, idempotent PSK resolution callback. Ticket identities travel in cleartext in the ClientHello, so lookup must not consume single-use state before the engine verifies the binder. Write the resolved entry into out and return true, or return false for a miss.

Fields

context: *anyopaque
lookup: *const fn (context: *anyopaque, query: *const PskQuery, out: *PskEntry) bool

struct SelectedPsk

src

Secret-free PSK selection metadata retained after handshake secrets are derived. The PSK bytes themselves are wiped at ServerHello.

Fields

kind: hkdf.PskKind
cipher_suite: CipherSuite
alpn: ?[]const u8

struct PskSelection

src

Fields

entry: PskEntry

Functions

pub fn secureZero(self: *PskSelection) void

src

enum EarlyDataSkip

src

Fields

off off
pending_decision pending_decision
await_client_hello2 await_client_hello2
trial_decrypt trial_decrypt

enum EndOfEarlyData

src

Fields

pending pending
received received

struct AcceptedEarlyData

src

Fields

secret: [48]u8
len: u8
limit: ?u32
received: u32
end: EndOfEarlyData

struct DeclinedEarlyData

src

Fields

skip: EarlyDataSkip
skipped: u32
limit: u32

union EarlyDataState

src
pub const EarlyDataState = union(enum)

The core accounts for plaintext and skipped ciphertext bytes, but never inspects a record header. The record adapter supplies those byte counts.

Fields

off off
accepted: AcceptedEarlyData
declined: DeclinedEarlyData

enum TicketCompatibility

src

Fields

unavailable unavailable
psk_dhe_ke psk_dhe_ke

enum State

src

Fields

wait_client_hello wait_client_hello
wait_client_hello2 wait_client_hello2
wait_server_hello wait_server_hello
wait_flight wait_flight
wait_client_flight wait_client_flight
wait_client_certificate wait_client_certificate
wait_client_verify wait_client_verify
wait_client_finished wait_client_finished
connected connected

union Phase

src
pub const Phase = union(State)

Fields

wait_client_hello2: RetryState
wait_server_hello: Negotiation
wait_flight: Negotiation
wait_client_flight: ClientFlight
wait_client_certificate: ClientFlight
wait_client_verify: ClientVerify
wait_client_finished: ClientFlight
connected: Connected

struct TranscriptHash

src
pub const TranscriptHash = Client.TranscriptHash

Fields

data: [48]u8
len: u8

Functions

pub fn init() TranscriptHash

src

pub fn slice(self: *const TranscriptHash) []const u8

src

pub const Array = stdx.mem.Array

src

module mlkem

src

Backend-supplied pure ML-KEM primitives used by RFC 10024 hybrid groups.

tls owns the hybrid construction: this module only generates ML-KEM keys, validates encapsulation keys, and encapsulates/decapsulates fixed-size ciphertexts. Keeping the combiner above the backend seam makes the TLS wire construction identical for OpenSSL, AWS-LC, BoringSSL, and native.

Constants

pub const ParameterSet = @import("crypto").ParameterSet

src

pub const Error = …

src
value
error{
    BufferTooShort,
    IdentityElement,
    LibcryptoFailed,
    MalformedKeyShare,
    UnsupportedPrimitive,
}

pub const max_public_key_len = ParameterSet.mlkem1024.publicKeyLen()

src

pub const max_ciphertext_len = ParameterSet.mlkem1024.ciphertextLen()

src

pub const max_shared_secret_len = ParameterSet.mlkem1024.sharedSecretLen()

src

Functions

pub fn generate(parameter_set: ParameterSet) Error!KeyHandle

src

pub fn publicKey(key: *const KeyHandle, out: []u8) Error![]u8

src

pub fn loadPeerPublic( parameter_set: ParameterSet, public_key: []const u8, out: *PeerHandle, ) Error!void

src

Validate before provider import because providers differ on when they apply the FIPS 203 §7.2 encapsulation-key check.

pub fn encapsulate( peer: *const PeerHandle, ciphertext_out: []u8, secret_out: []u8, ) Error!struct { ciphertext: []const u8, secret: []const u8 }

src

pub fn decapsulate( key: *const KeyHandle, ciphertext: []const u8, secret_out: []u8, ) Error![]u8

src

Types

struct KeyHandle

src

Fields

parameter_set: ParameterSet
key: kem_impl.KemKey

Functions

pub fn deinit(self: *KeyHandle) void

src

struct PeerHandle

src

Fields

parameter_set: ParameterSet
key: kem_impl.KemPeerKey

Functions

pub fn deinit(self: *PeerHandle) void

src

module Outbox

src

Transport-agnostic helper for draining one engine-produced TLS record.

Outbox does no I/O itself. Callers provide a tiny writer adapter with write(bytes) !usize; returning 0 means the transport made no progress (for example, WouldBlock). The queued record slice is borrowed and must stay valid until writeBlocked() becomes false.

Constants

pub const Error = …

src
value
error{
    PendingWrite,
    WriteOverflow,
}

pub const init: Outbox = .{ .pending = "" }

src

pub const WriterError = error{Failed}

src

Functions

pub fn writeBlocked(self: *const Outbox) bool

src

True while a TLS record has not been fully accepted by the transport. While blocked, callers must not feed another record-producing call to the engine.

pub fn send( self: *Outbox, hs: anytype, record: []const u8, writer: anytype, ) (Error || WriteErrorSet(@TypeOf(writer)))!FlushResult

src

Queue one engine-produced TLS record and immediately try to flush it. record is borrowed and must stay valid until this outbox drains. Returns error.PendingWrite if another record is still blocked.

pub fn flush( self: *Outbox, hs: anytype, writer: anytype, ) (Error || WriteErrorSet(@TypeOf(writer)))!FlushResult

src

Flush queued bytes through writer.write(bytes) !usize.

Calls hs.completeWrite() exactly once, and only after every queued byte has been accepted. On writer error or zero-byte progress, the pending tail is preserved and the engine remains write-blocked. hs must be a mutable handshake pointer, not a value.

Types

enum FlushResult

src

Fields

drained drained
pending pending

pub const p256 = kex.p256

src

The two NIST curves, one shared implementation in ec_kex.zig.

pub const p384 = kex.p384

src

enum ProtocolVersion

src
pub const ProtocolVersion = @import("protocol_version.zig").ProtocolVersion

Fields

tls_1_2 tls_1_2 = 0x0303
tls_1_3 tls_1_3 = 0x0304
_ _

module RecordBuffer

src

I/O-agnostic TLS record framing buffer.

more

The engine consumes one complete record at a time, but transports deliver a byte stream where records split and coalesce arbitrarily. RecordBuffer is the seam between the two: the caller reads transport bytes into writable(), reports how many with advance(), and pulls complete records with next(). No allocations, no I/O — the caller owns the storage and the transport.

Usage: var rb: RecordBuffer = .init(&storage); const n = try stream.read(rb.writable()); rb.advance(n); while (try rb.next()) |record| { // record is a mutable slice into storage, valid until the next // next()/writable() call. Decrypt it in place here. }

init requires min_storage bytes so any single record fits. initLimited accepts smaller storage and reports legal oversized-for-storage records.

Constants

pub const min_storage: usize = frame.max_wire_record_len

src

Smallest storage that guarantees any one record fits: a full-size wire record (header + maximum ciphertext).

pub const min_limited_storage: usize = RecordLayer.overhead + 64

src

Smallest storage that can frame the smallest legal RFC 8449 protected record. Larger headers receive an explicit verdict instead of spinning.

pub const recommended_storage = 2 * min_storage

src

A comfortable default: room for a partial record plus a full one, so a read that straddles a record boundary still makes progress without thrashing.

pub const MinStorage = buffer.Array(u8, min_storage)

src

pub const Storage = buffer.Array(u8, recommended_storage)

src

pub const empty: RecordBuffer = .{ .storage = &.{}, .pos = 0, .filled = 0 }

src

Detached storage for an idle connection. No input can be committed until the caller attaches a new buffer.

pub const NextError = …

src
value
error{
    /// The header's length exceeds the RFC 8446 §5.2 maximum.
    RecordTooLarge,
    /// A legal record cannot fit this caller-provided storage.
    RecordExceedsStorage,
    /// The header's content type is none of the four TLS 1.3 defines
    /// (RFC 8446 §5: terminate with `unexpected_message`).
    UnexpectedRecord,
}

Functions

pub fn init(storage: []u8) RecordBuffer

src

storage is caller-owned, and so is clearing it. Records are decrypted in place, so this buffer holds application plaintext; nothing here zeroes it. Zero it where it is declared. See #81.

pub fn initLimited(storage: []u8) RecordBuffer

src

Frame records in caller storage smaller than the TLS maximum. A legal record that cannot fit reports RecordExceedsStorage from its header.

pub fn writable(self: *RecordBuffer) []u8

src

Free space to read transport bytes into. Compacts first, so the returned slice is the largest contiguous region available. Call advance afterward with the number of bytes written. Invalidates any record from next().

pub fn advance(self: *RecordBuffer, n: usize) void

src

Report n bytes written into the slice from writable().

pub fn next(self: *RecordBuffer) NextError!?[]u8

src

Return the next complete record as a mutable slice into storage, or null if a full record isn't buffered yet (read more via writable/advance). The slice stays valid until the next next() or writable() call — decrypt it in place before then. RFC 8446 §5.1.

A header fails as soon as its 5 bytes arrive, before any wait for the body. A non-TLS peer (an HTTP request, a Postgres StartupMessage) reads as a header with a plausible length and no valid type, so waiting for its body would hold the connection until the peer gives up (#139).

pub fn pendingRecordLen(self: *const RecordBuffer) NextError!?u16

src

Total wire length of the buffered record once its header is available.

pub fn bufferedBytes(self: *const RecordBuffer) []const u8

src

Unprocessed transport bytes, including a partial header or record body.

pub fn reset(self: *RecordBuffer) void

src

Discard framing cursors while retaining the caller's storage.

pub fn detach(self: *RecordBuffer) []u8

src

Return the caller's storage and leave this buffer detached.

pub fn hasRecord(self: *const RecordBuffer) bool

src

True when the next next() call returns without more transport reads: a complete record is buffered, or the buffered header already fails. Poll-style drive loops use this to drain coalesced records, and to reach a header error, without blocking on the transport.

pub fn isEmpty(self: *const RecordBuffer) bool

src

True when no transport bytes remain buffered, including a partial record. A kTLS handoff must satisfy this before the kernel takes ownership of RX.

module RecordLayer

src

TLS 1.3 record protection — one direction of a TLS connection (read or write).

Composes record framing, nonce construction, and AEAD to implement TLSCiphertext encrypt/decrypt. RFC 8446 §5.2

Constants

pub const overhead = frame.header_len + 1 + tag_len

src

Bytes added to plaintext length to produce the encrypted wire record. Accounts for the 5-byte header, content type byte, and 16-byte AEAD tag.

pub const DecryptError = …

src
value
frame.ParseError || AeadError || error{
    UnexpectedContentType,
    RecordTooShort,
    SequenceNumberOverflow,
    KeyUpdateRequired,
    InvalidInnerPlaintext,
}

pub const EncryptError = …

src
value
AeadError || error{
    /// `out` is smaller than the resulting record.
    BufferTooShort,
    /// 2^64 records sent on this layer (RFC 8446 §5.5).
    SequenceNumberOverflow,
    /// AEAD usage limit reached for this traffic key (RFC 8446 §5.5).
    KeyUpdateRequired,
    /// `content` exceeds the per-record plaintext limit (RFC 8446 §5.2); the
    /// caller must fragment into multiple records.
    PlaintextTooLarge,
}

Functions

pub fn init(aead_: Aead, iv_: Iv) AeadError!RecordLayer

src

pub fn initLimited(aead_: Aead, iv_: Iv, inner_limit: u16) AeadError!RecordLayer

src

pub fn deinit(self: *RecordLayer) void

src

pub fn secureZeroMovedFrom(self: *RecordLayer) void

src

Zero every byte of this layer — key material, IV, sequence — WITHOUT releasing the backend context. For ownership transfers (ServerHandshake.extractEstablished): the copy that moved out owns the context and stays live; these are the bytes left behind, which on inline-context backends (AWS-LC, BoringSSL) hold the live traffic keys and on OpenSSL hold the key/IV duplicates plus now-stale context pointers. Zeroed context handles are safe to deinit again if a bug ever does.

pub fn clone(self: *const RecordLayer) AeadError!RecordLayer

src

pub fn ktlsInfo(self: *const RecordLayer) KtlsInfo

src

Export the current traffic key, base IV, and sequence number for caller-side Linux kTLS setup. RFC 8446 §5.3 constructs the per-record nonce from the 12-byte IV XOR sequence number; Linux kTLS splits AES-GCM IVs into a 4-byte salt and 8-byte IV but uses the same nonce construction.

pub fn decrypt(self: *RecordLayer, buf: []u8) DecryptError!DecryptedRecord

src

Decrypt a TLSCiphertext record in place.

more

buf must contain the full record as received from the wire (header + encrypted payload). Decryption overwrites the ciphertext portion of buf with the plaintext. The returned DecryptedRecord.content is a subslice of buf — no allocation, no copy.

Sequence number increments only on successful authentication.

On error.AuthenticationFailed, the whole ciphertext region of buf is zeroed. Callers must not inspect, log, or reuse its contents after this error.

RFC 8446 §5.2

pub fn encrypt( self: *RecordLayer, content_type: ContentType, content: []const u8, out: []u8, ) EncryptError![]u8

src

Encrypt a TLS record in place into buf.

Writes the full TLSCiphertext record into buf: 5-byte header, ciphertext, and authentication tag. buf must be at least frame.header_len + content.len + 1 + tag_len bytes.

Returns the number of bytes written.

RFC 8446 §5.2

pub fn encryptPrepared( self: *RecordLayer, content_type: ContentType, content_len: usize, out: []u8, ) EncryptError![]u8

src

Encrypt a TLS record after the caller has already written plaintext into out[5..][0..content_len]. This avoids the plaintext copy in encrypt for producers that can serialize directly into the record buffer.

Types

struct DecryptedRecord

src

Fields

content_type: ContentType
content: []u8

Subslice of the caller-provided output buffer — no copy.

enum KtlsCipherType

src
pub const KtlsCipherType = enum(u16)

Linux kTLS cipher type values from include/uapi/linux/tls.h. These are kernel UAPI values, not TLS cipher-suite code points.

Fields

aes_gcm_128 aes_gcm_128 = 51
aes_gcm_256 aes_gcm_256 = 52
chacha20_poly1305 chacha20_poly1305 = 54

struct KtlsInfo

src

TLS 1.3 traffic-key material packed for a caller that wants to configure Linux kTLS. This is a value type: it copies secret material out of RecordLayer so callers never borrow slices into state that deinit() will secure-zero.

Fields

version: u16
cipher_type: KtlsCipherType
key: [32]u8
key_len: u8
salt: [4]u8
salt_len: u8
iv: [12]u8
iv_len: u8
rec_seq: [8]u8

Functions

pub fn init( cipher_type: KtlsCipherType, key_len: u8, salt_len: u8, iv_len: u8, rec_seq: [8]u8, ) KtlsInfo

src

A TLS 1.3 snapshot with zeroed key, salt, and IV; the caller fills the secret and nonce bytes it needs. version is fixed at 0x0304.

pub fn secureZero(self: *KtlsInfo) void

src

Erase the exported traffic key, IV, and sequence snapshot. The snapshot is invalid after this call.

module server_hello

src

TLS 1.3 ServerHello handshake message parsing.

RFC 8446 §4.1.3

Constants

pub const ParseError = …

src
value
error{
    UnexpectedEof,
    /// Handshake type byte is not server_hello (0x02).
    InvalidHandshakeType,
    /// Handshake length field does not match the supplied message.
    InvalidHandshakeLength,
    /// Extension block or extension length is malformed.
    InvalidExtensionLength,
    /// A singleton extension appeared more than once.
    DuplicateExtension,
    /// A field contained an unrecognised enum value.
    InvalidEnumTag,
    /// Server selected HelloRetryRequest; tls does not implement the retry path yet.
    HelloRetryRequest,
    /// legacy_version is SSLv3-or-lower, or supported_versions is absent.
    UnsupportedTlsVersion,
    /// Semantic protocol violation requiring illegal_parameter.
    IllegalParameter,
    /// legacy_session_id_echo does not match the ClientHello legacy_session_id.
    InvalidSessionIdEcho,
    /// legacy_compression_method is not null compression.
    InvalidCompressionMethod,
    /// key_share extension uses an unsupported group.
    UnsupportedKeyShareGroup,
    /// key_share length or point encoding does not match the selected group.
    MalformedKeyShare,
    /// A recognized extension appeared in a message where TLS 1.3 does not allow it.
    UnexpectedExtension,
    /// Server sent an extension the client did not request (RFC 8446 §4.2).
    UnsupportedExtension,
    /// A required TLS 1.3 ServerHello extension was absent.
    MissingExtension,
}
value
[_]u8{
    0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11,
    0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91,
    0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
    0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
}

pub const HrrParseError = …

src
value
error{
    UnexpectedEof,
    /// Handshake type byte is not server_hello (0x02).
    InvalidHandshakeType,
    /// Handshake length field does not match the supplied message.
    InvalidHandshakeLength,
    /// The Random field does not match the HelloRetryRequest magic value.
    NotHelloRetryRequest,
    /// Extension block or extension length is malformed.
    InvalidExtensionLength,
    /// A singleton extension appeared more than once.
    DuplicateExtension,
    /// A field contained an unrecognised enum value.
    InvalidEnumTag,
    /// legacy_version is SSLv3-or-lower.
    UnsupportedTlsVersion,
    /// Semantic protocol violation requiring illegal_parameter.
    IllegalParameter,
    /// legacy_session_id_echo does not match the ClientHello legacy_session_id.
    InvalidSessionIdEcho,
    /// legacy_compression_method is not null compression.
    InvalidCompressionMethod,
    /// A recognized extension appeared in a message where TLS 1.3 does not allow it.
    UnexpectedExtension,
    /// Server sent an extension the client did not request (RFC 8446 §4.2).
    UnsupportedExtension,
    /// A required extension was absent or malformed.
    MissingExtension,
}

pub const encoded_len = 4 + 2 + 32 + 1 + 2 + 1 + 2 + (4 + 2 + 2 + 32) + (4 + 2)

src

pub const max_kem_share_len = 1665

src

RFC 10024 §4 — maximum client or server hybrid key_share size.

pub const EncodeError = error{BufferTooShort}

src

Functions

pub fn parseHelloRetryRequest(msg: []const u8) HrrParseError!HelloRetryRequest

src

Parse a HelloRetryRequest handshake message.

more

msg must be the complete handshake message including the 4-byte header (type + 3-byte length). It is the same wire format as ServerHello — type 0x02, with hello_retry_request_random in the Random field.

The caller must feed msg into the transcript hash after calling this function and applying the transcript collapse (see transcript.messageHashSynthetic).

RFC 8446 §4.1.4, §4.2.2, §4.2.8.

pub fn parseHelloRetryRequestWithSessionIdEcho( msg: []const u8, expected_session_id: ?[]const u8, ) HrrParseError!HelloRetryRequest

src

pub fn encodeHelloRetryRequest( out: []u8, legacy_session_id_echo: []const u8, cipher_suite: CipherSuite, selected_group: NamedGroup, ) EncodeError![]const u8

src

Encode a TLS 1.3 HelloRetryRequest handshake message. The caller supplies the legacy_session_id_echo from ClientHello1. RFC 8446 §4.1.4, Appendix D.4.

pub fn encode( out: []u8, random: [32]u8, session_id_echo: []const u8, cipher_suite: CipherSuite, public_key: x25519.PublicKey, ) EncodeError![]const u8

src

Encode a TLS 1.3 ServerHello handshake message. The caller supplies the legacy_session_id_echo from ClientHello; tls' client currently sends an empty one, but the server path needs to echo arbitrary caller-owned bytes. RFC 8446 §4.1.3.

pub fn encodeWithKeyShare( out: []u8, random: [32]u8, session_id_echo: []const u8, cipher_suite: CipherSuite, key_share: *const KeyShare, ) EncodeError![]const u8

src

pub fn encodeWithKeyShareAndPsk( out: []u8, random: [32]u8, session_id_echo: []const u8, cipher_suite: CipherSuite, key_share: *const KeyShare, selected_identity: u16, ) EncodeError![]const u8

src

Encode a ServerHello that selects a PSK identity (RFC 8446 §4.1.3, §4.2.11). Adds a pre_shared_key extension carrying the selected_identity index after supported_versions. PSK resumption uses psk_dhe_ke. The key_share remains present.

pub fn parse(msg: []const u8) ParseError!ServerHello

src

msg must be the complete handshake message including the 4-byte header (type + 3-byte length). Feed it into the transcript hash before calling.

RFC 8446 §4.1.3

pub fn parseWithSessionIdEcho( msg: []const u8, expected_session_id: ?[]const u8, out: *ServerHello, ) ParseError!void

src

Types

struct ServerHello

src

Fields

cipher_suite: CipherSuite

The negotiated cipher suite. Determines which HKDF hash to use.

key_share: KeyShare

Server's ephemeral public key from the key_share extension.

selected_identity: ?u16 = null

PSK identity index selected by the server (RFC 8446 §4.2.11), or null when the server did not resume with a PSK.

struct HelloRetryRequest

src

A parsed HelloRetryRequest message. RFC 8446 §4.1.4.

more

The HRR is wire-encoded identically to a ServerHello (type 0x02) but with a fixed Random value (hello_retry_request_random). This struct carries the fields that a client needs to construct ClientHello2.

cookie is a slice into the caller-supplied message buffer — it is only valid for the lifetime of that buffer.

Fields

cipher_suite: CipherSuite

The cipher suite selected by the server. Determines the transcript hash.

selected_group: ?NamedGroup

The named group the server wants the client to use for its key share. Null when the HRR contains no key_share extension (unusual but legal).

cookie: ?[]const u8

The server cookie, if present. RFC 8446 §4.2.2. The client MUST echo this verbatim in the cookie extension of ClientHello2.

union KeyShare

src
pub const KeyShare = union(enum)

Fields

x25519: x25519.PublicKey
secp256r1: p256.PublicKey
secp384r1: p384.PublicKey
kem: struct { group: NamedGroup, data: buffer.Array(u8, max_kem_share_len), }

RFC 10024 §4.2 hybrid server share. Component order is group-specific.

Functions

pub fn group(self: *const KeyShare) NamedGroup

src

module ServerHandshake

src

TLS 1.3 server record adapter over handshake_core.Server.

The core owns negotiation, the transcript, and the key schedule. This file owns record framing, caller-owned reassembly, and backend record layers. No allocations and no I/O. RFC 8446 §4, §5, and Appendix A.

Constants

pub const max_out_len = frame.max_wire_record_len

src

Largest a single record can be on the wire: header + maximum ciphertext. An output buffer of this size always holds any one record we emit.

pub const OutBuffer = frame.OutBuffer

src

pub const max_fragmented_flight_out_len: usize = …

src
value
frame.max_plaintext_len +
    (std.math.divCeil(usize, frame.max_plaintext_len, 63) catch unreachable) * RecordLayer.overhead

RFC 8449 §4 permits 63 content bytes per record, so a maximum-sized flight needs one record per 63 plaintext bytes in the worst case.

pub const FlightBuffer = buffer.Array(u8, max_fragmented_flight_out_len)

src

Prepared flights stage handshake plaintext in the record payload and encrypt it in place, so the caller needs only one buffer.

pub const SignError = signature.SignError

src

pub const CredentialError = certificate.ChainSignatureSchemesError

src

pub const SendError = handshake.SendError

src

pub const ReceiveError = handshake.ReceiveError

src

pub const AlertError = handshake.AlertError

src

pub const max_ticket_identity_len = 256

src

pub const ch_reassembly_buffer_size = handshake_header_len + 2 * frame.max_plaintext_len

src

pub const Storage = buffer.Array(u8, ch_reassembly_buffer_size)

src

pub const ConfigError = ServerConfig.ValidationError

src

pub const PrepareTicketError = …

src
value
error{
    NoResumptionSecret,
    IncompatiblePskModes,
    PendingTicket,
    TooManyNewSessionTickets,
    KtlsTxActive,
}

pub const TicketSendError = …

src
value
SendError || NewSessionTicket.EncodeError || error{
    InvalidTicketPsk,
    IncompatiblePskModes,
    KtlsTxActive,
}

pub const AcceptError = …

src
value
frame.ParseError || client_hello.ParseError || CoreError ||
    error{ IncompleteRecord, UnexpectedRecord }

pub const FlightError = CoreError || RecordLayer.EncryptError || error{PendingWrite}

src

pub const ClientFinishedError = …

src
value
CoreError || RecordLayer.DecryptError || frame.ParseError ||
    error{ UnexpectedRecord, UnsupportedClientCertificate }

pub const HandleError = …

src
value
AcceptError || FlightError || ClientFinishedError ||
    ReceiveError || SendError || alert.ParseError || error{PendingWrite}

pub const KtlsTxTransferError = error{ PendingWrite, PendingKeyUpdateResponse, PendingTicket }

src

Functions

pub fn init(server_config: ServerConfig, config: Config) ServerHandshake

src

pub fn bindStorage(self: *ServerHandshake, storage: StorageBinding) void

src

Bind lent storage after a self-referential wrapper reaches its final address.

pub fn deinit(self: *ServerHandshake) void

src

pub fn state(self: *const ServerHandshake) State

src

pub fn isConnected(self: *const ServerHandshake) bool

src

pub fn isResumed(self: *const ServerHandshake) bool

src

pub fn canIssueTicket(self: *const ServerHandshake) bool

src

True when the connected handshake can still emit a NewSessionTicket over userspace TX (client offered psk_dhe_ke and kTLS TX is not active).

pub fn completeWrite(self: *ServerHandshake) void

src

pub fn hasPendingWrite(self: *const ServerHandshake) bool

src

pub fn hasPendingTicket(self: *const ServerHandshake) bool

src

pub fn hasPendingKeyUpdateResponse(self: *const ServerHandshake) bool

src

pub fn needsServerFlight(self: *const ServerHandshake) bool

src

pub fn setServerCredentials( self: *ServerHandshake, credentials: ConfiguredCredentials, ) CredentialError!void

src

Select a pre-validated generation after inspecting clientServerName(). The handshake stays pinned; only its borrowed credential configuration changes.

pub fn lastPeerAlert(self: *const ServerHandshake) ?alert.Alert

src

pub fn trafficSecrets( self: *const ServerHandshake, ) error{NotRetained}!*const traffic_secrets.TrafficSecrets

src

pub fn missingExtension(self: *const ServerHandshake) u16

src

pub fn selectedAlpnProtocol(self: *const ServerHandshake) ?[]const u8

src

pub fn cipherSuite(self: *const ServerHandshake) CipherSuite

src

pub fn negotiatedGroup(self: *const ServerHandshake) ?NamedGroup

src

The key-exchange group the handshake settled on, or null before it has one. A server that must not serve classical key exchange checks this against capabilities.hybrid_groups and closes the connection otherwise.

pub fn clientServerName(self: *const ServerHandshake) ?[]const u8

src

pub fn clientCertificateDer(self: *const ServerHandshake) ?[]const u8

src

pub fn clientCertificate(self: *const ServerHandshake) ?Certificate.Parsed

src

pub fn extractEstablished(self: *ServerHandshake) EstablishedSession

src

pub fn deriveTicketPsk(self: *ServerHandshake) PrepareTicketError!TicketPsk

src

pub fn discardTicketPsk(self: *ServerHandshake, ticket: *TicketPsk) error{InvalidTicketPsk}!void

src

pub fn sendNewSessionTicket( self: *ServerHandshake, prepared: *const TicketPsk, params: TicketParams, out: []u8, ) TicketSendError![]const u8

src

pub fn acceptClientHello( self: *ServerHandshake, record: []const u8, out: []u8, ) AcceptError![]const u8

src

pub fn selectPsk( parsed: client_hello.Parsed, msg: []const u8, lookup: PskLookup, negotiated_suite: CipherSuite, ) error{ InvalidExtensionLength, InvalidVectorLength, UnexpectedEof, InvalidPskBinder, }!?struct { entry: PskEntry, identity_index: usize, }

src

pub fn sendServerFlight(self: *ServerHandshake, out: []u8) FlightError!?[]const u8

src

pub fn sendServerFlightBuffered( self: *ServerHandshake, out: *FlightBuffer, ) FlightError!?[]u8

src

pub fn handleRecord(self: *ServerHandshake, record: []u8, out: []u8) HandleError!Event

src

pub fn processClientFinished(self: *ServerHandshake, record: []u8) ClientFinishedError!void

src

pub fn processClientFinishedMessage( self: *ServerHandshake, plaintext: []const u8, ) ClientFinishedError!void

src

pub fn receiveRecord(self: *ServerHandshake, record: []u8) ReceiveError!ReceiveEvent

src

pub fn receiveKtlsRecord( self: *ServerHandshake, content_type: frame.ContentType, content: []u8, ) ReceiveError!ReceiveEvent

src

pub fn sendKeyUpdate( self: *ServerHandshake, out: []u8, request: KeyUpdateRequest, ) SendError![]u8

src

pub fn ratchetKtlsTx(self: *ServerHandshake, request: KeyUpdateRequest) SendError!void

src

pub fn sendAlert( self: *ServerHandshake, description: alert.Description, out: []u8, ) AlertError![]const u8

src

pub fn maxOutboundPlaintext(self: *const ServerHandshake) usize

src

RFC 8449 §4 — largest application fragment the current TX epoch accepts.

pub fn maxInboundPlaintext(self: *const ServerHandshake) usize

src

RFC 8449 §4 — largest application fragment the current RX epoch accepts.

pub fn sendApplicationData( self: *ServerHandshake, plaintext: []const u8, out: []u8, ) SendError![]u8

src

pub fn sendPreparedApplicationData( self: *ServerHandshake, plaintext_len: usize, out: []u8, ) SendError![]u8

src

pub fn txKtlsInfo(self: *const ServerHandshake) RecordLayer.KtlsInfo

src

pub fn markKtlsTxInstalled(self: *ServerHandshake) KtlsTxTransferError!void

src

pub fn rxKtlsInfo(self: *const ServerHandshake) RecordLayer.KtlsInfo

src

pub fn receiveApplicationData(self: *ServerHandshake, record: []u8) ReceiveError![]const u8

src

Types

enum KeyUpdateRequest

src
pub const KeyUpdateRequest = handshake.KeyUpdateRequest

RFC 8446 §4.6.3 — whether the KeyUpdate recipient must respond with its own.

Fields

update_not_requested update_not_requested = 0
update_requested update_requested = 1

struct KeyPairs

src
pub const KeyPairs = handshake_key_pairs.KeyPairs

Fields

x25519: x25519.KeyPair

Only secret_key is meaningful until derived contains .x25519.

p256: p256.KeyPair

Only secret_key is meaningful until derived contains .p256.

p384: ?p384.KeyPair
derived: std.EnumSet(Public)

The public keys that hold their scalar's point. A server can defer one: it stays all zero until deriveFor fills it. Every byte zero reads as nothing derived, so a wiped keypair cannot pass for one whose all-zero keys are real. P-384 is never deferred.

Constants

pub const DeriveError = x25519.Error || p256.Error

src

Functions

pub fn init(x25519_keypair: x25519.KeyPair) p256.Error!KeyPairs

src

Fallible because generating the P-256 half is: the backend can refuse, and a refusal it would repeat is the caller's to handle (shed this handshake), not this function's to hide behind a retry (#88).

pub fn initWithP256( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, ) KeyPairs

src

pub fn initDeferredP256( x25519_keypair: x25519.KeyPair, p256_secret: p256.SecretKey, ) KeyPairs

src

Server only: defer the P-256 public key. It is a fixed-base scalar multiplication (plus the backend's key check), wasted on every client that picks X25519. ServerHandshake derives it when a ClientHello selects a P-256 group. A client must send its shares up front, so ClientHandshake rejects deferred keypairs.

pub fn initDeferred(x25519_secret: x25519.SecretKey, p256_secret: p256.SecretKey) KeyPairs

src

Server only: defer both public keys. The server then pays one fixed-base multiplication, for the group the ClientHello selects, instead of one per group (#136). Same client rule as initDeferredP256.

pub fn deriveFor(self: *KeyPairs, group: NamedGroup) DeriveError!void

src

Derive the deferred public key that group puts on the wire: its own for a classical group, its classical component's for a hybrid. No-op for a key that was never deferred or is derived already.

pub fn initWithP256P384( x25519_keypair: x25519.KeyPair, p256_keypair: p256.KeyPair, p384_keypair: p384.KeyPair, ) KeyPairs

src

pub fn secureZero(self: *KeyPairs) void

src

Types

enum Public

src

Fields

x25519 x25519
p256 p256

struct Signer

src
pub const Signer = signature.Signer

Fields

scheme: SignatureScheme
context: *anyopaque
sign: *const fn (context: *anyopaque, msg: []const u8, out: []u8) SignError![]const u8

struct PskEntry

src
pub const PskEntry = Core.PskEntry

Fields

psk: buffer.Array(u8, max_psk_len)
cipher_suite: CipherSuite
kind: hkdf.PskKind
alpn: ?[]const u8

Constants

pub const empty: PskEntry = …

src
value
.{
            .psk = .empty,
            .cipher_suite = .aes_128_gcm_sha256,
            .kind = .resumption,
            .max_early_data_size = null,
            .alpn = null,
        }

Functions

pub fn init(psk: []const u8, cipher_suite: CipherSuite) PskEntry

src

pub fn pskSlice(self: *const PskEntry) []const u8

src

pub fn secureZero(self: *PskEntry) void

src

struct PskQuery

src
pub const PskQuery = Core.PskQuery

Context passed to PskLookup.lookup for each offered identity. server_name and selected_alpn come from the parsed ClientHello (ALPN selection runs before PSK lookup) so stateless ticket openers can authenticate both in AAD without storing them in the ticket payload.

Fields

identity: []const u8
server_name: ?[]const u8
selected_alpn: ?[]const u8

struct PskLookup

src
pub const PskLookup = Core.PskLookup

Pure, idempotent PSK resolution callback. Ticket identities travel in cleartext in the ClientHello, so lookup must not consume single-use state before the engine verifies the binder. Write the resolved entry into out and return true, or return false for a miss.

Fields

context: *anyopaque
lookup: *const fn (context: *anyopaque, query: *const PskQuery, out: *PskEntry) bool

struct SelectedPsk

src
pub const SelectedPsk = Core.SelectedPsk

Secret-free PSK selection metadata retained after handshake secrets are derived. The PSK bytes themselves are wiped at ServerHello.

Fields

kind: hkdf.PskKind
cipher_suite: CipherSuite
alpn: ?[]const u8

enum ClientAuthPolicy

src
pub const ClientAuthPolicy = Core.ClientAuthPolicy

Fields

none none
optional optional
required required

enum EarlyDataSkip

src
pub const EarlyDataSkip = Core.EarlyDataSkip

Fields

off off
pending_decision pending_decision
await_client_hello2 await_client_hello2
trial_decrypt trial_decrypt

struct Credentials

src
pub const Credentials = handshake_core.Credentials

What a role signs with when it authenticates. Construction parses the chain once so accepting a connection only intersects the retained two-byte bitset.

Fields

chain: CertificateChain
signer: signature.Signer
required: signature.OfferedCertificateSchemes

Constants

pub const InitError = certificate.ChainSignatureSchemesError

src

Functions

pub fn init(chain: CertificateChain, signer: signature.Signer) InitError!Credentials

src

RFC 8446 §4.2.3, §4.4.2.2 — validate the configured chain at load or rotation time rather than reparsing its DER for every connection.

union Event

src
pub const Event = handshake.Event

What a handled inbound record yielded. One shape covers both the handshake and connected phases, for both roles. new_session_ticket is client-role only, because tickets are server-issued. A connected engine returns neither write nor new_session_ticket.

Fields

application_data: []const u8

Decrypted application data (a slice into the caller's record buffer).

write: []const u8

A record that MUST be written to the transport before the engine may be called again — the server's ServerHello, the client's Finished, or a KeyUpdate response from either role. Written into out.

key_update: KeyUpdateEvent

The peer's KeyUpdate ratcheted one or both traffic keys. See KeyUpdateEvent for details. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: the server sent a NewSessionTicket post-handshake. The caller may call deriveSessionTicket to obtain a storable SessionTicket (identity + PSK + age/lifetime). The parsed fields borrow the caller's record buffer; copy what you need before the next handleRecord. RFC 8446 §4.6.1.

none none

Handled internally; nothing for the caller to do.

closed closed

The peer sent close_notify.

union ReceiveEvent

src
pub const ReceiveEvent = handshake.ReceiveEvent

Connected-state receive result. This path owns only RX state, so callers can process inbound records while an unrelated TX record remains in flight.

Fields

application_data: []const u8
key_update: KeyUpdateRequest

The RX key is already ratcheted. For update_requested, the caller MUST send update_not_requested before its next application-data record. RFC 8446 §4.6.3, §7.2.

new_session_ticket: NewSessionTicket

Client role only: see Event.new_session_ticket. A server never receives one, because tickets are issued by the server.

none none
closed closed

struct KeyUpdateEvent

src
pub const KeyUpdateEvent = handshake.KeyUpdateEvent

Surfaced when a peer KeyUpdate changes one or both traffic-key epochs. RFC 8446 §4.6.3. For kTLS callers: rx means the kernel RX path is paused (EKEYEXPIRED) until the new key is installed via setsockopt(TLS_RX); tx means the caller must reinstall TLS_TX after writing response and calling completeWrite().

Fields

response: ?[]const u8

Record to send first (the KeyUpdate response), or null if the peer sent update_not_requested and no response is needed. The caller MUST write this to the transport and call completeWrite() before reinstalling TLS_TX. The response is encrypted under the OLD TX key — the engine ratchets TX inside sendKeyUpdate after encryption.

rx: bool

RX traffic key was ratcheted — caller must reinstall TLS_RX.

tx: bool

TX traffic key was ratcheted (we are sending a KeyUpdate response) — caller must reinstall TLS_TX after writing response and calling completeWrite().

struct ServerNameCredential

src

Fields

server_name: []const u8
credentials: Credentials

struct ServerNameCredentials

src

RFC 6066 HostName matches ignore ASCII case as DNS names do (RFC 1035 §2.3.3). The fallback also serves clients that omit SNI; null leaves certificate authentication unavailable unless the handshake selects a PSK.

Fields

entries: []const ServerNameCredential
fallback: ?Credentials = null

union ConfiguredCredentials

src
pub const ConfiguredCredentials = union(enum)

Server credentials are configuration, not mutable handshake state. Candidate order is server preference; the core intersects each retained scheme bitset with the offer without parsing certificate DER.

Fields

none none
single: Credentials
candidates: []const Credentials
by_server_name: ServerNameCredentials

Functions

pub fn validate(self: *const ConfiguredCredentials) CredentialError!void

src

struct ServerConfig

src

Listener-wide policy borrowed by each connection.

Fields

supported_suites: []const CipherSuite = default_supported_suites
alpn_protocols: root.AlpnProtocols = &.{}
credentials: ConfiguredCredentials = .none
client_auth: ClientAuthPolicy = .none
client_auth_bundle: ?*const crypto.Certificate.Bundle = null
psk_lookup: ?PskLookup = null
hybrid_groups: []const NamedGroup = capabilities.recommended_server_groups

RFC 10024 hybrid groups accepted, in server preference order. Defaults to every group the backend implements; &.{} serves classical key exchange only.

early_data_skip_limit: u32 = default_early_data_skip_limit
record_size_limit: ?u16 = null

RFC 8449 §4 — the TLSInnerPlaintext limit advertised to offering clients.

Constants

pub const ValidationError = …

src
value
capabilities.HybridPolicyError ||
        error{ MissingP384KeyPair, InvalidRecordSizeLimit } || CredentialError

Functions

pub fn validate(self: *const ServerConfig, keypairs: *const KeyPairs) ValidationError!void

src

struct Config

src

Per-connection randomness, key material, and caller-owned storage.

Fields

keypairs: KeyPairs
random: Random
reassembly: ?[]u8 = null
client_cert_buffer: ?[]u8 = null
extra_extensions: []const extension_type.ExtraExtension = &.{}
required_extensions: []const u16 = &.{}
peer_extensions: ?*encrypted_extensions.ExtensionSink = null
traffic_secrets: ?*traffic_secrets.TrafficSecrets = null

struct StorageBinding

src

Storage whose address becomes stable only after an enclosing wrapper is pinned.

Fields

reassembly: ?[]u8 = null
client_certificate: ?[]u8 = null
traffic_secrets: ?*traffic_secrets.TrafficSecrets = null

enum State

src

Fields

wait_ch wait_ch
wait_client_finished wait_client_finished
connected connected
extracted extracted

struct TicketPsk

src

Fields

psk: buffer.Array(u8, 48)
cipher_suite: CipherSuite
ticket_nonce: [1]u8

Functions

pub fn init(cipher_suite: CipherSuite, ticket_nonce: [1]u8) TicketPsk

src

pub fn secureZero(self: *TicketPsk) void

src

struct TicketParams

src

Fields

ticket: []const u8
max_early_data_size: ?u32 = null

RFC 8446 §4.2.10 — absent keeps early data disabled for this ticket.

module signature

src

Signature helpers for TLS 1.3 CertificateVerify.

Constants

pub const max_certificate_signature_schemes = signature_scheme.max_certificate_signature_schemes

src

pub const ExplicitLoadError = …

src
value
if (backend.active == .native)
    LegacySignatureError || NativeSignatureExtras || NativeKeyLoadExtras
else
    LegacySignatureError

pub const SignError = …

src
value
if (backend.active == .native)
    LegacySignatureError || NativeSignatureExtras || error{DeterministicNonceUnsupported}
else
    LegacySignatureError || error{DeterministicNonceUnsupported}

pub const ScalarKeyError = …

src
value
if (backend.active == .native)
    LegacySignatureError || NativeSignatureExtras || error{InvalidPrivateKey}
else
    LegacySignatureError

pub const NonceMode = backend.sign.NonceMode

src

pub const LoadError = ExplicitLoadError || error{UnsupportedKeyScheme}

src

fromPemAuto load failure: the explicit loader errors plus the scheme-inference rejection (#112). fromPem and fromDer return backend.sign.LoadError directly, so this alias adds UnsupportedKeyScheme only to automatic loading.

pub const PairError = error{ CertificateKeyMismatch, InvalidCertificate }

src

pairsWith contract (#113): the leaf parsed but its key does not pair with the loaded private key (CertificateKeyMismatch), or the DER is not parseable X.509 (InvalidCertificate).

Functions

pub fn fromProvider(scheme: backend.SignatureAlgorithm) SignatureScheme

src

Types

struct OfferedCertificateSchemes

src
pub const OfferedCertificateSchemes = signature_scheme.OfferedCertificateSchemes

TLS 1.3 certificate signature schemes from a peer's effective signature_algorithms_cert list (or fallback signature_algorithms). Retain the mask instead of slices into a transient handshake record.

Fields

set: std.bit_set.Integer(max_certificate_signature_schemes)

Constants

pub const empty: OfferedCertificateSchemes = .{ .set = .empty }

src

Functions

pub fn clear(self: *OfferedCertificateSchemes) void

src

pub fn capture(self: *OfferedCertificateSchemes, wire_schemes: []const u8) void

src

Capture a validated, big-endian SignatureScheme vector.

pub fn captureSchemes( self: *OfferedCertificateSchemes, schemes: []const SignatureScheme, ) void

src

Capture an in-memory slice of SignatureScheme values.

pub fn insert(self: *OfferedCertificateSchemes, scheme: SignatureScheme) void

src

pub fn contains(self: OfferedCertificateSchemes, scheme: SignatureScheme) bool

src

pub fn eql(self: OfferedCertificateSchemes, other: OfferedCertificateSchemes) bool

src

pub fn containsAll( self: OfferedCertificateSchemes, required: OfferedCertificateSchemes, ) bool

src

pub fn intersect( self: OfferedCertificateSchemes, allowed: []const SignatureScheme, out: *[max_certificate_signature_schemes]SignatureScheme, ) []const SignatureScheme

src

Write the intersection of self and allowed into caller storage.

struct Signer

src

Fields

scheme: SignatureScheme
context: *anyopaque
sign: *const fn (context: *anyopaque, msg: []const u8, out: []u8) SignError![]const u8

struct OfferedSchemes

src

TLS 1.3 CertificateVerify schemes from a peer's signature_algorithms. Retain the mask instead of slices into a transient handshake record.

Fields

set: std.bit_set.Integer(signable_certificate_verify_schemes.len)

Constants

pub const empty: OfferedSchemes = .{ .set = .empty }

src

Functions

pub fn clear(self: *OfferedSchemes) void

src

pub fn capture(self: *OfferedSchemes, wire_schemes: []const u8) void

src

Capture a validated, big-endian SignatureScheme vector.

pub fn contains(self: OfferedSchemes, scheme: SignatureScheme) bool

src

struct PrivateKey

src

Fields

scheme: SignatureScheme
key: backend.sign.pkey
nonce_mode: NonceMode

RFC 6979 nonce strategy (baskingspot/tls#82): .deterministic makes identical ECDSA key and message yield identical signature bytes for byte-reproducible seeded transcripts on every backend. RSA-PSS rejects that mode rather than silently signing with a random nonce. Ed25519 is deterministic PureEdDSA under RFC 8032 in either mode.

Functions

pub fn fromDer(scheme: SignatureScheme, der: []const u8) ExplicitLoadError!PrivateKey

src

pub fn fromPem(scheme: SignatureScheme, pem: []const u8) ExplicitLoadError!PrivateKey

src

pub fn fromPemAuto(pem: []const u8) LoadError!PrivateKey

src

RFC 8446 §4.2.3 — infer the CertificateVerify scheme from the loaded key (#112). The explicit fromPem stays caller-pins-scheme; this path derives the scheme from the key's exact type and curve, then gates it against the active backend's advertised CertificateVerify schemes. A key the backend loads but cannot sign (P-521 today) fails here with error.UnsupportedKeyScheme, at load time instead of at the first handshake signature.

pub fn fromDerAuto(der: []const u8) LoadError!PrivateKey

src

RFC 8446 §4.2.3 — DER counterpart to fromPemAuto. The backend owns PKCS#8/SEC1 parsing; this layer owns scheme inference and policy.

pub fn fromEd25519Seed(seed: *const [Ed25519.KeyPair.seed_length]u8) LoadError!PrivateKey

src

RFC 8410 §7 — wrap a 32-byte Ed25519 seed in its PKCS#8 PrivateKeyInfo encoding so every backend uses the same validated key-loading path.

pub fn fromP256Scalar(scalar: *const [32]u8) ScalarKeyError!PrivateKey

src

pub fn deinit(self: *PrivateKey) void

src

pub fn signer(self: *PrivateKey) Signer

src

pub fn sign(self: *const PrivateKey, msg: []const u8, out: []u8) SignError![]const u8

src

pub fn pairsWith(self: *const PrivateKey, leaf_cert_der: []const u8) PairError!void

src

RFC 8446 §4.4.3 — the CertificateVerify signature must be made with the private key matching the end-entity certificate's public key (§4.4.2: the sender's certificate is first, so the leaf is element [0] of the chain). Explicit load-time validation for startup and certificate rotation (#113): error.CertificateKeyMismatch means the leaf parsed but the keys do not pair; error.InvalidCertificate means the input is not exactly one DER-encoded X.509 certificate — distinct outcomes, so a rotation log can tell a wrong pairing from a corrupt file. Both inputs are borrowed. Libcrypto owns and frees its parsed X509 inside the backend wrapper, while native parses DER without allocation. The private key is only read, so ownership and zeroization stay with deinit. Rotation lifetime: a PrivateKey must outlive every Signer it handed out — swap credentials only when no in-flight handshake holds the old signer.

module ticket

src

Allocation-free stateless session ticket sealing, opening, and key rotation.

Constants

pub const version: u8 = 1

src

pub const key_id_len = 4

src

pub const secret_len = Aes256Gcm.key_length

src

pub const nonce_len = Aes256Gcm.nonce_length

src

pub const tag_len = Aes256Gcm.tag_length

src

pub const header_len = 1 + key_id_len + nonce_len

src

pub const sealed_len_sha256 = header_len + plaintext_fixed_len + 32 + tag_len

src

pub const sealed_len_sha384 = header_len + plaintext_fixed_len + 48 + tag_len

src

pub const max_sealed_len = sealed_len_sha384

src

pub const max_keys = 4

src

pub const SealError = …

src
value
error{
    BufferTooShort,
    EmptyKeyRing,
    InvalidPskLength,
    TicketLifetimeTooLong,
    ZeroTicketLifetime,
    AuthLifetimeExpired,
    ServerNameTooLong,
    AlpnTooLong,
}

Types

struct Key

src

One ticket-encryption key (STEK) identified by a random 4-byte key ID.

Fields

id: [key_id_len]u8
secret: [secret_len]u8

Functions

pub fn secureZero(self: *Key) void

src

struct SealParams

src

Fields

psk: *const ServerHandshake.TicketPsk
nonce: [nonce_len]u8

Fresh 96-bit random nonce per issued ticket.

ticket_age_add: u32

Fresh 32-bit random obfuscation value mirrored in NewSessionTicket.

issued_at_ms: i64

Current wall/epoch time in milliseconds.

lifetime_sec: u32

Requested ticket lifetime in seconds (1..=604800).

auth_not_after_ms: ?i64 = null

Optional total authentication deadline (ms). When re-issuing on a resumed connection, pass the opened ticket's auth_not_after_ms so re-issuance cannot extend original authentication forever (RFC 8446 §4.6.1). Null defaults to issued_at_ms + lifetime_sec * 1000.

server_name: ?[]const u8 = null

SNI authenticated on this connection (bound in AAD, ASCII case-folded).

alpn: ?[]const u8 = null

ALPN selected on this connection (bound in AAD, exact bytes).

struct SealedTicket

src

Fields

identity: []const u8

Sealed opaque ticket identity slice backed by caller's out buffer.

lifetime_sec: u32

Effective lifetime in seconds (clamped to remaining auth_not_after_ms).

auth_not_after_ms: i64

Authentication deadline sealed inside the ticket.

struct OpenPolicy

src

Fields

now_ms: i64

Current wall/epoch time in milliseconds.

max_future_skew_ms: u32 = 60_000

Allowed clock skew for issued_at_ms in the future (e.g. fleet keys).

max_age_ms: ?u64 = null

Optional server-side maximum ticket age in ms, tighter than the ticket's sealed lifetime_sec.

age_window_ms: ?u32 = null

Optional tolerance (ms) between server elapsed age and the client's de-obfuscated obfuscated_ticket_age -% ticket_age_add. Null disables client-age window rejection (RFC 8446 §4.2.10 only mandates it for 0-RTT).

struct OpenedTicket

src

Fields

entry: ServerHandshake.PskEntry

Constants

pub const empty: OpenedTicket = …

src
value
.{
        .entry = .empty,
        .issued_at_ms = 0,
        .auth_not_after_ms = 0,
        .ticket_age_add = 0,
        .lifetime_sec = 0,
    }

Functions

pub fn secureZero(self: *OpenedTicket) void

src

struct KeyRing

src

Fixed-capacity rotating ticket key ring. Key 0 seals new tickets; every key in the ring can open tickets matching its id.

Fields

keys: buffer.Array(Key, max_keys)

Constants

pub const empty: KeyRing = .{ .keys = .empty }

src

Functions

pub fn init(initial: Key) KeyRing

src

pub fn rotate(self: *KeyRing, next_key: Key) void

src

Install next_key as the active sealing key (index 0) and retain older keys for decryption up to max_keys. Any evicted key is wiped.

pub fn secureZero(self: *KeyRing) void

src

pub fn sealedLen(suite: CipherSuite) usize

src

pub fn seal(self: *const KeyRing, params: SealParams, out: []u8) SealError!SealedTicket

src

Seal a derived TicketPsk into caller-owned out.

pub fn open( self: *const KeyRing, query: *const ServerHandshake.PskQuery, policy: OpenPolicy, out: *OpenedTicket, ) bool

src

Open and validate a ticket offered in a ClientHello. Any failure (unknown key, bad tag, SNI/ALPN mismatch, expiry, skew, or age window) wipes out and returns false so the server falls back to a full handshake.

pub fn openEntry( self: *const KeyRing, query: *const ServerHandshake.PskQuery, policy: OpenPolicy, out: *ServerHandshake.PskEntry, ) bool

src

Convenience adapter for ServerHandshake.PskLookup callbacks that need only the PskEntry output.

module traffic_secrets

src

Optional retention of TLS 1.3 traffic secrets (RFC 8446 §7.1).

Constants

pub const max_len = 48

src

Longest traffic secret: a SHA-384 output.

Types

struct Secret

src

One traffic secret. len is the negotiated hash length, 32 for SHA-256 suites and 48 for SHA-384.

Fields

data: [max_len]u8
len: u8

Functions

pub fn init(raw: []const u8) Secret

src

pub fn bytes(self: *const Secret) []const u8

src

pub fn secureZero(self: *Secret) void

src

struct TrafficSecrets

src

The secrets a caller asked to keep. Each is null until the handshake derives it, so a caller can tell "not yet" from "not retained".

Fields

client_handshake: ?Secret

RFC 8446 §7.1 - "c hs traffic", "s hs traffic".

server_handshake: ?Secret
client_application: ?Secret

RFC 8446 §7.1 - "c ap traffic", "s ap traffic".

client_early: ?Secret

RFC 8446 §7.1 - "c e traffic". Only with 0-RTT.

len: u8

Negotiated hash length: 32 or 48. Zero before negotiation.

Functions

pub fn init() TrafficSecrets

src

pub fn secureZero(self: *TrafficSecrets) void

src

Wipe every held secret. The caller owns this storage and owns clearing it; the engine never writes lent memory on teardown.

pub fn setHandshake(self: *TrafficSecrets, client: []const u8, server: []const u8) void

src

pub fn setClientApplication(self: *TrafficSecrets, bytes: []const u8) void

src

pub fn setServerApplication(self: *TrafficSecrets, bytes: []const u8) void

src

pub fn setClientEarly(self: *TrafficSecrets, bytes: []const u8) void

src

pub fn expand( comptime Hkdf: type, secret: *const Secret, comptime label: []const u8, out: []u8, ) void

src

RFC 8446 §7.1 HKDF-Expand-Label over a held secret, with an empty context. RFC 9001 §5.1 uses exactly this form with the labels "quic key", "quic iv", and "quic hp" - those labels belong to the QUIC implementation, not here.

enum SignatureScheme

src
pub const SignatureScheme = @import("signature_scheme.zig").SignatureScheme

RFC 8446 §4.2.3 signature schemes supported by tls.

Fields

rsa_pkcs1_sha256 rsa_pkcs1_sha256 = 0x0401
rsa_pkcs1_sha384 rsa_pkcs1_sha384 = 0x0501
rsa_pkcs1_sha512 rsa_pkcs1_sha512 = 0x0601
ecdsa_secp256r1_sha256 ecdsa_secp256r1_sha256 = 0x0403
ecdsa_secp384r1_sha384 ecdsa_secp384r1_sha384 = 0x0503
ecdsa_secp521r1_sha512 ecdsa_secp521r1_sha512 = 0x0603
rsa_pss_rsae_sha256 rsa_pss_rsae_sha256 = 0x0804
rsa_pss_rsae_sha384 rsa_pss_rsae_sha384 = 0x0805
rsa_pss_rsae_sha512 rsa_pss_rsae_sha512 = 0x0806
ed25519 ed25519 = 0x0807
_ _

Constants

pub const supported_handshake: []const SignatureScheme = …

src
value
&.{
        .ecdsa_secp256r1_sha256,
        .ecdsa_secp384r1_sha384,
        .rsa_pss_rsae_sha256,
        .rsa_pss_rsae_sha384,
        .ed25519,
    }

pub const supported_certificate: []const SignatureScheme = …

src
value
&.{
        .rsa_pkcs1_sha256,
        .rsa_pkcs1_sha384,
        .rsa_pkcs1_sha512,
        .ecdsa_secp256r1_sha256,
        .ecdsa_secp384r1_sha384,
        .rsa_pss_rsae_sha256,
        .rsa_pss_rsae_sha384,
        .rsa_pss_rsae_sha512,
        .ed25519,
    }

Functions

pub fn supportsHandshake(self: SignatureScheme) bool

src

module x25519

src

X25519 ephemeral key exchange for TLS 1.3.

RFC 8446 §4.2.8.2, RFC 7748

Constants

pub const Error = backend.x25519.Error

src

pub const public_length = 32

src

pub const secret_length = 32

src

pub const PublicKey = stdx.mem.Array(public_length)

src

pub const SecretKey = stdx.mem.Array(secret_length)

src

Functions

pub fn sharedSecret( secret_key: SecretKey, peer_public_key: PublicKey, out: *[secret_length]u8, ) Error!void

src

Compute the X25519 shared secret from our secret key and the peer's public key. The result feeds directly into hkdf.handshakeSecret as the DHE input.

RFC 8446 §7.4.2 The caller owns out. The function clears out on error.

Types

struct KeyPair

src

Caller-owned X25519 keypair. The secret key is the raw 32-byte scalar input; the libcrypto backend performs RFC 7748 clamping internally.

Fields

secret_key: SecretKey
public_key: PublicKey

Functions

pub fn generate() KeyPair

src

Generate a keypair using the OS CSPRNG. Aborts if the CSPRNG is unavailable (see entropy.fill). Use fromSecret to supply entropy.

pub fn fromSecret(secret_key: SecretKey) Error!KeyPair

src

Construct a keypair from a caller-supplied raw scalar. Production callers must supply fresh CSPRNG bytes for each handshake. The backend performs RFC 7748 clamping during public-key derivation.

pub fn generateDeterministic(seed: SecretKey) Error!KeyPair

src

pub fn secureZero(self: *KeyPair) void

src

pub const Random = Array(32)

src

RFC 8446 §4.1.2 — ClientHello random bytes.