security & Noise — the Noise link and its crypto backend¶
In one paragraph
The Noise link binding (RFC-0033)
carries frames inside a Noise_NNpsk0_25519_ChaChaPoly_SHA256 session. This module is its
cryptographic half, the handshake and transport steps written once over a crypto backend
chosen at compile time (OpenSSL, libsodium or mbedTLS through PSA), and the link built on
them, noise_link_t, which carries one request and its reply in two round trips. The core stays
crypto-free. A build that does not name a backend compiles none of this and links no crypto
library. Everything works on caller memory: no allocation of its own, no clock and no
randomness. On every backend, nothing allocates before a first message’s PSK tag is proven,
and nothing allocates per frame.
What it does¶
security_noise.hpp holds the protocol, written once over a backend type B:
symmetric_state_t<B>is Noise’s SymmetricState (ck,hand the handshake cipher key), a plain value that copies.psk_statebuilds the state after the prologue and thepsktoken. That state is the same for every handshake on a link, so a link computes it once and starts each handshake from a copy (RFC-0033 §5.8).handshake_t<B>is one side of the handshake over RFC-0033’s datagrams:write_firstandread_secondfor the initiator,read_firstandwrite_secondfor the responder, thensplit.read_firstchecks the PSK tag with no Diffie-Hellman and no key generation. The caller checks the counter against its mark, and onlywrite_secondrunsee. So a message under a wrong PSK, or a replayed one, costs oneMixHash, one HKDF and one tag check, and no memory. The tag is checked with the link’s handshake cipher, a backend cipher the link builds once beside its PSK state and passes to eachhandshake_t, which re-keys it per message. An all-zero X25519 result is refused (LOW_ORDER) whatever the backend does.transport_cipher_t<B>holds a session’s two transport keys, keyed into the backend once atsplit.sealwrites the type byte, the nonce, the ciphertext and the tag, in place when the frame already sits at its payload offset.parse_transport_headerreads the type and the nonce before any decryption, which is where the replay pre-check goes, andopenthen decrypts in place. Nonces at or above 2^62 are refused on both sides. A cipher takes one call at a time: the link serialises each direction’s senders, or keeps one session cipher per sending thread.
Every refusal is a refusal_t, which the link maps onto RFC-0033 §5.9’s counters.
The link¶
transport_noise.hpp is the link half, built on these types: noise_link_t<B, Host, Carrier>
is an ordinary transport_t to the router, and the frames it carries are byte-identical to the
ones its carrier would carry without it (reference/23 §1). It owns its carrier, a
udp_transport_t on a host, and takes three compile-time choices:
parameter |
what |
|
|---|---|---|
|
the crypto backend |
|
|
the application’s seams ( |
|
|
the datagram link underneath ( |
|
The PSK is named by reference (noise_config_t::psk_ref) and resolved once, when the link is
built. The library holds no key, no entropy and no clock.
One request and its reply. DIAL initiates and LISTEN answers. A send on a link with no
session fails at once, counted in dropped_tx, and on DIAL it starts a handshake (dial()
demands without a frame). Once the second message arrives, link_up() reports it: the
request sent then is the confirmation, the responder’s reply is the acknowledgement, and the
link reports UP after it. Four datagrams, two round trips:
link.dial(); // or the first send, which fails and dials
while (!link.link_up()) {
const std::uint64_t now = app_now(); // the app's clock
const std::uint64_t due = link.sweep(now, 0); // 0: no deadline armed
wait_until(due != 0 ? due : now + window); // the app's wait, capped at one window
}
link.send(request); // the confirmation
// ... the reply arrives on the receiver: the acknowledgement; link.state() == UP
Time. sweep(now, deadline), the one seam every link takes the application’s clock
through (a node’s transport_vertex_t::sweep calls it on each connection’s link), runs every
deadline now has passed and returns the next one, 0 when none is armed. Noise ignores
deadline, since its windows are its own configured spans: the initiator’s retry (the stored first message, or an empty
confirmation while unacknowledged, the interval doubling to retry_cap) and attempt deadlines,
and the responder’s pending expiry. A deadline of 0 is never due, and deadlines count from the
last now the link was given, so an application sweeps once before its first demand. A
return of 0 means nothing is armed now: a demand, or a peer that starts owing bytes after the
call, can arm something sooner, so an application caps its sleep at about one deadline window
(or wakes on its own events) rather than sleeping forever.
Memory. Everything the link holds about its sessions (the PSK state, the handshake cipher,
the two session slots, the handshake slot and its stored messages) is one block from the
link’s memory.state, drawn when the link is built. On x86-64 it is 504 B with PSA Crypto,
520 B with OpenSSL 3 (where each cipher is a pointer to a library context the backend builds
with it) and 664 B with libsodium. A handshake fills slots that already
exist, so a first message under a wrong PSK, or a replayed one, costs no memory. A transport
message is decrypted in place in the carrier’s receive buffer, and a send seals into one block
of frame + 25 bytes from memory.io, returned after the send.
Counters. Reference/23 §11’s ten noise_* nouns follow the universal three in the link’s
:stats.link.<child> block (transport_t::kind_stats).
Rekey. A rekey is a new handshake that only the initiator starts: at rekey_after, at a send
nonce of 2^60, or on noise_link_t::rekey. The old session stays current until the new one is
acknowledged, so the link stays up, and it then keeps receiving as the previous session until
previous_expiry or the next handshake. The previous session and an unconfirmed one never exist
together, so they share one slot and the overlap costs no RAM. reject_after and the 2^62 nonce
limit discard a session and take the link down. A session boundary (a session discarded with no
replacement, or a session whose peer started fresh becoming current) fires the link-down notifier
before any frame of the new session is delivered; a routine rekey fires nothing. A session past
its limit takes the previous one with it, and so does a fresh peer’s session.
The counter and the mark across reboots. Both survive a reboot only through the application
(reference/23 §4). The initiator’s next_counter() is a wall clock or a monotonic counter that
survives reboots; a node with neither returns noise::boot_counter_t::next(), a persisted boot
counter (one write per boot) as the high half and an attempt counter in RAM as the low half. If the
boot counter’s write fails, the node makes no handshake attempt that boot. The responder’s mark
stays in RAM unless the host is a noise::mark_store, which is a compile-time choice: a host that
also has restore_mark(ref) and persist_mark(ref, mark) gets the mark restored when a LISTEN link
is built and persisted each time it changes. That is one write per accepted first message, made
after the PSK tag verified and before the answer, so a peer without the PSK causes none.
persist_mark answers whether the write succeeded, and a write that fails refuses the message:
counted in noise_handshake_failed and answered by nothing. A host without the two seams pays
nothing. Such a link keeps its psk_ref, so the string must outlive it.
the application wants to |
it calls |
the mark |
|---|---|---|
admit a replacement initiator whose counter restarted |
|
0, persisted; recorded first messages pass the counter check once more each |
replace the PSK |
|
0, persisted under the new name; first messages under the old PSK fail the PSK check |
With the mark in RAM only, a responder reboot lets each recorded first message through at most once,
in increasing counter order; with it persisted, none. Sessions, and a handshake in flight, keep the
keys they began with across replace_psk.
On ESP-IDF, CONFIG_LIBTRACER_NOISE_CRYPTO_PSA turns the module on, and the
noise_link example carries one request and its reply over two
links on an ESP32-C6, with what each link costs.
Choosing a backend¶
One CMake cache variable, LIBTRACER_NOISE_CRYPTO, picks the backend. Any value but none
makes the header-only target libtracer_noise, which carries the library and a
LIBTRACER_NOISE_CRYPTO_<BACKEND> define. security_noise.hpp turns that define into the
alias tr::net::noise::default_crypto_t. There is no runtime switch.
value |
backend |
library |
notes |
|---|---|---|---|
|
— |
— |
the module is not compiled |
|
|
libcrypto 3 |
the fastest AEAD on a host at 1 KiB and above; needs the deprecated |
|
|
libsodium |
no allocation at all, handshake included |
|
|
mbedTLS 3.6.1+ or 4.x through PSA |
the ESP-IDF backend; needs a sized static key-slot table (below) |
A backend is a type that meets the crypto_backend concept (security_noise_crypto.hpp):
SHA-256, Noise’s HKDF, an X25519 key pair and a ChaCha20-Poly1305 cipher. hash, hkdf and
the cipher’s set_key, seal and open must not allocate; building a cipher and the X25519
calls may. A test can wrap a backend in another compile-time policy, as security_noise_test
does to count the X25519 calls a refused first message makes (none).
The PSA backend needs three things from the mbedTLS build:
MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS, or every PSA call copies its buffers through the heap. ESP-IDF’s port sets it.MBEDTLS_PSA_STATIC_KEY_SLOTSwithoutMBEDTLS_PSA_KEY_STORE_DYNAMIC(mbedTLS 3.6.1 and later), or every key import allocates, a first message’s handshake key included.security_noise_psa.hpprefuses to build without it.A slot table sized by the app, because every PSA user in the image shares it. The rule:
setting
at least
MBEDTLS_PSA_KEY_SLOT_COUNT6 per Noise link (two sessions of two keys during a rekey, the handshake cipher, the ephemeral key), plus the peak of the image’s other PSA users
MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZEthe largest key any of them imports; Noise’s keys are all 32 B
A Noise-only image needs 8 slots of 32 B: 360 B of
.bsson an ESP32-C6. The CI psa leg tests 14 slots, the fewest the suites pass with: its process holds both ends of a session, each at 6 during a rekey, and extra peers. Rough figures for a mixed image at 16 slots: about 2 KB with TLS that verifies only ECDSA P-256 or X25519 peers, about 5 KB with RSA-2048 server certificates, about 20 KB if the image holds its own RSA-2048 private key. Left unsized, mbedTLS sizes 32 slots for the largest key type enabled: 76,616 B at ESP-IDF’s defaults, which enable RSA-4096 key pairs. That figure is the unsized default, not the cost of Noise. A table that is too small fails at run time, when an import is refused, not at build. ESP-IDF has no option for any of this: the Kconfig help ofCONFIG_LIBTRACER_NOISE_CRYPTO_PSAshows the header an app passes asMBEDTLS_USER_CONFIG_FILE.A NARROW image that needs PSA for nothing else should use libsodium (ESP-IDF’s component registry has a port). It allocates nothing, has no global table, and needs no mbedTLS change. The backend is a compile-time choice, so the swap is one define.
On ESP-IDF,
CONFIG_MBEDTLS_CHACHA20_CandCONFIG_MBEDTLS_CHACHAPOLY_C, which are off by default. The Kconfig option selects them.
What it costs¶
Allocation calls, counted process-wide (malloc and its family) by security_noise_test
on the host (GCC 13, glibc). The library’s own allocations are included. The zero rows are
asserted.
openssl (3.0.13) |
sodium (1.0.18) |
psa (mbedTLS 4.1.1) |
psa (mbedTLS 3.6.5) |
|
|---|---|---|---|---|
per link: PSK state and handshake cipher |
3 |
0 |
0 |
0 |
per session: the two transport ciphers |
6 |
0 |
0 |
0 |
handshake, initiator |
34 |
0 |
6200 |
6244 |
handshake, responder |
34 |
0 |
6200 |
6244 |
a first message read, refused (wrong PSK) or accepted (a replay) |
0 |
0 |
0 |
0 |
per frame (seal + open), 0 B to 65519 B |
0 |
0 |
0 |
0 |
The handshake rows are the X25519 calls: EVP_PKEY objects on OpenSSL, and mbedTLS’s bignum
arithmetic on PSA, paid once per session and only after the PSK is proven. The #2065
harness measures the time of each step on each backend.
Conformance¶
conformance_runner replays every tests/conformance/vectors/v1/noise/<case>/transcript.json
on the build’s backend and compares each recorded value: the symmetric state after every
token, both handshake messages, the handshake hash, the transport keys and the transport
datagrams. The first case is RFC-0033 Appendix A. Two third-party Noise implementations
reproduce it too, as the RFC’s §15 Q6 ruling requires: noiseprotocol (Python) and snow
(Rust, over its own primitives). Their scripts and results sit next to the transcript.
API reference¶
-
template<class B>
concept crypto_backend¶ - #include <
security_noise_crypto.hpp>The compile-time contract of a Noise crypto backend, as this file’s comment states it.
-
template<crypto_backend B>
class symmetric_state_t¶ Noise’s SymmetricState (Noise §5.2): the chaining key, the handshake hash and the handshake cipher key with its nonce.
The cipher key is held as bytes, and each
EncryptAndHash/DecryptAndHashkeys the caller’s backend cipher for its one message, so the state is a plain value: it copies, and a copy of the state after the PSK starts each handshake. Its destructor wipes it.- Template Parameters:
B – The crypto backend.
Public Functions
-
symmetric_state_t(const symmetric_state_t&) = default¶
Copy the state (the handshake start).
-
symmetric_state_t &operator=(const symmetric_state_t&) = default¶
Copy-assign the state.
-
inline bool initialize(std::span<const std::byte> protocol_name)¶
Noise
InitializeSymmetric(protocol_name)for a name longer thanHASHLEN.- Returns:
False if the name is not longer than 32 bytes or the hash failed.
-
inline bool mix_hash(std::span<const std::byte> data)¶
h = HASH(h || data), fordataup to kMaxMixHash bytes.
-
inline bool mix_key(std::span<const std::byte> ikm)¶
ck, k = HKDF(ck, ikm, 2), thenInitializeKey(k).
-
inline bool mix_key_and_hash(std::span<const std::byte> ikm)¶
ck, temp_h, k = HKDF(ck, ikm, 3),MixHash(temp_h),InitializeKey(k).
-
inline bool encrypt_and_hash(typename B::aead_t &aead, std::span<const std::byte> pt, std::byte *out)¶
Noise
EncryptAndHash: sealptwithhas associated data intoout(pt.size() + kTagLenbytes), then mix the ciphertext intoh.NNpsk0’s first token is
psk, so a key is always set before any payload: the unkeyed pass-through Noise defines for other patterns is refused here instead of carried.- Parameters:
aead – The cipher to seal with, keyed here with
kand cleared again after use.
-
inline bool decrypt_and_hash(typename B::aead_t &aead, std::span<const std::byte> ct, std::byte *out)¶
Noise
DecryptAndHash: openctwithhas associated data intoout(ct.size() - kTagLenbytes), then mix the ciphertext intoh.- Parameters:
aead – The cipher to open with, keyed here with
kand cleared again after use.- Returns:
False on a bad tag, or with no key set;
hand the nonce are then unchanged.
-
inline bool split(key32_t &k1, key32_t &k2) const¶
Noise
Split():k1encrypts initiator to responder,k2the reverse.
-
inline const key32_t &chaining_key() const noexcept¶
The chaining key
ck.
-
inline const key32_t &handshake_hash() const noexcept¶
The handshake hash
h; after the last message, the channel binding.
-
inline const key32_t &cipher_key() const noexcept¶
The handshake cipher key
k, meaningful only while has_key holds.
-
inline bool has_key() const noexcept¶
Whether a cipher key is set (Noise
HasKey).
-
template<crypto_backend B>
bool tr::net::noise::psk_state(const key32_t &psk, symmetric_state_t<B> &out)¶ The symmetric state every handshake on a link starts from:
InitializeSymmetric,MixHash(prologue)and thepsktoken’sMixKeyAndHash(psk)(RFC-0033 §5.8).The link computes it once when it is built, and again only when its PSK is replaced.
-
template<crypto_backend B>
class handshake_t¶ One side’s NNpsk0 HandshakeState over RFC-0033’s datagrams.
The initiator calls write_first, then read_second; the responder calls read_first, then write_second. Either then calls split. A refused step leaves the state where it was, so a link can read a datagram into a scratch copy and keep its handshake slot untouched when it is refused.
Each handshake message is sealed or opened with the link’s handshake cipher, passed in and keyed for each message and cleared after it, so it holds no key between messages (RFC-0033 §6.8). The link builds it once, beside its PSK state, so a first message allocates nothing. Handshakes may share it while their calls do not overlap.
- Template Parameters:
B – The crypto backend.
Public Functions
-
inline handshake_t(role_t role, const symmetric_state_t<B> &keyed, typename B::aead_t &cipher)¶
Start a handshake from the link’s PSK state (psk_state).
- Parameters:
role – This side.
keyed – The state after the prologue and the PSK; copied.
cipher – The link’s handshake cipher; it must outlive this handshake.
-
inline std::expected<void, refusal_t> write_first(const key32_t &e_priv, first_payload_t payload, std::span<std::byte, kFirstMessageBytes> out)¶
Initiator: write
-> psk, ewithpayloadinto the 58-byteout.- Parameters:
e_priv – The ephemeral private key, from the application’s random source: fresh for each handshake, never reused, and wiped by the caller after this call (RFC-0033 §6.8).
-
inline std::expected<first_payload_t, refusal_t> read_first(std::span<const std::byte> datagram)¶
Responder: check and read a first message, with no Diffie-Hellman.
- Return values:
MALFORMED – Not 58 bytes, or not type 0x01.
AUTH – The PSK tag did not verify.
PAYLOAD – Flag bits 7-1 are set.
- Returns:
The authentic payload; the caller checks its counter before answering.
-
inline std::expected<void, refusal_t> write_second(const key32_t &e_priv, std::uint8_t flags, std::span<std::byte, kSecondMessageBytes> out)¶
Responder: write
<- e, eewith theflagsbyte into the 50-byteout.- Parameters:
e_priv – The ephemeral private key, from the application’s random source: fresh for each handshake, never reused, and wiped by the caller after this call (RFC-0033 §6.8).
- Return values:
LOW_ORDER –
DH(e, re)is all zero; nothing is written.
-
inline std::expected<std::uint8_t, refusal_t> read_second(std::span<const std::byte> datagram)¶
Initiator: check and read a second message.
- Return values:
MALFORMED – Not 50 bytes, or not type 0x02.
LOW_ORDER –
DH(e, re)is all zero.AUTH – The tag did not verify.
PAYLOAD – Flag bits 7-2 are set.
- Returns:
The authentic flags byte (bit 0 the key phase, bit 1
fresh).
-
inline std::expected<void, refusal_t> split(transport_cipher_t<B> &out) const¶
After the last message: key
outfor this side’s two directions.
-
inline const symmetric_state_t<B> &symmetric_state() const noexcept¶
The symmetric state so far; after the last message,
his the handshake hash.
-
template<crypto_backend B>
class transport_cipher_t¶ The two transport keys of one session, keyed into the backend once at
Split(): seal toward the peer, open from it (Noise §11.4, explicit nonces).Nonce choice, the replay window and the key phase are the link’s (RFC-0033 §5.5, §5.6); this type applies a given nonce and phase.
sealandopenallocate nothing, and take one call at a time per direction: a link serialises its senders, or keeps one session cipher per sending thread (the backend contract).- Template Parameters:
B – The crypto backend.
Public Functions
-
inline bool set_keys(const key32_t &send, const key32_t &recv)¶
Key both directions (what
Split()feeds).
-
inline void clear()¶
Drop both keys (wiped, or the library’s key slots freed), so a discarded session holds no key material (RFC-0033 §6.8); set_keys keys it again.
-
inline std::expected<std::size_t, refusal_t> seal(std::uint8_t phase, std::uint64_t n, std::span<const std::byte> frame, std::span<std::byte> out)¶
Write one transport datagram: the type byte for
phase, noncen, thenframesealed with empty associated data, and its tag.framemay already sit atout.data() + kTransportHeaderBytes, which seals in place; any other overlap withoutis undefined.- Return values:
MALFORMED –
phaseis not 0 or 1, the frame is above kMaxFrameBytes, oroutis too small.NONCE_BOUND –
nis at or above 2^62.
- Returns:
The datagram size,
frame.size() + kTransportOverhead.
-
inline std::expected<std::span<std::byte>, refusal_t> open(const transport_header_t &h, std::span<std::byte> datagram)¶
Check the tag of
datagramand decrypt it in place.- Parameters:
h – The header parse_transport_header read from
datagram.- Return values:
AUTH – The tag did not verify (the bytes are then unspecified).
- Returns:
The plaintext, inside
datagramat offset kTransportHeaderBytes; empty for a confirmation or an acknowledgement.
-
inline std::expected<transport_header_t, refusal_t> tr::net::noise::parse_transport_header(std::span<const std::byte> datagram) noexcept¶
Read a transport datagram’s type and nonce, with no decryption: the steps that come before the replay pre-check (RFC-0033 §5.5 steps 1 and 2).
- Return values:
MALFORMED – Fewer than 25 bytes, or a type byte other than 0x04 / 0x05.
NONCE_BOUND – The nonce is at or above 2^62.
-
enum class tr::net::noise::refusal_t : std::uint8_t¶
Why a step refused, mapped by the link onto RFC-0033 §5.9’s counters.
MALFORMEDandNONCE_BOUNDaremalformed_rx.AUTH,PAYLOADandLOW_ORDERon a handshake message arenoise_handshake_failed;AUTHon a transport message isnoise_decrypt_failed.STATEis a caller error, andBACKENDa library failure.Values:
-
enumerator MALFORMED¶
Wrong size or reserved type byte; nothing was decrypted.
-
enumerator AUTH¶
The tag did not verify.
-
enumerator PAYLOAD¶
An authentic handshake payload with reserved flag bits set.
-
enumerator LOW_ORDER¶
The peer’s ephemeral key gave an all-zero X25519 result.
-
enumerator NONCE_BOUND¶
A transport nonce at or above 2^62.
-
enumerator STATE¶
The step was called out of order for this role.
-
enumerator BACKEND¶
The crypto library failed.
-
enumerator MALFORMED¶
-
enum class tr::net::noise::msg_type_t : std::uint8_t¶
The datagram type byte (RFC-0033 §5.3); every other value is reserved.
Values:
-
enumerator FIRST¶
Handshake, first message (
-> psk, e).
-
enumerator SECOND¶
Handshake, second message (
<- e, ee).
-
enumerator TRANSPORT_PHASE_0¶
Transport message, key phase 0.
-
enumerator TRANSPORT_PHASE_1¶
Transport message, key phase 1.
-
enumerator FIRST¶
-
constexpr std::size_t tr::net::noise::kFirstMessageBytes = 1 + kDhLen + 9 + kTagLen¶
A first handshake message’s datagram: type,
e.pub, payload (9) and tag.
-
constexpr std::size_t tr::net::noise::kSecondMessageBytes = 1 + kDhLen + 1 + kTagLen¶
A second handshake message’s datagram: type,
e.pub, payload (1) and tag.
-
constexpr std::size_t tr::net::noise::kTransportHeaderBytes = 1 + 8¶
A transport datagram’s clear header: the type byte and the u64 nonce.
-
constexpr std::size_t tr::net::noise::kTransportOverhead = kTransportHeaderBytes + kTagLen¶
What a transport datagram adds to its frame: the header and the tag.
-
constexpr std::size_t tr::net::noise::kMaxFrameBytes = 65535 - kTagLen¶
The largest frame one Noise message carries: 65535 minus the tag (§5.3).
-
constexpr std::uint64_t tr::net::noise::kNonceLimit = std::uint64_t{1} << 62¶
No transport nonce at or above this is sent or decrypted (§5.5).
-
struct first_payload_t¶
The first message’s 9-byte payload (RFC-0033 §5.2).
-
struct transport_header_t¶
A transport datagram’s clear header, read before any decryption (§5.5).
Public Members
-
std::uint8_t phase = 0¶
The key phase, 0 or 1 (from the type byte).
-
std::uint64_t nonce = 0¶
The nonce, below kNonceLimit.
-
std::uint8_t phase = 0¶
-
struct openssl_crypto_t¶
libcrypto (OpenSSL 3):
EVP_CIPHER_CTXper cipher,EVP_PKEYfor X25519.Public Static Functions
-
static inline bool init()¶
Nothing to set up in OpenSSL 3.
-
static inline bool hash(std::span<const std::byte> in, key32_t &out)¶
SHA-256 of
in, on a stackSHA256_CTX(no allocation).
Public Static Attributes
-
static constexpr const char *kName = "openssl"¶
The backend’s name in reports.
-
struct aead_t¶
A ChaCha20-Poly1305 cipher: one
EVP_CIPHER_CTX, allocated when it is built.Public Functions
-
inline bool set_key(const key32_t &k)¶
Key the context in place, replacing any previous key (no allocation).
-
inline void clear()¶
Overwrite the key in the context with zeros (no allocation).
-
inline bool seal(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> pt, std::byte *out)¶
Seal
ptunder noncen;outtakespt.size() + kTagLenbytes.
-
inline bool open(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> ct, std::byte *out)¶
Open
ctunder noncenintoout; false on a bad tag.
-
inline bool set_key(const key32_t &k)¶
-
struct dh_key_t¶
An X25519 key pair held as an
EVP_PKEY.
-
static inline bool init()¶
-
struct sodium_crypto_t¶
libsodium: stateless calls, keys held in the backend’s own objects.
Public Static Functions
-
static inline bool init()¶
sodium_init; idempotent, false only if the library cannot run here.
-
static inline bool hash(std::span<const std::byte> in, key32_t &out)¶
SHA-256 of
in.
Public Static Attributes
-
static constexpr const char *kName = "sodium"¶
The backend’s name in reports.
-
struct aead_t¶
A ChaCha20-Poly1305 (IETF) cipher: its key.
Public Functions
-
inline bool set_key(const key32_t &k)¶
Store the key.
-
inline void clear()¶
Wipe the key.
-
inline bool seal(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> pt, std::byte *out)¶
Seal
ptunder noncen;outtakespt.size() + kTagLenbytes.
-
inline bool open(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> ct, std::byte *out)¶
Open
ctunder noncenintoout; false on a bad tag.
-
inline bool set_key(const key32_t &k)¶
-
struct dh_key_t¶
An X25519 key pair: the private scalar.
-
static inline bool init()¶
-
struct psa_crypto_t¶
mbedTLS through the PSA Crypto API: keys in volatile key slots.
Public Static Functions
-
static inline bool init()¶
psa_crypto_init; idempotent.
-
static inline bool hash(std::span<const std::byte> in, key32_t &out)¶
SHA-256 of
in.
-
static inline bool hkdf(const key32_t &ck, std::span<const std::byte> ikm, std::span<std::byte> out)¶
Noise HKDF as
PSA_ALG_HKDF(PSA_ALG_SHA_256)withsalt = ck, emptyinfo.
Public Static Attributes
-
static constexpr const char *kName = "psa"¶
The backend’s name in reports.
-
struct aead_t¶
A ChaCha20-Poly1305 cipher: its key, imported once into a volatile slot.
Public Functions
-
inline bool set_key(const key32_t &k)¶
Import
k, replacing any previous key.
-
inline void clear()¶
Destroy the key, which wipes it and frees its slot.
-
inline bool seal(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> pt, std::byte *out)¶
Seal
ptunder noncen;outtakespt.size() + kTagLenbytes.
-
inline bool open(std::uint64_t n, std::span<const std::byte> ad, std::span<const std::byte> ct, std::byte *out)¶
Open
ctunder noncenintoout; false on a bad tag.
-
inline bool set_key(const key32_t &k)¶
-
struct dh_key_t¶
An X25519 key pair in a volatile key slot.
-
static inline bool init()¶
-
template<noise::crypto_backend B, noise::link_host Host, noise::datagram_carrier Carrier>
class noise_link_t : public tr::net::transport_t¶ A Noise link (RFC-0033, reference/23) over a datagram carrier it owns.
DIAL is the initiator and LISTEN the responder; they never swap. See the file comment for the request/reply flow, the memory and what this slice leaves out.
Note
Thread-safety: the carrier’s receive thread, senders and
sweepmay run concurrently. One lock guards the session state. A frame is delivered with the lock released, so a receiver may send (an echo, a reply) from inside its callback.- Template Parameters:
B – The crypto backend.
Host – The application’s key store, random source and counter (tr::net::noise::link_host).
Carrier – The datagram link underneath (tr::net::noise::datagram_carrier).
Public Functions
-
template<class ...A>
inline noise_link_t(conn_role_t role, Host &host, const noise_config_t &config, A&&... carrier_args)¶ Build the link: draw its state from
config.memory.state, resolve its PSK and compute the PSK state, then build the carrier fromcarrier_args.Any failure leaves the link inert (ok false): a carrier that did not come up or whose datagram bound is below a first message’s 58 bytes (§3), an exhausted state store, an unknown PSK reference, or a backend that cannot start.
- Parameters:
role – DIAL initiates, LISTEN answers.
host – Must outlive the link.
-
inline ~noise_link_t()¶
Stop the carrier (joining its receive thread) before the state goes.
-
inline bool ok() const noexcept¶
True when the link came up: its state, its PSK and its carrier.
-
inline Carrier &carrier() noexcept¶
The carrier, for its own accessors (a UDP carrier’s
local_port).
-
inline std::size_t max_frame() const noexcept¶
The largest frame a send accepts; a larger one is refused (
noise_oversize).
-
inline virtual void send(std::span<const std::byte> frame) override¶
Seal and send one frame, as one transport message (§3).
-
inline virtual void send(std::span<const std::span<const std::byte>> iov) override¶
Seal and send the gathered spans as one frame, as one transport message.
Best effort, like every link: a frame above max_frame is refused (
noise_oversize); an empty one (an empty plaintext is the protocol’s own message, reference/23 §3), one sent with no session, or one with an exhaustedmemory.io, is dropped (dropped_tx). With no session on the DIAL side the send is also a demand: it starts a handshake.
-
inline void dial()¶
Demand the link without a frame: on the DIAL side, start a handshake if there is no session and none is in flight. A no-op on LISTEN.
-
inline void rekey()¶
Ask for a rekey now (reference/23 §6): a no-op on LISTEN, with no session to replace, or while a handshake is in flight.
-
inline bool clear_mark()¶
Responder: clear the mark to 0 (reference/23 §4), persisting it through a tr::net::noise::mark_store host. A no-op on DIAL.
This admits an initiator that restarted its counter, such as a replacement for one that lost it. It also lets every first message recorded under this PSK through the counter check again, each at most once and in increasing counter order. An initiator whose counter is below one used earlier under this PSK is recovered by replace_psk.
- Returns:
False when a mark store’s write fails; the mark in RAM is 0 regardless.
-
inline bool replace_psk(std::string_view ref)¶
Replace the link’s PSK with the key named
ref, and on LISTEN reset the mark to 0 (reference/23 §4: a counter is only meaningful under its PSK).The next first message is written or checked under the new key. Sessions, and a handshake in flight, keep the keys they began with. False, with nothing changed, when the link is inert or the key store has no such key. Also false when a mark store’s write of the reset mark fails: the new key is then in place and the mark in RAM is 0, and clear_mark retries the write.
- Parameters:
ref – Borrowed for the call only, unless
Hostis a tr::net::noise::mark_store.
-
inline virtual std::uint64_t sweep(std::uint64_t now, std::uint64_t deadline) override¶
Run every deadline that
nowhas passed, and answer the next (reference/23 §7).Retransmits a first message, sends an empty confirmation on a session still unacknowledged at its retry deadline, ends an attempt at its deadline, or expires a pending session; starts a rekey at
rekey_after, discards a session atreject_afterand a previous session at its expiry. A session’s own deadlines count from the first sweep that sees it current. The session and the liveness it leaves are link_up and state.- Parameters:
now – The application’s monotonic clock, in the config’s units.
deadline – Unused: every Noise window is its own configured span (§7).
- Returns:
The next armed deadline, 0 when none is: call again by then.
-
inline link_state_t state() const¶
The connection’s RFC-0014 liveness (reference/23 §10).
-
inline virtual bool link_up() const noexcept override¶
True while a send is admitted: the link holds a session.
-
inline virtual transport_drop_stats_t drop_stats() const noexcept override¶
The carrier’s three counters, plus what this link drops itself (its tally).
-
inline virtual void kind_stats(graph::stats_block_t &out) const noexcept override¶
The ten
noise_*nouns of reference/23 §11.
-
inline std::uint64_t count(noise::counter_t c) const¶
One
:statsnoun’s value; this link’s own drops are in drop_stats.
-
inline virtual bool start_receiving() override¶
The carrier receives from its constructor; a later start is passed on.
-
struct noise_config_t¶
A Noise link’s kind-private config (the lean rule: none of it is in the shared connection settings). Deadlines are in the application’s
nowunits; 0 is never due.Public Members
-
std::string_view psk_ref = {}¶
The PSK’s key-store name, resolved through
Host::resolve_pskwhile the link is built; borrowed for the constructor only, unlessHostis a tr::net::noise::mark_store. The key itself is never config.
-
std::size_t max_frame = 0¶
The largest Tracer frame (the universal
max_framekey): 0 means the carrier’s datagram bound less 25. The link’s datagram bound ismax_frame + 25; over IPv4 a frame is at most 65482 bytes (reference/23 §3).
-
std::uint64_t retry = 0¶
Initiator: the first retry interval; it doubles on each retry up to retry_cap.
-
std::uint64_t retry_cap = 0¶
Initiator: the largest retry interval; 0 keeps every interval at retry.
-
std::uint64_t attempt = 0¶
Initiator: the attempt deadline, from the attempt’s start (§7).
-
std::uint64_t pending_expiry = 0¶
Responder: how long a pending session waits for its confirmation.
-
std::uint64_t rekey_after = 0¶
Initiator: the current session’s age at which a rekey starts (§6, §7).
-
std::uint64_t reject_after = 0¶
Both: the current session’s age at which it is discarded and the link goes down.
-
std::uint64_t previous_expiry = 0¶
Both: how long a replaced session keeps receiving. 0 keeps it until the next handshake needs its phase.
-
link_memory_t memory = {}¶
state: the slot block, drawn once at build.io: one seal block per send.
-
std::string_view psk_ref = {}¶
-
template<class H>
concept link_host¶ - #include <
transport_noise.hpp>The application’s seams a Noise link calls (reference/23 §2, §4): a compile-time policy, so the link pays no indirect call for any of them.
resolve_psk(ref, out)resolves the PSK reference to its 32 bytes, from the application’s key store; false when the store has no such key. Called once, when the link is built. The key bytes never come from the wire.ephemeral(out)writes 32 bytes from a cryptographic random source: one fresh ephemeral private key per call, never reused (reference/23 §2, RFC-0033 Amendment 1). False when the source fails, and the handshake step is then not taken.next_counter()is the initiator counter: strictly increasing across every attempt an initiator makes under one PSK, the first at least 1 (reference/23 §4).
A link calls them under its own lock; a host shared by several links serialises itself.
-
template<class C>
concept datagram_carrier¶ - #include <
transport_noise.hpp>The datagram link a Noise link runs over (reference/23 §Terms, the carrier).
One datagram is delivered to the borrowed-span receiver, and its span is the carrier’s own receive buffer, writable for the call, which the Noise link decrypts in place (§8): tr::net::udp_transport_t states that contract. Addresses are opaque packed values, 0 meaning none:
inbound_source()is the in-flight datagram’s source (valid in the callback),peer_address()the configured peer a DIAL link sends to, andsend_tosends one datagram to a given address, so the Noise link, not the carrier, decides where a session’s traffic goes (§4 “Peer address”).effective_max_frame()is the largest datagram the carrier accepts.
-
template<class H>
concept mark_store¶ - #include <
transport_noise.hpp>A host that keeps a responder’s mark across reboots (reference/23 §4): two more seams, detected at compile time. A host without them keeps the mark in RAM only.
restore_mark(ref)answers the mark last persisted for the PSK namedref, 0 when none. Called once, when a LISTEN link is built.persist_mark(ref, mark)stores it and answers whether the write succeeded. Called each time the mark changes: once per accepted first message (after its PSK tag verified, before the answer is sent, so a peer without the PSK causes no write), and with 0 on tr::net::noise_link_t::clear_mark and tr::net::noise_link_t::replace_psk. A write that fails refuses the message: it is counted innoise_handshake_failedand answered by nothing (reference/23 §9). The mark in RAM still rises, so the message is not admitted later either; the initiator’s next attempt, with a higher counter, writes again.
Both are called under the link’s lock. A link of such a host keeps its
psk_refview, so the string must outlive the link. A key store that replaces a key while no link holds it clears that key’s persisted mark too: the mark is only meaningful under the PSK it was accepted with.
-
struct boot_counter_t¶
An initiator counter for a node with no clock that survives its reboots (reference/23 §4): a persisted boot counter as the high half and an attempt counter in RAM as the low half.
The application raises boot and persists it once per boot, before the first attempt (one write per boot), and returns next from its
next_counter(). Counters then rise across reboots under one PSK without a write per attempt. If that write fails, the application makes no handshake attempt this boot: a boot number that was not persisted can be handed out again after the next reboot, and its counters would repeat.Public Functions
-
inline constexpr std::uint64_t next() noexcept¶
The next counter,
boot << 32 | attempt; 0, which every mark refuses, once this boot’s 2^32 - 1 attempts are spent.
-
inline constexpr std::uint64_t next() noexcept¶
-
enum class tr::net::noise::counter_t : std::uint8_t¶
A Noise link’s counters: reference/23 §11’s ten nouns, in that order. The two universal ones it adds to its carrier’s (
malformed_rx,dropped_tx) are kept in its tr::net::drop_tally_t instead (#2482).Values:
-
enumerator HANDSHAKE_FAILED¶
noise_handshake_failed: tag, flags byte or all-zeroee.
-
enumerator HANDSHAKE_REPLAYED¶
noise_handshake_replayed: a counter not above the mark.
-
enumerator PENDING_SUPERSEDED¶
noise_pending_superseded: a newer first message won.
-
enumerator PENDING_EXPIRED¶
noise_pending_expired: a pending session timed out.
-
enumerator RETRANSMITS¶
noise_retransmits: a first or stored second message resent.
-
enumerator DECRYPT_FAILED¶
noise_decrypt_failed: a transport tag failed.
-
enumerator REPLAYED¶
noise_replayed: refused by the replay window.
-
enumerator STALE¶
noise_stale: well formed, for state this side lacks.
-
enumerator EXPIRED¶
noise_expired: a session discarded by age or nonce limit.
-
enumerator OVERSIZE¶
noise_oversize: a frame abovemax_frame, refused at send.
-
enumerator COUNT¶
The number of counters.
-
enumerator HANDSHAKE_FAILED¶
-
template<crypto_backend B>
struct session_t¶ One session: its two transport keys, the send nonce, the replay window and the address its traffic goes to (reference/23 §Terms, §5).
Public Functions
-
inline bool replay_refused(std::uint64_t n) const noexcept¶
Whether nonce
nis refused before any decryption (§5 step 3).
-
inline void accept(std::uint64_t n) noexcept¶
Record nonce
nas accepted, once its tag has verified (§5 step 5).
-
inline void arm(std::uint8_t p, std::uint64_t address) noexcept¶
Start a fresh session in phase
ptowardaddress; the keys are set apart.
-
inline void discard()¶
Discard the session: its keys are dropped and the slot is empty.
Public Members
-
transport_cipher_t<B> cipher = {}¶
The two directions’ keys.
-
std::uint64_t send_nonce = 0¶
The next nonce to seal under.
-
std::uint64_t seen = 0¶
Bit
imarks noncehighest - iaccepted.
-
std::uint64_t peer = 0¶
Where this session’s traffic is sent.
-
std::uint8_t phase = 0¶
The key phase, 0 or 1.
-
bool live = false¶
The slot holds a session.
-
bool any = false¶
A transport message has been accepted.
-
inline bool replay_refused(std::uint64_t n) const noexcept¶