Repository navigation
feat(core): M3 — transport: type-state machine + AEAD encrypted path - #65
Conversation
…file 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]>
…YS 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]>
…ost-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]>
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]>
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]>
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]>
Code reviewNo issues found. Checked for bugs and CLAUDE.md compliance. |
Review: M3 Transport — No remaining findingsAll 64 tests pass (56 lib + 8 integration). The four prior review rounds' findings are resolved:
Verified against CLAUDE.md commitments1. Memory-safe — zero first-party 2. Post-quantum by default — 3. Zero legacy — exactly two AEAD ciphers ( 4. Small surface — 5 new deps, all RustCrypto, all justified in Cargo.toml comments and PR body. 5. Apache-2.0 — maintained. Verified against threat model hard rules
No findings. LGTM. |
|
All validations pass. Confirmed:
No findings. All 5 prior-round findings are verified resolved:
The PR is clean against all five MANIFIESTO commitments, the threat model's hard rules, and ADR-0024's event schema. LGTM. |
gonzafg2
left a comment
There was a problem hiding this comment.
Code Review: PR #65 — feat(core): M3 — transport: type-state machine + AEAD encrypted path
Verificación automatizada
| Comando | Resultado |
|---|---|
cargo fmt --all -- --check |
✓ |
cargo clippy --workspace --all-targets -- -D warnings |
✓ (0 warnings) |
cargo test --workspace |
64 passed (56 lib + 8 integración) |
Hallazgos
No se encontraron bugs ni violaciones de las hard constraints.
La máquina type-state, los sealed traits, el fail-closed y la cobertura de Zeroizing están sólidos.
Observaciones (no bloqueantes)
1. Discrepancia en el conteo de tests del PR body
El PR dice "75 en total: 56 lib + 8 integración + 11 cipher". El conteo real es 64 (56 unitarios totales — que ya incluyen los 11 de cipher + 8 de integración). El cuerpo del PR parece sumar los 11 de cipher por separado cuando ya están dentro de los 56. Solo es inconsistencia documental.
2. transport.rs:601 — body_len pasa seqnr pero GCM lo ignora
PacketCipher::body_len(seqnr, length_bytes) pasa el seqnr pero la rama GCM no lo usa — solo lo usa la rama ChaCha20 para descifrar el length. No es incorrecto porque GCM mantiene su propio invocation counter, pero un debug_assert_eq!(seqnr as u64, self.invocation) dentro de GCM habría detectado desincronización de contadores más temprano.
3. cipher.rs:509 — error de seqnr mapeado a nivel genérico
En chacha_wrong_sequence_number_fails_closed, el test espera fallo con seqnr=6 tras sellar con seqnr=5. El test pasa correctamente, pero el error es indistinguible de BadTag o Wire(BadPacketLength). Un CipherError::BadSequence no cambiaría el comportamiento (ambos son fail-closed), pero mejoraría la auditabilidad si alguna vez hay que diagnosticar desincronización de contadores desde los logs.
Lo que más me gusta
transport.rs:550-562— El módulomod sealed+ traitsSealedRead/SealedWritees un patrón elegante.ServiceResponseestructuralmente no puede leer — no hay runtime branch que lo habilite.server.rs:111-114—Ok(never) => match never {}conInfallibledocumenta en el sistema de tipos que M3 siempre termina en denegación. Cuando M4 agregue el accept arm,run_connectioncambiará su tipo de retorno y esta línea no compilará — forzando al dev a manejar el nuevo caso. Excelente uso del type system como contrato.cipher.rs:516-540— Test de bit-flip exhaustivo byte a byte en ambos ciphers. Exactamente el tipo de test que quieres en una superficie criptográfica.cipher.rs:446-458+460-476— KATs paraChaCha20Legacy(djb vector) yPoly1305(RFC 8439 §2.5.2). Los primitivos están clavados.
Veredicto
LGTM. No hay objeciones para mergear.
Todas las verificaciones pasan, no hay regresiones en los tests M2 heredados, y la adición de ~1700 líneas sigue al pie de la letra el contrato de RFC-0003, ADR-0019, ADR-0021, ADR-0022 y ADR-0024. Los 3 hallazgos son observaciones menores — ninguno justifica bloquear el merge.
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]>
Resolución de las 3 observaciones del Code ReviewCommit f188e54 implementa la opción B completa: 1.
|
|
All validations pass:
Review: No findingsAll five prior-round findings remain resolved and independently verified:
The three post-round-4 observations are also addressed:
The PR is clean against all five MANIFIESTO commitments, threat-model hard rules, ADR-0021's negotiation profile, and ADR-0024's event schema. No findings. |
|
Code review again @claude[agent] please |
…each edit touched Claude checked the Links lines against the milestone PRs' file lists and found four wrong attributions: server.rs (ADR-0016) and everything ADR-0022 names landed in M0 (#62), not M5/M3; transport.rs (ADR-0021) landed in M3 (#65), not M2; and log_fields.rs (ADR-0024) came with #101 on 2026-07-06, after the ADR's acceptance. All four corrected, with the banners' milestone references. Each banner now says which section the edit touched (Context in 0018/0019, Related in 0021/0023/0024, both in 0022) instead of the same sentence everywhere. ADR-0020's Links line no longer carries a note about the unimplemented package pin — that is decision-level content and lives in ADR-0034 (#161). ADR-0023 no longer points at "PR #50 in review" for the event schema, and ADR-0021 drops a "(TBD)" next to the kex module. docs/adr/README.md step 5 distinguishes the governance state from the file's Status line and lists what actually happened (ADR-0027 merged Accepted; 0028/0029 flipped in their implementing PRs; 0030-0032 in #158) instead of calling one instance the practice. docs/infrastructure.md says first-party unsafe would need a superseding ADR, as ADR-0018 states, not an RFC. Findings by Claude and opencode on #159. Claude-Session: https://claude.ai/code/session_018UmL9wcgKBGFjdjGSSLafa Signed-off-by: Gonzalo Fleming <[email protected]>
Qué hace
Cuarto hito de Phase 1 (#9): la máquina type-state del transporte (RFC-0003) y el camino cifrado post-NEWKEYS. Una conexión hoy completa el handshake PQ, instala los AEAD negociados, recibe
EXT_INFObajo las llaves nuevas, y cruza unSSH_MSG_SERVICE_REQUESTcifrado — que M3 deniega conSSH_DISCONNECT_SERVICE_NOT_AVAILABLEporquessh-userauthllega en M4.Contenido
transport— la máquinaExpect<Stage>(RFC-0003)KexInit → HybridInit → NewKeys → ServiceRequest → ServiceResponse. Cada tipo expone solo los mensajes válidos de su etapa y cada transición consume la máquina — aceptar fuera de secuencia es un error de compilación, no un hallazgo de review (la propiedad anti-Terrapin que RFC-0003 toma de rustls). Cierra el hilo de scope diferido en feat(core): M2 — kex + host_key: negotiation and hybrid PQ key exchange #64.SealedReadySealedWritepor separado:ServiceResponsepuede responder pero estructuralmente no puede leer. Sin accept-and-branch, sinOptionruntime.run_connectionretornaResult<Infallible, _>: el tipo registra que en M3 toda conexión termina en denegación — sinunreachable!, sin panic.cipher— los dos AEAD del perfil ADR-0021, a nivel de paquete[email protected](PROTOCOL.chacha20poly1305): dos llaves de 256 bits, length cifrado aparte bajo la llave de header, llave Poly1305 por paquete desde el bloque 0 del keystream principal, nonce = seqnr BE de 64 bits. La construcción AEAD IETF no puede expresarlo → se arma con los primitivos sueltoschacha20+poly1305(el delta de dependencias que el plan de M0 anticipó; mismo org RustCrypto).[email protected](RFC 5647): length en claro como AAD, nonce = 4 bytes fijos ‖ contador de invocación de 64 bits que avanza por paquete.subtle— vuelve con su primer consumidor, como se prometió en feat(core): M2 — kex + host_key: negotiation and hybrid PQ key exchange #64) antes de descifrar.ChaCha20Legacycontra el vector original de djb (llave/nonce cero) y Poly1305 contra RFC 8439 §2.5.2 — fijan que los crates son la variante exacta que OpenSSH usa.EXT_INFO(cierra la otra refutación de scope de #64)Si el cliente ofreció
ext-info-c, elSSH_MSG_EXT_INFOconserver-sig-algs = ssh-ed25519viaja como primer paquete cifrado de la conexión, inmediatamente tras nuestro NEWKEYS (RFC 8308 §2.3; ADR-0021).serverSe reduce al accept loop + manejo de etapas; los helpers M2 que cargaba se mudaron a la máquina.
Dependencias nuevas (regla CLAUDE.md #4)
chacha20 0.9(exponeChaCha20Legacy, la variante djb de nonce 64-bit),poly1305 0.8,aes-gcm 0.10(generación cipher 0.4, alineada consha2 0.10),subtle 2. Todas RustCrypto, pure-Rust, sin FFI.cargo denyverde.Tests (64 en total: 56 lib + 8 integración — los de cipher están dentro de los 56)
tests/accept.rs): el cliente del test deriva las llaves, instala sus ciphers y conversa cifrado —EXT_INFOparseado bajo llaves nuevas + service request → DISCONNECT(7) sellado, por ambos ciphers (chacha20 con ext-info, aes256-gcm sin); un bit volteado en el ciphertext tira la conexión sin respuesta; más los caminos de rechazo M2 y el presupuesto de handshake lento.Validación local
cargo fmt --check✓ ·clippy --workspace --all-targets -- -D warnings✓ ·cargo test --workspace✓ (75 passed)Parte de #9 (M3). Refs: RFC-0003, ADR-0019, ADR-0021, ADR-0022, ADR-0024. Pendiente del hito para PR aparte si se prefiere: golden vectors de handshake OpenSSH (RFC-0003 §KAT) quedan mejor servidos por el gate interop de M6, que ejercita OpenSSH 10.x real.