Skip to content

feat(core): M3 — transport: type-state machine + AEAD encrypted path - #65

Merged
gonzafg2 merged 9 commits into
mainfrom
feat/m3-transport
Jun 13, 2026
Merged

gonzafg2 merged 9 commits into
mainfrom
feat/m3-transport

Conversation

@gonzafg2

@gonzafg2 gonzafg2 commented Jun 12, 2026 •

Copy link
Copy Markdown
Owner

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_INFO bajo las llaves nuevas, y cruza un SSH_MSG_SERVICE_REQUEST cifrado — que M3 deniega con SSH_DISCONNECT_SERVICE_NOT_AVAILABLE porque ssh-userauth llega en M4.

Contenido

transport — la máquina Expect<Stage> (RFC-0003)

  • Estados: 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.
  • El I/O cifrado es una capacidad por etapa vía traits sellados en un módulo privado — SealedRead y SealedWrite por separado: ServiceResponse puede responder pero estructuralmente no puede leer. Sin accept-and-branch, sin Option runtime.
  • strict-kex en la máquina: ambos contadores corren desde el identification exchange y se resetean a cero tras cada NEWKEYS (tx al enviar el nuestro, rx al recibir el del peer). El nonce ChaCha20 es ese contador — un bug de reset no puede pasar inadvertido: el primer paquete cifrado no descifraría.
  • run_connection retorna Result<Infallible, _>: el tipo registra que en M3 toda conexión termina en denegación — sin unreachable!, 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 sueltos chacha20 + 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.
  • Fail-closed en cada paso: length acotado antes de alocar, tag verificado (constant-time, 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.
  • KATs: keystream ChaCha20Legacy contra 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, el SSH_MSG_EXT_INFO con server-sig-algs = ssh-ed25519 viaja como primer paquete cifrado de la conexión, inmediatamente tras nuestro NEWKEYS (RFC 8308 §2.3; ADR-0021).

server

Se 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 (expone ChaCha20Legacy, la variante djb de nonce 64-bit), poly1305 0.8, aes-gcm 0.10 (generación cipher 0.4, alineada con sha2 0.10), subtle 2. Todas RustCrypto, pure-Rust, sin FFI. cargo deny verde.

Tests (64 en total: 56 lib + 8 integración — los de cipher están dentro de los 56)

  • cipher: round-trips ambos ciphers en múltiples tamaños, todo bit volteado en un paquete se rechaza (exhaustivo byte a byte), seqnr errado falla cerrado, nonce GCM avanza por paquete, length sobredimensionado rechazado pre-alocación, KATs.
  • integración (tests/accept.rs): el cliente del test deriva las llaves, instala sus ciphers y conversa cifrado — EXT_INFO parseado 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.

gonzafg2 added 2 commits June 12, 2026 13:13
…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]>
Comment thread crates/quantumssh-core/src/transport.rs Resolved
…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]>
Comment thread crates/quantumssh-core/src/transport.rs Resolved
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]>
Comment thread Cargo.toml Resolved
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]>
Comment thread crates/quantumssh-core/src/transport.rs Resolved
Comment thread Cargo.toml Resolved
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]>
@claude

claude Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

@opencode-agent

Copy link
Copy Markdown

Review: M3 Transport — No remaining findings

All 64 tests pass (56 lib + 8 integration). The four prior review rounds' findings are resolved:

Finding Status
kex.failed fired for post-NEWKEYS protocol violations Fixed — reject_sealed now uses general tier (transport.rs:648-658)
reject_plain unconditionally emitted kex.failed Fixed — bifurcates on disconnect_code (transport.rs:523-542)
aes-gcm/aes missing zeroize features Fixed — aes-gcm+aes both zeroize-enabled (Cargo.toml:50,56); confirmed via cargo tree
exchange_hash not in Zeroizing Fixed — field is Zeroizing<[u8; 32]> (transport.rs:105)
poly1305 missing zeroize feature Fixed — Cargo.toml:49

Verified against CLAUDE.md commitments

1. Memory-safe — zero first-party unsafe. unsafe_code = "forbid" in workspace lints (Cargo.toml:66). All crypto deps are pure-Rust, no FFI.

2. Post-quantum by default — kex::negotiate(peer, true) at transport.rs:181 rejects peers without mlkem768x25519-sha256 (ADR-0021). hybrid_exchange at kex.rs:608-659 aborts on either half failure — confirmed by low_order_x25519_point_aborts_the_exchange and corrupted_mlkem_key_is_rejected_by_fips_validation tests.

3. Zero legacy — exactly two AEAD ciphers ([email protected], [email protected]). No RSA/DSA/ECDSA-NIST/CBC/ssh-rsa/password-auth/compression compiled in.

4. Small surface — 5 new deps, all RustCrypto, all justified in Cargo.toml comments and PR body. aes crate is feature-switch only, never imported.

5. Apache-2.0 — maintained.

