ProtoCore v1.0.16
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
transport.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 transport.h
6 * @brief RFC 4253 transport layer: identification exchange, algorithm negotiation, key exchange.
7 */
8
9#ifndef PROTOCORE_TRANSPORT_TRANSPORT_H
10#define PROTOCORE_TRANSPORT_TRANSPORT_H
11
16#include "crypto/hash/sha256/sha256.h" // PROTOCORE_SHA256_DIGEST_LEN - the exchange hash and session id
17#include "locus_carcerum/locus_carcerum.h" // mmgr_zero_buf (the canonical secure wipe)
20
21#include "protocore_config.h"
22
23EMBED_BEGIN_DECLS
24
25/**
26 * @brief One direction's codec state, handed to the packet layer per call.
27 *
28 * RFC 4253 sec 6 sits under sec 7, so the codec is told which keys to use rather than reading the
29 * session that negotiated them. Each direction switches on its own SSH_MSG_NEWKEYS (sec 7.3).
30 */
31typedef struct
32{
33 embed_bool enc; ///< that direction's cipher/MAC is active
34 uint8_t epoch; ///< key epoch it reads out of ssh_keys[slot][]
35} SshDir;
36
37/** @brief Negotiated key-exchange method. */
39 SSH_KEX_DH_GROUP14 = 0, ///< diffie-hellman-group14-sha256 (RFC 8268)
40 SSH_KEX_CURVE25519 = 1, ///< curve25519-sha256 (RFC 8731)
41 SSH_KEX_MLKEM768_X25519 = 2, ///< mlkem768x25519-sha256
42 SSH_KEX_ECDH_NISTP256 = 3, ///< ecdh-sha2-nistp256 (RFC 5656 sec 4)
43 SSH_KEX_SNTRUP761_X25519 = 4 ///< sntrup761x25519-sha512@openssh.com
44);
45
46/** @brief Negotiated host-key / signature algorithm. */
47EMBED_ENUM_BYTE(SshHostkeyAlg,
48 SSH_HOSTKEY_RSA_SHA256 = 0, ///< rsa-sha2-256 (RFC 8332)
49 SSH_HOSTKEY_ED25519 = 1, ///< ssh-ed25519 (RFC 8709)
50 SSH_HOSTKEY_RSA_SHA512 = 2, ///< rsa-sha2-512 (RFC 8332)
51 SSH_HOSTKEY_ECDSA_NISTP256 = 3 ///< ecdsa-sha2-nistp256 (RFC 5656)
52);
53
54/**
55 * @brief SSH transport/session state for one connection (BSS pool).
56 *
57 * Holds the handshake phase plus the values that must persist across messages to compute the
58 * exchange hash H: the identification strings (V_C, V_S) and the two KEXINIT payloads (I_C, I_S).
59 * The exchange hash from the first KEX is retained as the session id.
60 */
61typedef struct
62{
63 SshPhase phase; ///< Current handshake phase.
64
65 SshKexAlg kex_alg; ///< negotiated in KEXINIT.
66 SshHostkeyAlg hostkey_alg; ///< negotiated in KEXINIT.
67 // RFC 4253 sec 7.1 negotiates each direction's cipher and MAC from its own name-list, so the two
68 // directions may differ and are kept apart from KEXINIT through to key install.
69 uint8_t cipher_alg_c2s; ///< SSH_CIPHER_* client-to-server.
70 uint8_t cipher_alg_s2c; ///< SSH_CIPHER_* server-to-client.
71 uint8_t mac_alg_c2s; ///< SSH_MAC_* client-to-server (aes cipher only; 0 = hmac-sha2-256).
72 uint8_t mac_alg_s2c; ///< SSH_MAC_* server-to-client (aes cipher only; 0 = hmac-sha2-256).
73
74 // Every buffer below is the constants region of the connection's span, at its own named offset.
75 // Null until the connection claims the slot and splits that borrow.
76 uint8_t *ecdh_sk; ///< 32B: X25519 scalar / P-256 d, ephemeral private. Wiped by ssh_dh_wipe().
77 uint8_t *ecdh_pk; ///< 32B: X25519 ephemeral public (curve25519 KEX only).
78
79 char *v_c; ///< SSH_VERSION_MAX: client identification string (no CR LF).
80 uint16_t v_c_len; ///< Length of v_c.
81 char *v_s; ///< SSH_VERSION_MAX: server identification string (no CR LF).
82 uint16_t v_s_len; ///< Length of v_s.
83
84 uint8_t *ident_buf; ///< SSH_VERSION_MAX: accumulator for the inbound identification string.
85 uint16_t ident_len; ///< Bytes buffered in ident_buf.
86
87 uint8_t *i_c; ///< PROTOCORE_SSH_I_C_MAX: client KEXINIT payload (for H).
88 uint16_t i_c_len; ///< Length of i_c.
89 uint8_t *i_s; ///< PROTOCORE_SSH_I_S_MAX: server KEXINIT payload (for H).
90 uint16_t i_s_len; ///< Length of i_s.
91
92 uint8_t *cpub; ///< PROTOCORE_SSH_CPUB_MAX: exchange value the client sent - e, Q_C or C_INIT (for H).
93 uint16_t cpub_len; ///< Length of cpub.
94
95 uint8_t *session_id; ///< SSH_KEXHASH_MAX_LEN: H from the first KEX (RFC 4253 sec 7.2).
96 uint8_t session_id_len; ///< Session id length (the first KEX's exchange-hash length).
97 embed_bool have_session_id; ///< True once the first KEX completes.
98
99 // RFC 4253 sec 6 is a layer under sec 7, so the codec is handed one of these per call rather
100 // than reading them. Each switches on its own SSH_MSG_NEWKEYS (sec 7.3).
101 SshDir out; ///< Our outbound direction: encrypted once we sent NEWKEYS, and the epoch it reads.
102 SshDir in; ///< Our inbound direction: encrypted once the peer's arrives.
103
104 embed_bool kex_active; ///< An exchange is running, from KEXINIT to NEWKEYS (sec 9).
105 // sec 7.1 restricts what may be sent from the moment THIS end sends its KEXINIT until it sends
106 // its NEWKEYS, which is a narrower window than kex_active: an exchange is already running while
107 // this end is still waiting to send its own KEXINIT, and that first one must not be refused.
108 embed_bool kexinit_sent; ///< This end sent its KEXINIT and not yet its NEWKEYS (sec 7.1).
109 // sec 9: "the state of the higher-level protocols is not affected by the key exchange", so a
110 // re-exchange has to put the connection back where it interrupted it. The phase alone cannot say
111 // where that was - every exchange ends in SSH_PHASE_NEWKEYS however it started.
112 SshPhase phase_before_kex; ///< What to resume when this exchange completes (sec 9).
113 embed_bool drop_guessed_kex_pkt; ///< The peer guessed a KEX that lost negotiation (sec 7.1).
114 embed_bool ext_info_enabled; ///< Peer offered its role's RFC 8308 sec 2.2 indicator.
115 embed_bool ext_info_sent; ///< EXT_INFO already went out; RFC 8308 sec 2.4 allows it once.
116 embed_bool authed; ///< True after successful user authentication.
117 uint32_t last_kex_ms; ///< protocore_millis() when the last KEX completed.
118} SshSession;
119
120/** @brief Static pool of SSH session state (BSS), one per SSH slot. */
122
123/**
124 * @brief Steer KEX and host-key negotiation toward RSA with DH-group14, or toward curve25519 with
125 * ed25519.
126 *
127 * Both suites are advertised whatever this is set to; it orders them, so a peer that supports only
128 * one still connects. Runtime-selectable, before the handshake.
129 */
130void ssh_kex_set_prefer_rsa(embed_bool prefer);
131
132/** @brief Current negotiation preference (true = prefer RSA / DH). */
133embed_bool ssh_kex_prefer_rsa(void);
134
135/**
136 * @brief The session identifier for slot @p i, or null before the first key exchange completes.
137 *
138 * RFC 4253 sec 10: "When the service starts, it may have access to the session identifier generated
139 * during the key exchange." It is the first exchange's hash H (sec 7.2) and does not change on a
140 * re-exchange, so a service that binds to it stays bound.
141 *
142 * @param i SSH slot index.
143 * @param len Set to the identifier's length: 32 for the SHA-256 methods, 64 for the SHA-512 one.
144 */
145const uint8_t *ssh_session_id(uint8_t i, size_t *len);
146
147/**
148 * @brief Latch the first exchange's hash as slot @p i's session identifier (RFC 4253 sec 7.2).
149 *
150 * "The exchange hash H from the first key exchange is additionally used as the session identifier."
151 * Both roles compute H in their own half of sec 8 and hand it here; the second and later exchanges
152 * are ignored, so the identifier never moves under a service that bound to it.
153 */
154void ssh_session_id_latch(uint8_t i, const uint8_t *h, size_t h_len);
155
156/** @brief True when @p a hashes with SHA-512 rather than SHA-256 (RFC 8268, RFC 8731). */
157embed_bool ssh_kex_is_sha512(SshKexAlg a);
158
159/**
160 * @brief Verify the server's signature over the exchange hash with its host key (RFC 4253 sec 8).
161 *
162 * @param i the SSH slot the exchange belongs to
163 * @param ks the host key blob the server sent
164 * @param ks_len its length
165 * @param sig the signature blob
166 * @param sig_len its length
167 * @param h the exchange hash the signature is taken over
168 * @param h_len its length
169 * @return true when the signature checks out under the blob's own algorithm.
170 */
171embed_bool ssh_hostkey_verify(uint8_t i, const uint8_t *ks, size_t ks_len, const uint8_t *sig, size_t sig_len,
172 const uint8_t *h, size_t h_len);
173
174/** @brief RFC 4253 sec 6 binary packet: the bytes a receive consumes, and the body it carries. */
175typedef struct
176{
177 const uint8_t *data; ///< bytes a receive consumes
178 const uint8_t *payload; ///< a KEXINIT or KEXDH payload
179 size_t len; ///< how many
180 size_t consumed; ///< bytes a receive took from data
182
183/** @brief Where a build or a send writes, and what it wrote. */
184typedef struct
185{
186 uint8_t *out; ///< where a build or a send writes
187 size_t out_len; ///< what it wrote
188 size_t cap; ///< how much room it has
190
191/** @brief RFC 4253 sec 8: every term the exchange hash H is taken over, and where H lands. */
192typedef struct
193{
194 embed_bool pub_is_string; ///< the peer public value is a string, not an mpint
195 const uint8_t *cpub; ///< the client public value
196 size_t cpub_len; ///< its length
197 const uint8_t *spub; ///< the server public value
198 size_t spub_len; ///< its length
199 const uint8_t *k_be; ///< the shared secret, big-endian
200 size_t k_len; ///< its length
201 const uint8_t *ks; ///< the host key blob
202 size_t ks_len; ///< its length
203 embed_bool k_is_string; ///< that secret is a string, not an mpint
204 embed_bool is512; ///< the method hashes with SHA-512
205 uint8_t hash[SSH_KEXHASH_MAX_LEN]; ///< where the exchange hash H lands
206 size_t hash_len; ///< its length: 32 for the SHA-256 methods, 64 for the SHA-512 one
208
209/** @brief RFC 4253 sec 9 key re-exchange: what passed since the last one, against its budget. */
210typedef struct
211{
212 uint32_t seq_send; ///< packets sent since the last exchange
213 uint32_t seq_recv; ///< packets received since it
214 uint32_t elapsed_ms; ///< time since it
215 uint32_t pkt_threshold; ///< the volume budget
216 uint32_t time_threshold_ms; ///< the time budget
218
219/**
220 * @brief The RFC 4253 transport state machine, as the operations both roles consume.
221 *
222 * One member per rule the RFC states, so a section number resolves to exactly one implementation.
223 * Role selects which half of a mirrored pair a caller sends - it does not select a second machine.
224 *
225 * @var SshTransportNs::recv_ident sec 4.2 receive the peer identification string
226 * @var SshTransportNs::send_ident sec 4.2 send ours
227 * @var SshTransportNs::kexinit_build sec 7.1 build our KEXINIT, keeping a copy for H
228 * @var SshTransportNs::kexinit_parse sec 7.1 parse the peer's and negotiate every list
229 * @var SshTransportNs::kex_generate sec 8 generate this exchange's ephemeral
230 * @var SshTransportNs::exchange_hash sec 8 the exchange hash H over the negotiated method's terms
231 * @var SshTransportNs::kexdh_reply sec 8 the KEXDH half this role sends
232 * @var SshTransportNs::newkeys_sent sec 7.3 our outbound switches when we send NEWKEYS
233 * @var SshTransportNs::newkeys_complete sec 7.3 our inbound switches when the peer's arrives
234 * @var SshTransportNs::rekey_due sec 9 the volume and time budget since the last exchange
235 * @var SshTransportNs::begin_rekey sec 9 start a re-exchange, when not already doing one
236 *
237 * A caller sets the members a call takes, invokes it through ::SshTransport, and reads the outcome
238 * off the same handle.
239 *
240 * @var SshTransportNs::slot the SSH slot a call acts on
241 * @var SshTransportNs::pkt sec 6 the bytes one message occupies
242 * @var SshTransportNs::out_args where a build or a send writes
243 * @var SshTransportNs::kexhash sec 8 the terms the exchange hash H is taken over
244 * @var SshTransportNs::rekey sec 9 the volume and time budget since the last exchange
245 * @var SshTransportNs::ok a call's true/false outcome
246 * @var SshTransportNs::i32 a call's signed outcome
247 */
248
249typedef struct
250{
251 uint8_t slot; ///< the SSH slot a call acts on
252 SshPacketArgs pkt; ///< sec 6 the bytes one message occupies
253 SshTransportOut out_args; ///< where a build or a send writes
254 SshKexHashArgs kexhash; ///< sec 8 the terms the exchange hash H is taken over
255 SshRekeyArgs rekey; ///< sec 9 the volume and time budget since the last exchange
256 embed_bool ok;
257 int i32;
259
260/** @brief The operands and the outcome. */
262
263/** @brief The entries. */
264typedef struct
265{
266 void (*const recv_ident)(const uint8_t *work);
267 void (*const send_ident)(const uint8_t *work);
268 void (*const kexinit_build)(const uint8_t *work);
269 void (*const kexinit_parse)(uint8_t *work);
270 void (*const kex_generate)(const uint8_t *work);
271 void (*const exchange_hash)(const uint8_t *work);
272 void (*const kexdh_reply)(const uint8_t *work);
273 void (*const newkeys_sent)(const uint8_t *work);
274 void (*const newkeys_complete)(uint8_t *work);
275 void (*const rekey_due)(const uint8_t *work);
276 void (*const begin_rekey)(const uint8_t *work);
278
279// What the table binds, defined once in the .c and taking one parameter each: everything
280// else an entry needs is an operand in SshTransportV or a region of the borrow at a fixed offset.
281void protocore_ssh_transport_recv_ident(const uint8_t *work);
282void protocore_ssh_transport_send_ident(const uint8_t *work);
285void protocore_ssh_transport_kex_generate(const uint8_t *work);
287void protocore_ssh_transport_kexdh_reply(const uint8_t *work);
288void protocore_ssh_transport_newkeys_sent(const uint8_t *work);
290void protocore_ssh_transport_rekey_due(const uint8_t *work);
291void protocore_ssh_transport_begin_rekey(const uint8_t *work);
292
293// `static const`, initialised HERE rather than `extern` against a definition in the .c: a
294// const object whose initializer every translation unit can see is a COMPILE-TIME FACT, so
295// `SshTransport.recv_ident(work)` resolves to a named function and becomes a DIRECT call. An extern table
296// leaves the call indirect and the symbol live at every level, -O2 -flto included.
297static const SshTransportNs SshTransport __attribute__((unused)) = {
309};
310
311/**
312 * @brief The PROTOCORE_SSH_TRANSPORT_BORROW bytes this module's state lives in.
313 *
314 * Stated beside the namespace rather than on it: an entry takes a borrow, and this is where
315 * that borrow comes from. Taken once from the end of the pool, which no mark and no release
316 * walks, so the state lasts the life of the program.
317 *
318 * @return the span.
319 */
321
322/**
323 * @brief Install the server's ssh-ed25519 host key (RFC 8709) from its 32-byte private seed.
324 * @param seed the private seed; its public key is derived here and both are kept.
325 */
326void protocore_ssh_hostkey_ed25519_set(const uint8_t seed[32]);
327
328/** @brief Whether an ssh-ed25519 host key is installed. */
330
331/**
332 * @brief Install the server's ecdsa-sha2-nistp256 host key (RFC 5656) from its private scalar.
333 * @param priv the 32-byte scalar; an invalid one installs no key.
334 */
335void protocore_ssh_hostkey_ecdsa_set(const uint8_t *priv);
336
337/** @brief Whether an ecdsa-sha2-nistp256 host key is installed. */
339
340/** @brief Reader shorthand: SSH_TRANSPORT->kexinit_parse(...). */
341#define SSH_TRANSPORT (&SshTransport)
342
343#if PROTOCORE_SSH_KEX_BENCH
344// Wall-clock KEX bench (perf / FEATURE_PERFORMANCE): one owned context holding the two device-side compute
345// spans of a key exchange, in microseconds. ssh_kex_generate records the ephemeral-keygen span (one X25519
346// base multiply for a curve25519 KEX) into last_kexgen_us; ssh_kexdh_handle records the reply span
347// (shared-secret X25519 + host-key sign + exchange hash + KDF + reply assembly) into last_kexreply_us and
348// bumps kex_count. The rig firmware watches kex_count and prints both over its own serial - src writes and
349// output. Compiled out entirely unless PROTOCORE_SSH_KEX_BENCH is defined (a rig-only measurement build).
350typedef struct
351{
352 volatile long long last_kexgen_us; ///< ssh_kex_generate: ephemeral X25519 base-multiply span.
353 volatile long long last_kexreply_us; ///< ssh_kexdh_handle: reply span (shared secret + sign + hash + KDF).
354 volatile unsigned kex_count; ///< bumped after each completed KEX; the rig prints on change.
355} SshKexBenchCtx;
356extern SshKexBenchCtx protocore_ssh_kex_bench;
357#endif
358
359/** @brief Max bytes ssh_kdf_derive() can produce (4 SHA-256 blocks). */
360#define SSH_KDF_MAX (4 * PROTOCORE_SHA256_DIGEST_LEN)
361
362/**
363 * @brief One key exchange's derivation inputs, passed by reference.
364 *
365 * Every value here is fixed for the whole of a KEX and read by each of the six derivations, so it
366 * travels as one pointer: an argument list this wide spills past the register window and pays for it
367 * on every call, at the deepest call depth in the library.
368 */
369typedef struct
370{
371 uint8_t *work; ///< PROTOCORE_SSH_KDF_BORROW bytes: the hash context, then the K1 || K2 chain.
372 const uint8_t *K_be; ///< Shared secret K, big-endian, 256 bytes.
373 const uint8_t *H; ///< Current exchange hash.
374 const uint8_t *session_id; ///< H of the first KEX; equals H until the first re-key.
375 size_t h_len; ///< Length of H.
376 size_t sid_len; ///< Length of session_id.
377 embed_bool k_is_string; ///< Encode K as a plain SSH string (hybrid KEX), not an mpint.
378 embed_bool is512; ///< Hash with SHA-512 instead of SHA-256.
380
381// ---------------------------------------------------------------------------
382// Packet state per connection
383// ---------------------------------------------------------------------------
384
385/**
386 * @brief Per-connection SSH binary packet state.
387 *
388 * Allocated in ssh_pool[] (BSS); one entry per SSH connection slot.
389 * Key material is in ssh_keys[] - a separate BSS symbol to prevent linear
390 * overflow from packet buffers into key material.
391 */
392typedef struct
393{
394 // RFC 4253 sec 6.4: incremented per packet and never reset, not even across a re-exchange, so
395 // these stay with the codec rather than moving to the session with the protocol flags.
396 uint32_t seq_no_send; ///< Outgoing sequence number.
397 uint32_t seq_no_recv; ///< Incoming sequence number.
398
399 // SSH keys are named by direction (client->server "c2s", server->client "s2c"), fixed by RFC 4253
400 // §7.2 regardless of role. A server sends s2c / receives c2s; a client is the mirror. This flag
401 // selects the direction at each cipher/MAC site so one packet implementation serves both roles.
402 // Default false = server (so existing server code is unchanged); ssh_pkt_set_client() flips it.
403 embed_bool is_client;
404
405 // Receive reassembly: we may receive partial packets across TCP segments. rx_buf is the whole of
406 // the data packet region of the connection's span, at its own named offset.
407 uint8_t *rx_buf; ///< SSH_RX_ASM_CAP bytes at SSH_OFF_RX_ASM. Null until claimed.
408 size_t rx_len; ///< Bytes currently in rx_buf.
409
410 // One finished packet waiting for a worker to put it on the wire. The codec frames into
411 // tx_wire and raises tx_ready; the worker sends from tx_off and lowers the flag when the last
412 // byte is out. The codec never reaches the wire itself.
413 //
414 // tx_wire is taken once from the secure pool's persistent end - the end no mark walks - and
415 // reused for every packet on this slot. Releasing per packet would wipe the whole wire buffer
416 // each time, and the mark end cannot hold it anyway: mark/release is a bump discipline, so one
417 // slot's release would reclaim another slot's borrow.
418 uint8_t *tx_wire; ///< The wire buffer for this slot. Null until the first packet.
419 size_t tx_len; ///< Bytes of the framed packet.
420 size_t tx_off; ///< Bytes already put on the wire.
421 embed_bool tx_ready; ///< A packet is framed and waiting for a worker.
422
423 // The packet MAC and the key exchange work out of these, and they come from the same one borrow as
424 // tx_wire. Held for the slot's life so neither costs a borrow or a wipe on the packet path.
425 uint8_t *mac_work; ///< PROTOCORE_HMAC_SHA256_BORROW bytes. Null until the first packet.
426 // SSH_CIPHER_WORK_LEN bytes for the negotiated record cipher, its own region so a MAC and a
427 // cipher on the same packet never reach each other's bytes.
428 uint8_t *cipher_work;
429 // PROTOCORE_CRYPTO_BORROW_MAX bytes for the handshake's crypto: the exchange hash, the RFC 4253 sec 7.2 KDF,
430 // the host-key signature and the userauth one. Those run in sequence, never at once, so they share.
431 uint8_t *crypto_work;
433
434/** @brief Static packet state pool (BSS). One entry per SSH slot. */
436
437/**
438 * @brief Initialize the packet state for SSH connection slot @p i.
439 *
440 * Zeroes the sequence numbers and the transmit state, keeping the slot's storage pointers. The
441 * protocol flags are the session's (ssh_transport.h) and are reset by ssh_transport_init().
442 *
443 * @param i SSH slot index.
444 */
445void ssh_pkt_init(uint8_t i);
446
447/**
448 * @brief Bind the session state for SSH connection slot @p i to the slot's storage.
449 *
450 * Zeroes the session, then points each of its buffers and both key epochs at their offsets within
451 * the slot, leaves the phase at SSH_PHASE_IDENT with the first key exchange already running, and
452 * marks both epochs inactive.
453 *
454 * @param i SSH slot index.
455 */
456void ssh_transport_init(uint8_t i);
457
458/**
459 * @brief Take the slot's one persistent borrow if it has none yet, and split it.
460 *
461 * Sets @ref SshPacketState::tx_wire, @ref SshPacketState::mac_work and @ref SshPacketState::crypto_work.
462 * Idempotent, and false only when the pool cannot cover the slot.
463 */
465
466/**
467 * @brief Mark slot @p i as the SSH client role (call once, right after ssh_pkt_init).
468 *
469 * Flips the send/receive key direction: the client encrypts with the c2s key set and decrypts with
470 * the s2c one, the mirror of the server. Without this a slot defaults to the server role.
471 */
472void ssh_pkt_set_client(uint8_t i);
473
474/**
475 * @brief Frame the @p payload_len bytes already written at @p wire + @ref SSH_WIRE_PAYLOAD_OFF.
476 *
477 * The in-place form of ssh_pkt_send(): same framing, padding, encryption and MAC, over a payload the
478 * caller has already placed. @p wire holds the finished packet on return.
479 *
480 * @return 0 on success, -1 on overflow or sequence-number exhaustion.
481 */
482int ssh_pkt_send_at(uint8_t i, uint8_t *wire, size_t payload_len, size_t *out_len, size_t wire_cap, const SshDir *dir);
483
484/**
485 * @brief Frame @p payload for slot @p i into the secure pool and raise the flag a worker drains.
486 *
487 * Borrows the wire buffer itself, for a caller that already holds its message somewhere else -
488 * handshake and control traffic, which is small and infrequent. On return the packet is framed and
489 * @ref SshPacketState::tx_ready is set; a worker puts the bytes on the wire and releases the
490 * borrow. This layer never reaches the wire.
491 *
492 * @return 0 on success, -1 if a packet is already pending, the pool is exhausted, or framing fails.
493 */
494int ssh_pkt_emit(uint8_t i, const uint8_t *payload, size_t len, const SshDir *dir);
495
496/**
497 * @brief Build and send one SSH binary packet.
498 *
499 * Frames @p payload according to RFC 4253 §6:
500 * - Adds random padding to align to 16-byte boundary.
501 * - If encrypted: encrypts with AES-256-CTR, appends HMAC-SHA2-256 MAC.
502 * - Increments seq_no_send; closes connection if threshold reached.
503 *
504 * The serialized packet is written into @p out. *@p out_len is set to the
505 * number of bytes written. @p out must be at least
506 * (4 + 1 + payload_len + 16 + 32) bytes.
507 *
508 * @param i SSH slot index.
509 * @param payload Plaintext SSH message payload.
510 * @param payload_len Length of @p payload.
511 * @param out Output buffer for the wire packet.
512 * @param out_len Set to the number of bytes written into @p out.
513 * @param out_cap Capacity of @p out.
514 * @return 0 on success, -1 on overflow or sequence-number exhaustion.
515 */
516int ssh_pkt_send(uint8_t i, const uint8_t *payload, size_t payload_len, uint8_t *out, size_t *out_len, size_t out_cap,
517 const SshDir *dir);
518
519/**
520 * @brief Callback invoked once per complete, verified inbound SSH message.
521 *
522 * @param slot SSH slot index.
523 * @param msg_type First payload byte (SSH message number).
524 * @param payload Decrypted message payload (includes @p msg_type at [0]).
525 * @param payload_len Length of @p payload.
526 */
527typedef void (*ssh_msg_handler_t)(uint8_t slot, uint8_t msg_type, const uint8_t *payload, size_t payload_len);
528
529/**
530 * @brief Receive and process one or more SSH binary packets from @p data.
531 *
532 * Appends @p len bytes from @p data to the receive buffer for slot @p i,
533 * then extracts complete packets. For each complete packet:
534 * - If encrypted: decrypts with AES-256-CTR, verifies HMAC-SHA2-256.
535 * Closes connection (returns -1) on MAC failure without processing payload.
536 * - Increments seq_no_recv; closes connection if threshold reached.
537 * - Calls @p handler(slot, msg_type, payload, payload_len) for the payload.
538 *
539 * @param i SSH slot index.
540 * @param data Received bytes (from TCP).
541 * @param len Number of bytes in @p data.
542 * @param handler Callback invoked once per complete, verified packet.
543 * @return 0 on success, -1 on MAC failure or sequence-number exhaustion
544 * (caller must close the TCP connection).
545 */
546int ssh_pkt_recv(uint8_t i, const uint8_t *data, size_t len, ssh_msg_handler_t handler, const SshDir *dir);
547
548/**
549 * @brief Send SSH_MSG_DISCONNECT with reason @p reason_code.
550 *
551 * Sends the packet, then zeroes the packet state and key material for slot @p i.
552 *
553 * @param i SSH slot index.
554 * @param reason_code One of SSH_DISCONNECT_* constants.
555 * @param out Output buffer for the wire packet.
556 * @param out_len Set to the number of bytes written.
557 * @param out_cap Capacity of @p out.
558 * @return 0 on success, -1 on error.
559 */
560int ssh_pkt_disconnect(uint8_t i, uint32_t reason_code, uint8_t *out, size_t *out_len, size_t out_cap,
561 const SshDir *dir);
562
563// ---------------------------------------------------------------------------
564// RFC 4253 sec 11.4 - Reserved Messages
565// ---------------------------------------------------------------------------
566
567/** @brief Bytes in an SSH_MSG_UNIMPLEMENTED payload: the message number and one uint32. */
568#define SSH_UNIMPLEMENTED_LEN 5u
569
570/**
571 * @brief Build the SSH_MSG_UNIMPLEMENTED payload answering the packet slot @p i last received.
572 *
573 * "An implementation MUST respond to all unrecognized messages with an SSH_MSG_UNIMPLEMENTED
574 * message in the order in which the messages were received." The sequence number it carries is
575 * the receive counter's, which this layer owns; the caller frames and sends the payload.
576 *
577 * @param i SSH slot index.
578 * @param out Output buffer for the payload.
579 * @param out_len Set to SSH_UNIMPLEMENTED_LEN.
580 * @param out_cap Capacity of @p out.
581 * @return 0 on success, -1 on a bad slot or too small a buffer.
582 */
583int ssh_pkt_unimplemented(uint8_t i, uint8_t *out, size_t *out_len, size_t out_cap);
584
585// ---------------------------------------------------------------------------
586// RFC 4253 sec 7.2 - key material
587// ---------------------------------------------------------------------------
588
589// These two are anonymous enums: the constants are what the code names, and the negotiated value
590// travels as a uint8_t through ssh_kex_install_keys, ssh_mac_is_etm, ssh_mac_len, and the
591// per-direction cipher_mode_* / mac_mode_* session fields.
592
593/** @brief Negotiated bulk cipher for a session. */
594enum
595{
596 SSH_CIPHER_AES256CTR = 0, ///< aes256-ctr + a separate HMAC (the fallback)
597 SSH_CIPHER_CHACHA20POLY1305 = 1, ///< chacha20-poly1305@openssh.com (AEAD; no separate MAC)
598 SSH_CIPHER_AES256GCM = 2, ///< aes256-gcm@openssh.com (AEAD, RFC 5647; no separate MAC)
599};
600
601/** @brief Negotiated MAC for the aes256-ctr cipher (unused with the chacha AEAD). */
602enum
603{
604 SSH_MAC_HMAC_SHA256 = 0, ///< hmac-sha2-256 (encrypt-and-MAC, RFC 4253)
605 SSH_MAC_HMAC_SHA512 = 1, ///< hmac-sha2-512 (encrypt-and-MAC)
606 SSH_MAC_HMAC_SHA256_ETM = 2, ///< hmac-sha2-256-etm@openssh.com (encrypt-then-MAC)
607 SSH_MAC_HMAC_SHA512_ETM = 3, ///< hmac-sha2-512-etm@openssh.com (encrypt-then-MAC)
608};
609
610/** @brief True if @p mac_mode is an encrypt-then-MAC variant (length in the clear, MAC over ciphertext). */
611static inline embed_bool ssh_mac_is_etm(uint8_t mac_mode)
612{
613 return mac_mode == SSH_MAC_HMAC_SHA256_ETM || mac_mode == SSH_MAC_HMAC_SHA512_ETM;
614}
615/** @brief MAC tag / key length in bytes for @p mac_mode (32 for SHA-256, 64 for SHA-512). */
616static inline uint8_t ssh_mac_len(uint8_t mac_mode)
617{
618 return (mac_mode == SSH_MAC_HMAC_SHA512 || mac_mode == SSH_MAC_HMAC_SHA512_ETM) ? 64 : 32;
619}
620
621// Secure wipe: the canonical mmgr_zero_buf() lives in locus_carcerum/locus_carcerum.h (included above). Use it for
622// any buffer that held key material - a volatile store the compiler may not elide, unlike a dead memset.
623
624// ---------------------------------------------------------------------------
625// Session key material (one entry per SSH connection)
626// ---------------------------------------------------------------------------
627
628/**
629 * @brief AES-256-CTR + HMAC-SHA2-256 session keys for one SSH connection.
630 *
631 * This struct occupies a separate BSS symbol (ssh_keys[]) from the packet
632 * receive buffer (ssh_pool[].pkt_buf). See the security model at the top
633 * of this file for why that separation matters.
634 *
635 * Key derivation follows RFC 4253 §7.2. After the DH exchange hash H is
636 * known and K is available, six values are derived:
637 *
638 * IV_c2s = SHA256(K || H || "A" || session_id) [16 bytes]
639 * IV_s2c = SHA256(K || H || "B" || session_id) [16 bytes]
640 * key_c2s = SHA256(K || H || "C" || session_id) [32 bytes]
641 * key_s2c = SHA256(K || H || "D" || session_id) [32 bytes]
642 * mac_c2s = SHA256(K || H || "E" || session_id) [32 bytes]
643 * mac_s2c = SHA256(K || H || "F" || session_id) [32 bytes]
644 *
645 * aes_key/aes_ctr C→S are the client-to-server key + counter (server decrypts inbound); S→C are the
646 * reverse (server encrypts outbound).
647 */
648typedef struct
649{
650 // aes256-ctr stores the raw 32-byte key and the 16-byte IV per direction and rebuilds its key schedule
651 // per packet in the shared crypto scratch, so no expanded CTR key lingers here. The IV is the running
652 // 128-bit counter (see aes256ctr.h).
653 //
654 // aes256-gcm@openssh.com shares aes_iv_* (the modes are mutually exclusive) but NOT aes_key_* - see the
655 // keyed contexts below.
656 // Every key buffer below is one epoch of the kmt region of the connection's span, at its own
657 // named offset. Null until the connection claims the slot and splits its borrow.
658 uint8_t *aes_key_c2s; ///< PROTOCORE_AES256CTR_KEY_LEN: AES key C→S (server decrypts inbound).
659 uint8_t *aes_key_s2c; ///< PROTOCORE_AES256CTR_KEY_LEN: AES key S→C (server encrypts outbound).
660 uint8_t *aes_iv_c2s; ///< PROTOCORE_AES256CTR_CTR_LEN: AES IV C→S (CTR counter / GCM nonce); advances per packet.
661 uint8_t *aes_iv_s2c; ///< PROTOCORE_AES256CTR_CTR_LEN: AES IV S→C (CTR counter / GCM nonce); advances per packet.
662
663 uint8_t *mac_key_c2s; ///< 64B: HMAC key, client-to-server (aes mode); 32 bytes for SHA-256, 64 for SHA-512.
664 uint8_t *mac_key_s2c; ///< 64B: HMAC key, server-to-client (aes mode).
665 // RFC 4253 sec 7.1 negotiates the cipher and the MAC per direction, so each is stored per direction
666 // and a session may run different ones each way (0 = aes256-ctr / hmac-sha2-256 E&M).
667 uint8_t mac_mode_c2s; ///< SSH_MAC_* client-to-server (aes256-ctr only).
668 uint8_t mac_mode_s2c; ///< SSH_MAC_* server-to-client (aes256-ctr only).
669 uint8_t cipher_mode_c2s; ///< SSH_CIPHER_* client-to-server.
670 uint8_t cipher_mode_s2c; ///< SSH_CIPHER_* server-to-client.
671 // chacha20-poly1305@openssh.com: 512-bit key per direction (K_main || K_header); no IV, no MAC key.
672 uint8_t *chacha_key_c2s; ///< PROTOCORE_CHACHAPOLY_KEY_LEN: client-to-server, used only in chacha mode.
673 uint8_t *chacha_key_s2c; ///< PROTOCORE_CHACHAPOLY_KEY_LEN: server-to-client, used only in chacha mode.
674
675 // aes256-gcm@openssh.com (RFC 5647) reuses aes_iv_* above (mode-exclusive with CTR): the low 12 bytes
676 // are the nonce, advanced per packet by AesGcm.iv_increment. No separate MAC key.
677 //
678 // It does NOT use aes_key_*. A GCM key becomes a keyed context at install time and the raw key is
679 // wiped there, so in this mode the expanded schedule is the only key material resident - strictly
680 // less than CTR mode keeps. The context stays for the life of the key because standing one up costs
681 // ~9,200 cycles on an ESP32-S3, a fixed price per packet that dominates small interactive traffic
682 // (see aesgcm.h). Wiped on rekey and by ssh_keymat_wipe() on close.
683 // These two open the kmt epoch, so the region's 8-alignment is the epoch's own start.
684 uint8_t *gcm_ctx_c2s; ///< PROTOCORE_AESGCM_BORROW: keyed GCM context C→S (server opens inbound).
685 uint8_t *gcm_ctx_s2c; ///< PROTOCORE_AESGCM_BORROW: keyed GCM context S→C (server seals outbound).
686
687 embed_bool active; ///< True once keys are installed after successful KEX.
688} SshKeyMat;
689
690/**
691 * @brief Pool of session key material, two epochs per MAX_SSH_CONNS.
692 *
693 * RFC 4253 sec 7.3 switches each direction on its own NEWKEYS, so a re-key derives into the epoch
694 * neither direction is reading and each direction moves to it when its NEWKEYS crosses.
695 * The SshDir the codec is handed selects which one that site reads.
696 * Zeroed on connection close by ssh_keymat_wipe(slot).
697 */
699
700// ---------------------------------------------------------------------------
701// DH ephemeral state (one entry per SSH connection, zeroed after KEX)
702// ---------------------------------------------------------------------------
703
704/**
705 * @brief Ephemeral Diffie-Hellman state for one SSH connection.
706 *
707 * The three protocore_bignum fields (y, f, K) together hold 768 bytes of sensitive
708 * material. The entire struct is wiped by ssh_dh_wipe() immediately after
709 * session keys are derived from K.
710 *
711 * FIELD LIFETIME:
712 * y - generated by ssh_dh_generate(); zeroed in ssh_dh_wipe().
713 * f - computed in ssh_dh_generate() as g^y mod p; sent in KEXDH_REPLY;
714 * zeroed in ssh_dh_wipe().
715 * K - computed in ssh_dh_finish() as e^y mod p; used for key derivation;
716 * zeroed in ssh_dh_wipe() AFTER keys are installed.
717 */
718// All three sit in the kmt region of the connection's span, each at its own named offset, after the
719// two key epochs. Null until the connection claims the slot and splits its borrow.
720typedef struct
721{
722 protocore_bignum *y; ///< Server ephemeral private DH scalar (SENSITIVE - wiped after KEX).
723 protocore_bignum *f; ///< Server DH public value = g^y mod p (sent to client).
724 protocore_bignum *K; ///< Shared DH secret = e^y mod p (SENSITIVE - wiped after key derivation).
725} SshDhState;
726
727/** @brief Pool of ephemeral DH state, one entry per MAX_SSH_CONNS. */
729
730/**
731 * @brief Generate slot @p i's DH ephemeral: a random y, and f = g^y mod p (RFC 4253 sec 8).
732 * @return 0 on success, -1 if the slot has no storage.
733 */
734int ssh_dh_generate(uint8_t i);
735
736/**
737 * @brief Derive the RFC 4253 sec 7.2 keys from K, H and the session id into slot @p i's epoch,
738 * one letter per direction.
739 */
740/**
741 * @brief One RFC 4253 sec 7.2 derivation: @p out_len bytes of the key @p label names.
742 *
743 * "Encryption keys MUST be computed as HASH, of a known value and K": K1 = HASH(K || H || X ||
744 * session_id) with X the label byte, and where more bytes are wanted than one hash gives,
745 * "the key is extended by computing HASH of the concatenation of K and H and the entire key so
746 * far" - K2 = HASH(K || H || K1), K3 = HASH(K || H || K1 || K2), key = K1 || K2 || K3.
747 *
748 * @param label 'A'..'F', the six keys sec 7.2 lists in order.
749 * @param out_len Bytes wanted, clamped to SSH_KDF_MAX.
750 */
751void ssh_kdf_derive(const SshKdfInputs *in, char label, uint8_t *out, size_t out_len);
752
753void ssh_kex_install_keys(uint8_t i, const SshKdfInputs *in);
754
755// ---------------------------------------------------------------------------
756// Wipe helpers
757// ---------------------------------------------------------------------------
758
759/**
760 * @brief Zero all key material for slot @p i on disconnect or KEX failure.
761 *
762 * Each buffer is wiped through its pointer at its own declared length: the bytes are the
763 * connection's, and zeroing the struct would clear the bindings and leave the keys in the span.
764 */
765static inline void ssh_keymat_wipe(uint8_t i)
766{
767 if (i >= MAX_SSH_CONNS)
768 {
769 return;
770 }
771 for (uint8_t e = 0; e < 2u; e++)
772 {
773 SshKeyMat *km = &ssh_keys[i][e];
774 if (km->gcm_ctx_c2s != NULL)
775 {
776 // A keyed GCM context may hold what the accelerator arm attached, so zeroing the bytes alone
777 // would leak it once per closed connection. Release first, then wipe. Each direction owns its
778 // context, and only the direction that negotiated GCM stood one up.
780 {
781 AesGcm.key_wipe(km->gcm_ctx_c2s);
782 }
784 {
785 AesGcm.key_wipe(km->gcm_ctx_s2c);
786 }
787 mmgr_zero_buf(km->gcm_ctx_c2s, PROTOCORE_AESGCM_BORROW);
788 mmgr_zero_buf(km->gcm_ctx_s2c, PROTOCORE_AESGCM_BORROW);
789 mmgr_zero_buf(km->chacha_key_c2s, PROTOCORE_CHACHAPOLY_KEY_LEN);
790 mmgr_zero_buf(km->chacha_key_s2c, PROTOCORE_CHACHAPOLY_KEY_LEN);
791 mmgr_zero_buf(km->mac_key_c2s, 64);
792 mmgr_zero_buf(km->mac_key_s2c, 64);
793 mmgr_zero_buf(km->aes_key_c2s, PROTOCORE_AES256CTR_KEY_LEN);
794 mmgr_zero_buf(km->aes_key_s2c, PROTOCORE_AES256CTR_KEY_LEN);
795 mmgr_zero_buf(km->aes_iv_c2s, PROTOCORE_AES256CTR_CTR_LEN);
796 mmgr_zero_buf(km->aes_iv_s2c, PROTOCORE_AES256CTR_CTR_LEN);
797 km->mac_mode_c2s = 0;
798 km->mac_mode_s2c = 0;
799 km->cipher_mode_c2s = 0;
800 km->cipher_mode_s2c = 0;
801 km->active = EMBED_FALSE;
802 }
803 }
804}
805
806/**
807 * @brief Zero every ephemeral KEX private for slot @p i after keys are derived.
808 *
809 * The scalars live in the connection's kmt region, so the wipe follows the pointers to the bytes.
810 * Zeroing the struct itself would only clear the pointers and leave the scalars in the span. The
811 * X25519 / P-256 pair sits beside y, f and K, so one call covers both of its members.
812 */
813static inline void ssh_dh_wipe(uint8_t i)
814{
815 if (i >= MAX_SSH_CONNS)
816 {
817 return;
818 }
819 if (ssh_dh[i].y != NULL)
820 {
821 mmgr_zero_buf(ssh_dh[i].y, sizeof(protocore_bignum));
822 mmgr_zero_buf(ssh_dh[i].f, sizeof(protocore_bignum));
823 mmgr_zero_buf(ssh_dh[i].K, sizeof(protocore_bignum));
824 }
825 if (ssh_sess[i].ecdh_sk != NULL)
826 {
827 mmgr_zero_buf(ssh_sess[i].ecdh_sk, SSH_ECDH_PAIR_LEN);
828 }
829}
830
831/** @brief Send DISCONNECT with the no-more-auth-methods reason, then drop. */
832/**
833 * @brief Build an SSH_MSG_DISCONNECT payload (RFC 4253 sec 11.1).
834 *
835 * @param reason_code One of SSH_DISCONNECT_* constants.
836 * @param desc Description bytes, sent as the message's first string.
837 * @param desc_len Length of @p desc.
838 * @param out Output buffer for the payload.
839 * @param out_len Set to the number of bytes written.
840 * @param cap Capacity of @p out.
841 * @return 0 on success, -1 when @p cap cannot hold the whole message.
842 */
843int ssh_pkt_build_disconnect(uint32_t reason_code, const char *desc, size_t desc_len, uint8_t *out, size_t *out_len,
844 size_t cap);
845
846/** @brief Dispatch one decrypted message; 50 and above go up to the authentication protocol. */
847int ssh_transport_dispatch(uint8_t i, uint8_t msg_type, const uint8_t *payload, size_t len);
848
849/** @brief Emit a fresh KEXINIT for slot @p i once its volume or time budget is spent. */
851
852/**
853 * @brief Handle SSH_MSG_SERVICE_REQUEST; emit SERVICE_ACCEPT for ssh-userauth (RFC 4253 sec 10).
854 * @return 0 and writes SERVICE_ACCEPT to @p out, or -1 if the service is not "ssh-userauth" or the
855 * message is malformed.
856 */
857int ssh_transport_service_request(const uint8_t *payload, size_t len, uint8_t *out, size_t *out_len, size_t cap);
858
859/**
860 * @brief Take the peer identification string off @p buf (RFC 4253 sec 4.2).
861 * @return 1 once it is whole and the phase advanced, 0 while more bytes are needed, -1 on a
862 * string the section does not admit. @p off is left at the first binary packet byte.
863 */
864int ssh_transport_version_exchange_recv(uint8_t i, const uint8_t *buf, size_t n, size_t *off);
865
866// ---------------------------------------------------------------------------
867// Public key algorithms (RFC 4253 sec 6.6)
868// ---------------------------------------------------------------------------
869
870// ---------------------------------------------------------------------------
871// RFC 4253 sec 8 - the shared secret K, from the initiating role's side
872// ---------------------------------------------------------------------------
873
874/**
875 * @brief The initiating role's ephemeral, as the sec 8 method needs to read it.
876 *
877 * @var SshKexEphemeral::alg the negotiated method, which selects every term below
878 * @var SshKexEphemeral::priv 32 bytes: X25519 scalar, P-256 d, or the DH exponent
879 * @var SshKexEphemeral::hybrid_sk a PQ/T hybrid's decapsulation key, null for the classical methods
880 * @var SshKexEphemeral::work crypto scratch, borrowed from the caller's slot
881 */
882typedef struct
883{
884 SshKexAlg alg;
885 const uint8_t *priv;
886 const uint8_t *hybrid_sk;
887 uint8_t *work;
889
890/**
891 * @brief Compute K from the peer's exchange value, for the role that sent the first message.
892 *
893 * One switch over the negotiated method, beside the responder half that shares this file: RFC 4253
894 * sec 8 is the transport's, whichever end is running it. K is written right-aligned into @p k_be,
895 * which is how sec 8 and sec 7.2 both consume it - as an mpint for the classical methods, and as a
896 * fixed 32 or 64-byte string for the hybrids.
897 *
898 * @param e This end's ephemeral for the exchange.
899 * @param peer_pub The peer's exchange value: Q_S, f, or ciphertext || Q_S for a hybrid.
900 * @param peer_pub_len Length of @p peer_pub; each method checks it against its own.
901 * @param k_be 256 bytes, zeroed then filled from the right.
902 * @return false on a wrong length, a rejected point (RFC 7748 sec 6.1), or an unsupported method.
903 */
904embed_bool ssh_kex_shared_secret(const SshKexEphemeral *e, const uint8_t *peer_pub, uint32_t peer_pub_len,
905 uint8_t k_be[256]);
906
907/** @brief True when @p blob holds a public key in one of the formats this build decodes. */
908embed_bool ssh_pubkey_blob_valid(const uint8_t *blob, uint32_t blob_len);
909
910/**
911 * @brief True when @p pk_algo names an algorithm this end verifies, and @p blob is of its key type.
912 *
913 * RFC 4252 sec 7: "Any public key algorithm may be offered for use in authentication... If the
914 * server does not support some algorithm, it MUST simply reject the request." The name arrives
915 * independently of the blob, so both are checked against what the blob parsers here accept: either
916 * RSA signature name takes an "ssh-rsa" blob, the other two take a blob named for themselves.
917 */
918embed_bool ssh_pubkey_algo_supported(const char *pk_algo, const uint8_t *blob, uint32_t blob_len);
919
920/**
921 * @brief Verify @p sig over @p signed_data against the public key in @p blob, out of slot @p i's
922 * crypto_work. The key type comes from the blob; @p pk_algo steers the RSA signature hash (RFC 8332).
923 */
924embed_bool ssh_pubkey_verify(uint8_t i, const char *pk_algo, const uint8_t *blob, uint32_t blob_len, const uint8_t *sig,
925 uint32_t sig_len, const uint8_t *signed_data, size_t signed_len);
926
927EMBED_END_DECLS
928
929#endif // PROTOCORE_TRANSPORT_TRANSPORT_H
AES-256-CTR stream cipher (aes256-ctr, RFC 4344 §4).
AES-256-GCM AEAD (RFC 5116) - keyed, detached tag.
2048-bit big-integer arithmetic for DH-group14 and RSA-2048.
#define MAX_SSH_CONNS
Maximum simultaneous SSH connections.
chacha20-poly1305@openssh.com AEAD cipher (OpenSSH PROTOCOL.chacha20poly1305).
#define PROTOCORE_AESGCM_BORROW
The handshake phase machine, RFC 4253 sec 4.2 through sec 10.
Root infrastructure: fixed widths, serializers, opcodes and sizes, for every layer above.
#define SSH_ECDH_PAIR_LEN
The ECDH ephemeral pair, private then public: what one wipe covers.
Definition common.h:169
SHA-256 (FIPS 180-4) - streaming and one-shot digest.
#define SSH_KEXHASH_MAX_LEN
Longest exchange hash / session_id the two KEX hashes produce (SHA-512).
Definition ssh_kexhash.h:26
Ephemeral Diffie-Hellman state for one SSH connection.
Definition transport.h:721
protocore_bignum * K
Shared DH secret = e^y mod p (SENSITIVE - wiped after key derivation).
Definition transport.h:724
protocore_bignum * f
Server DH public value = g^y mod p (sent to client).
Definition transport.h:723
protocore_bignum * y
Server ephemeral private DH scalar (SENSITIVE - wiped after KEX).
Definition transport.h:722
One direction's codec state, handed to the packet layer per call.
Definition transport.h:32
uint8_t epoch
key epoch it reads out of ssh_keys[slot][]
Definition transport.h:34
embed_bool enc
that direction's cipher/MAC is active
Definition transport.h:33
One key exchange's derivation inputs, passed by reference.
Definition transport.h:370
const uint8_t * session_id
H of the first KEX; equals H until the first re-key.
Definition transport.h:374
const uint8_t * H
Current exchange hash.
Definition transport.h:373
embed_bool is512
Hash with SHA-512 instead of SHA-256.
Definition transport.h:378
const uint8_t * K_be
Shared secret K, big-endian, 256 bytes.
Definition transport.h:372
size_t sid_len
Length of session_id.
Definition transport.h:376
uint8_t * work
PROTOCORE_SSH_KDF_BORROW bytes: the hash context, then the K1 || K2 chain.
Definition transport.h:371
size_t h_len
Length of H.
Definition transport.h:375
embed_bool k_is_string
Encode K as a plain SSH string (hybrid KEX), not an mpint.
Definition transport.h:377
SshKexAlg alg
Definition transport.h:884
uint8_t * work
Definition transport.h:887
const uint8_t * priv
Definition transport.h:885
const uint8_t * hybrid_sk
Definition transport.h:886
RFC 4253 sec 8: every term the exchange hash H is taken over, and where H lands.
Definition transport.h:193
size_t ks_len
its length
Definition transport.h:202
const uint8_t * spub
the server public value
Definition transport.h:197
size_t cpub_len
its length
Definition transport.h:196
embed_bool k_is_string
that secret is a string, not an mpint
Definition transport.h:203
const uint8_t * cpub
the client public value
Definition transport.h:195
uint8_t hash[SSH_KEXHASH_MAX_LEN]
where the exchange hash H lands
Definition transport.h:205
const uint8_t * k_be
the shared secret, big-endian
Definition transport.h:199
embed_bool pub_is_string
the peer public value is a string, not an mpint
Definition transport.h:194
size_t k_len
its length
Definition transport.h:200
size_t spub_len
its length
Definition transport.h:198
size_t hash_len
its length: 32 for the SHA-256 methods, 64 for the SHA-512 one
Definition transport.h:206
const uint8_t * ks
the host key blob
Definition transport.h:201
embed_bool is512
the method hashes with SHA-512
Definition transport.h:204
AES-256-CTR + HMAC-SHA2-256 session keys for one SSH connection.
Definition transport.h:649
uint8_t * chacha_key_s2c
PROTOCORE_CHACHAPOLY_KEY_LEN: server-to-client, used only in chacha mode.
Definition transport.h:673
uint8_t * aes_iv_c2s
PROTOCORE_AES256CTR_CTR_LEN: AES IV C→S (CTR counter / GCM nonce); advances per packet.
Definition transport.h:660
uint8_t mac_mode_s2c
SSH_MAC_* server-to-client (aes256-ctr only).
Definition transport.h:668
embed_bool active
True once keys are installed after successful KEX.
Definition transport.h:687
uint8_t * aes_iv_s2c
PROTOCORE_AES256CTR_CTR_LEN: AES IV S→C (CTR counter / GCM nonce); advances per packet.
Definition transport.h:661
uint8_t * gcm_ctx_s2c
PROTOCORE_AESGCM_BORROW: keyed GCM context S→C (server seals outbound).
Definition transport.h:685
uint8_t * mac_key_c2s
64B: HMAC key, client-to-server (aes mode); 32 bytes for SHA-256, 64 for SHA-512.
Definition transport.h:663
uint8_t * aes_key_s2c
PROTOCORE_AES256CTR_KEY_LEN: AES key S→C (server encrypts outbound).
Definition transport.h:659
uint8_t cipher_mode_s2c
SSH_CIPHER_* server-to-client.
Definition transport.h:670
uint8_t mac_mode_c2s
SSH_MAC_* client-to-server (aes256-ctr only).
Definition transport.h:667
uint8_t * gcm_ctx_c2s
PROTOCORE_AESGCM_BORROW: keyed GCM context C→S (server opens inbound).
Definition transport.h:684
uint8_t * mac_key_s2c
64B: HMAC key, server-to-client (aes mode).
Definition transport.h:664
uint8_t * chacha_key_c2s
PROTOCORE_CHACHAPOLY_KEY_LEN: client-to-server, used only in chacha mode.
Definition transport.h:672
uint8_t * aes_key_c2s
PROTOCORE_AES256CTR_KEY_LEN: AES key C→S (server decrypts inbound).
Definition transport.h:658
uint8_t cipher_mode_c2s
SSH_CIPHER_* client-to-server.
Definition transport.h:669
RFC 4253 sec 6 binary packet: the bytes a receive consumes, and the body it carries.
Definition transport.h:176
const uint8_t * payload
a KEXINIT or KEXDH payload
Definition transport.h:178
const uint8_t * data
bytes a receive consumes
Definition transport.h:177
size_t consumed
bytes a receive took from data
Definition transport.h:180
size_t len
how many
Definition transport.h:179
Per-connection SSH binary packet state.
Definition transport.h:393
embed_bool tx_ready
A packet is framed and waiting for a worker.
Definition transport.h:421
uint8_t * crypto_work
Definition transport.h:431
uint8_t * cipher_work
Definition transport.h:428
size_t rx_len
Bytes currently in rx_buf.
Definition transport.h:408
uint32_t seq_no_recv
Incoming sequence number.
Definition transport.h:397
size_t tx_len
Bytes of the framed packet.
Definition transport.h:419
uint8_t * mac_work
PROTOCORE_HMAC_SHA256_BORROW bytes. Null until the first packet.
Definition transport.h:425
size_t tx_off
Bytes already put on the wire.
Definition transport.h:420
uint8_t * rx_buf
SSH_RX_ASM_CAP bytes at SSH_OFF_RX_ASM. Null until claimed.
Definition transport.h:407
embed_bool is_client
Definition transport.h:403
uint32_t seq_no_send
Outgoing sequence number.
Definition transport.h:396
uint8_t * tx_wire
The wire buffer for this slot. Null until the first packet.
Definition transport.h:418
RFC 4253 sec 9 key re-exchange: what passed since the last one, against its budget.
Definition transport.h:211
uint32_t pkt_threshold
the volume budget
Definition transport.h:215
uint32_t seq_send
packets sent since the last exchange
Definition transport.h:212
uint32_t seq_recv
packets received since it
Definition transport.h:213
uint32_t time_threshold_ms
the time budget
Definition transport.h:216
uint32_t elapsed_ms
time since it
Definition transport.h:214
SSH transport/session state for one connection (BSS pool).
Definition transport.h:62
embed_bool ext_info_enabled
Peer offered its role's RFC 8308 sec 2.2 indicator.
Definition transport.h:114
uint8_t * ecdh_sk
32B: X25519 scalar / P-256 d, ephemeral private. Wiped by ssh_dh_wipe().
Definition transport.h:76
uint8_t mac_alg_c2s
SSH_MAC_* client-to-server (aes cipher only; 0 = hmac-sha2-256).
Definition transport.h:71
embed_bool authed
True after successful user authentication.
Definition transport.h:116
char * v_s
SSH_VERSION_MAX: server identification string (no CR LF).
Definition transport.h:81
uint8_t session_id_len
Session id length (the first KEX's exchange-hash length).
Definition transport.h:96
uint16_t v_s_len
Length of v_s.
Definition transport.h:82
uint8_t * session_id
SSH_KEXHASH_MAX_LEN: H from the first KEX (RFC 4253 sec 7.2).
Definition transport.h:95
SshDir in
Our inbound direction: encrypted once the peer's arrives.
Definition transport.h:102
SshKexAlg kex_alg
negotiated in KEXINIT.
Definition transport.h:65
uint8_t * ident_buf
SSH_VERSION_MAX: accumulator for the inbound identification string.
Definition transport.h:84
embed_bool kex_active
An exchange is running, from KEXINIT to NEWKEYS (sec 9).
Definition transport.h:104
SshHostkeyAlg hostkey_alg
negotiated in KEXINIT.
Definition transport.h:66
uint8_t * i_c
PROTOCORE_SSH_I_C_MAX: client KEXINIT payload (for H).
Definition transport.h:87
embed_bool kexinit_sent
This end sent its KEXINIT and not yet its NEWKEYS (sec 7.1).
Definition transport.h:108
uint16_t i_c_len
Length of i_c.
Definition transport.h:88
embed_bool ext_info_sent
EXT_INFO already went out; RFC 8308 sec 2.4 allows it once.
Definition transport.h:115
SshPhase phase
Current handshake phase.
Definition transport.h:63
SshDir out
Our outbound direction: encrypted once we sent NEWKEYS, and the epoch it reads.
Definition transport.h:101
char * v_c
SSH_VERSION_MAX: client identification string (no CR LF).
Definition transport.h:79
uint16_t i_s_len
Length of i_s.
Definition transport.h:90
embed_bool have_session_id
True once the first KEX completes.
Definition transport.h:97
uint8_t * cpub
PROTOCORE_SSH_CPUB_MAX: exchange value the client sent - e, Q_C or C_INIT (for H).
Definition transport.h:92
uint32_t last_kex_ms
protocore_millis() when the last KEX completed.
Definition transport.h:117
uint16_t cpub_len
Length of cpub.
Definition transport.h:93
uint8_t * ecdh_pk
32B: X25519 ephemeral public (curve25519 KEX only).
Definition transport.h:77
uint8_t * i_s
PROTOCORE_SSH_I_S_MAX: server KEXINIT payload (for H).
Definition transport.h:89
uint8_t cipher_alg_s2c
SSH_CIPHER_* server-to-client.
Definition transport.h:70
embed_bool drop_guessed_kex_pkt
The peer guessed a KEX that lost negotiation (sec 7.1).
Definition transport.h:113
SshPhase phase_before_kex
What to resume when this exchange completes (sec 9).
Definition transport.h:112
uint8_t cipher_alg_c2s
SSH_CIPHER_* client-to-server.
Definition transport.h:69
uint16_t ident_len
Bytes buffered in ident_buf.
Definition transport.h:85
uint8_t mac_alg_s2c
SSH_MAC_* server-to-client (aes cipher only; 0 = hmac-sha2-256).
Definition transport.h:72
uint16_t v_c_len
Length of v_c.
Definition transport.h:80
The entries.
Definition transport.h:265
void(*const kex_generate)(const uint8_t *work)
Definition transport.h:270
void(*const kexinit_parse)(uint8_t *work)
Definition transport.h:269
void(*const newkeys_sent)(const uint8_t *work)
Definition transport.h:273
void(*const exchange_hash)(const uint8_t *work)
Definition transport.h:271
void(*const send_ident)(const uint8_t *work)
Definition transport.h:267
void(*const begin_rekey)(const uint8_t *work)
Definition transport.h:276
void(*const newkeys_complete)(uint8_t *work)
Definition transport.h:274
void(*const rekey_due)(const uint8_t *work)
Definition transport.h:275
void(*const recv_ident)(const uint8_t *work)
Definition transport.h:266
void(*const kexdh_reply)(const uint8_t *work)
Definition transport.h:272
void(*const kexinit_build)(const uint8_t *work)
Definition transport.h:268
Where a build or a send writes, and what it wrote.
Definition transport.h:185
size_t out_len
what it wrote
Definition transport.h:187
uint8_t * out
where a build or a send writes
Definition transport.h:186
size_t cap
how much room it has
Definition transport.h:188
SshRekeyArgs rekey
sec 9 the volume and time budget since the last exchange
Definition transport.h:255
embed_bool ok
Definition transport.h:256
SshPacketArgs pkt
sec 6 the bytes one message occupies
Definition transport.h:252
SshTransportOut out_args
where a build or a send writes
Definition transport.h:253
SshKexHashArgs kexhash
sec 8 the terms the exchange hash H is taken over
Definition transport.h:254
uint8_t slot
the SSH slot a call acts on
Definition transport.h:251
embed_bool ssh_pubkey_algo_supported(const char *pk_algo, const uint8_t *blob, uint32_t blob_len)
True when pk_algo names an algorithm this end verifies, and blob is of its key type.
uint8_t * protocore_ssh_transport_span(void)
The PROTOCORE_SSH_TRANSPORT_BORROW bytes this module's state lives in.
SshPacketState ssh_pkt[MAX_SSH_CONNS]
Static packet state pool (BSS). One entry per SSH slot.
embed_bool ssh_pkt_slot_storage(SshPacketState *s)
Take the slot's one persistent borrow if it has none yet, and split it.
SshTransportVars SshTransportV
The operands and the outcome.
embed_bool ssh_pubkey_blob_valid(const uint8_t *blob, uint32_t blob_len)
True when blob holds a public key in one of the formats this build decodes.
int ssh_pkt_emit(uint8_t i, const uint8_t *payload, size_t len, const SshDir *dir)
Frame payload for slot i into the secure pool and raise the flag a worker drains.
void protocore_ssh_transport_newkeys_sent(const uint8_t *work)
void protocore_ssh_transport_kex_generate(const uint8_t *work)
const uint8_t * ssh_session_id(uint8_t i, size_t *len)
The session identifier for slot i, or null before the first key exchange completes.
void protocore_ssh_transport_recv_ident(const uint8_t *work)
void protocore_ssh_transport_send_ident(const uint8_t *work)
void protocore_ssh_transport_kexdh_reply(const uint8_t *work)
embed_bool ssh_kex_shared_secret(const SshKexEphemeral *e, const uint8_t *peer_pub, uint32_t peer_pub_len, uint8_t k_be[256])
Compute K from the peer's exchange value, for the role that sent the first message.
int ssh_pkt_build_disconnect(uint32_t reason_code, const char *desc, size_t desc_len, uint8_t *out, size_t *out_len, size_t cap)
Send DISCONNECT with the no-more-auth-methods reason, then drop.
@ SSH_MAC_HMAC_SHA256_ETM
hmac-sha2-256-etm@openssh.com (encrypt-then-MAC)
Definition transport.h:606
@ SSH_MAC_HMAC_SHA256
hmac-sha2-256 (encrypt-and-MAC, RFC 4253)
Definition transport.h:604
@ SSH_MAC_HMAC_SHA512
hmac-sha2-512 (encrypt-and-MAC)
Definition transport.h:605
@ SSH_MAC_HMAC_SHA512_ETM
hmac-sha2-512-etm@openssh.com (encrypt-then-MAC)
Definition transport.h:607
embed_bool protocore_ssh_hostkey_ecdsa_available(void)
Whether an ecdsa-sha2-nistp256 host key is installed.
void protocore_ssh_hostkey_ecdsa_set(const uint8_t *priv)
Install the server's ecdsa-sha2-nistp256 host key (RFC 5656) from its private scalar.
SshKeyMat ssh_keys[MAX_SSH_CONNS][2]
Pool of session key material, two epochs per MAX_SSH_CONNS.
void protocore_ssh_transport_newkeys_complete(uint8_t *work)
int ssh_pkt_send(uint8_t i, const uint8_t *payload, size_t payload_len, uint8_t *out, size_t *out_len, size_t out_cap, const SshDir *dir)
Build and send one SSH binary packet.
void ssh_kex_set_prefer_rsa(embed_bool prefer)
Steer KEX and host-key negotiation toward RSA with DH-group14, or toward curve25519 with ed25519.
int ssh_pkt_send_at(uint8_t i, uint8_t *wire, size_t payload_len, size_t *out_len, size_t wire_cap, const SshDir *dir)
Frame the payload_len bytes already written at wire + SSH_WIRE_PAYLOAD_OFF.
int ssh_transport_dispatch(uint8_t i, uint8_t msg_type, const uint8_t *payload, size_t len)
Dispatch one decrypted message; 50 and above go up to the authentication protocol.
void ssh_transport_key_re_exchange(uint8_t i)
Emit a fresh KEXINIT for slot i once its volume or time budget is spent.
int ssh_pkt_recv(uint8_t i, const uint8_t *data, size_t len, ssh_msg_handler_t handler, const SshDir *dir)
Receive and process one or more SSH binary packets from data.
int ssh_pkt_unimplemented(uint8_t i, uint8_t *out, size_t *out_len, size_t out_cap)
Build the SSH_MSG_UNIMPLEMENTED payload answering the packet slot i last received.
embed_bool ssh_hostkey_verify(uint8_t i, const uint8_t *ks, size_t ks_len, const uint8_t *sig, size_t sig_len, const uint8_t *h, size_t h_len)
Verify the server's signature over the exchange hash with its host key (RFC 4253 sec 8).
void ssh_session_id_latch(uint8_t i, const uint8_t *h, size_t h_len)
Latch the first exchange's hash as slot i's session identifier (RFC 4253 sec 7.2).
void protocore_ssh_transport_exchange_hash(const uint8_t *work)
int ssh_transport_version_exchange_recv(uint8_t i, const uint8_t *buf, size_t n, size_t *off)
Take the peer identification string off buf (RFC 4253 sec 4.2).
void protocore_ssh_transport_kexinit_build(const uint8_t *work)
void protocore_ssh_hostkey_ed25519_set(const uint8_t seed[32])
Install the server's ssh-ed25519 host key (RFC 8709) from its 32-byte private seed.
int ssh_pkt_disconnect(uint8_t i, uint32_t reason_code, uint8_t *out, size_t *out_len, size_t out_cap, const SshDir *dir)
Send SSH_MSG_DISCONNECT with reason reason_code.
SshSession ssh_sess[MAX_SSH_CONNS]
Static pool of SSH session state (BSS), one per SSH slot.
embed_bool ssh_pubkey_verify(uint8_t i, const char *pk_algo, const uint8_t *blob, uint32_t blob_len, const uint8_t *sig, uint32_t sig_len, const uint8_t *signed_data, size_t signed_len)
Verify sig over signed_data against the public key in blob, out of slot i's crypto_work....
void protocore_ssh_transport_rekey_due(const uint8_t *work)
embed_bool ssh_kex_prefer_rsa(void)
Current negotiation preference (true = prefer RSA / DH).
SshDhState ssh_dh[MAX_SSH_CONNS]
Pool of ephemeral DH state, one entry per MAX_SSH_CONNS.
void protocore_ssh_transport_kexinit_parse(uint8_t *work)
void ssh_transport_init(uint8_t i)
Bind the session state for SSH connection slot i to the slot's storage.
void ssh_pkt_init(uint8_t i)
Initialize the packet state for SSH connection slot i.
void protocore_ssh_transport_begin_rekey(const uint8_t *work)
EMBED_ENUM_BYTE(SshKexAlg, SSH_KEX_DH_GROUP14=0, SSH_KEX_CURVE25519=1, SSH_KEX_MLKEM768_X25519=2, SSH_KEX_ECDH_NISTP256=3, SSH_KEX_SNTRUP761_X25519=4)
Negotiated key-exchange method.
void ssh_pkt_set_client(uint8_t i)
Mark slot i as the SSH client role (call once, right after ssh_pkt_init).
@ SSH_CIPHER_CHACHA20POLY1305
chacha20-poly1305@openssh.com (AEAD; no separate MAC)
Definition transport.h:597
@ SSH_CIPHER_AES256GCM
aes256-gcm@openssh.com (AEAD, RFC 5647; no separate MAC)
Definition transport.h:598
@ SSH_CIPHER_AES256CTR
aes256-ctr + a separate HMAC (the fallback)
Definition transport.h:596
void ssh_kdf_derive(const SshKdfInputs *in, char label, uint8_t *out, size_t out_len)
Derive the RFC 4253 sec 7.2 keys from K, H and the session id into slot i's epoch,...
int ssh_transport_service_request(const uint8_t *payload, size_t len, uint8_t *out, size_t *out_len, size_t cap)
Handle SSH_MSG_SERVICE_REQUEST; emit SERVICE_ACCEPT for ssh-userauth (RFC 4253 sec 10).
embed_bool protocore_ssh_hostkey_ed25519_available(void)
Whether an ssh-ed25519 host key is installed.
embed_bool ssh_kex_is_sha512(SshKexAlg a)
True when a hashes with SHA-512 rather than SHA-256 (RFC 8268, RFC 8731).
void(* ssh_msg_handler_t)(uint8_t slot, uint8_t msg_type, const uint8_t *payload, size_t payload_len)
Callback invoked once per complete, verified inbound SSH message.
Definition transport.h:527
void ssh_kex_install_keys(uint8_t i, const SshKdfInputs *in)
int ssh_dh_generate(uint8_t i)
Generate slot i's DH ephemeral: a random y, and f = g^y mod p (RFC 4253 sec 8).