Skip to content

fix(kex): zeroize intermediate copies of the KEX shared secret - #100

Merged
gonzafg2 merged 1 commit into
mainfrom
fix/kex-zeroize-intermediates
Jul 6, 2026
Merged

gonzafg2 merged 1 commit into
mainfrom
fix/kex-zeroize-intermediates

Conversation

@gonzafg2

@gonzafg2 gonzafg2 commented Jul 6, 2026

Copy link
Copy Markdown
Owner

Qué

Cierra las cuatro copias intermedias del secreto del KEX que escapaban al régimen Zeroizing (threat model §4.3), todas en kex.rs:

  1. hybrid_exchange: m (la aleatoriedad de encapsulación, que junto a la EK pública recomputa K_PQ completo) y k_pq — SharedKey de ml-kem 0.3 es un array plano sin zeroize-on-drop (su feature zeroize solo cubre DecapsulationKey/DecryptionKey). K_PQ ahora se incorpora al hash y se borra antes de la mitad clásica, así los early-returns de esa mitad (bad-hybrid-init-length, rng-failure, invalid-x25519-key) tampoco lo dejan vivo.
  2. derive_key: el buffer string(K) se dropeaba plano en cada KEX y cada re-key (4 veces por derive_cipher_pair); ahora vive en Zeroizing. El bloque [u8; 32] del loop de extensión también se borra.
  3. exchange_hash: el buffer del Writer que embebe K ahora se borra on-drop.
  4. ExchangeHashInputs: su derive(Debug) imprimía K verbatim; se reemplaza por un impl manual redactado, consistente con HybridOutcome, HostKey y AuthorizedKeys, más test debug_never_leaks_the_shared_secret (patrón de host_key.rs).

Por qué

Defensa en profundidad, no explotable por red: requiere core dump o lectura de memoria del proceso. El threat model §4.3 exige material de claves zeroizado tras uso, y el contraste con lo que sí estaba cubierto (shared_secret, exchange_hash/session_id, salida de derive_key) hacía de estas copias el hueco restante.

Hallazgo de una revisión de seguridad del código Phase-1 mergeado. Sin cambio de comportamiento observable: mismo protocolo, mismos bytes en el wire.

Validación

  • cargo fmt / clippy --workspace --all-targets -- -D warnings / cargo test --workspace: verdes (107 tests, +1 nuevo).
  • Sin dependencias nuevas; Zeroize ya era dep del workspace.

https://claude.ai/code/session_017JuwgCHx6Uv5E13g1BHAud

The Zeroizing regime covered the combined secret K, the exchange
hash, and derive_key's output, but four intermediate copies escaped
it (threat model §4.3):

- m and k_pq in hybrid_exchange: ml-kem 0.3's SharedKey is a plain
  array with no zeroize-on-drop, and m regenerates K_PQ given the
  public EK. K_PQ is now folded into the hash and erased before the
  classical half runs, so its error paths never leave it live.
- derive_key's string(K) buffer, dropped plain on every KEX and
  re-key (four times per derive_cipher_pair).
- exchange_hash's Writer buffer, which embeds K.
- The per-round block in derive_key's extension loop.

Also replaces ExchangeHashInputs's derive(Debug) — which printed K
verbatim — with a redacted manual impl matching HybridOutcome and
HostKey, plus a debug_never_leaks_the_shared_secret test following
host_key.rs's pattern.

Found by security review of the merged Phase-1 code; not remotely
exploitable (requires a core dump or process-memory read), defence
in depth per §4.3.

Claude-Session: https://claude.ai/code/session_017JuwgCHx6Uv5E13g1BHAud
Signed-off-by: Gonzalo Fleming <[email protected]>
Copilot AI review requested due to automatic review settings July 6, 2026 16:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the QuantumSSH core KEX implementation against memory disclosure by ensuring intermediate buffers containing KEX shared-secret material are zeroized promptly and never exposed via Debug, aligning with the repo’s threat model §4.3.

Changes:

  • Zeroize intermediate ML-KEM and derived buffers in hybrid_exchange (including wiping m and K_PQ before entering the X25519 half).
  • Ensure serialized string(K) and other transient derivation buffers in derive_key and exchange_hash are erased on drop (via Zeroizing) and explicitly wipe per-iteration digest blocks.
  • Replace ExchangeHashInputs’ #[derive(Debug)] with a redacted manual Debug impl and add a regression test preventing secret leakage in debug output.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@opencode-agent

opencode-agent Bot commented Jul 6, 2026

Copy link
Copy Markdown

All checks pass: fmt clean, clippy zero warnings, 107 tests green (including the new debug_never_leaks_the_shared_secret).


PR Review: fix(kex): zeroize intermediate copies of the KEX shared secret

Verdict: Approve. No blockers. This is a textbook defence-in-depth hardening that closes the four remaining Zeroizing gaps in the KEX path. No behavior change, no new dependencies, consistent with existing patterns.

High-signal findings

✅ hybrid_exchange — m and k_pq (Lines 657–673)

The two most consequential changes. m (B32, the ML-KEM encapsulation randomness) can recompute K_PQ given the public EK, which is transmitted in cleartext as part of C_INIT. Zeroizing m immediately after encapsulate_deterministic is correct. Zeroizing k_pq after feeding it into the SHA-256 hasher — and moving that fold-in before the classical half — means early-returns from invalid-x25519-key or rng-failure no longer leave the PQ secret live. The observation that ml-kem 0.3's SharedKey lacks zeroize-on-drop is accurate.

✅ ExchangeHashInputs — manual Debug impl (Lines 724–729)

#[derive(Debug)] on a struct containing shared_secret: &[u8; 32] would print the secret verbatim. The manual impl using finish_non_exhaustive() matches HybridOutcome (line 622) and the HostKey/AuthorizedKeys pattern cited in the PR. The new test debug_never_leaks_the_shared_secret (line 940) validates this.

✅ exchange_hash — Writer buffer (Lines 748–751)

The old Sha256::digest(w.into_bytes()) dropped the serialization buffer (containing string(K)) as a plain Vec<u8>. Wrapping in Zeroizing before hashing is correct — the borrow for buf.as_slice() is scoped to that expression.

✅ derive_key — string(K) and loop block (Lines 768–789)

The k_string buffer and the extension-loop block: [u8; 32] were both plain allocations. Now zeroized — consistent with the already-zeroized out return value. The as_slice() calls on Zeroizing<Vec<u8>> borrow correctly within the function scope.

Alignment with review criteria

Criterion Evidence
MANIFIESTO #1 (memory-safe) No new unsafe; Zeroize/Zeroizing already audited.
MANIFIESTO #4 (sharp edges) No new dependencies; Zeroize already in workspace deps.
Threat model §4.3 (key material) Four copies now erased on drop; debug never leaks K.
Pre-auth surface No changes to parser/wire path.
Fail closed k_pq fold-in moved before classical error paths — early-reject no longer leaks PQ material.
Code conventions Debug impl uses finish_non_exhaustive(); no stubs; clippy clean.

github run

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Code review

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

@gonzafg2
gonzafg2 merged commit 0502f65 into main Jul 6, 2026
12 checks passed
@gonzafg2
gonzafg2 deleted the fix/kex-zeroize-intermediates branch July 6, 2026 16:45
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.

2 participants