Verified against threat model hard rules

  • Pre-auth path (read_plain, read_sealed): length bounded by wire::MAX_PACKET (35000) before vec![0u8; body_len] allocation. read_sealed additionally validates the encrypted length through PacketCipher::body_len → validate_aead_length.
  • Fail closed: bad AEAD tag in read_sealed returns TransportError::Rejected("packet-auth-failed") with no DISCONNECT sent — the ? at transport.rs:391 propagates to connection.closed. Constant-time tag comparison via subtle::ConstantTimeEq (cipher.rs:315).
  • Type-state machine: Expect<Stage> consumed by each transition. SealedRead/SealedWrite traits sealed in a private module. ServiceResponse implements only SealedWrite (transport.rs:578), structurally preventing reads.
  • Strict-kex: seq counters reset to 0 at NEWKEYS (transport.rs:315,322). ChaCha20 nonce is the counter — a reset bug would prevent decryption of the first encrypted packet.
  • Key zeroization: shared_secret (Zeroizing), exchange_hash (Zeroizing), k_main/k_header (Zeroizing), derive_key returns Zeroizing<Vec<u8>>. All Debug impls suppress key material (cipher.rs:80-87, kex.rs:587-591). cargo tree -i zeroize confirms aes, aes-gcm, chacha20, poly1305, cipher all link zeroize.

No findings. LGTM.

github run

@gonzafg2 gonzafg2 self-assigned this Jun 13, 2026
@opencode-agent

Copy link
Copy Markdown

All validations pass. Confirmed:

  • unsafe zero in first-party code (only occurrence is the forbid doc comment)
  • aes crate never imported — pure feature switch for zeroize on the round-key schedule
  • poly1305 zeroize chain confirmed via cargo tree
  • cargo fmt --check ✓ · clippy -- -D warnings ✓ · cargo test --workspace ✓ (64 passed) · cargo build --release ✓

No findings. All 5 prior-round findings are verified resolved:

Finding Fix Verified
kex.failed in reject_sealed General tier (transport.rs:648-657) ✓
reject_plain unconditionally kex.failed Bifurcates on disconnect_code (transport.rs:523-541) ✓
aes-gcm/aes missing zeroize Both zeroize-enabled (Cargo.toml:50,56) ✓ via cargo tree -i zeroize
exchange_hash not in Zeroizing Zeroizing<[u8; 32]> (transport.rs:105) ✓
poly1305 missing zeroize features = ["zeroize"] (Cargo.toml:49) ✓ via cargo tree -i zeroize

The PR is clean against all five MANIFIESTO commitments, the threat model's hard rules, and ADR-0024's event schema. LGTM.

github run

@gonzafg2 gonzafg2 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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ódulo mod sealed + traits SealedRead/SealedWrite es un patrón elegante. ServiceResponse estructuralmente no puede leer — no hay runtime branch que lo habilite.
  • server.rs:111-114 — Ok(never) => match never {} con Infallible documenta en el sistema de tipos que M3 siempre termina en denegación. Cuando M4 agregue el accept arm, run_connection cambiará 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 para ChaCha20Legacy (djb vector) y Poly1305 (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]>
@gonzafg2

Copy link
Copy Markdown
Owner Author

Resolución de las 3 observaciones del Code Review

Commit f188e54 implementa la opción B completa:

1. CipherError::BadSequence — cipher.rs:47-53

Nueva variante del enum. Cuando ChaCha20 descifra el length con un seqnr errado, la validación falla y ahora retorna Err(BadSequence) en vez de Err(Wire(BadPacketLength)). El test chacha_wrong_sequence_number_fails_closed lo asserta directamente.

2. debug_assert_eq! en GCM — cipher.rs:345, 375, 398

Aes256GcmOpenssh guarda el initial_invocation y seal() y open() comparan (invocation − initial) == seqnr en debug. Si alguna vez el contador externo y el interno se desincronizan, el pánico ocurre en el acto — no silenciosamente. Cero costo en release.

3. Conteo de tests corregido en el PR body

75 → 64 (los 11 de cipher ya están dentro de los 56 unitarios).


Verificación: cargo fmt ✓ · clippy ✓ (0 warnings) · cargo test --workspace ✓ (64 passed).

@opencode-agent

Copy link
Copy Markdown

All validations pass:

Command Result
cargo fmt --all -- --check ✓
cargo clippy --workspace --all-targets -- -D warnings ✓ (0 warnings)
cargo test --workspace ✓ (64 passed: 56 unit + 8 integration)
cargo tree -i zeroize ✓ chain confirmed through all crypto deps
First-party unsafe ✓ zero (only the forbid doc comment)
aes crate imported ✓ never (feature-switch only)

Review: No findings

All five prior-round findings remain resolved and independently verified:

Finding Fix Verified
kex.failed in reject_sealed General tier (transport.rs:648-658) ✓
reject_plain unconditionally kex.failed Bifurcates on disconnect_code (transport.rs:523-542) ✓
aes-gcm/aes missing zeroize Both zeroize-enabled (Cargo.toml:50,56) ✓ via cargo tree -i zeroize
exchange_hash not in Zeroizing Zeroizing<[u8; 32]> (transport.rs:105) ✓
poly1305 missing zeroize features = ["zeroize"] (Cargo.toml:49) ✓ via cargo tree -i zeroize

The three post-round-4 observations are also addressed:

  • CipherError::BadSequence — cipher.rs:47-54, wired through body_len at cipher.rs:305
  • debug_assert_eq! GCM counter guards — cipher.rs:383-387 (seal), :413-417 (open)
  • Test count corrected to 64

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.

github run

@gonzafg2

Copy link
Copy Markdown
Owner Author

Code review again @claude[agent] please

@gonzafg2
gonzafg2 merged commit a4c736c into main Jun 13, 2026
10 checks passed
@gonzafg2
gonzafg2 deleted the feat/m3-transport branch June 13, 2026 05:17
gonzafg2 added a commit that referenced this pull request Sep 22, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant