Repository navigation
feat(core): M2 — kex + host_key: negotiation and hybrid PQ key exchange - #64
Merged
Merged
Conversation
…byte First half of the kex milestone. The crypto dependency layer enters the tree (RFC-0003/ADR-0019 pins: ml-kem 0.3, x25519-dalek, ed25519- dalek, sha2, subtle, zeroize — no hmac, per ADR-0021), and the negotiation logic the ADR-0021 review cycle defined becomes code: - build_kexinit(): the exact ten-name-list profile with random cookie, first_kex_packet_follows = false, callers keep the bytes as I_S for the exchange hash. - parse_kexinit(): zero-copy, strict, trailing-garbage rejected. - negotiate(): client-list-wins (RFC 4253 7.1); markers filtered before selection AND before the emptiness check; the negotiated KEX must be mlkem768x25519-sha256; strict-kex required on the initial KEXINIT and ignored on re-key; MAC never consulted (AEAD-only skip); every rejection is KEY_EXCHANGE_FAILED (3) with a structured reason for the kex.failed audit event; ext-info-c detected (initial only); wrong-guess detection for first_kex_packet_follows. Tests encode the review findings as fixtures: the hostile marker echo, the classical-only client (ADR-0020's negative case), client cipher preference beating ours, the legacy-cipher fail-closed path, MAC mismatch never failing, strict-kex initial-vs-rekey, and both guess outcomes. Refs #9 (M2, part 1 — hybrid exchange, host keys and derivation follow in this branch). Signed-off-by: Gonzalo Fleming <[email protected]>
…ivation Second half of the kex milestone — the post-quantum core: - hybrid_exchange(): the server side of draft-ietf-sshm-mlkem-hybrid- kex. The ML-KEM encapsulation key is validated per FIPS 203 7.2 during decoding (EncapsulationKey::new — the check ADR-0019 mandates before encapsulating); a low-order X25519 point fails was_contributory and aborts. Failure of EITHER hybrid half aborts with KEY_EXCHANGE_FAILED — never a fallback to the surviving half (ADR-0021, threat model 5.2.1). K = SHA-256(K_PQ || K_CL) over the RAW concatenation: the ADR-0019 encoding test asserts no mpint and no length prefixes anywhere near the secret. - exchange_hash(): the draft's H with the full I_C/I_S KEXINIT payloads bound in, and K entering as a string (not mpint). The threat-model 5.2.2 mutation test is implemented: flipping one byte of either KEXINIT, or of K, changes H. - derive_key(): RFC 4253 7.2 with SHA-256 and string-encoded K, extension rounds for keys longer than one digest (chacha20- [email protected] needs 64 bytes), verified against an independently-computed first block. - host_key module: unencrypted openssh-key-v1 (ssh-keygen -t ed25519) parsing with cross-checks (check bytes; embedded public halves must match the seed — tampering is Inconsistent, fail closed), RFC 8709 public blob + signature blob, SHA256: fingerprint (ADR-0024 format). Debug never exposes key material (threat model 4.3); the decoded container is Zeroizing. Internal minimal base64 (encode-nopad + strict decode) rather than a new dependency. - Tests: client-side simulation agreeing on K end-to-end, RFC 7748 6.1 X25519 vectors, FIPS-validation rejection of corrupted ML-KEM keys, low-order-point abort, wrong-length C_INIT, derivation separation/extension, host-key tamper detection. Refs #9 (M2, part 2 — handler integration closes the milestone next). Signed-off-by: Gonzalo Fleming <[email protected]>
Post-banner, each connection now completes the entire key exchange: KEXINIT exchange with the strict-kex first-packet rule, ADR-0021 negotiation (rejections emit kex.failed and DISCONNECT with the mandated reason code), wrong-guess packet skip, HYBRID_INIT -> signed HYBRID_REPLY, NEWKEYS both ways, and the kex.completed audit event. The encrypted transport that follows NEWKEYS is M3; until it lands the server closes there. The binary gains the required --host-key flag (unencrypted openssh-key-v1, ADR-0022 read-at-startup), and server.started is now schema-complete with host_key_fingerprint (ADR-0024). Integration tests drive a real client side: ML-KEM decapsulation, X25519, exchange-hash recomputation and Ed25519 signature verification over H, plus disconnect-code checks for non-hybrid peers, missing strict-kex, and pre-KEXINIT IGNORE messages. Signed-off-by: Gonzalo Fleming <[email protected]>
Review findings on #64: the Ed25519 seed was copied into a plain [u8; 32] before SigningKey::from_bytes, and the binary held the full PEM (which embeds the seed) in a plain String for the process lifetime. Both now sit in Zeroizing wrappers, and the PEM buffer is dropped as soon as the key is parsed (threat model section 4.3). Signed-off-by: Gonzalo Fleming <[email protected]>
Review finding on #64: subtle was declared as a direct dependency in M2 but nothing imports it — every comparison in this milestone is over public data (name-lists, message numbers) or the operator's own key file. Its first real consumer is the constant-time authorized_keys blob comparison in M4; it returns there with the code that uses it. It remains in the tree transitively via the dalek crates. Signed-off-by: Gonzalo Fleming <[email protected]>
Review finding on #64: the compression name-lists were parsed but never inspected, so a client offering only zlib passed negotiation. Zero-legacy rule: no compression code is compiled in, so a peer that does not accept none in both directions has no mutual algorithm — reject with SSH_DISCONNECT_KEY_EXCHANGE_FAILED (3), reason no-compression, like every other required list. Also tightens the module doc that overclaimed code 3 for every rejection path: wire-level malformations are PROTOCOL_ERROR (2) at the transport layer; code 3 is for negotiation rejections. Signed-off-by: Gonzalo Fleming <[email protected]>
Contributor
Code reviewNo issues found. Checked for bugs and CLAUDE.md compliance. |
gonzafg2
added a commit
that referenced
this pull request
Jun 13, 2026
…65) * feat(core): AEAD packet ciphers — the two ciphers of the ADR-0021 profile The cipher module seals and opens whole Binary Packet Protocol packets for the encrypted transport (M3): - [email protected] per OpenSSH's PROTOCOL.chacha20poly1305: two independent 256-bit keys, the packet length encrypted separately under the header key, the per-packet Poly1305 key drawn from block 0 of the main keystream, nonce = the packet sequence number as 64-bit big-endian. The IETF AEAD crate cannot express this (96-bit nonce, single key), so it is assembled from the loose chacha20 + poly1305 primitives — the dependency delta the M0 plan anticipated. ChaCha20Legacy is pinned by a known-answer test against djb's original zero-key vector, and Poly1305 against the RFC 8439 section 2.5.2 vector. - [email protected] per RFC 5647: cleartext length as AAD, nonce = 4-byte fixed field plus 64-bit invocation counter advancing per packet. Fail-closed at every step: the declared length is bounded before any allocation, the tag is verified (constant-time, subtle) before any decryption, and a single flipped bit anywhere in a packet — length, body, or tag — is rejected, which the tests assert exhaustively. Key material lives in Zeroizing buffers and Debug prints names only. subtle returns with its first consumer, as promised in #64. Signed-off-by: Gonzalo Fleming <[email protected]> * feat(core): transport type-state machine and the encrypted post-NEWKEYS path The Expect<Stage> machine RFC-0003 mandates: each stage type exposes only the messages valid in that stage — KexInit, HybridInit, NewKeys, ServiceRequest, ServiceResponse — every transition consumes the machine, and encrypted I/O is a capability granted per stage through sealed traits (read and write separately), so out-of-sequence acceptance and accept-and-branch are compile errors, not review findings. Strict-kex sequence discipline lives in the machine: both counters run from the identification exchange and reset to zero after each NEWKEYS (send counter on ours, receive counter on the peer's). The ChaCha20 nonce is this counter, so a reset bug cannot ship silently. After NEWKEYS the connection is AEAD end to end: the RFC 4253 section 7.2 key schedule installs the negotiated cipher per direction, and when the client offered ext-info-c the EXT_INFO carrying server-sig-algs = ssh-ed25519 rides the new keys as the first encrypted packet (RFC 8308; ADR-0021). The service-request stage accepts exactly SSH_MSG_SERVICE_REQUEST; ssh-userauth arrives with M4, so M3's only response arm denies with SSH_DISCONNECT_SERVICE_NOT_AVAILABLE (RFC 4253 section 10) — encoded as Infallible in the handler, no unreachable panic. server.rs shrinks to the accept loop plus stage driving; the M2 handshake helpers it carried move into the machine. Integration tests drive the client side of the full encrypted conversation: EXT_INFO parsed under the new keys, service request sealed and denied over [email protected] and [email protected], and a single flipped ciphertext bit drops the connection without a response. Signed-off-by: Gonzalo Fleming <[email protected]> * fix(core): keep kex.failed scoped to negotiation — general tier for post-NEWKEYS violations Review finding on #65: reject_sealed emitted the kex.failed audit event for a post-NEWKEYS protocol violation, but ADR-0024 scopes that event to ADR-0021's negotiation rejection paths. Both the sealed rejection and the M3 service denial now log on the general tier (the ADR-0024 vocabulary is closed; connection.closed carries the reason for the record); the audit-tier kex.failed remains exactly where the schema puts it. Signed-off-by: Gonzalo Fleming <[email protected]> * fix(core): fire kex.failed only on negotiation rejections (code 3) Review finding on #65, completing 60de492: reject_plain emitted the kex.failed audit event for every plaintext rejection, including the wire-level protocol violations that disconnect with code 2. ADR-0024 scopes the event to ADR-0021's negotiation rejection paths, which always carry SSH_DISCONNECT_KEY_EXCHANGE_FAILED (3). Protocol violations now log on the general tier; connection.closed carries their reason for the record. Signed-off-by: Gonzalo Fleming <[email protected]> * fix(core): zeroize the AES-GCM key schedule on drop Review finding on #65: aes-gcm was declared without its zeroize feature, leaving the AES round keys un-erased on drop while the ChaCha20 side already zeroized (threat model section 4.3). Enabling aes-gcm/zeroize alone only covers the GHASH key — the feature does not forward to the aes crate, whose round-key schedule is the bulk of the material. The workspace therefore also declares aes 0.8.4 solely to switch on its own zeroize feature through Cargo feature unification; no first-party code imports it, which the manifest comments state explicitly. Signed-off-by: Gonzalo Fleming <[email protected]> * fix(core): zeroize the exchange hash and the Poly1305 key state Review findings on #65, round 4: the exchange hash H is derived with K as input and doubles as the session identifier, so it now lives in Zeroizing like the secret itself; and poly1305 gains its zeroize feature so the per-packet MAC state is erased on drop, matching every other primitive in the block (threat model section 4.3). Signed-off-by: Gonzalo Fleming <[email protected]> * fix(core): distinguish BadSequence errors and assert GCM seqnr sync Three review findings from #65: - CipherError::BadSequence: new variant so a ChaCha20 packet read with the wrong sequence number is diagnosed as "mismatch" rather than silently folded into Wire(BadPacketLength). body_len() on ChaCha20 now returns Err(BadSequence) when the decrypted length fails validation — the keystream was derived from the wrong nonce. - GCM defence-in-depth: Aes256GcmOpenssh gains an initial_invocation field and debug_assert_eq! guards in seal() and open() that compare (invocation - initial) against the supplied seqnr. The assertions are debug-only (zero cost in release) and catch counter skew the moment the caller and the cipher step out of lockstep. - Both GCM private methods now take seqnr: u32 explicitly rather than ignoring the value PacketCipher already passed them. Tests updated: chacha_wrong_sequence_number asserts BadSequence directly; gcm_roundtrip uses sequential seqnrs from 0; the flipped-bit test sets seqnr=0 for both cipher families; gcm_nonce_advances uses seqnr 0→1 instead of duplicating 0. Signed-off-by: Gonzalo Fleming <[email protected]> --------- Signed-off-by: Gonzalo Fleming <[email protected]>
Merged
4 of 12 tasks
gonzafg2
added a commit
that referenced
this pull request
Sep 23, 2026
…; three banner and wording fixes ADR-0020's Decision said the interop job runs the full test suite; it never did (cargo test runs in ci.yml) and the banner records the correction. ADR-0021's Context names M2 (#64) next to the kex module so its banner describes the edit accurately; AGENTS.md tags the transport stages M3–M5; docs/adr/README.md step 5 says "load-bearing" on merge and leaves "in effect" to the Accepted status, as the Lifecycle section defines it. Raised by opencode and Claude on #159. Claude-Session: https://claude.ai/code/session_018UmL9wcgKBGFjdjGSSLafa Signed-off-by: Gonzalo Fleming <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Qué hace
Tercer hito de Phase 1 (#9): el módulo
kex, el módulohost_key, y su integración en el handler de conexiones. Un peer que se conecta hoy completa el handshake post-quantum entero — version exchange, KEXINIT,mlkem768x25519-sha256, NEWKEYS — y el servidor cierra ahí (el transporte cifrado es M3).Contenido
kex— el perfil ADR-0021, byte a bytegetrandom,first_kex_packet_follows = false, reserved 0) y parser del KEXINIT del peer con bounds explícitos.kex-strict-*,ext-info-*) se filtran antes de la selección y nunca son seleccionables;[email protected]es obligatorio en el KEXINIT inicial; detección deext-info-c(flag para M3); skip de un paquete si el guess defirst_kex_packet_followsfue errado. Todo rechazo →SSH_DISCONNECT_KEY_EXCHANGE_FAILED(3) + eventokex.failed {reason, disconnect_code}.draft-ietf-sshm-mlkem-hybrid-kex): validación FIPS 203 §7.2 de la llave ML-KEM antes de encapsular (ADR-0019), chequeo contributivo X25519 (punto de orden bajo → abort), falla de cualquiera de las dos mitades aborta — sin fallback.K = SHA-256(K_PQ ‖ K_CL)como concatenación cruda (encoding string del draft, no mpint), con el test de encoding del ADR-0019.I_C/I_Scompletos y key derivation RFC 4253 §7.2 (HASH = SHA-256).host_keyopenssh-key-v1sin cifrar (ssh-keygen -t ed25519): cross-checkcheck1 == check2, la pública derivada de la seed debe coincidir con ambas copias embebidas.ssh-ed25519, firma sobre H, fingerprintSHA256:(base64 sin padding) para logs.Debugjamás expone material de llave; contenedores decodificados enZeroizing.Integración (
server+ binario)run_handshake: el flujo M2 completo con strict-kex — el primer paquete debe ser KEXINIT; cualquier otro (incl.SSH_MSG_IGNORE) termina la conexión.--host-key <PATH>obligatorio (lectura única al inicio, ADR-0022); error de carga →server.config_error.server.startedahora schema-completo conhost_key_fingerprint(ADR-0024).Seguridad
KenZeroizing; jamás en logs, errores niDebug.Reader(threat model §4.1);HYBRID_INITacotado a los 1216 bytes exactos deC_INIT.Tests (52 en total)
tests/accept.rs): un cliente real en el test decapsula ML-KEM, computa X25519, recomputa H y verifica la firma Ed25519 del servidor; más: peer no-híbrido → código 3, sin strict-kex → 3,IGNOREpre-KEXINIT → terminado, handshake lento → cerrado al budget, identificación malformada → rechazada.Validación local
cargo fmt --check✓ ·cargo clippy --workspace --all-targets -- -D warnings✓ ·cargo test --workspace✓ (52 passed)Parte de #9 (M2). Refs: ADR-0019, ADR-0021, ADR-0022, ADR-0024, RFC-0003.