Skip to content

Latest commit

 

History

History
738 lines (624 loc) · 51.3 KB

TLS.md

File metadata and controls

738 lines (624 loc) · 51.3 KB

TLS 1.3 in stdnet

stdnet ships a built-in TLS 1.3 engine, client and server, extracted from WebFront's TLS (WebFront #631, ADR-024) and reworked for stdnet (#33): no exception, no allocation on the record path, errors as values, and credentials loaded from memory. It is header-only and links no TLS library. The same adaptors also drive an OpenSSL engine (hosted systems, Web PKI) and an mbedTLS engine (the TLS library of ESP-IDF and of most Cortex-M SDKs): see Engines.

Reviewed for timing, not externally audited. Every operation of the built-in engine on a secret (X25519, P-256 scalar multiplication and ECDH, ECDSA signing, HKDF, ChaCha20-Poly1305, AES-128-GCM, the MAC and Finished checks, the removal of the record padding, the base64 decoding of a PEM key) is checked for secret-dependent branches and memory addresses with Valgrind on x86-64, and for secret-dependent branches and variable-time instructions in the Thumb code of the Cortex-M0, M3, M4 and M33 under QEMU (Constant time). No third party has audited the engine; the audit is prepared in TLS-AUDIT.md (scope, threat model, evidence, questions), not commissioned. Power or electromagnetic side channels are out of scope. ECDSA and RSA verification handle public data only and are not constant time.

Two surfaces

TAPS (the portable surface). security_parameters{} on a preconnection means "secure transport required" (SPEC D6). A listener with a local identity performs the handshakes and async_accept delivers connections whose handshake is complete:

auto id = net::tls::credentials::from_pem(chain_pem, key_pem);          // from memory
net::listener l = net::listen(ctx, net::preconnection(
        net::local_endpoint().with_port(8443), net::transport_properties::reliable_stream(),
        net::security_parameters{}.local_identity(id).alpn({"h2", "http/1.1"})));
net::connection c = co_await net::async_accept(l);                      // handshake done
std::size_t n = co_await net::async_receive(c, net::buffer(buf));       // decrypted; 0 = close_notify
co_await net::async_send(c, net::buffer(reply));                        // encrypted
c.close();                                                              // sends close_notify

A client states how it authenticates the server, then initiate connects, runs the handshake and delivers a connection once the server is authenticated:

auto pin = net::tls::certificate::from_pem(server_cert_pem);             // the server's certificate
net::preconnection pc(net::remote_endpoint().with_hostname("device.local").with_port(8443),
                      net::transport_properties::reliable_stream(),
                      net::security_parameters{}.pinned_server_certificate({pin}).alpn({"http/1.1"}));
net::connection c = co_await net::initiate(sch, std::move(pc));          // TCP, then TLS 1.3
co_await net::async_send(c, net::buffer(request));

or, with the TAPS trust-verification callback, a sender of bool:

auto sp = net::security_parameters{}.trust_verification([&](const net::tls::trust_request& r) {
    return check_with_my_policy(r.server_name, r.certificates);          // any sender of bool
});

With the OpenSSL or mbedTLS engine, a client given neither a pin nor a trust verification validates the server with the Web PKI, against the system's trust store (OpenSSL) or the roots it is given (trust_anchors, a stdnet extension; required with mbedTLS, which has no system store):

net::preconnection pc(net::remote_endpoint().with_hostname("example.com").with_port(443),
                      net::transport_properties::reliable_stream(),
                      net::security_parameters{}.alpn({"http/1.1"}));        // Web PKI (OpenSSL)
auto sp = net::security_parameters{}.trust_anchors({net::tls::certificate::from_pem(my_root_pem)});
auto ca = net::security_parameters{}.trust_anchors(net::tls::certificate::all_from_pem_file("/etc/my-ca/bundle.pem"));

This is the forward-compatible surface: the names come from RFC 9622 §6.3, which P3482 builds on. Code that only uses it moves to std::net with the namespace change if the standard ever gets TLS, or keeps working on stdnet if it does not.

tls::stream (a stdnet extension). For programs on the socket layer:

net::tls::stream<tcp::socket> s(std::move(socket), config);             // config: shared engine_config
co_await net::tls::async_handshake(s, net::tls::role::server, 10s);     // or role::client; deadline
n = co_await net::async_receive(s, net::buffer(buf));
co_await net::async_send(s, net::buffer(reply));
co_await net::tls::async_shutdown(s);

Its senders have the names and completion signatures of the socket senders, so code written against the byte_stream concept (tcp::socket, tls::stream, connection) is written once (see serve_http in examples/https_hello.cpp). tls::stream is not proposed for standardisation, like asio::ssl. Its second template parameter is the engine (tls::stream<tcp::socket, tls::openssl_engine>); it defaults to tls::default_engine, the engine of the TAPS layer.

