ProtoCore v1.0.16
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
common.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 common.h
6 * @brief Root infrastructure: fixed widths, serializers, opcodes and sizes, for every layer above.
7 */
8
9#ifndef PROTOCORE_SSH_COMMON_H
10#define PROTOCORE_SSH_COMMON_H
11
12#ifndef __cplusplus
13#include "cellularum_laboro/cellularum_laboro.h" // cellul.len: the length prefix on a written string
14#endif
15#include "crypto/aead/chachapoly/chachapoly.h" // PROTOCORE_CHACHAPOLY_KEY_LEN - the chacha keys in the memory map
16#include "crypto/asymmetric/bignum/bignum.h" // protocore_bignum - the DH ephemeral in the memory map
17#include "crypto/cipher/aes256ctr/aes256ctr.h" // PROTOCORE_AES256CTR_KEY_LEN / _CTR_LEN - the aes keys and IVs
18#include "crypto/mac/hmac_sha256/hmac_sha256.h" // PROTOCORE_HMAC_SHA256_BORROW - the packet MAC scratch
19#include "crypto/pqc/sntrup761/sntrup761.h" // PROTOCORE_SNTRUP761_PK_BYTES - the PQC public key in the memory map
20#include "memoria_operor/memoria_operor.h" // memor.cpy: the copy out of a read string
21#include "network_drivers/presentation/ssh/transport/ssh_kexhash/ssh_kexhash.h" // SSH_KEXHASH_MAX_LEN - the session id span
22#include "octetus_introitus_exitus/octetus_introitus_exitus.h" // mmgr_span, bytes.* writers, byteio.rd_str / byteio.take_be readers
23#include "spatium/spatium.h"
24
25#include "protocore_config.h" // protocore_types.h for the fixed widths, EMBED_INLINE, the SSH sizing constants
26
27// ---------------------------------------------------------------------------
28// Sizing
29// ---------------------------------------------------------------------------
30
31/** @brief Max stored length of an SSH identification string (RFC 4253 sec 4.2: 255). */
32#define SSH_VERSION_MAX 256
33
34/** @brief Longest identification string RFC 4253 sec 4.2 admits: 255 on the wire, CR and LF counted. */
35#define SSH_VERSION_CONTENT_MAX 253
36
37/**
38 * @brief Max stored size of our own KEXINIT (I_S). Sized for the full advertised suite: the
39 * kex list (mlkem + dh + ecdsa-nistp256 + curve25519 x2 + ext-info-s), all three host-key types,
40 * the cipher (chacha + 2x aes) and MAC (2x aes + 2x plain) lists, and zlib s2c compression
41 * (worst case ~580 bytes; 704 leaves headroom for future algorithm additions).
42 */
43#define PROTOCORE_SSH_KEXINIT_S_MAX 704
44
45/**
46 * @brief Capacity of I_C and I_S. A buffer takes the peer bound in the role that receives into it,
47 * our own bound in the role that writes it.
48 */
49#if PROTOCORE_ENABLE_SSH_CLIENT && PROTOCORE_ENABLE_SSH_SERVER
50#define PROTOCORE_SSH_I_C_MAX SSH_KEXINIT_MAX
51#define PROTOCORE_SSH_I_S_MAX SSH_KEXINIT_MAX
52#elif PROTOCORE_ENABLE_SSH_CLIENT
53#define PROTOCORE_SSH_I_C_MAX PROTOCORE_SSH_KEXINIT_S_MAX
54#define PROTOCORE_SSH_I_S_MAX SSH_KEXINIT_MAX
55#else
56#define PROTOCORE_SSH_I_C_MAX SSH_KEXINIT_MAX
57#define PROTOCORE_SSH_I_S_MAX PROTOCORE_SSH_KEXINIT_S_MAX
58#endif
59
60/** @brief Server identification string (no CR LF; appended on the wire). */
61#define SSH_SERVER_VERSION "SSH-2.0-1.0"
62
63/** @brief Client identification string (no CR LF; appended on the wire). */
64#define SSH_CLIENT_VERSION "SSH-2.0-PROTOCORE_client_1.0"
65
66EMBED_BEGIN_DECLS
67
68/** @brief Protocol opcodes, by the number each RFC assigns it (RFC 4250 sec 4.1.2). */
70 // Transport layer, RFC 4253: generic 1 to 19, negotiation 20 to 29, method specific 30 to 49.
71 SSH_MSG_DISCONNECT = 1, SSH_MSG_IGNORE = 2, SSH_MSG_UNIMPLEMENTED = 3, SSH_MSG_DEBUG = 4,
72 SSH_MSG_SERVICE_REQUEST = 5, SSH_MSG_SERVICE_ACCEPT = 6,
73 SSH_MSG_EXT_INFO = 7, // RFC 8308 extension negotiation
74 SSH_MSG_KEXINIT = 20, SSH_MSG_NEWKEYS = 21, SSH_MSG_KEXDH_INIT = 30, SSH_MSG_KEXDH_REPLY = 31,
75
76 // User authentication, RFC 4252: generic 50 to 59, method specific 60 to 79.
77 SSH_MSG_USERAUTH_REQUEST = 50, SSH_MSG_USERAUTH_FAILURE = 51, SSH_MSG_USERAUTH_SUCCESS = 52,
78 SSH_MSG_USERAUTH_BANNER = 53, // RFC 4252 sec 5.4: text for the user, any time before success
79 SSH_MSG_USERAUTH_PK_OK = 60,
80 // 60 is method specific: PK_OK for publickey, INFO_REQUEST for keyboard-interactive
81 // (RFC 4256 sec 3.2). The current auth phase decides which handler owns an inbound 60.
82 SSH_MSG_USERAUTH_INFO_REQUEST = 60,
83 SSH_MSG_USERAUTH_INFO_RESPONSE = 61, // RFC 4256 sec 3.4
84
85 // Connection protocol, RFC 4254: global 80 to 89, channel 90 to 127.
86 SSH_MSG_GLOBAL_REQUEST = 80, SSH_MSG_REQUEST_SUCCESS = 81, SSH_MSG_REQUEST_FAILURE = 82,
87 SSH_MSG_CHANNEL_OPEN = 90, SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91, SSH_MSG_CHANNEL_OPEN_FAILURE = 92,
88 SSH_MSG_CHANNEL_WINDOW_ADJUST = 93, SSH_MSG_CHANNEL_DATA = 94,
89 SSH_MSG_CHANNEL_EXTENDED_DATA = 95, // data_type_code + string
90 SSH_MSG_CHANNEL_EOF = 96, SSH_MSG_CHANNEL_CLOSE = 97, SSH_MSG_CHANNEL_REQUEST = 98,
91 SSH_MSG_CHANNEL_SUCCESS = 99, SSH_MSG_CHANNEL_FAILURE = 100, );
92
93/** @brief Disconnect reason codes (RFC 4253 sec 11.1, numbered by RFC 4250 sec 4.2.2). */
94EMBED_ENUM_BYTE(SshDisconnectReason, SSH_DISCONNECT_PROTOCOL_ERROR = 2, SSH_DISCONNECT_MAC_ERROR = 5,
95 SSH_DISCONNECT_SERVICE_NOT_AVAILABLE = 7, SSH_DISCONNECT_BY_APPLICATION = 11,
96 SSH_DISCONNECT_TOO_MANY_CONNECTIONS = 12, SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14, );
97
98/** @brief Channel open failure reason codes (RFC 4254 sec 5.1). */
99EMBED_ENUM_BYTE(SshOpenFailureReason, SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1, SSH_OPEN_CONNECT_FAILED = 2,
100 SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3, SSH_OPEN_RESOURCE_SHORTAGE = 4, );
101
102/**
103 * @brief The connection's memory map: every byte it uses, at a named offset from its slot base.
104 *
105 * Laid out kmt | constants | control packet | data packet, each offset the previous one plus that
106 * member's size. The storage is ssh.c's; a translation unit takes its pointer as
107 * @c ssh_conn_slot(i) + the offset and already knows the member's size.
108 */
109
110// One key epoch: the six RFC 4253 sec 7.2 keys in every cipher mode negotiation can pick, at
111// offsets from the epoch's own base. Both epochs are laid out this way.
112#define SSH_OFF_GCM_C2S 0u
113#define SSH_OFF_GCM_S2C (SSH_OFF_GCM_C2S + PROTOCORE_AESGCM_BORROW)
114#define SSH_OFF_CHACHA_C2S (SSH_OFF_GCM_S2C + PROTOCORE_AESGCM_BORROW)
115#define SSH_OFF_CHACHA_S2C (SSH_OFF_CHACHA_C2S + PROTOCORE_CHACHAPOLY_KEY_LEN)
116#define SSH_OFF_MAC_C2S (SSH_OFF_CHACHA_S2C + PROTOCORE_CHACHAPOLY_KEY_LEN)
117#define SSH_OFF_MAC_S2C (SSH_OFF_MAC_C2S + 64u)
118#define SSH_OFF_AES_KEY_C2S (SSH_OFF_MAC_S2C + 64u)
119#define SSH_OFF_AES_KEY_S2C (SSH_OFF_AES_KEY_C2S + PROTOCORE_AES256CTR_KEY_LEN)
120#define SSH_OFF_AES_IV_C2S (SSH_OFF_AES_KEY_S2C + PROTOCORE_AES256CTR_KEY_LEN)
121#define SSH_OFF_AES_IV_S2C (SSH_OFF_AES_IV_C2S + PROTOCORE_AES256CTR_CTR_LEN)
122#define SSH_EPOCH_STRIDE (SSH_OFF_AES_IV_S2C + PROTOCORE_AES256CTR_CTR_LEN)
123
124// Order: wire | session | exchange | packet | rx. Slots are contiguous, so the region an overrun
125// carries into the next slot is the one at offset 0 - the wire, which is framing, not key material.
126// A run off the end of rx therefore kills both connections rather than reaching either one's keys.
127// Bounds are enforced where bytes enter; this ordering is what remains if one is ever missed.
128//
129// The regions are grouped by how long their contents live, because that is what decides how many
130// copies a build needs:
131//
132// wire, rx one per connection, and the only regions whose size follows the packet size.
133// session one per connection, alive from the first key exchange to the last packet.
134// exchange alive only from KEXINIT to NEWKEYS (RFC 4253 sec 7.1), so one per exchange in
135// flight rather than one per connection.
136// packet alive only for the message being framed or verified, so one per worker.
137//
138// exchange and packet are still per-slot here. They are grouped so that stays visible, and so
139// lifting them out is a change of base pointer rather than a re-layout.
140
141// wire: the framed packet. The payload is written at SSH_WIRE_PAYLOAD_OFF and framed in place.
142#define SSH_OFF_WIRE 0u
143
144// session: what outlives a single exchange - the identification strings both ends hash into every
145// exchange hash, the session id the first KEX fixes (RFC 4253 sec 7.2), and the two key epochs. The
146// second epoch holds the keys a re-key derives while the first still decrypts, until both
147// directions switched (sec 7.3).
148#define SSH_OFF_V_C (SSH_OFF_WIRE + SSH_WIRE_CAP)
149#define SSH_OFF_V_S (SSH_OFF_V_C + SSH_VERSION_MAX)
150#define SSH_OFF_SESSION_ID (SSH_OFF_V_S + SSH_VERSION_MAX)
151#define SSH_OFF_EPOCH_0 (SSH_OFF_SESSION_ID + SSH_KEXHASH_MAX_LEN)
152#define SSH_OFF_EPOCH_1 (SSH_OFF_EPOCH_0 + SSH_EPOCH_STRIDE)
153#define SSH_SESSION_END (SSH_OFF_EPOCH_1 + SSH_EPOCH_STRIDE)
154
155// exchange: everything an exchange needs and nothing else reads once NEWKEYS is sent - the peer
156// identification being collected, both KEXINIT payloads the exchange hash covers, the client's
157// public value, and every ephemeral private. One exchange runs at a time per worker.
158#define SSH_OFF_IDENT SSH_SESSION_END
159#define SSH_OFF_I_C (SSH_OFF_IDENT + SSH_VERSION_MAX)
160#define SSH_OFF_I_S (SSH_OFF_I_C + PROTOCORE_SSH_I_C_MAX)
161#define SSH_OFF_KEXINIT (SSH_OFF_I_S + PROTOCORE_SSH_I_S_MAX)
162#define SSH_OFF_CPUB (SSH_OFF_KEXINIT + PROTOCORE_SSH_KEXINIT_S_MAX)
163#define SSH_OFF_DH_Y (SSH_OFF_CPUB + PROTOCORE_SSH_CPUB_MAX)
164#define SSH_OFF_DH_F (SSH_OFF_DH_Y + sizeof(protocore_bignum))
165#define SSH_OFF_DH_K (SSH_OFF_DH_F + sizeof(protocore_bignum))
166#define SSH_OFF_ECDH_SK (SSH_OFF_DH_K + sizeof(protocore_bignum))
167#define SSH_OFF_ECDH_PK (SSH_OFF_ECDH_SK + 32u)
168/** @brief The ECDH ephemeral pair, private then public: what one wipe covers. */
169#define SSH_ECDH_PAIR_LEN 64u
170#define SSH_OFF_CRYPTO_WORK (SSH_OFF_ECDH_PK + 32u)
171#define SSH_EXCHANGE_END (SSH_OFF_CRYPTO_WORK + PROTOCORE_CRYPTO_BORROW_MAX)
172
173// packet: the bytes one message's MAC works out of, then the bytes its cipher does. Live for that
174// message only. The two are separate regions rather than one shared max, so a MAC and a cipher on
175// the same packet cannot reach each other's bytes whatever order a mode runs them in. The cipher's
176// width is the wider of the two negotiable ones, since a connection runs one of them.
177#define SSH_OFF_MAC_WORK SSH_EXCHANGE_END
178#define SSH_OFF_CIPHER_WORK (SSH_OFF_MAC_WORK + PROTOCORE_HMAC_SHA256_BORROW)
179#if PROTOCORE_CHACHAPOLY_BORROW > PROTOCORE_AES256CTR_BORROW
180#define SSH_CIPHER_WORK_LEN PROTOCORE_CHACHAPOLY_BORROW
181#endif
182#if PROTOCORE_CHACHAPOLY_BORROW <= PROTOCORE_AES256CTR_BORROW
183#define SSH_CIPHER_WORK_LEN PROTOCORE_AES256CTR_BORROW
184#endif
185#define SSH_PACKET_END (SSH_OFF_CIPHER_WORK + SSH_CIPHER_WORK_LEN)
186
187// rx: the bytes drained off the transport ring, then the reassembly they feed. Last, so what it
188// runs into is the next slot's wire.
189#define SSH_OFF_RX_READ SSH_PACKET_END
190#define SSH_OFF_RX_ASM (SSH_OFF_RX_READ + RX_BUF_SIZE)
191
192/** @brief Capacity of the reassembly region at SSH_OFF_RX_ASM: what rx_buf actually spans. */
193#define SSH_RX_ASM_CAP ((size_t)SSH_RFC_MAX_PAYLOAD)
194
195/** @brief One connection's whole span, and the stride between slots. */
196#define SSH_SLOT_BORROW (SSH_OFF_RX_ASM + SSH_RX_ASM_CAP)
197
198// What each region costs, so the count a build needs is arithmetic rather than a guess. exchange
199// and packet are the two that do not have to be replicated per connection: one exchange runs at a
200// time per worker, and one message is framed at a time per worker.
201#define SSH_SESSION_SIZE (SSH_SESSION_END - SSH_OFF_V_C)
202#define SSH_EXCHANGE_SIZE (SSH_EXCHANGE_END - SSH_OFF_IDENT)
203#define SSH_PACKET_SIZE (SSH_PACKET_END - SSH_OFF_MAC_WORK)
204#define SSH_RX_SIZE (SSH_SLOT_BORROW - SSH_OFF_RX_READ)
205
206// ---------------------------------------------------------------------------
207// SSH wire types (RFC 4251 sec 5, RFC 4253 sec 7.1)
208// ---------------------------------------------------------------------------
209
210/** @brief Read a uint32 in network byte order (RFC 4251 sec 5). */
211static inline uint32_t read_u32_be(const uint8_t *p)
212{
213 return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3];
214}
215
216/** @brief Write a uint32 in network byte order (RFC 4251 sec 5). */
217static inline void write_u32_be(uint8_t *p, uint32_t v)
218{
219 p[0] = (uint8_t)(v >> 24);
220 p[1] = (uint8_t)(v >> 16);
221 p[2] = (uint8_t)(v >> 8);
222 p[3] = (uint8_t)(v);
223}
224
225// The writers below and the readers further down are C. They reach MMgr's string and octet tables,
226// and a C++ sketch that includes this header for its types and sizes has no use for them.
227#ifndef __cplusplus
228/** @brief Append a string: uint32 length, then @p n bytes of @p data. */
229EMBED_INLINE void protocore_ssh_wr_str(mmgr_span *w, const void *data, size_t n)
230{
231 EMBED_CALL(byteio.put_be, OctetusCfg, .write_span = w, .value = (uint64_t)n, .bytes = 4);
232 EMBED_CALL(byteio.raw, OctetusCfg, .write_span = w, .src = data, .bytes = n);
233}
234
235/**
236 * @brief Append a NUL-terminated @p s as a string, its length taken up to the span's capacity.
237 *
238 * A comma-separated name-list (RFC 4253 sec 7.1) is one of these.
239 */
240EMBED_INLINE void protocore_ssh_wr_cstr(mmgr_span *w, const char *s)
241{
242 protocore_ssh_wr_str(w, s, EMBED_CALL(cellul.len, CatenaFinitaCfg, .src = s, .cap = w->cap));
243}
244
245/**
246 * @brief Append @p len big-endian bytes as an mpint: leading zero bytes stripped, a 0x00 prepended
247 * when the top bit is set, and a zero value written as the empty string.
248 */
249EMBED_INLINE void protocore_ssh_wr_mpint(mmgr_span *w, const uint8_t *be, size_t len)
250{
251 size_t off = 0;
252 while (off < len && be[off] == 0)
253 {
254 off++;
255 }
256 if (off == len)
257 {
258 EMBED_CALL(byteio.put_be, OctetusCfg, .write_span = w, .value = 0, .bytes = 4);
259 return;
260 }
261 embed_bool pad = (be[off] & 0x80u) != 0;
262 uint64_t mlen = (uint64_t)(len - off);
263 if (pad)
264 {
265 mlen++;
266 }
267 EMBED_CALL(byteio.put_be, OctetusCfg, .write_span = w, .value = mlen, .bytes = 4);
268 if (pad)
269 {
270 EMBED_CALL(byteio.put, OctetusCfg, .write_span = w, .byte = 0x00);
271 }
272 EMBED_CALL(byteio.raw, OctetusCfg, .write_span = w, .src = be + off, .bytes = len - off);
273}
274#endif
275
276// ---------------------------------------------------------------------------
277// Sequence number overflow threshold
278// ---------------------------------------------------------------------------
279
280/**
281 * @brief Close the connection when seq_no reaches this value.
282 *
283 * Set to 0xFFFFFFF0 (16 below the 32-bit wrap) as a conservative margin.
284 * This prevents CTR keystream reuse that would occur at wrap. The counter is
285 * never reset; a re-key at SSH_REKEY_PACKET_THRESHOLD keeps it far from here.
286 */
287#define SSH_SEQ_CLOSE_THRESHOLD 0xFFFFFFF0u
288
289// ---------------------------------------------------------------------------
290// Wire buffer sizing
291// ---------------------------------------------------------------------------
292
293// Worst-case on-wire bytes for a payload of up to SSH_PKT_BUF_SIZE: the 4-byte packet_length, the
294// 1-byte padding_length, the effective payload, worst-case padding, and the largest MAC tag. When
295// s2c compression is built in, the "effective payload" is the compressor's worst-case output
296// (ssh_deflate_bound of a full payload) since fixed-Huffman can slightly expand incompressible data.
297// Callers MUST size the wire buffer with this so a compressed packet never overflows and desyncs the
298// stateful cipher / compression stream (a dropped packet mid-stream would corrupt the session).
299#if PROTOCORE_ENABLE_SSH_ZLIB
300#define SSH_MAX_EFFECTIVE_PAYLOAD (2 + SSH_RFC_MAX_PAYLOAD + (SSH_RFC_MAX_PAYLOAD >> 3) + 32) // = ssh_deflate_bound()
301#else
302#define SSH_MAX_EFFECTIVE_PAYLOAD (SSH_RFC_MAX_PAYLOAD)
303#endif
304#define SSH_MAX_PAD 32 // worst-case padding across block-8 / block-16 modes (min-4 rule)
305#define SSH_MAX_MAC 64 // largest MAC tag (hmac-sha2-512); chacha's Poly1305 tag is 16
306#define SSH_PKT_WIRE_MAX ((size_t)(4 + 1 + SSH_MAX_EFFECTIVE_PAYLOAD + SSH_MAX_PAD + SSH_MAX_MAC))
307
308/**
309 * @brief Uncompressed payload RFC 4253 sec 6.1 requires an implementation to process.
310 *
311 * "All implementations MUST be able to process packets with an uncompressed payload length of
312 * 32768 bytes or less". This tree sizes its own spans on this rather than on SSH_PKT_BUF_SIZE,
313 * which the pre-move tree still shares.
314 */
315#define SSH_RFC_MAX_PAYLOAD 32768u
316
317/** @brief Largest total packet RFC 4253 sec 6.1 requires an implementation to process. */
318#define SSH_RFC_MAX_PACKET 35000u
319
320// Two framed packets. ssh_pkt_emit() appends at tx_len when a packet is framed and not yet drained,
321// so a pair (KEXDH_REPLY then NEWKEYS at the kex boundary) leaves on one drain instead of the second
322// being refused. The payload is written at SSH_WIRE_PAYLOAD_OFF and framed in place by
323// ssh_pkt_send_at(), so each packet costs its own bytes and no copy of them.
324#define SSH_WIRE_CAP ((size_t)131072u)
325static_assert(SSH_WIRE_CAP >= 2u * SSH_PKT_WIRE_MAX, "the wire span must frame two of this end's largest packets");
326static_assert(SSH_WIRE_CAP >= 2u * SSH_RFC_MAX_PACKET,
327 "the wire span must hold two of the 35000-byte packets RFC 4253 sec 6.1 requires processing");
328static_assert((SSH_WIRE_CAP & (SSH_WIRE_CAP - 1u)) == 0u, "SSH_WIRE_CAP must stay a power of two");
329
330// Scratch the transport layer (RFC 4253) borrows to frame one packet, and nothing more - the wire
331// buffer and the payload being framed belong to whoever called in, because this layer is the framer,
332// not the wire. The receive side is the peak: a plaintext scratch (largest across the cipher modes)
333// is live while the payload is decompressed into a second buffer. The send side borrows only the
334// compressor's output bound. RFC 4251 sec 1 stacks auth and connection on top of this, so the arena
335// sums the layers; it does not fold them into each other.
336#if PROTOCORE_ENABLE_SSH_ZLIB
337#define PROTOCORE_PLAINTEXT_WORK_SSH_TRANSPORT ((size_t)(SSH_PKT_BUF_SIZE + 64 + SSH_PKT_BUF_SIZE))
338#else
339#define PROTOCORE_PLAINTEXT_WORK_SSH_TRANSPORT ((size_t)(SSH_PKT_BUF_SIZE + 64))
340#endif
341
342// The secure-pool term the connection declares against PROTOCORE_SECURE_ARENA_SIZE, proved against what
343// is actually borrowed. The wire is not borrowed: it is the slot's own span at SSH_OFF_WIRE, framed in
344// place by ssh_pkt_send_at(). What remains on the pool is a payload-sized transient.
345static_assert(PROTOCORE_WORK_SSH_CONN >= (size_t)SSH_PKT_BUF_SIZE,
346 "PROTOCORE_WORK_SSH_CONN must cover one transient payload: raise it in protocore_config.h");
347
348// PROTOCORE_SSH_SLOT_BYTES is sized in protocore_config.h, which cannot see the offset chain above.
349// This is the translation unit that includes both, so it is where the number is checked against the
350// span it has to cover.
352 "PROTOCORE_SSH_SLOT_BYTES must cover one connection's whole span: raise it in protocore_config.h, "
353 "which sums it into the secure arena");
354
355// PROTOCORE_SSH_CPUB_MAX is sized in protocore_config.h, which cannot see the PQC key sizes. This is the
356// translation unit that includes both, so it is where the two spellings are checked against it.
357#if PROTOCORE_ENABLE_PQC_KEX
358static_assert(PROTOCORE_SSH_CPUB_MAX >= MLKEM768_EK_BYTES + 32u,
359 "PROTOCORE_SSH_CPUB_MAX must cover an ML-KEM-768 C_INIT: raise it in protocore_config.h");
360#endif
361#if PROTOCORE_ENABLE_SSH_SNTRUP761
363 "PROTOCORE_SSH_CPUB_MAX must cover an sntrup761 C_INIT: raise it in protocore_config.h");
364#endif
365
366// The library's own caller is the connection: every KDF here runs out of slot i's crypto_work.
368 "a slot's crypto_work must cover the RFC 4253 sec 7.2 KDF: raise PROTOCORE_CRYPTO_BORROW_MAX");
369
370/**
371 * @brief Where a payload sits inside a wire buffer: past packet_length and padding_length.
372 *
373 * Every cipher mode lays those two fields down ahead of the payload and encrypts from there, so a
374 * caller that writes its message at this offset hands ssh_pkt_send_at() a packet the framer never
375 * has to move. A pipe (forwarding, a channel data pump) reads its source straight into that slot and
376 * the bytes are copied once, into the packet they leave in.
377 */
378#define SSH_WIRE_PAYLOAD_OFF 5
379
380// ---------------------------------------------------------------------------
381// RFC 4251 sec 5 - bounded reader over a payload
382// ---------------------------------------------------------------------------
383
384// Reader over a payload with bounds checking.
385typedef struct
386{
387 const uint8_t *buf;
388 size_t len;
389 size_t off;
390 embed_bool ok;
391} Rd;
392#ifndef __cplusplus
393EMBED_INLINE uint8_t protocore_ssh_rd_u8(Rd *r)
394{
395 if (r->off + 1 > r->len)
396 {
397 r->ok = EMBED_FALSE;
398 return 0;
399 }
400 return r->buf[r->off++];
401}
402EMBED_INLINE uint32_t protocore_ssh_rd_u32(Rd *r)
403{
404 mmgr_cspan c = {.buf = r->buf, .len = r->len, .pos = r->off, .err = EMBED_FALSE};
405 uint64_t v = 0;
406 if (!EMBED_CALL(byteio.take_be, OctetusCfg, .read_span = &c, .out = &v, .bytes = 4))
407 {
408 r->ok = EMBED_FALSE;
409 return 0;
410 }
411 r->off = c.pos;
412 return (uint32_t)v;
413}
414// Returns a pointer to an in-place string of length *n; advances past it. Fails closed on overflow.
415EMBED_INLINE const uint8_t *protocore_ssh_rd_string(Rd *r, uint32_t *n)
416{
417 mmgr_cspan c = {.buf = r->buf, .len = r->len, .pos = r->off, .err = EMBED_FALSE};
418 const uint8_t *p = NULL;
419 size_t got = 0;
420 if (!EMBED_CALL(byteio.rd_str, OctetusCfg, .read_span = &c, .blob = &p, .blob_bytes = &got))
421 {
422 r->ok = EMBED_FALSE;
423 *n = 0;
424 return NULL;
425 }
426 r->off = c.pos;
427 *n = (uint32_t)got; // the length was read as four bytes, so it fits
428 return p;
429}
430
431// ---------------------------------------------------------------------------
432// Wire helpers
433// ---------------------------------------------------------------------------
434
435// Read a uint32 at *off; advances *off. Fails closed with *off and *out as they were.
436EMBED_INLINE embed_bool protocore_ssh_read_u32_at(const uint8_t *p, size_t len, size_t *off, uint32_t *out)
437{
438 mmgr_cspan c = {.buf = p, .len = len, .pos = *off, .err = EMBED_FALSE};
439 uint64_t v = 0;
440 if (!EMBED_CALL(byteio.take_be, OctetusCfg, .read_span = &c, .out = &v, .bytes = 4))
441 {
442 return EMBED_FALSE;
443 }
444 *off = c.pos;
445 *out = (uint32_t)v;
446 return EMBED_TRUE;
447}
448
449// Point *out at the SSH string at *off and store its length; advances *off. Fails closed with *off,
450// *out and *slen as they were.
451EMBED_INLINE embed_bool protocore_ssh_read_string_at(const uint8_t *p, size_t len, size_t *off, const uint8_t **out,
452 uint32_t *slen)
453{
454 mmgr_cspan c = {.buf = p, .len = len, .pos = *off, .err = EMBED_FALSE};
455 const uint8_t *s = NULL;
456 size_t got = 0;
457 if (!EMBED_CALL(byteio.rd_str, OctetusCfg, .read_span = &c, .blob = &s, .blob_bytes = &got))
458 {
459 return EMBED_FALSE;
460 }
461 *off = c.pos;
462 *out = s;
463 *slen = (uint32_t)got; // the length was read as four bytes, so it fits
464 return EMBED_TRUE;
465}
466
467// Write the mpint m into out as a fixed-width big-endian field of outlen bytes. EMBED_FALSE where
468// its value does not fit.
469EMBED_INLINE embed_bool protocore_ssh_mpint_fixed(const uint8_t *m, uint32_t mlen, uint8_t *out, size_t outlen)
470{
471 mmgr_span w = {.buf = out, .cap = outlen, .pos = 0, .overflow = EMBED_FALSE};
472 return EMBED_CALL(byteio.mpint_fixed, OctetusCfg, .write_span = &w, .src = m, .bytes = mlen);
473}
474
475// Copy an SSH string into a fixed buffer and null-terminate it. Advances *off.
476// Returns false on truncation or if the string does not fit (buffer too small).
477//
478// Reading the field by reference is byteio.rd_str()'s job. This only adds the copy and the terminator,
479// which is what separates it from the by-reference reads below.
480static embed_bool read_string(const uint8_t *p, size_t len, size_t *off, char *out, size_t outcap)
481{
482 mmgr_cspan c = {.buf = p, .len = len, .pos = *off, .err = EMBED_FALSE};
483 const uint8_t *s = NULL;
484 size_t n = 0;
485 if (!EMBED_CALL(byteio.rd_str, OctetusCfg, .read_span = &c, .blob = &s, .blob_bytes = &n))
486 {
487 return EMBED_FALSE;
488 }
489 if (n >= outcap)
490 {
491 return EMBED_FALSE; // does not fit our fixed buffer; same contract as byteio.rd_str: *off stays on its own
492 // field
493 }
494 *off = c.pos;
495 EMBED_CALL(memor.cpy, MemoriaCfg, .dst = out, .src = s, .bytes = n);
496 out[n] = '\0';
497 return EMBED_TRUE;
498}
499#endif
500
501EMBED_END_DECLS
502
503#endif // PROTOCORE_SSH_COMMON_H
AES-256-CTR stream cipher (aes256-ctr, RFC 4344 ยง4).
2048-bit big-integer arithmetic for DH-group14 and RSA-2048.
#define PROTOCORE_CRYPTO_BORROW_MAX
#define PROTOCORE_SSH_KDF_BORROW
#define SSH_PKT_BUF_SIZE
Packet assembly buffer per SSH connection (bytes).
#define PROTOCORE_SSH_SLOT_BYTES
One connection's whole span: the wire, the session, the exchange, the packet and the rx regions end t...
chacha20-poly1305@openssh.com AEAD cipher (OpenSSH PROTOCOL.chacha20poly1305).
#define PROTOCORE_WORK_SSH_CONN
#define PROTOCORE_SSH_CPUB_MAX
Reverse-SSH tunnel: max concurrent forwarded-tcpip channels bridged at once. A relay that forwards to...
HMAC-SHA2-256 (RFC 2104 + FIPS 198-1) - streaming context and one-shot API.
#define MLKEM768_EK_BYTES
encapsulation key (public key): 384*k + 32
Definition mlkem.h:52
EMBED_INLINE void protocore_ssh_wr_mpint(mmgr_span *w, const uint8_t *be, size_t len)
Append len big-endian bytes as an mpint: leading zero bytes stripped, a 0x00 prepended when the top b...
Definition common.h:249
#define SSH_RFC_MAX_PACKET
Largest total packet RFC 4253 sec 6.1 requires an implementation to process.
Definition common.h:318
EMBED_INLINE uint8_t protocore_ssh_rd_u8(Rd *r)
Definition common.h:393
EMBED_INLINE const uint8_t * protocore_ssh_rd_string(Rd *r, uint32_t *n)
Definition common.h:415
EMBED_INLINE embed_bool protocore_ssh_mpint_fixed(const uint8_t *m, uint32_t mlen, uint8_t *out, size_t outlen)
Definition common.h:469
EMBED_INLINE embed_bool protocore_ssh_read_string_at(const uint8_t *p, size_t len, size_t *off, const uint8_t **out, uint32_t *slen)
Definition common.h:451
EMBED_INLINE uint32_t protocore_ssh_rd_u32(Rd *r)
Definition common.h:402
EMBED_INLINE void protocore_ssh_wr_cstr(mmgr_span *w, const char *s)
Append a NUL-terminated s as a string, its length taken up to the span's capacity.
Definition common.h:240
#define SSH_PKT_WIRE_MAX
Definition common.h:306
#define SSH_SLOT_BORROW
One connection's whole span, and the stride between slots.
Definition common.h:196
EMBED_INLINE embed_bool protocore_ssh_read_u32_at(const uint8_t *p, size_t len, size_t *off, uint32_t *out)
Definition common.h:436
EMBED_INLINE void protocore_ssh_wr_str(mmgr_span *w, const void *data, size_t n)
Append a string: uint32 length, then n bytes of data.
Definition common.h:229
#define SSH_WIRE_CAP
Definition common.h:324
EMBED_BEGIN_DECLS EMBED_ENUM_BYTE(SshMsgId, SSH_MSG_DISCONNECT=1, SSH_MSG_IGNORE=2, SSH_MSG_UNIMPLEMENTED=3, SSH_MSG_DEBUG=4, SSH_MSG_SERVICE_REQUEST=5, SSH_MSG_SERVICE_ACCEPT=6, SSH_MSG_EXT_INFO=7, SSH_MSG_KEXINIT=20, SSH_MSG_NEWKEYS=21, SSH_MSG_KEXDH_INIT=30, SSH_MSG_KEXDH_REPLY=31, SSH_MSG_USERAUTH_REQUEST=50, SSH_MSG_USERAUTH_FAILURE=51, SSH_MSG_USERAUTH_SUCCESS=52, SSH_MSG_USERAUTH_BANNER=53, SSH_MSG_USERAUTH_PK_OK=60, SSH_MSG_USERAUTH_INFO_REQUEST=60, SSH_MSG_USERAUTH_INFO_RESPONSE=61, SSH_MSG_GLOBAL_REQUEST=80, SSH_MSG_REQUEST_SUCCESS=81, SSH_MSG_REQUEST_FAILURE=82, SSH_MSG_CHANNEL_OPEN=90, SSH_MSG_CHANNEL_OPEN_CONFIRMATION=91, SSH_MSG_CHANNEL_OPEN_FAILURE=92, SSH_MSG_CHANNEL_WINDOW_ADJUST=93, SSH_MSG_CHANNEL_DATA=94, SSH_MSG_CHANNEL_EXTENDED_DATA=95, SSH_MSG_CHANNEL_EOF=96, SSH_MSG_CHANNEL_CLOSE=97, SSH_MSG_CHANNEL_REQUEST=98, SSH_MSG_CHANNEL_SUCCESS=99, SSH_MSG_CHANNEL_FAILURE=100,)
Protocol opcodes, by the number each RFC assigns it (RFC 4250 sec 4.1.2).
Streamlined NTRU Prime sntrup761 KEM - keygen, encapsulation, decapsulation.
#define PROTOCORE_SNTRUP761_PK_BYTES
public key (Rq-encoded h)
Definition sntrup761.h:41
One key-exchange digest that dispatches SHA-256 or SHA-512 by the negotiated method.
Definition common.h:386
const uint8_t * buf
Definition common.h:387
size_t off
Definition common.h:389
size_t len
Definition common.h:388
embed_bool ok
Definition common.h:390