ProtoCore v1.0.16
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
tls.h
Go to the documentation of this file.
1// ProtoCore v1.0.16 - Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file tls.h
6 * @brief The TLS connection resource (RFC 8446), and the no-op surface a build without TLS sees.
7 *
8 * This file owns the connection: ::TlsConn, its configuration and its handshake phase. The layers
9 * that act on it are beside it - handshake/ drives the handshake (RFC 8446 sec 4), record/ frames
10 * for it (sec 5), key_schedule/ derives its secrets (sec 7.1).
11 *
12 * The portable TLS 1.3 arm (PROTOCORE_ENABLE_TLS) is the implementation; a caller reaches it
13 * through ::TlsConnection. The slot-indexed protocore_tls_* calls below are no-ops, so a call site
14 * that predates the portable arm still compiles and needs no extra guards.
15 */
16
17#ifndef PROTOCORE_TLS_H
18#define PROTOCORE_TLS_H
19#include "protocore_config.h" // the entry point: the enable gate below, and the widths
20
21#if PROTOCORE_ENABLE_TLS
22
23EMBED_BEGIN_DECLS
24
25// ---------------------------------------------------------------------------
26// The connection resource (RFC 8446): what a handshake and a record layer act on
27// ---------------------------------------------------------------------------
28// This file owns the connection; handshake/ drives it and record/ frames for it.
29
33
34/** @brief Handshake progress. A client and a server walk the same phases from opposite ends. */
35EMBED_ENUM_BYTE(TlsConnState,
36 TLS_CONN_START, ///< server: awaiting ClientHello; client: nothing sent yet
37 TLS_CONN_WAIT_SH, ///< client only: ClientHello sent, awaiting ServerHello
38 TLS_CONN_WAIT_FLIGHT, ///< client only: awaiting the encrypted server flight
39 TLS_CONN_WAIT_FINISHED, ///< server only: flight sent, awaiting the client Finished
40 TLS_CONN_DONE, ///< handshake complete; application keys installed
41 TLS_CONN_FAILED ///< fatal (see @ref TlsConnNs::alert)
42);
43
44/** @brief Which end of the handshake this connection drives. */
45EMBED_ENUM_BYTE(TlsRole, TLS_ROLE_SERVER = 0, TLS_ROLE_CLIENT);
46
47/**
48 * @brief The long-lived credential plus this handshake's fresh randomness.
49 *
50 * @c ed25519_seed is this end's signing key and @c ed25519_pub the raw public key it presents
51 * (RFC 7250); a client that only verifies leaves both null. @c peer_pub is the raw public key the
52 * peer must present - this is the whole of peer authentication on the portable arm, so a client
53 * with no @c peer_pub is encrypt-only and unauthenticated. @c ephemeral_priv and @c random must be
54 * freshly generated per connection from a CSPRNG.
55 */
56typedef struct
57{
58 const uint8_t *ed25519_seed; ///< 32-byte Ed25519 signing seed, or NULL when this end does not sign
59 const uint8_t *ed25519_pub; ///< 32-byte raw public key this end presents (matches @c ed25519_seed)
60 const uint8_t *peer_pub; ///< 32-byte raw public key the peer must present, or NULL to skip verification
61 const uint8_t *ephemeral_priv; ///< 32-byte X25519 ephemeral private key (fresh per handshake)
62 const uint8_t *random; ///< 32-byte Hello random (fresh per handshake)
63 const char *hostname; ///< client: the SNI to offer, and the name a certificate must speak for
64 // Client: the trust anchor a presented X.509 chain is validated to (RFC 5280 sec 6.1). When it
65 // is set the peer is authenticated by certificate - the chain to this anchor, and @c hostname
66 // matched by RFC 6125 - and @c peer_pub is not consulted. When it is null the peer is
67 // authenticated by raw public key against @c peer_pub, which is what this arm does by default.
68 const uint8_t *ca_der; ///< one DER trust anchor, or NULL
69 size_t ca_len; ///< its length
70 uint64_t now; ///< seconds since the POSIX epoch, for the validity window (sec 6.1.3 (a)(2))
71 // Server: the DER certificate to present instead of a raw public key. @c ed25519_seed still
72 // signs the CertificateVerify, so it must be the key this certificate carries.
73 const uint8_t *cert_der; ///< one DER certificate, or NULL to present the raw public key
74 size_t cert_len; ///< its length
75 // Server: the protocols this listener answers, in descending preference (RFC 7301 sec 3.1). A
76 // null list leaves ALPN unanswered; a client that offered it then gets no extension back.
77 const char *const *alpn; ///< NUL-terminated protocol names, or NULL
78 uint8_t alpn_count; ///< how many
79 // The suite this end runs: a client offers it, a server answers with it, and it fixes the AEAD,
80 // the key schedule's hash and the Transcript-Hash together (RFC 8446 sec 7.1). Zero-initialising
81 // the config leaves TLS_CIPHER_AES_128_GCM_SHA256, the sec 9.1 mandatory-to-implement suite.
82 TlsCipher cipher;
83} TlsConnConfig;
84
85/**
86 * @brief One TLS 1.3 handshake: the session state, and the three regions of one secure-pool borrow.
87 *
88 * The borrow is taken once by @ref TlsConnNs::init from the pool's persistent end and split by
89 * offset - TX at 0, RX at PROTOCORE_TLS_CONN_MSG_CAP, TERMS after it. No storage is declared here: a
90 * message is built in TX and handed to the record layer, a record is opened into RX, and the four
91 * TLS13_SECRET_MAX-strided handshake terms sit in TERMS. No heap.
92 */
93typedef struct
94{
95 const TlsConnConfig *cfg; ///< the caller's, borrowed for the life of the connection
96 TlsConnState state;
97 TlsRole role;
98 uint8_t alert; ///< RFC 8446 sec 6 alert code when @c state is FAILED (0 otherwise)
99
100 uint8_t *transcript; ///< running Transcript-Hash over the handshake messages
101 Tls13KeySchedule ks; ///< TLS 1.3 key schedule
102 TlsRecordKeys hs_tx; ///< handshake traffic keys, this end writing
103 TlsRecordKeys hs_rx; ///< handshake traffic keys, this end reading
104 TlsRecordKeys ap_tx; ///< application traffic keys, this end writing
105 TlsRecordKeys ap_rx; ///< application traffic keys, this end reading
106 embed_bool hrr_sent; ///< a HelloRetryRequest has been answered on this connection (sec 4.1.4)
107 embed_bool hs_keys_ready; ///< the handshake traffic keys are installed
108 embed_bool ap_keys_ready; ///< the application traffic keys are installed
109
110 uint8_t *tx; ///< PROTOCORE_TLS_CONN_MSG_CAP: a message built to send, or a received record opened into it
111 uint8_t *rx; ///< PROTOCORE_TLS_CONN_REC_CAP: the record the worker filled
112 uint8_t
113 *terms; ///< PROTOCORE_TLS_CONN_TERMS_CAP: the five terms, one TLS13_SECRET_MAX slot each, at TLS_TERM_* offsets
114 uint8_t *hash_work; ///< PROTOCORE_TLS13_TRANSCRIPT_BORROW: the bytes @ref transcript works out of
115 uint8_t *sign_work; ///< PROTOCORE_SHA512_BORROW: the bytes the CertificateVerify signature works out of
116 uint8_t *ks_work; ///< PROTOCORE_TLS13_KS_BORROW: the bytes the key schedule works out of
117 Tls13ClientHello *hello; ///< the peer's parsed ClientHello
118 const char *alpn; ///< the protocol selected from TlsConnConfig::alpn, or NULL when none was
119} TlsConn;
120
121// The handle that drives one connection (network_drivers/tls/handshake). Declared here because
122// this file owns ::TlsConn: the driver acts on the resource, so the resource publishes the seam
123// and the driver defines it. A separate header would have to include this one, and this one
124// would have to reach back for the handle.
125/** @brief RFC 8446 sec 4: which end this connection drives, and what it presents. */
126typedef struct
127{
128 TlsRole role; ///< which end of the handshake this connection drives
129 const TlsConnConfig *cfg; ///< the credential and this handshake's randomness
130} TlsInitArgs;
131
132/** @brief The bytes one call moves: a received record in, application data out. */
133typedef struct
134{
135 size_t rx_len; ///< how much of TlsConn::rx the worker filled
136 const uint8_t *data; ///< application bytes a seal takes
137 size_t len; ///< how many
138 const uint8_t *rec; ///< the received application record an open takes
139 size_t rec_len; ///< how many bytes of it there are
140} TlsConnIoArgs;
141
142/** @brief Where a call writes, and what it wrote. */
143typedef struct
144{
145 uint8_t *out; ///< where the records this end owes are written
146 size_t out_cap; ///< how much room it has
147 size_t *out_len; ///< where an open reports the plaintext length, or NULL
148} TlsConnOut;
149
150/**
151 * @brief One TLS 1.3 handshake over a stream. ::TlsConn is the resource; this drives it.
152 *
153 * A caller sets the members a call takes, invokes it through ::TlsConnection, and reads the outcome
154 * off the same handle. The connection itself is the caller's, named in @ref TlsConnNs::conn.
155 *
156 * @var TlsConnNs::conn the connection every call acts on
157 * @var TlsConnNs::init_args which end this connection drives, and what it presents
158 * @var TlsConnNs::io the bytes one call moves
159 * @var TlsConnNs::out_args where a call writes, and what it wrote
160 * @var TlsConnNs::ok a call's true/false outcome
161 * @var TlsConnNs::n bytes written to @c out_args.out
162 * @var TlsConnNs::i32 bytes written, or a negative alert-bearing failure
163 * @var TlsConnNs::u8 the alert a lookup reports
164 * @var TlsConnNs::init bind a connection to its role and configuration. The borrow is taken
165 * on first use and kept, so a connection initialised again reuses the
166 * bytes it already holds
167 * @var TlsConnNs::start client only: write the ClientHello; bytes written, or 0
168 * @var TlsConnNs::process the worker filled @ref TlsConn::rx with one record of @c io.rx_len
169 * bytes; consume it, writing whatever it owes into @c out_args.out
170 * @var TlsConnNs::established whether the handshake completed
171 * @var TlsConnNs::alert the alert that ended the connection, or 0
172 * @var TlsConnNs::seal_app seal application data into one record; bytes written, or 0
173 * @var TlsConnNs::open_app open one received application record; false on an AEAD failure
174 *
175 * No storage member: one secure-pool borrow per connection lives in ::TlsConn, taken by
176 * @ref TlsConnNs::init and split by offset.
177 */
178typedef struct
179{
180 TlsConn *conn;
181 TlsInitArgs init_args;
182 TlsConnIoArgs io;
183 TlsConnOut out_args;
184 embed_bool ok;
185 size_t n;
186 int i32;
187 uint8_t u8;
188} TlsConnectionVars;
189
190/** @brief The operands and the outcome. */
191extern TlsConnectionVars TlsConnectionV;
192
193/** @brief The entries. */
194typedef struct
195{
196 void (*const init)(uint8_t *work);
197 void (*const start)(uint8_t *work);
198 void (*const process)(uint8_t *work);
199 void (*const established)(uint8_t *work);
200 void (*const alert)(uint8_t *work);
201 void (*const seal_app)(uint8_t *work);
202 void (*const open_app)(uint8_t *work);
203} TlsConnNs;
204
205// What the table binds, defined once in the .c and taking one parameter each: everything
206// else an entry needs is an operand in TlsConnectionV or a region of the borrow at a fixed offset.
207void protocore_tls_connection_init(uint8_t *work);
208void protocore_tls_connection_start(uint8_t *work);
209void protocore_tls_connection_process(uint8_t *work);
210void protocore_tls_connection_established(uint8_t *work);
211void protocore_tls_connection_alert(uint8_t *work);
212void protocore_tls_connection_seal_app(uint8_t *work);
213void protocore_tls_connection_open_app(uint8_t *work);
214
215// `static const`, initialised HERE rather than `extern` against a definition in the .c: a
216// const object whose initializer every translation unit can see is a COMPILE-TIME FACT, so
217// `TlsConnection.init(work)` resolves to a named function and becomes a DIRECT call. An extern table
218// leaves the call indirect and the symbol live at every level, -O2 -flto included.
219static const TlsConnNs TlsConnection __attribute__((unused)) = {
220 .init = protocore_tls_connection_init,
221 .start = protocore_tls_connection_start,
222 .process = protocore_tls_connection_process,
223 .established = protocore_tls_connection_established,
224 .alert = protocore_tls_connection_alert,
225 .seal_app = protocore_tls_connection_seal_app,
226 .open_app = protocore_tls_connection_open_app,
227};
228
229/** @brief The connection standing on @p slot, or NULL when the index is out of range. */
230TlsConn *protocore_tls_conn_at(uint8_t slot);
231
232/**
233 * @brief The protocol ALPN selected on @p slot, or NULL when none was negotiated.
234 *
235 * Points into the listener's ::TlsConnConfig::alpn list, which outlives the connection.
236 */
237const char *protocore_tls_alpn(uint8_t slot);
238
239/** @brief Where a stepped TLS exchange stands. */
240EMBED_ENUM_BYTE(protocore_tls_state,
241 PROTOCORE_TLS_READY = 0, ///< the move landed
242 PROTOCORE_TLS_BUSY, ///< the peer's bytes are still in flight; ask again on the next tick
243 PROTOCORE_TLS_FAILED, ///< the session did not stand up, or it is closed / fatal
244);
245
246/**
247 * @brief Install the credential this end presents, before any connection begins.
248 *
249 * The credential is an RFC 7250 raw public key: @p cert is the 32-byte Ed25519 public key and
250 * @p key the 32-byte signing seed that matches it. This end presents no X.509 chain, and asks
251 * the peer for none.
252 *
253 * @return true once a connection may begin.
254 */
255embed_bool protocore_tls_global_init(const uint8_t *cert, size_t cert_len, const uint8_t *key, size_t key_len);
256
257/** @brief Whether a credential is installed and a connection may begin. */
258embed_bool protocore_tls_ready(void);
259
260/** @brief Stand a TLS connection up on @p slot, taking the pcb it will write through. */
261embed_bool protocore_tls_conn_begin(uint8_t slot);
262
263/**
264 * @brief Pump the handshake on @p slot with whatever ciphertext arrived.
265 *
266 * @return < 0 the connection failed and must be aborted; 0 still handshaking, ask again when more
267 * ciphertext lands; > 0 the handshake completed.
268 */
269int protocore_tls_handshake(uint8_t slot);
270
271/** @brief Whether the handshake on @p slot completed. */
272embed_bool protocore_tls_established(uint8_t slot);
273
274/**
275 * @brief Open one received application record on @p slot into @p buf.
276 *
277 * @return the plaintext length, 0 when no whole record arrived, or < 0 on an AEAD failure,
278 * which RFC 8446 sec 5.2 makes fatal to the connection.
279 */
280int protocore_tls_read(uint8_t slot, uint8_t *buf, size_t len);
281
282/**
283 * @brief Seal @p len bytes into one application record on @p slot and put it on the wire.
284 *
285 * @return @p len once the record is queued, or < 0 when it did not fit one record or the transport
286 * refused it.
287 */
288int protocore_tls_write(uint8_t slot, const void *data, size_t len);
289
290/** @brief End the connection on @p slot and wipe every key generation it installed. */
291void protocore_tls_conn_end(uint8_t slot);
292
293/** @brief Release @p slot's connection without ending it: the transport is already gone. */
294void protocore_tls_conn_free(uint8_t slot);
295
296/** @brief The high-water mark of the pool this engine's connections are taken from. */
297size_t protocore_tls_arena_peak(void);
298
299EMBED_END_DECLS
300
301#endif // PROTOCORE_ENABLE_TLS
302
303#endif // PROTOCORE_TLS_H
EMBED_ENUM_BYTE(ProtoConn, PROTO_NONE=0, PROTO_HTTP=1, PROTO_TELNET=2, PROTO_SSH=3, PROTO_MODBUS=4, PROTO_OPCUA=5, PROTO_SSH_RFWD=6, PROTO_RELAY=7, PROTO_BRIDGE=8, PROTO_NTRIP_CASTER=9, PROTO_MESH=10, PROTO_UDP=11,)
Application protocol spoken on a listener port or connection slot.
TLS 1.3 key schedule (RFC 8446 sec 7.1) for the QUIC handshake.
TLS 1.3 record layer over a reliable stream (RFC 8446 sec 5).
TLS 1.3 handshake messages for the QUIC handshake (RFC 8446 sec 4).