Semantics

  • The RFC 9622 restrictions (#45): allowed_protocols, cipher_suites, groups and signature_algorithms (IANA code points, <stdnet/tls/parameters.hpp>), in order of preference. An empty list leaves the choice to the engine. A list the engine cannot honour fails with error::not_supported in preconnection::select(), initiate and listen (and tls::errc::unsupported_parameters from an engine driven directly): never a silent widening. connection and tls::stream report negotiated_version(), negotiated_cipher_suite() and negotiated_group() (none when the engine cannot tell: the group with mbedTLS and Schannel).

    Engine Protocols Suites, groups, signature schemes
    built-in TLS 1.3 ChaCha20-Poly1305 and AES-128-GCM (#50), x25519 and secp256r1 (#51), in the order given; ECDSA P-256 (signs and verifies), RSA-PSS and PKCS#1 v1.5 with SHA-256 (verifies, #51); with an identity to present, ecdsa_secp256r1_sha256 must be allowed (the only scheme it signs with)
    OpenSSL TLS 1.3, and TLS 1.2 when allowed explicitly what this OpenSSL build has (probed by supports; ML-KEM hybrids from OpenSSL 3.5); with TLS 1.2, the suites restrict both versions (TLS 1.2 ones by IANA code point), and a version left without a suite is disabled
    mbedTLS TLS 1.3 the TLS 1.3 suites; secp256r1/384r1/521r1, x25519, x448; no EdDSA
    Schannel TLS 1.3, and TLS 1.2 when allowed explicitly not restrictable (the system's policy): refused
  • async_receive completing with 0 is an authenticated end of stream (close_notify). The end of the transport without close_notify is tls::errc::truncated_stream, an error.

  • async_send encrypts and transmits the whole buffer sequence, in records of at most 16 KiB (or the peer's record_size_limit, RFC 8449).

  • Errors are std::error_codes: tls::errc has one value per TLS alert (RFC 8446 §6), sent or received, plus local conditions (handshake_timeout, truncated_stream, invalid_credentials, no_local_identity, ...), in tls_category(). | as_expected works unchanged.

  • One handshake, one receive and one send (or shutdown) may be outstanding on a stream at a time; they may complete on different threads of the io_context (the engine is locked).

  • connection::close() sends close_notify without blocking (best effort); abort() does not.

  • The role is fixed by the first async_handshake of a stream (engine::set_role); another role afterwards is error::not_supported.

  • Each KeyUpdate(update_requested) of the peer is answered at once, by its own KeyUpdate, without waiting for the next application record (#53).

The listener

Handshakes run inside the listener, several at once, so that a slow client does not hold up the others: max_concurrent_handshakes (default 16) slots, each with handshake_timeout (default 10 s) from accept to the client's Finished. When every slot is busy, new TCP connections wait in the kernel backlog. A failed handshake drops that connection only and is not reported to async_accept. Sixteen idle connections still keep every slot for ten seconds and can be renewed: the limit bounds the work in progress, it is not a defence against denial of service.

Supported profile (built-in engine)

Both roles: TLS 1.3 only, TLS_CHACHA20_POLY1305_SHA256 and TLS_AES_128_GCM_SHA256 (#50; the mandatory-to-implement suite of RFC 8446 §9.1), x25519 and secp256r1 (#51), ECDSA P-256 with SHA-256 (its own signatures, and the peer's), RSA-PSS (rsa_pss_rsae_sha256, a peer's CertificateVerify) and PKCS#1 v1.5 (rsa_pkcs1_sha256, offered for certificate signatures) with RSA keys of 2048 to 4096 bits (#51), HelloRetryRequest, KeyUpdate, close_notify, the middlebox-compatibility change_cipher_spec, ALPN from security_parameters::alpn(), record size limit (RFC 8449, see below). Handshake messages may span records, up to 16 KiB each (STDNET_TLS_MAX_HANDSHAKE), and a record may carry several of them.

Server. The server's ALPN order wins; an offer with no common protocol gets no_application_protocol. It takes the client's key share for its first group the client sent one for (x25519, then secp256r1, or the configured groups), else asks with a HelloRetryRequest for its first group the client supports. The client's server_name chooses among named identities (see Identities by name). With a session cache it issues one ticket per handshake and resumes the sessions of its tickets (see Resumption); no 0-RTT (offered early data is skipped, up to 64 KiB). It asks for client certificates when configured (see Client certificates).

Its order of preference is the configured cipher_suites, else ChaCha20-Poly1305 then AES-128-GCM: ChaCha20 is fast in portable code, while the AES here is bitsliced (constant time, no table) and GHASH bit-serial, several times slower than ChaCha20-Poly1305 and than AES instructions; AES-128-GCM is there for the peers and the policies that require it.

Client. It offers the suites, groups and signature schemes above, so it talks to servers with an ECDSA P-256 certificate or an RSA one of 2048 to 4096 bits (#51; RSA-PSS CertificateVerify, as TLS 1.3 requires) that accept one of its suites. It sends one key share, for its first group (x25519 unless groups says otherwise); a HelloRetryRequest may ask for its other group (secp256r1) or add a cookie. SNI carries with_hostname (or engine_config::server_name) unless it is an IP literal. When the server asks for a certificate, the client presents its ECDSA P-256 identity (if the server accepts ecdsa_secp256r1_sha256), chosen by the identity challenge or its local identity; otherwise an empty Certificate (see Client certificates). With a session cache it keeps the tickets and resumes (no 0-RTT). The server's chain is accepted up to 16 certificates in a 16 KiB Certificate message.

Authenticating the server. The built-in engine does no Web PKI path validation: no trust store, no chain building, no name or validity-date check. The server proves that it holds the key of its leaf certificate (CertificateVerify, then Finished), and the client accepts it when:

  • its leaf's public key is the one of a pinned certificate (pinned_server_certificate): public-key pinning, which survives a renewal with the same key; a mismatch is unknown_ca;
  • and, if one is given, the trust-verification sender completes with true (trust_verification, tls::trust_verifier); it receives the requested server name and the chain (DER, leaf first) and can implement any policy (a private CA, a fingerprint list, names and dates); false or an error is certificate_unknown; it is stopped by the handshake deadline.

With neither, initiate and async_handshake(role::client) fail with tls::errc::no_trust_policy before sending anything: secure by default. General-purpose Web PKI clients use the OpenSSL or mbedTLS engine.

Credentials: a certificate chain, leaf first, and its private key, as PEM (CERTIFICATE blocks, then one PRIVATE KEY (PKCS#8), EC PRIVATE KEY (SEC 1), RSA PRIVATE KEY (PKCS#1) or ENCRYPTED PRIVATE KEY block) or DER. The loader checks the DER structure of every certificate and that the leaf matches the key, not the validity dates or the chain's trust (the client does). credentials is an immutable value: to renew, build new credentials and give them to the listener with listener::renew (#49); existing connections keep their keys. from_pem_files is a hosted convenience.

Key types (#52), reported by credentials::key():

Key built-in OpenSSL mbedTLS Schannel
ECDSA P-256 yes yes yes no identity (client role, no client certificate)
RSA, 2048 bits and more refused yes yes –
Ed25519 refused yes refused (no EdDSA in mbedTLS 3.6) –
P-256 behind a hardware signer (from_signer) yes refused refused –

An engine refuses credentials it cannot use with invalid_credentials: listen(), initiate() (a client certificate) and listener::renew check them against the default engine (supports_credentials), and an engine used directly fails when its role is set. The RSA key must have the certificate's modulus; an Ed25519 key is matched with its certificate by OpenSSL when the engine loads it (SSL_check_private_key).

Encrypted keys. credentials::from_pem(chain, key, passphrase) takes an ENCRYPTED PRIVATE KEY (PKCS#8 with PBES2, as openssl pkcs8 -topk8 -v2 aes-256-cbc writes it). The key is decrypted once, when the credentials are loaded, by the library of the OpenSSL or mbedTLS engine: the configured engine's (STDNET_TLS_ENGINE) directly, whatever the initialisation order; otherwise the one whose header (<stdnet/tls/openssl.hpp>, <stdnet/tls/mbedtls.hpp>) the program includes, which registers it during dynamic initialisation (load such keys once main has started). The built-in engine has no decryption of its own: without either library, or with a wrong passphrase, the result is invalid_credentials. The decrypted key lives in the credentials (wiped when they are destroyed).

Keys in hardware. credentials::from_signer(chain_pem, signer) takes, in place of the private key, a p256_signer: a callable that signs a SHA-256 digest with the ECDSA P-256 key of a secure element, an HSM or a TPM and writes r || s (64 bytes). The loader calls it once on a fixed digest and checks the signature with the leaf's key; the built-in engine then calls it for each CertificateVerify it sends (synchronously, on the thread that drives the connection). A signer that fails during a handshake ends it with internal_error. The OpenSSL and mbedTLS engines refuse such credentials: their own mechanisms (OpenSSL providers, mbedTLS PSA drivers) reach hardware keys.

Certificates (pins, trust anchors): certificate::from_pem takes exactly one CERTIFICATE block; certificate::all_from_pem takes a bundle (a private CA chain, a system CA file) and returns every CERTIFICATE block in order, ignoring the text around them (comments, blocks of other types) as OpenSSL does. A bundle may hold up to 4 MiB (certificate::max_bundle_bytes); no block, or a malformed one, is invalid_credentials. all_from_pem_file is its hosted convenience.

Engines

The adaptors (tls::stream, the TAPS connection and listener) drive any type modelling tls::engine. Four engines model it; STDNET_TLS_ENGINE selects the one of the TAPS layer (tls::default_engine), and the others stay usable with tls::stream when their library is linked:

Engine Header Library Server authentication (client) Use
tls::builtin_engine <stdnet/tls/engine.hpp> none pin and/or trust-verification sender every profile, embedded targets, servers with their own identity
tls::openssl_engine <stdnet/tls/openssl.hpp> OpenSSL 3 pin and/or sender, else Web PKI (system store or trust_anchors) hosted clients of the public Internet
tls::mbedtls_engine <stdnet/tls/mbedtls.hpp> mbedTLS 3.6 pin and/or sender, else Web PKI (trust_anchors) ESP32 (ESP-TLS), Cortex-M SDKs, hardware acceleration
tls::schannel_engine <stdnet/tls/schannel.hpp> Schannel (Windows) pin and/or sender, else Web PKI (Windows' chain engine, or trust_anchors) Windows clients: nothing to ship, the system's roots and policies

The engine concept

An engine is a sans-I/O state machine: it never performs I/O, never blocks, never throws, and reports errors as tls::errc values. Its configuration is a std::shared_ptr<const engine_config> (identity, ALPN, server name, pins, trust-verification sender, trust anchors, random source). The adaptors use exactly these members:

Member Meaning
E(std::shared_ptr<const engine_config>) construction; nothing happens until the role is set
static bool can_authenticate_server(const engine_config&) a client with this configuration can authenticate a server; initiate checks it before connecting (no_trust_policy)
static bool supports(const engine_config&) the engine can honour the allowed protocols, suites, groups and signature schemes (#45); select() checks it (not_supported), set_role fails with unsupported_parameters
bool set_role(role) fixes the role once (a client queues its first flight); false for another role later
span<byte> receive_buffer(), received(n), received_eof() bytes from the transport, and its end
span<const byte> send_buffer(), sent(n) bytes for the transport (handshake flights, records, alerts)
span<const byte> read_buffer(), consume(n) decrypted application data
span<byte> write_buffer(), commit(n) plaintext of one record, protected by commit
shutdown() queues close_notify after the data already committed
trust_pending(), verified(bool) the handshake waits for the trust-verification sender, then gets its decision
handshake_complete(), peer_closed(), failed(), error() state; peer_closed is the authenticated end of the stream (close_notify)
alpn(), role(), peer_certificates() the negotiated protocol, the role, the peer's chain (DER, leaf first)
wants_input(), close_sent() more bytes from the peer are needed and there is room; close_notify has left send_buffer
negotiated_version(), negotiated_cipher_suite(), negotiated_group() what the handshake negotiated (#45), none before it completes or when the engine cannot tell

tls::server_engine keeps the phase 1 behaviour: a builtin_engine whose role is fixed to server at construction. The adaptors serialise the calls on one engine (one mutex per stream). The other engines only have to model this concept: a future std::net TLS, a platform library (Schannel, below), or a hardware TLS offload.

Trust policy, the same on every engine

Configuration of the client Built-in OpenSSL mbedTLS Schannel
pinned certificate(s) the leaf's public key must match same same same
trust-verification sender asked once the server's Finished is checked asked once the server's Finished is checked (the client's flight is held back until the decision) asked once the server's Finished is checked (the handshake is driven step by step) asked once the handshake is verified (the client's Finished is held back)
neither, with a server name no_trust_policy Web PKI: system trust store, or trust_anchors; name (DNS or IP) and dates checked Web PKI with trust_anchors (no_trust_policy without them) Web PKI: Windows' chain engine, or exclusively trust_anchors
neither, without a name no_trust_policy no_trust_policy no_trust_policy no_trust_policy

A mismatched pin is unknown_ca, a rejection by the sender certificate_unknown (the alert the server receives too; the OpenSSL and mbedTLS clients send it in plaintext, which an mbedTLS server reports as bad_record_mac). A Web PKI failure is unknown_ca (no path to a root), certificate_expired, certificate_unknown (another name) or bad_certificate.

OpenSSL engine

tls::openssl_engine (OpenSSL 3.0 or later; STDNET_TLS_ENGINE=openssl links OpenSSL::SSL): memory BIOs between OpenSSL and the adaptors, TLS 1.3 only, every suite and group OpenSSL enables (AES-GCM, ChaCha20-Poly1305; X25519, P-256, the hybrid post-quantum groups), RSA and ECDSA server certificates. Server credentials are the same tls::credentials (an ECDSA P-256 chain). Resumption and external PSKs as below (OpenSSL's own session cache is not used). engine_config::random is not used (OpenSSL has its own generator). The system trust store is loaded once per process (see Trust stores). Each connection allocates OpenSSL objects and four 16 KiB staging buffers. Built and tested on Linux, on Windows with MSVC (vcpkg's OpenSSL, static and as DLLs) and on macOS (Homebrew's, static).

Trust stores

tls::system_trust_anchors(ec) (hosted) returns the platform's roots as tls::certificates, for security_parameters::trust_anchors or any engine:

Platform Source
Windows the ROOT system store (CertOpenSystemStoreW): the roots an administrator installed and those Windows Update has downloaded (Windows fetches a public root the first time a chain needs it; stdnet's engines never fetch anything, being sans-I/O), without the Disallowed ones and those restricted from server authentication
macOS the system's anchors (SecTrustCopyAnchorCertificates, Security.framework, linked by CMake), as Apple's own verification sees them; /etc/ssl/cert.pem only if they cannot be read (it lags behind: a root of 2022 is missing there)
Linux, BSDs SSL_CERT_FILE if it names a file, else the first bundle found among the distributions' locations (Go's list: /etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt, ...)

What a Web PKI client trusts when it is given no trust_anchors:

Engine Linux, BSDs macOS Windows
built-in no Web PKI (no_trust_policy) same same
OpenSSL OpenSSL's locations (OPENSSLDIR, SSL_CERT_FILE, SSL_CERT_DIR) and system_trust_anchors() same same
mbedTLS no_trust_policy: give it trust_anchors (for instance system_trust_anchors()) same same
Schannel - - Windows' chain engine: offline: the ROOT store (roots Windows has downloaded), Disallowed, the usages an administrator set

With OpenSSL linked statically, OPENSSLDIR is a directory of the build machine and usually does not exist where the program runs; the platform's roots make Web PKI work there anyway. The CI jobs tls-openssl-windows and tls-openssl-macos check it against a public server with OpenSSL's own locations made empty.

Schannel engine (Windows, client role)

tls::schannel_engine (#43): SSPI with memory buffers (InitializeSecurityContextW, EncryptMessage, DecryptMessage), never a socket. Nothing to ship or patch: Schannel is serviced with Windows. TLS 1.3 only, like the other engines, which Schannel offers from Windows 11 and Windows Server 2022 (an older system fails the handshake); the suites (AES-GCM; Schannel has no ChaCha20-Poly1305), groups and signature schemes are those the system enables. Web PKI goes through Windows' chain engine (CertGetCertificateChain, CERT_CHAIN_POLICY_SSL): the roots of the ROOT store (the public roots Windows has downloaded; nothing is fetched, the engine being sans-I/O), the Disallowed store, the usages an administrator set, the server's DNS name or IP address; with trust_anchors, those roots only. Revocation is not checked, as with the other engines. The client role only: set_role(role::server) returns false, so with STDNET_TLS_ENGINE=schannel a TAPS listener fails with not_supported (servers use the built-in or OpenSSL engine). Each connection allocates about 50 KiB of staging buffers.

Network.framework (macOS, iOS): not an engine. Investigated for #43: Network.framework performs its own I/O (nw_connection owns the socket, and its framers sit above TLS), so it cannot be fed records by the adaptors, which is what tls::engine requires. Security.framework's SSLContext, which could, is deprecated and has no TLS 1.3. On Apple platforms the OpenSSL engine with system_trust_anchors() (/etc/ssl/cert.pem) is the supported way. Using Network.framework would mean a transport of its own behind the TAPS layer (a connection whose stack is Network.framework end to end), not an engine; that is outside #43.

mbedTLS engine (ESP32, RP2040 and hosted)

tls::mbedtls_engine (STDNET_TLS_ENGINE=mbedtls links mbedtls, mbedx509 and mbedcrypto): mbedTLS's I/O callbacks only move bytes between its staging buffers and the SSL context. TLS 1.3 only, the suites and groups of the mbedTLS configuration, Web PKI against trust_anchors. engine_config::random feeds mbedTLS's generator, so an embedded target plugs its TRNG there (esp_fill_random, the RP2040's ROSC); psa_crypto_init() is called once.

Supported versions (#54): mbedTLS 3.6.3 to 3.6.8, the 3.6 LTS line, tested in CI at both ends (tls-engine-mbedtls-3.6.3, -3.6.8). The header refuses others with #error and CMake does not find them. 3.6.0 lacks the NewSessionTicket signal that resumption uses (#46); the servers of 3.6.1 and 3.6.2 fail on a client's ECDSA certificate (internal_error); 3.6.3 is also the security release of the hostname check (CVE-2025-27809). The engine reads two members that mbedTLS 3.6 keeps private (MBEDTLS_PRIVATE): the handshake state, to pause the client between the server's Finished and its own flight for the trust-verification sender, and the last record, for the description of a received alert; there is no public accessor for either, hence the pinned line. mbedTLS 4 (ESP-IDF 6) is not supported yet.

The SDKs' mbedTLS is in that range: ESP-IDF 5.4 and 5.5 ship 3.6.7, pico-sdk 2.3.1 ships 3.6.6. ESP-IDF's TLS 1.3 is off by default, and so are C++ exceptions, which the mbedTLS engine uses to report allocation failures: tests/embedded/esp-idf/sdkconfig.defaults turns both on (CONFIG_MBEDTLS_SSL_PROTO_TLS1_3, CONFIG_COMPILER_CXX_EXCEPTIONS).

Identities by name and renewal

A listener may hold several identities, chosen by the server name the client asks for (SNI, RFC 6066), and they can be replaced while it runs (#49):

auto sp = net::security_parameters{}
              .local_identity("api.example.com", api_id)       // an exact name
              .local_identity("*.example.com", wildcard_id)    // any single label in the domain
              .local_identity(default_id);                     // everything else (optional)
net::listener l(ctx, net::preconnection(local, {}, sp));
// ... later, renewed certificates, without closing the listener:
l.renew(new_default_id, {{"api.example.com", new_api_id}});
  • Exact names first, then *.domain (one label), case-insensitive, a trailing dot ignored (on the requested name and on the configured ones); then the identity without a name. Without it, an unknown name (or no name) fails with unrecognized_name.
  • connection::requested_server_name() (and tls::stream's, and the engine's) is the name the client asked for on an accepted connection, with one identity as with several; the name sent on an initiated one, empty for an IP literal, which is not sent (RFC 6066 §3). The exception is mbedTLS checking an IP address against the certificate (Web PKI): it sends what it checks, and the accessor then reports it.
  • A session ticket is bound to the name it was issued for and to the listener's credentials for it, its certificate and its external PSK (whichever it has, both if it has both): it is resumed only under that name and while the listener has the same certificate and PSK for it, so a ticket cannot carry a client from one identity to another, to a name the listener no longer serves, or past a renewal (listener::renew) through a shared session cache. The built-in engine keeps the binding in the encrypted ticket, OpenSSL in the ticket's application data, mbedTLS in an HMAC appended to its ticket. A requested name longer than 255 bytes is refused (unrecognized_name).
  • listener::renew swaps the identities for the handshakes that start afterwards; the connections already accepted or in progress keep theirs. A selection sender (certificates loaded on demand) is not provided: renew the listener when the set changes.
  • Every engine with a server role chooses by name: the built-in engine from the ClientHello, OpenSSL in its servername callback, mbedTLS in its SNI callback.

Client certificates

RFC 9622 §6.3.2 "Identity challenge callback" (#47), <stdnet/tls/identity_challenge.hpp>:

auto sp = net::security_parameters{}.pinned_server_certificate({pin}).local_identity(client_id);
auto sp2 = net::security_parameters{}.pinned_server_certificate({pin}).identity_challenge(
    [&](const net::tls::identity_request& r) {          // the server asked for a certificate
        return ex::just(wallet.pick(r.server_name, r.certificate_authorities));   // credentials, or {}
    });
  • A client presents a certificate only when the server asks (CertificateRequest): the credentials the identity-challenge sender completes with, else its local_identity, else none (an empty Certificate, which a server that requires one refuses: certificate_required).
  • The sender gets the server name, the signature schemes the server accepts and the CA names it listed (certificate_authorities, often empty). It is asked once the server is authenticated (after the trust decision), runs under the handshake deadline and can be stopped; set_error presents none. It is not asked when the server does not ask, nor on a resumed handshake.
  • tls::stream takes it as engine_config::identity_challenge; the engine concept has identity_pending(), pending_identity_request() and provide_identity(credentials).
Engine Local identity Identity challenge
built-in an ECDSA P-256 identity, if the server accepts ecdsa_secp256r1_sha256 yes
OpenSSL yes yes (SSL_set_cert_cb, which suspends the handshake)
mbedTLS yes no: not_supported (mbedTLS takes the certificate before the handshake)
Schannel no: not_supported no

On a listener (#48):

auto sp = net::security_parameters{}.local_identity(id)
              .client_authentication(net::tls::client_authentication::require)   // or request
              .pinned_client_certificate({device_cert});                         // or trust_verification, trust_anchors
net::connection c = co_await net::async_accept(listener);
auto der = c.peer_certificate();                                                 // the client's leaf
  • request asks for a certificate and accepts an empty Certificate; require fails the handshake with certificate_required without one. Not on a resumed (PSK) handshake.
  • The certificate is authenticated as a client authenticates a server: the client proves it holds the key (CertificateVerify), then pinned_client_certificate (its public key), the trust-verification sender (given the client's chain; asked before the connection is delivered), or trust_anchors (OpenSSL, mbedTLS: the chain validated for client authentication, without a name). With none of them listen() fails with no_trust_policy (the concept's can_authenticate_client(config)).
  • A failed client authentication drops that connection only, like any failed handshake in the listener; connection::peer_certificate() on an accepted connection is the client's leaf.
  • A server that asks for client certificates neither issues nor accepts tickets, whatever its engine: every connection authenticates its client, even when its session cache is shared with a listener without that policy whose tickets would otherwise skip the check (an external PSK still authenticates the client by itself).
Engine Request / require Pins, sender Trust anchors
built-in yes (it asks for ecdsa_secp256r1_sha256) yes no (no path validation)
OpenSSL yes yes yes (X509_PURPOSE_SSL_CLIENT)
mbedTLS yes yes yes
Schannel no server role

Resumption and external PSK

RFC 9622 §6.3.1 "Session cache options" and "Pre-shared key" (#46), <stdnet/tls/session.hpp>:

net::tls::session_cache cache;                       // shared by the connections, thread-safe
auto client = net::security_parameters{}.pinned_server_certificate({pin}).session_cache(cache);
auto server = net::security_parameters{}.local_identity(id).session_cache(server_cache);
net::tls::pre_shared_key psk{"sensor-3", key};       // an external PSK: no certificate needed
auto device = net::security_parameters{}.pre_shared_key(psk);
  • Tickets (RFC 8446 §4.6.1). A server given a cache sends one NewSessionTicket after each handshake, encrypted with keys the cache holds and rotates every lifetime (2 hours by default, at most 7 days; a ticket of the previous key stays valid); the servers sharing a cache accept each other's tickets. A client given a cache keeps the tickets per server name, each used once, and offers the most recent in its next handshake with that server; it sends psk_key_exchange_modes whenever it has a cache, so that servers issue tickets. Ticket ages and lifetimes follow std::chrono::system_clock: on bare metal, back it with an RTC or SNTP (newlib: _gettimeofday), or a cache cannot expire its tickets.
  • psk_dhe_ke only: a resumed handshake still runs an (EC)DHE exchange (forward secrecy). 0-RTT is not supported.
  • Trust: a resumed session is authenticated by the session it resumes. Before offering a ticket, the client checks the current pins against the certificate the session was established with (a changed pin means a full handshake); it does not ask the trust-verification sender again. Share a cache only between connections with the same trust policy. peer_certificates() of a resumed connection is the certificate of the original session.
  • External PSK (TLS 1.3, SHA-256): it authenticates both sides; a client with one needs no pin, a listener with one needs no local identity. A wrong key fails the binder (decrypt_error); an unknown identity on a server without certificate is handshake_failure.
  • connection::resumed() / tls::stream::resumed() / the engine's resumed(): a ticket or an external PSK was used.
Engine Tickets (client / server) External PSK
built-in yes / yes (ChaCha20-Poly1305 tickets, the cache's keys) yes
OpenSSL yes / yes (AES-256-CBC + HMAC-SHA256 tickets, the cache's keys) yes (SHA-256 suites)
mbedTLS yes / yes (its ticket context, shared through the cache) yes
Schannel no: each engine has its own credentials handle, so Schannel's cache never resumes no (not_supported)

The formats differ: a client's cached session is offered again only by the engine that kept it.

Record size limit and footprint

The built-in engine keeps its buffers inside the engine object (no allocation on the record path). Their size comes from two build options, written to <stdnet/config_site.hpp>:

  • STDNET_TLS_MAX_RECORD (512 to 16384, default 16384): the largest record plaintext it receives and sends. It is advertised to the peer with the record_size_limit extension (RFC 8449), in the ClientHello and in the server's EncryptedExtensions; the peer's limit bounds the records sent to it. A peer that ignores the extension and sends larger records gets record_overflow. Unprotected handshake records (a ClientHello, a ServerHello) are not subject to the limit: the input buffer also holds one of STDNET_TLS_MAX_HANDSHAKE bytes. Without a reduced limit, the content of a record is checked once its padding is removed (at most 2^14 bytes). OpenSSL does not implement RFC 8449 (-max_send_frag caps its records); mbedTLS does with MBEDTLS_SSL_RECORD_SIZE_LIMIT.
  • STDNET_TLS_MAX_HANDSHAKE (2048 to 16384, default 16384): the largest handshake message it accepts (a ClientHello on a server, the server's Certificate on a client, kept for peer_certificates()).

tls::basic_builtin_engine<Record, Handshake> is the engine with other limits; builtin_engine uses the configured ones. On x86-64 the default engine takes about 68 KiB.

Measured on Cortex-M by tests/embedded/run.py (xPack GCC 15.2.1, -Os, Thumb, newlib-nano, -fno-exceptions -fno-rtti, with #52; the test program completes a TLS 1.3 handshake between two engines, exchanges data and closes; code size of the whole program, without the start-up code's few hundred bytes):

Target Limits (record / handshake) Code (.text) Constants (.rodata) RAM per engine Peak stack Heap
Cortex-M0+ (RP2040, built only) 16384 / 16384 53.3 KiB 6.5 KiB 74.5 KiB – –
Cortex-M0+ (RP2040, built only) 2048 / 4096 53.4 KiB 6.5 KiB 24.2 KiB – –
Cortex-M3 (QEMU mps2-an385) 16384 / 16384 52.6 KiB 6.5 KiB 74.5 KiB 4.0 KiB 2.3 KiB
Cortex-M3 (QEMU mps2-an385) 2048 / 4096 52.7 KiB 6.5 KiB 24.2 KiB 3.9 KiB 2.3 KiB
Cortex-M4 (QEMU mps2-an386) 16384 / 16384 52.7 KiB 6.5 KiB 74.5 KiB 3.9 KiB 2.3 KiB
Cortex-M4 (QEMU mps2-an386) 2048 / 4096 52.7 KiB 6.5 KiB 24.2 KiB 3.9 KiB 2.3 KiB
Cortex-M33 (QEMU mps2-an505) 16384 / 16384 52.6 KiB 6.5 KiB 74.5 KiB 3.9 KiB 2.3 KiB
Cortex-M33 (QEMU mps2-an505) 2048 / 4096 52.6 KiB 6.5 KiB 24.2 KiB 3.9 KiB 2.3 KiB

The heap holds the configurations and the credentials (loaded once); the handshakes and records do not allocate. The peak stack is the deepest one of the whole run (ECDSA signing on the server); the test program's peer has an ECDSA certificate, and the verification of an RSA one adds about 4 KiB (a 4096-bit key) while it runs. The CI job embedded prints the full report (every target, both limits) in its summary. Its traces stream through a pipe: on the Cortex-M0 and M3, whose long multiplications are calls, they run to several gigabytes.

The code (X25519 and P-256 ECDHE, P-256 signing and verification, RSA-PSS and PKCS#1 v1.5 verification, SHA-256, HMAC, ChaCha20-Poly1305, AES-128-GCM, both roles) fits the 2 MiB flash of an RP2040 and the 4 MiB of an ESP32 many times over. With the default limits, one connection needs 75 KiB of RAM (an RP2040 has 264 KiB); with 2048 / 4096, 24 KiB. On the ESP32 (Xtensa) only the mbedTLS path is planned; the built-in engine is portable C++ and should compile there unchanged, unmeasured.

Constant time

The built-in engine is written so that no branch and no memory address depends on a secret: field arithmetic with masks (select, nonzero, a volatile mask that keeps Clang from turning a selection back into a branch), the Montgomery ladder of X25519, a fixed double-and-add schedule for P-256 with masked selection (the base point for signing and key shares, the peer's point for ECDHE, #51), Fermat inversion with a public exponent, ChaCha20 and SHA-256 without tables, Poly1305 in 26-bit limbs, AES-128 bitsliced on 32-bit words (the Boyar-Peralta S-box circuit, BearSSL's aes_ct structure: no table, no multiplication) and GHASH bit by bit with masks (#50), constant-time comparison of tags and Finished messages. What the engine discloses on purpose (a signature, the outcome of a MAC check, the content type and length of a record, a rejected RFC 6979 candidate or P-256 key-share scalar) is marked with STDNET_TLS_DECLASSIFY. RSA verification (#51) handles public values only (key, message, signature) and is not constant time; it works in fixed arrays (no allocation), about 4 KiB of stack for a 4096-bit key, and its padding checks are tested against Project Wycheproof's vectors (tests/fixtures/tls/wycheproof_rsa.txt).

Two checks run in CI:

  • Valgrind, x86-64 (stdnet_tls_constant_time, GCC and Clang -O2): the secrets are marked undefined (the scalars, the ECDSA key, the traffic secrets, the record plaintext) and Memcheck fails on any conditional jump or memory address that depends on them.
  • QEMU, Cortex-M (tests/embedded/run.py, job embedded): each secret operation runs on two secrets on the Cortex-M0 (ARMv6-M, as the RP2040's M0+), M3, M4 and M33; QEMU logs every translation block executed, and the two runs must execute the same blocks in the same order. The instructions of every function executed are checked for division (UDIV/SDIV, software division) and, on the Cortex-M3, for the long multiplications whose latency depends on the operands.

The review on Thumb found two problems, fixed in #33 phase 3:

  • On ARMv6-M (Cortex-M0, M0+, so the RP2040), the field and Poly1305 multiplications compiled to calls to libgcc's __aeabi_lmul, which branches on its operands: X25519, P-256 and ECDSA signing were not constant time there. On the Cortex-M3, UMULL/UMLAL terminate early on small operands. multiply_wide now forms 32 x 32-bit products from four 16 x 16-bit MUL, which take a fixed time, on ARMv6-M, ARMv7-M (M3) and ARMv8-M Baseline (M23); the M4, M7 and M33 keep their single-cycle long multiply. A value barrier keeps GCC from turning x + (x << 2) back into a multiplication. On the M3 an X25519 now executes about 1.5 million translation blocks, against 0.58 million on the M4.
  • Poly1305 divided public loop indices (UDIV on the M3/M4, a variable-time library call on the M0): replaced by comparisons and a table computed at compile time, so that the "no division" rule holds without exception.

Also fixed by the review: the removal of the record padding scanned from the end and stopped at the content type, so its time revealed the length of the padding (which exists to hide the content's length): it now scans the whole record with masks. The PEM base64 decoder looked digits up with string::find, whose time depends on the character of the private key: replaced by arithmetic.

Limits: the QEMU check covers control flow and instruction choice, not memory addresses (Valgrind covers those, on x86-64, for the same source; the engine has no secret-indexed table), nor the timing of an instruction that QEMU does not model (a conditional instruction in an IT block is executed whether its condition holds or not, and takes a fixed time on these cores). Caches and flash wait states are not modelled; Cortex-M parts without a data cache do not have cache-timing channels, Cortex-M7 parts do. The OpenSSL and mbedTLS engines inherit the side-channel properties of their libraries.

Configuration and profiles

STDNET_TLS_ENGINE (CMake, written to <stdnet/config_site.hpp>, #34) selects builtin (default), openssl, mbedtls, schannel (Windows) or none; STDNET_TLS_MAX_RECORD and STDNET_TLS_MAX_HANDSHAKE size the built-in engine. Feature detection: STDNET_LIB_TLS (202612L) in <stdnet/version.hpp>, stdnet::lib_tls and stdnet::tls::available in code, also after import stdnet;.

Profile TLS
Hosted (Linux, macOS, Windows) built-in engine (client and server), or OpenSSL (Web PKI); on Windows also Schannel (client)
Cortex-M (#5) built-in engine (measured above, smaller limits with RFC 8449), or mbedTLS
ESP32 (#6) mbedTLS (ESP-TLS); the built-in engine is portable, unmeasured
8-bit AVR (#3, #4) none: 16 KiB records, the transcript and the certificate do not fit in 2–16 KB of RAM

With none, the TLS names stay declared and fail to compile when used, and security_parameters{} reports error::not_supported at run time: never a silent fallback to cleartext.

Not implemented yet

  • 0-RTT (early data): no replay protection; it would need an application-level opt-in.
  • Web PKI in the built-in engine (path building, names, dates): by design, it is the job of the OpenSSL and mbedTLS engines (and of the trust-verification sender for custom policies).
  • RSA and Ed25519 keys in the built-in engine (it verifies RSA-PSS since #51 but signs with ECDSA P-256 only), Ed25519 verification, and the decryption of encrypted keys without OpenSSL or mbedTLS. An asynchronous (sender-based) hardware signer.
  • Measurements of the mbedTLS engine on ESP32 and RP2040 hardware with ESP-IDF and pico-sdk, and of the built-in engine on Xtensa.
  • An external audit (prepared in TLS-AUDIT.md, #55); side channels other than timing (power, electromagnetic, faults).

Conformance and interoperability (#53)

The CI workflow TLS interop (.github/workflows/interop.yml) runs on the pull requests that touch TLS, on every push to develop and nightly. Its scripts are in tests/interop/.

Interoperability matrix (matrix.py). The built-in server (tests/tls_server.cpp) against each peer's TLS 1.3 client, and the built-in client (tests/tls_client.cpp) against each peer's server. The peer restricts itself to one suite and one group, so the combination is the one the handshake negotiates:

Peer Suites Groups
Go crypto/tls (tests/interop/go/peer.go) the peer's choice (Go does not let TLS 1.3 suites be chosen) x25519, secp256r1
GnuTLS (gnutls-cli, gnutls-serv) ChaCha20-Poly1305, AES-128-GCM x25519, secp256r1
BoringSSL (bssl, pinned commit) the peer's choice x25519, P-256
wolfSSL (example programs, pinned release) ChaCha20-Poly1305, AES-128-GCM the peer's choice
rustls (tlsclient-mio, tlsserver-mio, pinned release) ChaCha20-Poly1305, AES-128-GCM the peer's choice
NSS (tstclnt, selfserv; Fedora container) ChaCha20-Poly1305, AES-128-GCM x25519, P256

Every combination is expected to pass (EXPECTED_FAILURES is empty); the job's summary holds the table. Go was also run locally, in both directions and with both groups.

Conformance (tlsfuzzer.py). tlsfuzzer's TLS 1.3 scripts (pinned commit, with tlslite-ng) against the built-in server, which has a session cache and an external PSK so that the resumption and PSK scripts apply. The scripts are written for an RSA server: a bootstrap (tlsfuzzer_bootstrap.py) puts ecdsa_secp256r1_sha256 in place of the last scheme of the modern RSA lists, keeping every length and offset (the scripts pad to exact sizes and fuzz bytes at fixed positions). A script passes when its failing cases all match a documented expected failure: TLS 1.2, AES-256-GCM and CCM, x448, P-384 and P-521, FFDHE, ClientHellos above STDNET_TLS_MAX_HANDSHAKE (16 KiB, decode_error), and repeated change_cipher_spec records (RFC 8446 §5 has a receiver drop each one received before the peer's Finished; tlsfuzzer expects the second to be refused). The scripts for what the engine does not implement (certificate compression, post-handshake authentication, RSA or EdDSA servers, ML-KEM, psk_ke, obsolete curves) are listed as not applicable with their reason. Running them found and fixed (#53):

  • an empty Handshake or Alert record answered with decode_error instead of unexpected_message (RFC 8446 §5.1, §5.4);
  • a TLSInnerPlaintext of more than 2^14 + 1 bytes (content, type and padding) accepted when its content fits in 2^14: now record_overflow;
  • a ClientHello with more than 128 extensions refused: any number of unknown extensions is now ignored, and duplicates are refused for the types the engine reads;
  • an unprotected application_data record during the handshake answered with protocol_version (its record version) or decode_error (zero length) instead of unexpected_message;
  • a ClientHello offering a PSK without signature_algorithms refused with missing_extension: RFC 8446 §9.2 requires that extension only without pre_shared_key; the engine now requires it only when no PSK is agreed.

Two deliberate differences remain, documented with the scripts: a client that lists no psk_key_exchange_modes the engine supports (psk_dhe_ke) gets no NewSessionTicket (RFC 8446 §4.2.9: it could not use it), and repeated change_cipher_spec records are dropped (see above).

Public servers (public_servers.py, nightly). The built-in client, accepting any chain through its trust-verification sender (the built-in engine has no Web PKI), against twenty public HTTPS servers (CDNs, cloud front ends, server stacks, several with RSA certificates). Locally, every one completed a TLS 1.3 handshake and answered; four end without close_notify, which the report notes.

Long fuzzing (nightly). An hour of libFuzzer on tests/fuzz/fuzz_tls.cpp, whose corpus is kept between runs; a crash uploads its input. CI's own run stays at 60 seconds.

Tests

  • stdnet_tls_tests: RFC 5869, 7748, 6979 and 8439 vectors (ECDSA signing and verification), the RFC 8448 key schedule, ClientHello and record refusals with their alerts, padding and sequence limits, credentials and certificates, the server engine driven without I/O (RFC 8448 ClientHello, fragmented ClientHello, HelloRetryRequest), a client engine against the server engine (pinning, a mismatched pin, the trust decision, SNI, a tampered flight, a TLS 1.2 ServerHello, a HelloRetryRequest with a cookie), tls::stream client handshakes with the trust-verification sender (accepted, rejected, stopped by the deadline), and initiate against a secure listener.
  • stdnet_tls_interop_taps / _stream (Linux, with openssl and Python): OpenSSL clients against tests/tls_server.cpp on four threads: keep-alive, ALPN, 1 MiB download and 300 kB upload, HelloRetryRequest, repeated change_cipher_spec, refused ALPN (alert 120), client close_notify, truncation, handshake deadline, handshake slots and the backlog. Also run under ASan, UBSan and TSan in CI.
  • stdnet_tls_client_interop_taps / _stream (Linux, with openssl and Python): tests/tls_client.cpp against openssl s_server: the status page, session tickets, ALPN, a 1 MiB download, a CertificateRequest, a mismatched pin, a server without the suite (handshake_failure), a TLS 1.2 server (protocol_version), ALPN refused (alert 120).
  • stdnet_tls_engine_tests: every engine against every engine (built-in, OpenSSL and mbedTLS when they are found), through the concept only: handshake, ALPN, 40 KB both ways, close_notify, truncation, a wrong pin, no common ALPN, the trust decision accepted and rejected, no trust policy, and Web PKI with trust anchors (good name, IP address, other name, other root) for the OpenSSL and mbedTLS clients. The RFC 8449 tests (a constrained server and a constrained client, an oversized record) are in stdnet_tls_tests.
  • The TAPS and tls::stream tests and the OpenSSL interoperability tests also run with STDNET_TLS_ENGINE=openssl and mbedtls in CI (job tls-engines; mbedTLS 3.6 built from its release, as Ubuntu 24.04 has 2.28).
  • stdnet_tls_constant_time (Linux, with Valgrind): the scalar multiplications, ECDSA signing, record protection with secret keys and plaintext, and the comparisons of secrets (see Constant time).
  • tests/embedded/run.py (CI job embedded, arm-none-eabi-g++ and QEMU): the constant-time traces on Cortex-M0, M3, M4 and M33, a TLS 1.3 handshake between two engines on the emulated M3, M4 and M33 boards, and the footprint report.
  • tests/fuzz/fuzz_tls.cpp (-DSTDNET_BUILD_FUZZ=ON, Clang): libFuzzer on the parsers, ECDSA verification and the whole engine in both roles, with the default and with small record limits (the corpus holds a real server flight for the fuzzer's deterministic client, so that the encrypted client states are reached); CI runs it for 60 seconds under ASan and UBSan.