╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 //! In-process SSH server: full server side of SSH-2 for haxy's use case. 2 //! 3 //! handles, per connection: version exchange, KEXINIT, curve25519 key 4 //! exchange, NEWKEYS, key derivation, chacha20-poly1305 packet codec, 5 //! ssh-userauth service request, publickey authentication (ed25519 only; 6 //! captures the SHA256 fingerprint of the verified key), channel-layer 7 //! requests (pty-req, env, window-change, shell, exec), CHANNEL_DATA 8 //! flow with sender/receiver windows, and clean teardown 9 //! (exit-status / EOF / CLOSE). 10 //! 11 //! public surface for haxy code: 12 //! handleConnection — call from the listener with a session handler. 13 //! SessionCtx — handed to the handler; carries the channel + ciphers, 14 //! the verified key's fingerprint, and an event / 15 //! writeBytes / exit API. 16 //! SessionReader / SessionWriter — std.Io adapters so consumers (xit's 17 //! pack code, StreamTerminal, etc.) can use ordinary 18 //! Reader/Writer interfaces. 19 //! Request — what the client asked for: shell+pty or exec command. 20 //! HostKey — generated or loaded once at startup. 21 //! 22 //! hardcoded choices to keep the implementation small: 23 //! KEX: curve25519-sha256 (RFC 8731) 24 //! host key: ssh-ed25519 (RFC 8709) 25 //! cipher: chacha20-poly1305@openssh.com (RFC 4253 + openssh extension) 26 //! MAC: none (implicit in AEAD) 27 //! compress: none 28 //! user auth: publickey + ssh-ed25519 only (RSA/ECDSA deferred) 29 //! 30 //! TODO: add SSH session idle deadlines. A reachable SSH listener can currently 31 //! hold one task per idle connection while blocked in banner exchange, KEX, 32 //! auth, channel setup, waiting for send WINDOW_ADJUST, reading git pack data, 33 //! or waiting for peer CLOSE during teardown. The eventual fix should enforce a 34 //! per-connection idle timeout that is refreshed by successful SSH packet I/O 35 //! and closes/shuts down the underlying stream when no progress occurs. Prefer 36 //! an I/O-layer deadline if std.Io exposes one; otherwise use a carefully-owned 37 //! watchdog that cannot outlive the connection state it observes. 38 39 const std = @import("std"); 40 const builtin = @import("builtin"); 41 const Ed25519 = std.crypto.sign.Ed25519; 42 const X25519 = std.crypto.dh.X25519; 43 const Sha256 = std.crypto.hash.sha2.Sha256; 44 const ChaCha20 = std.crypto.stream.chacha.ChaCha20With64BitNonce; 45 const Poly1305 = std.crypto.onetimeauth.Poly1305; 46 47 pub const server_version = "SSH-2.0-haxy_0.0"; 48 pub const host_key_file_name = "ssh_host_ed25519_key"; 49 50 const max_packet_len: u32 = 35000; // RFC 4253 §6.1 — minimum implementations must support 51 const max_name_list_len: u32 = 4096; 52 const max_auth_attempts: u32 = 20; 53 const max_exit_drain_packets: u32 = 32; 54 55 // SSH message type bytes (RFC 4250 §4.1) 56 pub const SSH_MSG_DISCONNECT: u8 = 1; 57 pub const SSH_MSG_IGNORE: u8 = 2; 58 pub const SSH_MSG_UNIMPLEMENTED: u8 = 3; 59 pub const SSH_MSG_DEBUG: u8 = 4; 60 pub const SSH_MSG_SERVICE_REQUEST: u8 = 5; 61 pub const SSH_MSG_SERVICE_ACCEPT: u8 = 6; 62 pub const SSH_MSG_KEXINIT: u8 = 20; 63 pub const SSH_MSG_NEWKEYS: u8 = 21; 64 pub const SSH_MSG_KEX_ECDH_INIT: u8 = 30; 65 pub const SSH_MSG_KEX_ECDH_REPLY: u8 = 31; 66 pub const SSH_MSG_USERAUTH_REQUEST: u8 = 50; 67 pub const SSH_MSG_USERAUTH_FAILURE: u8 = 51; 68 pub const SSH_MSG_USERAUTH_SUCCESS: u8 = 52; 69 pub const SSH_MSG_USERAUTH_PK_OK: u8 = 60; // method-specific name for publickey 70 pub const SSH_MSG_GLOBAL_REQUEST: u8 = 80; 71 pub const SSH_MSG_REQUEST_SUCCESS: u8 = 81; 72 pub const SSH_MSG_REQUEST_FAILURE: u8 = 82; 73 pub const SSH_MSG_CHANNEL_OPEN: u8 = 90; 74 pub const SSH_MSG_CHANNEL_OPEN_CONFIRMATION: u8 = 91; 75 pub const SSH_MSG_CHANNEL_OPEN_FAILURE: u8 = 92; 76 pub const SSH_MSG_CHANNEL_WINDOW_ADJUST: u8 = 93; 77 pub const SSH_MSG_CHANNEL_DATA: u8 = 94; 78 pub const SSH_MSG_CHANNEL_EXTENDED_DATA: u8 = 95; 79 pub const SSH_MSG_CHANNEL_EOF: u8 = 96; 80 pub const SSH_MSG_CHANNEL_CLOSE: u8 = 97; 81 pub const SSH_MSG_CHANNEL_REQUEST: u8 = 98; 82 pub const SSH_MSG_CHANNEL_SUCCESS: u8 = 99; 83 pub const SSH_MSG_CHANNEL_FAILURE: u8 = 100; 84 85 pub const SSH_DISCONNECT_PROTOCOL_ERROR: u32 = 2; 86 87 // SSH_OPEN_* reason codes for CHANNEL_OPEN_FAILURE 88 pub const SSH_OPEN_RESOURCE_SHORTAGE: u32 = 4; 89 pub const SSH_OPEN_UNKNOWN_CHANNEL_TYPE: u32 = 3; 90 91 // data type code for CHANNEL_EXTENDED_DATA (stderr) 92 pub const SSH_EXTENDED_DATA_STDERR: u32 = 1; 93 94 // initial flow-control window we advertise. typical openssh setting; large 95 // enough that small interactive sessions never need a WINDOW_ADJUST. 96 const initial_recv_window: u32 = 1 << 20; 97 const max_packet_size: u32 = 32768; 98 const max_incoming_buffered: usize = initial_recv_window; 99 const incoming_refill_threshold: usize = max_incoming_buffered / 2; 100 101 // --------------------------------------------------------------------------- 102 // host key 103 // --------------------------------------------------------------------------- 104 105 pub const HostKey = struct { 106 keypair: Ed25519.KeyPair, 107 108 pub fn loadOrGenerate(io: std.Io, allocator: std.mem.Allocator, data_dir_path: []const u8) !HostKey { 109 const path = try std.fs.path.join(allocator, &.{ data_dir_path, host_key_file_name }); 110 defer allocator.free(path); 111 112 const cwd = std.Io.Dir.cwd(); 113 if (cwd.openFile(io, path, .{ .mode = .read_only })) |file| { 114 defer file.close(io); 115 var buf: [Ed25519.SecretKey.encoded_length]u8 = undefined; 116 var read_storage: [128]u8 = undefined; 117 var file_reader = file.reader(io, &read_storage); 118 try file_reader.interface.readSliceAll(&buf); 119 const sk = try Ed25519.SecretKey.fromBytes(buf); 120 const keypair = try Ed25519.KeyPair.fromSecretKey(sk); 121 return .{ .keypair = keypair }; 122 } else |err| switch (err) { 123 error.FileNotFound => {}, 124 else => return err, 125 } 126 127 const keypair = Ed25519.KeyPair.generate(io); 128 const file = try cwd.createFile(io, path, .{}); 129 defer file.close(io); 130 try file.writeStreamingAll(io, &keypair.secret_key.bytes); 131 if (builtin.os.tag != .windows) { 132 try file.setPermissions(io, @enumFromInt(0o600)); 133 } 134 return .{ .keypair = keypair }; 135 } 136 137 /// SSH wire-format ed25519 public key blob (used as K_S in the hash and 138 /// returned in KEX_ECDH_REPLY): string "ssh-ed25519" || string pubkey. 139 pub fn appendPublicBlob(self: HostKey, buf: *std.ArrayList(u8), allocator: std.mem.Allocator) !void { 140 try writeStringField(buf, allocator, "ssh-ed25519"); 141 try writeStringField(buf, allocator, &self.keypair.public_key.bytes); 142 } 143 144 /// SSH wire-format signature blob: string "ssh-ed25519" || string sig. 145 fn appendSignatureBlob(self: HostKey, buf: *std.ArrayList(u8), allocator: std.mem.Allocator, message: []const u8) !void { 146 const sig = try self.keypair.sign(message, null); 147 const sig_bytes = sig.toBytes(); 148 try writeStringField(buf, allocator, "ssh-ed25519"); 149 try writeStringField(buf, allocator, &sig_bytes); 150 } 151 }; 152 153 // --------------------------------------------------------------------------- 154 // public session API 155 // --------------------------------------------------------------------------- 156 157 /// what the client wants to do on this channel. 158 pub const Request = union(enum) { 159 shell: ?PtySize, // pty info if a pty-req arrived before the shell 160 exec: []const u8, // command string from the exec request 161 }; 162 163 /// next thing that arrived from the client. 164 pub const Event = union(enum) { 165 data: []u8, // CHANNEL_DATA payload — caller owns and must free via sess.allocator 166 resize: PtySize, // window-change request 167 close, // peer sent EOF or CHANNEL_CLOSE 168 }; 169 170 /// session bridge handed to the consumer's handleSession callback. exposes a 171 /// pumped event API plus a byte-write API; the byte stream goes out as 172 /// CHANNEL_DATA packets respecting the channel's flow-control window. 173 pub const SessionCtx = struct { 174 io: std.Io, 175 allocator: std.mem.Allocator, 176 reader: *std.Io.Reader, 177 writer: *std.Io.Writer, 178 cs_cipher: *Cipher, 179 sc_cipher: *Cipher, 180 channel: *Channel, 181 /// SHA256 fingerprint of the pubkey this session authenticated with, 182 /// formatted as "SHA256:<base64-no-padding>" — same value the openssh 183 /// client logs as `Offering public key: ED25519 SHA256:…`. consumers 184 /// can use it as a stable per-key identity. 185 fingerprint: [fingerprint_len]u8, 186 closed: bool = false, 187 188 // shared state for the blocking I/O mode (SessionReader + writeBytes 189 // window-stall pump). incoming CHANNEL_DATA bytes accumulate here 190 // until the consumer drains them via SessionReader. 191 incoming_buffer: std.ArrayList(u8) = .empty, 192 incoming_eof: bool = false, 193 // resize seen by the background pump, returned by the next nextEvent call 194 pending_resize: ?PtySize = null, 195 196 pub fn deinit(self: *SessionCtx) void { 197 self.incoming_buffer.deinit(self.allocator); 198 } 199 200 /// pump SSH packets until something interesting (data / resize / close) 201 /// arrives. background traffic (window adjusts, env requests, etc.) is 202 /// handled silently. used by pumped-event consumers (e.g. the TUI path); 203 /// do not mix with SessionReader, which has its own packet pump. 204 pub fn nextEvent(self: *SessionCtx) !Event { 205 if (self.pending_resize) |sz| { 206 self.pending_resize = null; 207 return .{ .resize = sz }; 208 } 209 while (true) { 210 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch |err| switch (err) { 211 error.EndOfStream => { 212 self.closed = true; 213 return .close; 214 }, 215 else => return err, 216 }; 217 defer self.allocator.free(packet); 218 if (packet.len < 1) return error.EmptyPacket; 219 220 switch (packet[0]) { 221 SSH_MSG_CHANNEL_DATA => { 222 const payload = try parseChannelData(packet, false, self.channel.local_id); 223 const data_len: u32 = @intCast(payload.len); 224 if (data_len > self.channel.local_window) return error.WindowExceeded; 225 self.channel.local_window -= data_len; 226 try maybeRefillRecvWindow(self.io, self.allocator, self.sc_cipher, self.writer, self.channel); 227 // hand the payload bytes to the caller (caller owns) 228 return .{ .data = try self.allocator.dupe(u8, payload) }; 229 }, 230 SSH_MSG_CHANNEL_EXTENDED_DATA => { 231 // stderr from the client is unusual; discard, but adjust window 232 try discardChannelData(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, packet, true); 233 }, 234 SSH_MSG_CHANNEL_WINDOW_ADJUST => try handleWindowAdjust(self.channel, packet), 235 SSH_MSG_KEXINIT => { 236 try sendDisconnect(self.io, self.allocator, self.sc_cipher, self.writer, "rekey is not supported"); 237 return error.RekeyUnsupported; 238 }, 239 SSH_MSG_CHANNEL_REQUEST => { 240 var r = std.Io.Reader.fixed(packet[1..]); 241 const recipient_channel = try r.takeInt(u32, .big); 242 if (recipient_channel != self.channel.local_id) return error.UnknownChannel; 243 const req_type = try takeStringField(self.allocator, &r, 64); 244 defer self.allocator.free(req_type); 245 const want_reply = (try r.takeByte()) != 0; 246 if (std.mem.eql(u8, req_type, "window-change")) { 247 const sz = try takePtySize(&r); 248 if (self.channel.pty != null) self.channel.pty = sz; 249 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, true); 250 return .{ .resize = sz }; 251 } 252 // unknown / not interesting — fail it and keep going 253 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, false); 254 }, 255 SSH_MSG_CHANNEL_EOF, SSH_MSG_CHANNEL_CLOSE => { 256 try parseChannelId(packet, self.channel.local_id); 257 self.closed = true; 258 return .close; 259 }, 260 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(self.io, self.allocator, self.sc_cipher, self.writer, packet), 261 else => {}, 262 } 263 } 264 } 265 266 /// send bytes to the client's stdout (CHANNEL_DATA). 267 pub fn writeBytes(self: *SessionCtx, bytes: []const u8) !void { 268 try self.writeChannel(bytes, false); 269 } 270 271 /// send bytes to the client's stderr (CHANNEL_EXTENDED_DATA). use this for 272 /// server messages on a git exec session, where stdout carries the pack 273 /// protocol and stray text breaks the client's pkt-line parser. 274 pub fn writeStderr(self: *SessionCtx, bytes: []const u8) !void { 275 try self.writeChannel(bytes, true); 276 } 277 278 /// ship bytes as one or more stdout CHANNEL_DATA (or stderr 279 /// CHANNEL_EXTENDED_DATA) packets, respecting the peer's max-packet size. 280 /// if the remote window is exhausted, pump incoming SSH packets until a 281 /// WINDOW_ADJUST arrives (background packets are processed for their side 282 /// effects — incoming CHANNEL_DATA goes into incoming_buffer for a future 283 /// SessionReader). 284 fn writeChannel(self: *SessionCtx, bytes: []const u8, extended: bool) !void { 285 var rest = bytes; 286 while (rest.len > 0) { 287 while (self.channel.remote_window == 0) { 288 if (self.incoming_eof) return error.RemoteClosed; 289 try self.processOneBackgroundPacket(); 290 } 291 const cap = @min(@min(rest.len, self.channel.max_packet), self.channel.remote_window); 292 const chunk_len: u32 = @intCast(cap); 293 294 var msg: std.ArrayList(u8) = .empty; 295 defer msg.deinit(self.allocator); 296 try msg.append(self.allocator, if (extended) SSH_MSG_CHANNEL_EXTENDED_DATA else SSH_MSG_CHANNEL_DATA); 297 try writeU32(&msg, self.allocator, self.channel.remote_id); 298 if (extended) try writeU32(&msg, self.allocator, SSH_EXTENDED_DATA_STDERR); 299 try writeStringField(&msg, self.allocator, rest[0..chunk_len]); 300 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, msg.items); 301 302 self.channel.remote_window -= chunk_len; 303 rest = rest[chunk_len..]; 304 } 305 } 306 307 /// process exactly one SSH packet for side effects only. CHANNEL_DATA 308 /// payloads accumulate in incoming_buffer; CHANNEL_EOF/CLOSE flips 309 /// incoming_eof; WINDOW_ADJUST updates the channel state; window-change 310 /// is stashed in pending_resize for the next nextEvent call; other 311 /// channel/global requests get a polite failure. used both by 312 /// SessionReader (waiting for inbound bytes) and writeBytes (waiting 313 /// for send-window). 314 fn processOneBackgroundPacket(self: *SessionCtx) !void { 315 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch |err| switch (err) { 316 error.EndOfStream => { 317 self.incoming_eof = true; 318 return; 319 }, 320 else => return err, 321 }; 322 defer self.allocator.free(packet); 323 if (packet.len < 1) return; 324 325 switch (packet[0]) { 326 SSH_MSG_CHANNEL_DATA => { 327 const payload = try parseChannelData(packet, false, self.channel.local_id); 328 const data_len: u32 = @intCast(payload.len); 329 if (data_len > self.channel.local_window) return error.WindowExceeded; 330 self.channel.local_window -= data_len; 331 if (payload.len > max_incoming_buffered - self.incoming_buffer.items.len) { 332 return error.IncomingBufferExceeded; 333 } 334 try self.incoming_buffer.appendSlice(self.allocator, payload); 335 try self.maybeRefillRecvWindowForBufferedInput(); 336 }, 337 SSH_MSG_CHANNEL_EXTENDED_DATA => { 338 try discardChannelData(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, packet, true); 339 }, 340 SSH_MSG_CHANNEL_WINDOW_ADJUST => try handleWindowAdjust(self.channel, packet), 341 SSH_MSG_KEXINIT => { 342 try sendDisconnect(self.io, self.allocator, self.sc_cipher, self.writer, "rekey is not supported"); 343 return error.RekeyUnsupported; 344 }, 345 SSH_MSG_CHANNEL_REQUEST => { 346 var r = std.Io.Reader.fixed(packet[1..]); 347 const recipient_channel = try r.takeInt(u32, .big); 348 if (recipient_channel != self.channel.local_id) return error.UnknownChannel; 349 const req_type = try takeStringField(self.allocator, &r, 64); 350 defer self.allocator.free(req_type); 351 const want_reply = (try r.takeByte()) != 0; 352 if (std.mem.eql(u8, req_type, "window-change")) { 353 const sz = try takePtySize(&r); 354 if (self.channel.pty != null) self.channel.pty = sz; 355 self.pending_resize = sz; 356 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, true); 357 } else { 358 // other mid-session channel requests aren't honored — fail them 359 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, false); 360 } 361 }, 362 SSH_MSG_CHANNEL_EOF, SSH_MSG_CHANNEL_CLOSE => { 363 try parseChannelId(packet, self.channel.local_id); 364 self.incoming_eof = true; 365 }, 366 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(self.io, self.allocator, self.sc_cipher, self.writer, packet), 367 else => {}, 368 } 369 } 370 371 fn maybeRefillRecvWindowForBufferedInput(self: *SessionCtx) !void { 372 if (self.incoming_buffer.items.len >= incoming_refill_threshold) return; 373 try maybeRefillRecvWindow(self.io, self.allocator, self.sc_cipher, self.writer, self.channel); 374 } 375 376 /// signal the consumer's exit status and tear the channel down. 377 pub fn exit(self: *SessionCtx, status: u32) !void { 378 if (self.closed) return; 379 self.closed = true; 380 381 // exit-status request (informational; client uses it as the 382 // command's exit code) 383 { 384 var req: std.ArrayList(u8) = .empty; 385 defer req.deinit(self.allocator); 386 try req.append(self.allocator, SSH_MSG_CHANNEL_REQUEST); 387 try writeU32(&req, self.allocator, self.channel.remote_id); 388 try writeStringField(&req, self.allocator, "exit-status"); 389 try req.append(self.allocator, 0); // want_reply MUST be false 390 try writeU32(&req, self.allocator, status); 391 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, req.items); 392 } 393 394 // EOF then CLOSE 395 var eof: std.ArrayList(u8) = .empty; 396 defer eof.deinit(self.allocator); 397 try eof.append(self.allocator, SSH_MSG_CHANNEL_EOF); 398 try writeU32(&eof, self.allocator, self.channel.remote_id); 399 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, eof.items); 400 401 var close: std.ArrayList(u8) = .empty; 402 defer close.deinit(self.allocator); 403 try close.append(self.allocator, SSH_MSG_CHANNEL_CLOSE); 404 try writeU32(&close, self.allocator, self.channel.remote_id); 405 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, close.items); 406 407 // read and discard until the peer closes (TCP FIN) before letting the 408 // caller close the socket. a git client, after our CHANNEL_CLOSE, still 409 // sends its own CHANNEL_CLOSE and SSH_MSG_DISCONNECT before closing; if 410 // we close with those unread, Linux sends RST instead of FIN, which the 411 // client reports as "Connection reset by peer" and treats as a failed 412 // push even though the ref updated. draining to EOF leaves nothing 413 // unread, so we send a clean FIN. we're tearing down, so the packet 414 // contents don't matter — just get them off the socket. 415 var drain_packets: u32 = 0; 416 while (drain_packets < max_exit_drain_packets) : (drain_packets += 1) { 417 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch break; 418 self.allocator.free(packet); 419 } 420 } 421 }; 422 423 /// std.Io.Writer adapter that ships bytes to a SessionCtx as CHANNEL_DATA. 424 /// useful for plugging the session into anything that wants a *std.Io.Writer 425 /// (e.g. xitui.StreamTerminal). 426 pub const SessionWriter = struct { 427 interface: std.Io.Writer, 428 sess: *SessionCtx, 429 430 pub fn init(sess: *SessionCtx, buffer: []u8) SessionWriter { 431 return .{ 432 .interface = .{ 433 .vtable = &.{ .drain = drain }, 434 .buffer = buffer, 435 }, 436 .sess = sess, 437 }; 438 } 439 440 fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { 441 const self: *SessionWriter = @fieldParentPtr("interface", w); 442 443 // first ship anything already accumulated in the Writer's buffer 444 const buffered = w.buffered(); 445 if (buffered.len > 0) { 446 self.sess.writeBytes(buffered) catch return error.WriteFailed; 447 } 448 449 // then ship the bytes passed in directly. data[0..len-1] are written 450 // once each; data[len-1] is written `splat` times (this is how the 451 // Writer interface represents fan-out / repeated patterns). 452 var extra: usize = 0; 453 if (data.len > 1) { 454 for (data[0 .. data.len - 1]) |chunk| { 455 if (chunk.len == 0) continue; 456 self.sess.writeBytes(chunk) catch return error.WriteFailed; 457 extra += chunk.len; 458 } 459 } 460 if (data.len > 0) { 461 const pattern = data[data.len - 1]; 462 if (pattern.len > 0) { 463 var i: usize = 0; 464 while (i < splat) : (i += 1) { 465 self.sess.writeBytes(pattern) catch return error.WriteFailed; 466 extra += pattern.len; 467 } 468 } 469 } 470 471 // consume tells the Writer how many bytes (buffered + data) were 472 // processed and clears w.end. it returns the count attributed to 473 // data, which is what `write` propagates back to the caller. 474 return w.consume(buffered.len + extra); 475 } 476 }; 477 478 /// std.Io.Reader adapter that drains incoming CHANNEL_DATA from a SessionCtx. 479 /// when the consumer reads beyond what's buffered, runs the SSH packet loop 480 /// (via processOneBackgroundPacket) until more bytes arrive or the peer 481 /// closes the channel. 482 pub const SessionReader = struct { 483 interface: std.Io.Reader, 484 sess: *SessionCtx, 485 486 pub fn init(sess: *SessionCtx, buffer: []u8) SessionReader { 487 return .{ 488 .interface = .{ 489 .vtable = &.{ 490 .readVec = readVec, 491 .stream = stream, 492 }, 493 .buffer = buffer, 494 .seek = 0, 495 .end = 0, 496 }, 497 .sess = sess, 498 }; 499 } 500 501 fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { 502 const self: *SessionReader = @fieldParentPtr("interface", r); 503 504 // wait for data to arrive (or EOF) 505 while (self.sess.incoming_buffer.items.len == 0) { 506 if (self.sess.incoming_eof) return error.EndOfStream; 507 self.sess.processOneBackgroundPacket() catch return error.ReadFailed; 508 } 509 510 // drain as much of incoming_buffer as the limit allows, in one go 511 const chunk = limit.sliceConst(self.sess.incoming_buffer.items); 512 const written = try w.write(chunk); 513 514 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, self.sess.incoming_buffer.items[written..]); 515 self.sess.incoming_buffer.shrinkRetainingCapacity(self.sess.incoming_buffer.items.len - written); 516 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 517 518 return written; 519 } 520 521 fn readVec(r: *std.Io.Reader, data: [][]u8) std.Io.Reader.Error!usize { 522 const self: *SessionReader = @fieldParentPtr("interface", r); 523 524 // wait until something is in incoming_buffer (or EOF) 525 while (self.sess.incoming_buffer.items.len == 0) { 526 if (self.sess.incoming_eof) return error.EndOfStream; 527 self.sess.processOneBackgroundPacket() catch return error.ReadFailed; 528 } 529 530 const src = self.sess.incoming_buffer.items; 531 532 // vtable.readVec contract: if data[0] is empty, write into r.buffer 533 // instead and return 0. without this branch the caller spins, 534 // calling readVec repeatedly with the same empty buffer. 535 if (data.len == 0 or data[0].len == 0) { 536 const dest = r.buffer[r.end..]; 537 if (dest.len == 0) return 0; 538 const copy = @min(dest.len, src.len); 539 @memcpy(dest[0..copy], src[0..copy]); 540 r.end += copy; 541 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, src[copy..]); 542 self.sess.incoming_buffer.shrinkRetainingCapacity(src.len - copy); 543 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 544 return 0; 545 } 546 547 const dest = data[0]; 548 const copy = @min(dest.len, src.len); 549 @memcpy(dest[0..copy], src[0..copy]); 550 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, src[copy..]); 551 self.sess.incoming_buffer.shrinkRetainingCapacity(src.len - copy); 552 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 553 return copy; 554 } 555 }; 556 557 // --------------------------------------------------------------------------- 558 // public entry point 559 // --------------------------------------------------------------------------- 560 561 /// `handler` must be a pointer to a struct with a method: 562 /// pub fn handleSession(self, sess: *SessionCtx, request: Request) anyerror!void 563 /// invoked once the channel is open and a shell/exec request has arrived. 564 /// 565 /// `reader` and `writer` are the bidirectional byte stream 566 pub fn handleConnection( 567 io: std.Io, 568 allocator: std.mem.Allocator, 569 reader: *std.Io.Reader, 570 writer: *std.Io.Writer, 571 host_key: *const HostKey, 572 handler: anytype, 573 ) !void { 574 const client_version = try exchangeVersions(allocator, reader, writer); 575 defer allocator.free(client_version); 576 577 const kex = try runKex(io, allocator, reader, writer, host_key, client_version); 578 579 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com. 580 // both sides started counting packet seqnos at 0. we sent exactly 581 // KEXINIT, KEX_ECDH_REPLY and NEWKEYS, so our first encrypted packet 582 // uses seqno 3; the client's count includes any skipped IGNORE/DEBUG. 583 var cs_cipher = Cipher.init(&kex.cs_key, kex.next_cs_seq); 584 var sc_cipher = Cipher.init(&kex.sc_key, 3); 585 586 const fingerprint = try runAuth(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &kex.session_id); 587 588 try runChannelLayer(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &fingerprint, handler); 589 } 590 591 // --------------------------------------------------------------------------- 592 // version exchange (RFC 4253 §4.2) 593 // --------------------------------------------------------------------------- 594 595 fn exchangeVersions( 596 allocator: std.mem.Allocator, 597 reader: *std.Io.Reader, 598 writer: *std.Io.Writer, 599 ) ![]u8 { 600 try writer.writeAll(server_version ++ "\r\n"); 601 try writer.flush(); 602 603 // the spec allows the client to send arbitrary comment lines before its 604 // banner; skip anything that isn't an "SSH-2.0-…" / "SSH-1.99-…" line. 605 while (true) { 606 const line = (try reader.takeDelimiter('\n')) orelse return error.UnexpectedEof; 607 const trimmed = if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; 608 if (std.mem.startsWith(u8, trimmed, "SSH-2.0-") or std.mem.startsWith(u8, trimmed, "SSH-1.99-")) { 609 return try allocator.dupe(u8, trimmed); 610 } 611 } 612 } 613 614 // --------------------------------------------------------------------------- 615 // binary packet codec, unencrypted form (RFC 4253 §6) 616 // --------------------------------------------------------------------------- 617 618 pub fn writePlainPacket(io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 619 const block: usize = 8; 620 const initial_pad = block - ((5 + payload.len) % block); 621 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 622 const packet_len: u32 = @intCast(1 + payload.len + padding_len); 623 624 try writer.writeInt(u32, packet_len, .big); 625 try writer.writeByte(padding_len); 626 try writer.writeAll(payload); 627 628 var padding: [255]u8 = undefined; 629 io.random(padding[0..padding_len]); 630 try writer.writeAll(padding[0..padding_len]); 631 try writer.flush(); 632 } 633 634 pub fn readPlainPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 635 const packet_len = try reader.takeInt(u32, .big); 636 if (packet_len < 8 or packet_len > max_packet_len) return error.InvalidPacketLength; 637 const padding_len = try reader.takeByte(); 638 if (padding_len < 4 or @as(u32, padding_len) + 1 > packet_len) return error.InvalidPadding; 639 const payload_len = packet_len - 1 - @as(u32, padding_len); 640 641 const payload = try reader.readAlloc(allocator, payload_len); 642 errdefer allocator.free(payload); 643 try reader.discardAll(padding_len); 644 return payload; 645 } 646 647 // IGNORE/DEBUG/UNIMPLEMENTED may arrive at any time (RFC 4253 §11); skip 648 // them wherever a specific message is expected 649 fn isIgnorableMsg(msg_type: u8) bool { 650 return msg_type == SSH_MSG_IGNORE or msg_type == SSH_MSG_UNIMPLEMENTED or msg_type == SSH_MSG_DEBUG; 651 } 652 653 // read a plaintext packet, skipping ignorable messages. counts every packet 654 // consumed in `seq` so the caller knows the peer's next sequence number. 655 fn readPlainKexPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader, seq: *u64) ![]u8 { 656 while (true) { 657 const packet = try readPlainPacket(allocator, reader); 658 seq.* += 1; 659 if (packet.len >= 1 and isIgnorableMsg(packet[0])) { 660 allocator.free(packet); 661 continue; 662 } 663 return packet; 664 } 665 } 666 667 // read an encrypted packet, skipping ignorable messages 668 fn readNonIgnoredPacket(cipher: *Cipher, allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 669 while (true) { 670 const packet = try cipher.readPacket(allocator, reader); 671 if (packet.len >= 1 and isIgnorableMsg(packet[0])) { 672 allocator.free(packet); 673 continue; 674 } 675 return packet; 676 } 677 } 678 679 // --------------------------------------------------------------------------- 680 // SSH field encoders / decoders (RFC 4251 §5) 681 // --------------------------------------------------------------------------- 682 683 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 684 var len_bytes: [4]u8 = undefined; 685 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 686 try buf.appendSlice(allocator, &len_bytes); 687 try buf.appendSlice(allocator, bytes); 688 } 689 690 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 691 var total: usize = 0; 692 for (names, 0..) |name, i| { 693 if (i > 0) total += 1; // comma separator 694 total += name.len; 695 } 696 var len_bytes: [4]u8 = undefined; 697 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 698 try buf.appendSlice(allocator, &len_bytes); 699 for (names, 0..) |name, i| { 700 if (i > 0) try buf.append(allocator, ','); 701 try buf.appendSlice(allocator, name); 702 } 703 } 704 705 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 706 /// our use (X25519 shared secret) the value is always non-negative, so we 707 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 708 /// the most-significant byte is set (to keep it parsed as positive). 709 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 710 var start: usize = 0; 711 while (start < bytes.len and bytes[start] == 0) start += 1; 712 const trimmed = bytes[start..]; 713 if (trimmed.len == 0) { 714 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 715 return; 716 } 717 const prepend = (trimmed[0] & 0x80) != 0; 718 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 719 var len_bytes: [4]u8 = undefined; 720 std.mem.writeInt(u32, &len_bytes, out_len, .big); 721 try buf.appendSlice(allocator, &len_bytes); 722 if (prepend) try buf.append(allocator, 0); 723 try buf.appendSlice(allocator, trimmed); 724 } 725 726 pub fn takeStringField(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_len: u32) ![]u8 { 727 const len = try reader.takeInt(u32, .big); 728 if (len > max_len) return error.FieldTooLarge; 729 return try reader.readAlloc(allocator, len); 730 } 731 732 fn nameListContainsAny(haystack: []const u8, our_options: []const []const u8) bool { 733 var iter = std.mem.splitScalar(u8, haystack, ','); 734 while (iter.next()) |name| { 735 for (our_options) |opt| { 736 if (std.mem.eql(u8, name, opt)) return true; 737 } 738 } 739 return false; 740 } 741 742 // --------------------------------------------------------------------------- 743 // KEXINIT (RFC 4253 §7.1) 744 // --------------------------------------------------------------------------- 745 746 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 747 748 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 749 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 750 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 751 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 752 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 753 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 754 const our_compression = [_][]const u8{"none"}; 755 756 /// Build a KEXINIT payload with the given algorithm name-lists 757 pub fn buildKexInit( 758 io: std.Io, 759 allocator: std.mem.Allocator, 760 kex_algos: []const []const u8, 761 host_key_algos: []const []const u8, 762 ciphers: []const []const u8, 763 ) ![]u8 { 764 var buf: std.ArrayList(u8) = .empty; 765 errdefer buf.deinit(allocator); 766 767 try buf.append(allocator, SSH_MSG_KEXINIT); 768 769 var cookie: [16]u8 = undefined; 770 io.random(&cookie); 771 try buf.appendSlice(allocator, &cookie); 772 773 try writeNameList(&buf, allocator, kex_algos); 774 try writeNameList(&buf, allocator, host_key_algos); 775 try writeNameList(&buf, allocator, ciphers); // c->s 776 try writeNameList(&buf, allocator, ciphers); // s->c 777 try writeNameList(&buf, allocator, &our_macs); 778 try writeNameList(&buf, allocator, &our_macs); 779 try writeNameList(&buf, allocator, &our_compression); 780 try writeNameList(&buf, allocator, &our_compression); 781 try writeNameList(&buf, allocator, &.{}); // langs c->s 782 try writeNameList(&buf, allocator, &.{}); // langs s->c 783 try buf.append(allocator, 0); // first_kex_packet_follows = false 784 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 785 786 return try buf.toOwnedSlice(allocator); 787 } 788 789 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 790 return buildKexInit(io, allocator, &our_kex_algos, &our_host_key_algos, &our_ciphers); 791 } 792 793 const ParsedKexInit = struct { 794 kex_algos: []u8, 795 host_key_algos: []u8, 796 cs_cipher: []u8, 797 sc_cipher: []u8, 798 799 fn deinit(self: ParsedKexInit, allocator: std.mem.Allocator) void { 800 allocator.free(self.kex_algos); 801 allocator.free(self.host_key_algos); 802 allocator.free(self.cs_cipher); 803 allocator.free(self.sc_cipher); 804 } 805 }; 806 807 fn parseClientKexInit(allocator: std.mem.Allocator, payload: []const u8) !ParsedKexInit { 808 if (payload.len < 1 + 16) return error.KexInitTruncated; 809 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 810 811 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 812 813 const kex_algos = try takeStringField(allocator, &reader, max_name_list_len); 814 errdefer allocator.free(kex_algos); 815 const host_key_algos = try takeStringField(allocator, &reader, max_name_list_len); 816 errdefer allocator.free(host_key_algos); 817 const cs_cipher = try takeStringField(allocator, &reader, max_name_list_len); 818 errdefer allocator.free(cs_cipher); 819 const sc_cipher = try takeStringField(allocator, &reader, max_name_list_len); 820 errdefer allocator.free(sc_cipher); 821 822 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 823 for (0..6) |_| { 824 const len = try reader.takeInt(u32, .big); 825 if (len > max_name_list_len) return error.FieldTooLarge; 826 try reader.discardAll(len); 827 } 828 _ = try reader.takeByte(); // first_kex_packet_follows 829 _ = try reader.takeInt(u32, .big); // reserved 830 831 return .{ 832 .kex_algos = kex_algos, 833 .host_key_algos = host_key_algos, 834 .cs_cipher = cs_cipher, 835 .sc_cipher = sc_cipher, 836 }; 837 } 838 839 // --------------------------------------------------------------------------- 840 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 841 // --------------------------------------------------------------------------- 842 843 const KexResult = struct { 844 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 845 sc_key: [64]u8, // server → client cipher key material 846 session_id: [Sha256.digest_length]u8, 847 next_cs_seq: u64, // packets the client has sent, including skipped ones 848 }; 849 850 fn runKex( 851 io: std.Io, 852 allocator: std.mem.Allocator, 853 reader: *std.Io.Reader, 854 writer: *std.Io.Writer, 855 host_key: *const HostKey, 856 client_version: []const u8, 857 ) !KexResult { 858 var client_seq: u64 = 0; 859 860 // exchange KEXINITs 861 const server_kex_init = try buildServerKexInit(io, allocator); 862 defer allocator.free(server_kex_init); 863 try writePlainPacket(io, writer, server_kex_init); 864 865 const client_kex_init = try readPlainKexPacket(allocator, reader, &client_seq); 866 defer allocator.free(client_kex_init); 867 868 var parsed = try parseClientKexInit(allocator, client_kex_init); 869 defer parsed.deinit(allocator); 870 871 // pick the first kex algo in the client's preference list that we also 872 // support (RFC 4253 §7.1.3). 873 const kex_algo = blk: { 874 var iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 875 while (iter.next()) |name| { 876 for (our_kex_algos) |opt| { 877 if (std.mem.eql(u8, name, opt)) break :blk opt; 878 } 879 } 880 return error.NoCommonKexAlgorithm; 881 }; 882 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 883 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 884 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 885 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 886 887 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 888 // wire shape, only the string size differs). 889 const ecdh_init = try readPlainKexPacket(allocator, reader, &client_seq); 890 defer allocator.free(ecdh_init); 891 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 892 893 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 894 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 895 const client_blob = try takeStringField(allocator, &ecdh_init_reader, expected_client_len); 896 defer allocator.free(client_blob); 897 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 898 899 // derive server reply blob (S_REPLY) + shared secret K. 900 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 901 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 902 // K = SHA-256(K_MLKEM || K_X25519). 903 var server_blob: []u8 = undefined; 904 var k: []u8 = undefined; 905 { 906 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 907 var x25519_client_pub: [X25519.public_length]u8 = undefined; 908 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 909 const server_kp = X25519.KeyPair.generate(io); 910 const x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 911 912 if (hybrid) { 913 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 914 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 915 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 916 const encap = pq_pub.encaps(io); 917 918 server_blob = try allocator.alloc(u8, hybrid_server_blob_len); 919 @memcpy(server_blob[0..MLKem768.ciphertext_length], &encap.ciphertext); 920 @memcpy(server_blob[MLKem768.ciphertext_length..], &server_kp.public_key); 921 922 var h = Sha256.init(.{}); 923 h.update(&encap.shared_secret); 924 h.update(&x25519_shared); 925 k = try allocator.dupe(u8, &h.finalResult()); 926 } else { 927 server_blob = try allocator.dupe(u8, &server_kp.public_key); 928 k = try allocator.dupe(u8, &x25519_shared); 929 } 930 } 931 defer allocator.free(server_blob); 932 defer allocator.free(k); 933 934 // build host key blob (K_S) 935 var host_key_blob: std.ArrayList(u8) = .empty; 936 defer host_key_blob.deinit(allocator); 937 try host_key.appendPublicBlob(&host_key_blob, allocator); 938 939 // build exchange hash input and compute H 940 const exchange_hash = try computeExchangeHash( 941 allocator, 942 client_version, 943 server_version, 944 client_kex_init, 945 server_kex_init, 946 host_key_blob.items, 947 client_blob, 948 server_blob, 949 k, 950 hybrid, 951 ); 952 953 // sign H with the host key, format as ssh signature blob 954 var signature_blob: std.ArrayList(u8) = .empty; 955 defer signature_blob.deinit(allocator); 956 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 957 958 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 959 var reply: std.ArrayList(u8) = .empty; 960 defer reply.deinit(allocator); 961 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 962 try writeStringField(&reply, allocator, host_key_blob.items); 963 try writeStringField(&reply, allocator, server_blob); 964 try writeStringField(&reply, allocator, signature_blob.items); 965 try writePlainPacket(io, writer, reply.items); 966 967 // NEWKEYS — both sides switch to encrypted mode after this is sent and 968 // the peer's NEWKEYS is received. 969 try writePlainPacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 970 971 const peer_newkeys = try readPlainKexPacket(allocator, reader, &client_seq); 972 defer allocator.free(peer_newkeys); 973 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 974 975 // derive session keys per RFC 4253 §7.2. session_id == H for the first 976 // KEX. only the encrypt keys are needed for chacha20-poly1305 (no 977 // separate MAC/IV). 978 var keys: SessionKeys = undefined; 979 try deriveSessionKeys(allocator, k, &exchange_hash, &exchange_hash, &keys, hybrid); 980 981 return .{ 982 .cs_key = keys.cs_enc, 983 .sc_key = keys.sc_enc, 984 .session_id = exchange_hash, 985 .next_cs_seq = client_seq, 986 }; 987 } 988 989 // --------------------------------------------------------------------------- 990 // exchange hash (RFC 4253 §8, RFC 5656 §4) 991 // --------------------------------------------------------------------------- 992 993 pub fn computeExchangeHash( 994 allocator: std.mem.Allocator, 995 client_version: []const u8, 996 server_version_str: []const u8, 997 client_kex_init: []const u8, 998 server_kex_init: []const u8, 999 host_key_blob: []const u8, 1000 client_ephemeral: []const u8, 1001 server_ephemeral: []const u8, 1002 shared_secret: []const u8, 1003 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1004 /// as a plain SSH string (length-prefixed bytes). 1005 k_is_string: bool, 1006 ) ![Sha256.digest_length]u8 { 1007 var buf: std.ArrayList(u8) = .empty; 1008 defer buf.deinit(allocator); 1009 1010 try writeStringField(&buf, allocator, client_version); 1011 try writeStringField(&buf, allocator, server_version_str); 1012 try writeStringField(&buf, allocator, client_kex_init); 1013 try writeStringField(&buf, allocator, server_kex_init); 1014 try writeStringField(&buf, allocator, host_key_blob); 1015 try writeStringField(&buf, allocator, client_ephemeral); 1016 try writeStringField(&buf, allocator, server_ephemeral); 1017 if (k_is_string) { 1018 try writeStringField(&buf, allocator, shared_secret); 1019 } else { 1020 try writeMpint(&buf, allocator, shared_secret); 1021 } 1022 1023 var hasher = Sha256.init(.{}); 1024 hasher.update(buf.items); 1025 return hasher.finalResult(); 1026 } 1027 1028 // --------------------------------------------------------------------------- 1029 // key derivation (RFC 4253 §7.2) 1030 // --------------------------------------------------------------------------- 1031 1032 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1033 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1034 // blocks chained per RFC 4253. 1035 pub const SessionKeys = struct { 1036 cs_enc: [64]u8, 1037 sc_enc: [64]u8, 1038 }; 1039 1040 pub fn deriveSessionKeys( 1041 allocator: std.mem.Allocator, 1042 shared_secret: []const u8, 1043 exchange_hash: []const u8, 1044 session_id: []const u8, 1045 out: *SessionKeys, 1046 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1047 k_is_string: bool, 1048 ) !void { 1049 // pre-build the K || H prefix once; reused for every derivation 1050 var prefix: std.ArrayList(u8) = .empty; 1051 defer prefix.deinit(allocator); 1052 if (k_is_string) { 1053 try writeStringField(&prefix, allocator, shared_secret); 1054 } else { 1055 try writeMpint(&prefix, allocator, shared_secret); 1056 } 1057 try prefix.appendSlice(allocator, exchange_hash); 1058 1059 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 1060 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 1061 } 1062 1063 fn deriveKey( 1064 allocator: std.mem.Allocator, 1065 prefix: []const u8, // K || H, already encoded 1066 letter: u8, 1067 session_id: []const u8, 1068 out: []u8, 1069 ) !void { 1070 // first block: HASH(K || H || letter || session_id) 1071 var first_block: [Sha256.digest_length]u8 = undefined; 1072 { 1073 var hasher = Sha256.init(.{}); 1074 hasher.update(prefix); 1075 hasher.update(&[_]u8{letter}); 1076 hasher.update(session_id); 1077 first_block = hasher.finalResult(); 1078 } 1079 const first_copy = @min(out.len, first_block.len); 1080 @memcpy(out[0..first_copy], first_block[0..first_copy]); 1081 1082 // chain additional blocks if requested length exceeds one hash: 1083 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 1084 var chained: std.ArrayList(u8) = .empty; 1085 defer chained.deinit(allocator); 1086 try chained.appendSlice(allocator, first_block[0..]); 1087 1088 var produced: usize = first_copy; 1089 while (produced < out.len) { 1090 var hasher = Sha256.init(.{}); 1091 hasher.update(prefix); 1092 hasher.update(chained.items); 1093 const block = hasher.finalResult(); 1094 const copy_len = @min(out.len - produced, block.len); 1095 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 1096 produced += copy_len; 1097 try chained.appendSlice(allocator, block[0..]); 1098 } 1099 } 1100 1101 // --------------------------------------------------------------------------- 1102 // chacha20-poly1305@openssh.com packet codec 1103 // --------------------------------------------------------------------------- 1104 // 1105 // per openssh's PROTOCOL.chacha20poly1305: 1106 // K_2 = first 32 bytes of key material — encrypts the packet body 1107 // K_1 = next 32 bytes — encrypts the 4-byte length field 1108 // nonce = 64-bit big-endian sequence number 1109 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1110 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1111 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1112 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1113 // 1114 // padding is computed on the body alone (padding_length byte + payload + 1115 // padding) — the 4-byte length field is excluded from alignment. body must 1116 // be a multiple of 8 bytes; minimum padding 4 bytes. 1117 1118 pub const Cipher = struct { 1119 main_key: [32]u8, // K_2 1120 header_key: [32]u8, // K_1 1121 seq: u64, 1122 1123 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1124 return .{ 1125 .main_key = key_material[0..32].*, 1126 .header_key = key_material[32..64].*, 1127 .seq = initial_seq, 1128 }; 1129 } 1130 1131 fn makeNonce(seq: u64) [8]u8 { 1132 var nonce: [8]u8 = undefined; 1133 std.mem.writeInt(u64, &nonce, seq, .big); 1134 return nonce; 1135 } 1136 1137 pub fn writePacket( 1138 self: *Cipher, 1139 io: std.Io, 1140 allocator: std.mem.Allocator, 1141 writer: *std.Io.Writer, 1142 payload: []const u8, 1143 ) !void { 1144 const block: usize = 8; 1145 const initial_pad = block - ((1 + payload.len) % block); 1146 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1147 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1148 1149 const nonce = makeNonce(self.seq); 1150 1151 // plaintext body = padding_length || payload || random padding 1152 const body = try allocator.alloc(u8, body_len); 1153 defer allocator.free(body); 1154 body[0] = padding_len; 1155 @memcpy(body[1 .. 1 + payload.len], payload); 1156 io.random(body[1 + payload.len ..]); 1157 1158 // encrypt body in place with counter=1 1159 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1160 1161 // encrypt length field with header key, counter=0 1162 var enc_length: [4]u8 = undefined; 1163 var length_plain: [4]u8 = undefined; 1164 std.mem.writeInt(u32, &length_plain, body_len, .big); 1165 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1166 1167 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1168 var poly_key: [Poly1305.key_length]u8 = undefined; 1169 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1170 1171 // mac over encrypted_length || encrypted_body 1172 var poly = Poly1305.init(&poly_key); 1173 poly.update(&enc_length); 1174 poly.update(body); 1175 var tag: [Poly1305.mac_length]u8 = undefined; 1176 poly.final(&tag); 1177 1178 try writer.writeAll(&enc_length); 1179 try writer.writeAll(body); 1180 try writer.writeAll(&tag); 1181 try writer.flush(); 1182 1183 self.seq += 1; 1184 } 1185 1186 pub fn readPacket( 1187 self: *Cipher, 1188 allocator: std.mem.Allocator, 1189 reader: *std.Io.Reader, 1190 ) ![]u8 { 1191 const nonce = makeNonce(self.seq); 1192 1193 var enc_length: [4]u8 = undefined; 1194 try reader.readSliceAll(&enc_length); 1195 1196 var length_plain: [4]u8 = undefined; 1197 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1198 const body_len = std.mem.readInt(u32, &length_plain, .big); 1199 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1200 1201 const enc_body = try allocator.alloc(u8, body_len); 1202 defer allocator.free(enc_body); 1203 try reader.readSliceAll(enc_body); 1204 1205 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1206 try reader.readSliceAll(&tag_recv); 1207 1208 var poly_key: [Poly1305.key_length]u8 = undefined; 1209 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1210 1211 var poly = Poly1305.init(&poly_key); 1212 poly.update(&enc_length); 1213 poly.update(enc_body); 1214 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1215 poly.final(&tag_computed); 1216 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1217 return error.MacVerificationFailed; 1218 } 1219 1220 // decrypt the body in place, then copy out the payload (caller owns) 1221 ChaCha20.xor(enc_body, enc_body, 1, self.main_key, nonce); 1222 1223 const padding_len = enc_body[0]; 1224 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1225 const payload_len = body_len - 1 - @as(u32, padding_len); 1226 1227 const payload = try allocator.dupe(u8, enc_body[1 .. 1 + payload_len]); 1228 1229 self.seq += 1; 1230 return payload; 1231 } 1232 }; 1233 1234 // --------------------------------------------------------------------------- 1235 // post-KEX: service request + user authentication (RFC 4252) 1236 // --------------------------------------------------------------------------- 1237 1238 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1239 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1240 /// `Offering public key: … SHA256:…`. 1241 pub const fingerprint_len = 50; 1242 1243 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1244 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1245 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1246 var digest: [Sha256.digest_length]u8 = undefined; 1247 Sha256.hash(pubkey_blob, &digest, .{}); 1248 1249 var out: [fingerprint_len]u8 = undefined; 1250 @memcpy(out[0..7], "SHA256:"); 1251 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1252 std.debug.assert(encoded.len == fingerprint_len - 7); 1253 return out; 1254 } 1255 1256 fn runAuth( 1257 io: std.Io, 1258 allocator: std.mem.Allocator, 1259 reader: *std.Io.Reader, 1260 writer: *std.Io.Writer, 1261 cs_cipher: *Cipher, 1262 sc_cipher: *Cipher, 1263 session_id: *const [Sha256.digest_length]u8, 1264 ) ![fingerprint_len]u8 { 1265 // step 1: service request for ssh-userauth → service accept 1266 { 1267 const req = try readNonIgnoredPacket(cs_cipher, allocator, reader); 1268 defer allocator.free(req); 1269 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1270 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1271 return error.RekeyUnsupported; 1272 } 1273 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1274 1275 var req_reader = std.Io.Reader.fixed(req[1..]); 1276 const service = try takeStringField(allocator, &req_reader, 64); 1277 defer allocator.free(service); 1278 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1279 1280 var accept: std.ArrayList(u8) = .empty; 1281 defer accept.deinit(allocator); 1282 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1283 try writeStringField(&accept, allocator, "ssh-userauth"); 1284 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1285 } 1286 1287 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1288 // signature verifies against the offered pubkey. 1289 var auth_attempts: u32 = 0; 1290 while (true) { 1291 const req = try readNonIgnoredPacket(cs_cipher, allocator, reader); 1292 defer allocator.free(req); 1293 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1294 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1295 return error.RekeyUnsupported; 1296 } 1297 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1298 1299 var req_reader = std.Io.Reader.fixed(req[1..]); 1300 const user_name = try takeStringField(allocator, &req_reader, 256); 1301 defer allocator.free(user_name); 1302 const service_name = try takeStringField(allocator, &req_reader, 64); 1303 defer allocator.free(service_name); 1304 const method = try takeStringField(allocator, &req_reader, 64); 1305 defer allocator.free(method); 1306 1307 if (!std.mem.eql(u8, method, "publickey")) { 1308 auth_attempts += 1; 1309 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1310 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1311 continue; 1312 } 1313 1314 const has_signature = (try req_reader.takeByte()) != 0; 1315 const algo = try takeStringField(allocator, &req_reader, 64); 1316 defer allocator.free(algo); 1317 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1318 defer allocator.free(pubkey_blob); 1319 1320 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1321 auth_attempts += 1; 1322 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1323 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1324 continue; 1325 } 1326 1327 if (!has_signature) { 1328 // probes count as attempts so a client can't loop here forever 1329 auth_attempts += 1; 1330 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1331 // probe — tell the client this key is acceptable so it'll send 1332 // the signed version next. 1333 var pk_ok: std.ArrayList(u8) = .empty; 1334 defer pk_ok.deinit(allocator); 1335 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1336 try writeStringField(&pk_ok, allocator, algo); 1337 try writeStringField(&pk_ok, allocator, pubkey_blob); 1338 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1339 continue; 1340 } 1341 1342 // has signature — verify it 1343 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1344 defer allocator.free(signature_blob); 1345 1346 const ok = verifyUserauthSignature( 1347 allocator, 1348 session_id, 1349 user_name, 1350 service_name, 1351 algo, 1352 pubkey_blob, 1353 signature_blob, 1354 ) catch false; 1355 1356 if (!ok) { 1357 auth_attempts += 1; 1358 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1359 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1360 continue; 1361 } 1362 1363 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1364 return formatFingerprint(pubkey_blob); 1365 } 1366 } 1367 1368 fn sendUserauthFailure( 1369 io: std.Io, 1370 allocator: std.mem.Allocator, 1371 sc_cipher: *Cipher, 1372 writer: *std.Io.Writer, 1373 ) !void { 1374 var buf: std.ArrayList(u8) = .empty; 1375 defer buf.deinit(allocator); 1376 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1377 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1378 try buf.append(allocator, 0); // partial_success = false 1379 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1380 } 1381 1382 fn sendDisconnect( 1383 io: std.Io, 1384 allocator: std.mem.Allocator, 1385 sc_cipher: *Cipher, 1386 writer: *std.Io.Writer, 1387 description: []const u8, 1388 ) !void { 1389 var buf: std.ArrayList(u8) = .empty; 1390 defer buf.deinit(allocator); 1391 try buf.append(allocator, SSH_MSG_DISCONNECT); 1392 try writeU32(&buf, allocator, SSH_DISCONNECT_PROTOCOL_ERROR); 1393 try writeStringField(&buf, allocator, description); 1394 try writeStringField(&buf, allocator, ""); 1395 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1396 } 1397 1398 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1399 /// Used by the server to recompute the signed input for verification 1400 pub fn appendPublickeySignedData( 1401 buf: *std.ArrayList(u8), 1402 allocator: std.mem.Allocator, 1403 session_id: []const u8, 1404 user_name: []const u8, 1405 service_name: []const u8, 1406 algo: []const u8, 1407 pubkey_blob: []const u8, 1408 ) !void { 1409 try writeStringField(buf, allocator, session_id); 1410 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1411 try writeStringField(buf, allocator, user_name); 1412 try writeStringField(buf, allocator, service_name); 1413 try writeStringField(buf, allocator, "publickey"); 1414 try buf.append(allocator, 1); 1415 try writeStringField(buf, allocator, algo); 1416 try writeStringField(buf, allocator, pubkey_blob); 1417 } 1418 1419 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1420 // verify the supplied signature against them. 1421 fn verifyUserauthSignature( 1422 allocator: std.mem.Allocator, 1423 session_id: *const [Sha256.digest_length]u8, 1424 user_name: []const u8, 1425 service_name: []const u8, 1426 algo: []const u8, 1427 pubkey_blob: []const u8, 1428 signature_blob: []const u8, 1429 ) !bool { 1430 var signed: std.ArrayList(u8) = .empty; 1431 defer signed.deinit(allocator); 1432 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1433 1434 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1435 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1436 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1437 defer allocator.free(pk_algo); 1438 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1439 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1440 defer allocator.free(raw_pubkey); 1441 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1442 1443 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1444 var sig_reader = std.Io.Reader.fixed(signature_blob); 1445 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1446 defer allocator.free(sig_algo); 1447 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1448 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1449 defer allocator.free(raw_sig); 1450 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1451 1452 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1453 @memcpy(&pubkey_bytes, raw_pubkey); 1454 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1455 @memcpy(&sig_bytes, raw_sig); 1456 1457 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1458 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1459 sig.verify(signed.items, pk) catch return false; 1460 return true; 1461 } 1462 1463 // --------------------------------------------------------------------------- 1464 // connection layer (RFC 4254): channels, requests, data, flow control 1465 // --------------------------------------------------------------------------- 1466 1467 const Channel = struct { 1468 local_id: u32, 1469 remote_id: u32, 1470 local_window: u32, // bytes peer may still send us before we adjust 1471 remote_window: u32, // bytes we may still send to peer before they adjust 1472 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1473 pty: ?PtySize = null, 1474 }; 1475 1476 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1477 1478 // take the uint32 width/height cell counts of a pty-req or window-change, 1479 // clamped to u16 1480 fn takePtySize(r: *std.Io.Reader) !PtySize { 1481 const width = try r.takeInt(u32, .big); 1482 const height = try r.takeInt(u32, .big); 1483 return .{ 1484 .width_cells = @intCast(@min(width, 0xFFFF)), 1485 .height_cells = @intCast(@min(height, 0xFFFF)), 1486 }; 1487 } 1488 1489 fn runChannelLayer( 1490 io: std.Io, 1491 allocator: std.mem.Allocator, 1492 reader: *std.Io.Reader, 1493 writer: *std.Io.Writer, 1494 cs_cipher: *Cipher, 1495 sc_cipher: *Cipher, 1496 fingerprint: *const [fingerprint_len]u8, 1497 handler: anytype, 1498 ) !void { 1499 var channel: ?Channel = null; 1500 var pending_exec: ?[]u8 = null; 1501 defer if (pending_exec) |s| allocator.free(s); 1502 1503 while (true) { 1504 const packet = try cs_cipher.readPacket(allocator, reader); 1505 defer allocator.free(packet); 1506 if (packet.len < 1) return error.EmptyPacket; 1507 const msg_type = packet[0]; 1508 1509 switch (msg_type) { 1510 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1511 1512 SSH_MSG_KEXINIT => { 1513 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1514 return error.RekeyUnsupported; 1515 }, 1516 1517 SSH_MSG_CHANNEL_OPEN => { 1518 if (channel != null) { 1519 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1520 continue; 1521 } 1522 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1523 }, 1524 1525 SSH_MSG_CHANNEL_REQUEST => { 1526 const ch = if (channel) |*c| c else continue; 1527 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1528 if (start_request) |req_kind| { 1529 const request: Request = switch (req_kind) { 1530 .shell => .{ .shell = ch.pty }, 1531 .exec => .{ .exec = pending_exec.? }, 1532 }; 1533 var sess = SessionCtx{ 1534 .io = io, 1535 .allocator = allocator, 1536 .reader = reader, 1537 .writer = writer, 1538 .cs_cipher = cs_cipher, 1539 .sc_cipher = sc_cipher, 1540 .channel = ch, 1541 .fingerprint = fingerprint.*, 1542 }; 1543 defer sess.deinit(); 1544 handler.handleSession(&sess, request) catch |session_err| { 1545 // try to send a non-zero exit status before closing 1546 sess.exit(1) catch {}; 1547 return session_err; 1548 }; 1549 if (!sess.closed) try sess.exit(0); 1550 return; 1551 } 1552 }, 1553 1554 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1555 const ch = if (channel) |*c| c else continue; 1556 try handleWindowAdjust(ch, packet); 1557 }, 1558 1559 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1560 const ch = if (channel) |*c| c else continue; 1561 // before shell/exec the client shouldn't be sending data, but 1562 // some clients are chatty; discard and refill window. 1563 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1564 }, 1565 1566 SSH_MSG_CHANNEL_EOF => { 1567 if (channel) |*c| try parseChannelId(packet, c.local_id); 1568 }, 1569 1570 SSH_MSG_CHANNEL_CLOSE => { 1571 if (channel) |*c| try parseChannelId(packet, c.local_id); 1572 return; 1573 }, 1574 1575 else => {}, // ignore unknown messages 1576 } 1577 } 1578 } 1579 1580 fn handleGlobalRequest( 1581 io: std.Io, 1582 allocator: std.mem.Allocator, 1583 sc_cipher: *Cipher, 1584 writer: *std.Io.Writer, 1585 packet: []const u8, 1586 ) !void { 1587 // byte SSH_MSG_GLOBAL_REQUEST 1588 // string request_name 1589 // boolean want_reply 1590 // …request-specific data we ignore 1591 var r = std.Io.Reader.fixed(packet[1..]); 1592 const name = try takeStringField(allocator, &r, 256); 1593 defer allocator.free(name); 1594 const want_reply = (try r.takeByte()) != 0; 1595 if (want_reply) { 1596 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1597 } 1598 } 1599 1600 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1601 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1602 /// return null. 1603 fn handleChannelOpen( 1604 io: std.Io, 1605 allocator: std.mem.Allocator, 1606 sc_cipher: *Cipher, 1607 writer: *std.Io.Writer, 1608 packet: []const u8, 1609 ) !?Channel { 1610 // byte SSH_MSG_CHANNEL_OPEN 1611 // string channel_type 1612 // uint32 sender_channel (peer's id) 1613 // uint32 initial_window 1614 // uint32 max_packet 1615 var r = std.Io.Reader.fixed(packet[1..]); 1616 const ch_type = try takeStringField(allocator, &r, 64); 1617 defer allocator.free(ch_type); 1618 const remote_id = try r.takeInt(u32, .big); 1619 const initial_window = try r.takeInt(u32, .big); 1620 const max_packet = try r.takeInt(u32, .big); 1621 1622 if (!std.mem.eql(u8, ch_type, "session")) { 1623 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1624 return null; 1625 } 1626 1627 // a zero max_packet would leave writeChannel looping without progress 1628 if (max_packet == 0) { 1629 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1630 return null; 1631 } 1632 1633 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1634 var reply: std.ArrayList(u8) = .empty; 1635 defer reply.deinit(allocator); 1636 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1637 try writeU32(&reply, allocator, remote_id); 1638 try writeU32(&reply, allocator, local_id); 1639 try writeU32(&reply, allocator, initial_recv_window); 1640 try writeU32(&reply, allocator, max_packet_size); 1641 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1642 1643 return .{ 1644 .local_id = local_id, 1645 .remote_id = remote_id, 1646 .local_window = initial_recv_window, 1647 .remote_window = initial_window, 1648 .max_packet = max_packet, 1649 }; 1650 } 1651 1652 fn sendChannelOpenFailure( 1653 io: std.Io, 1654 allocator: std.mem.Allocator, 1655 sc_cipher: *Cipher, 1656 writer: *std.Io.Writer, 1657 open_packet: []const u8, 1658 reason: u32, 1659 description: []const u8, 1660 ) !void { 1661 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1662 // address the failure to the correct id 1663 var r = std.Io.Reader.fixed(open_packet[1..]); 1664 const ch_type_len = try r.takeInt(u32, .big); 1665 try r.discardAll(ch_type_len); 1666 const remote_id = try r.takeInt(u32, .big); 1667 1668 var reply: std.ArrayList(u8) = .empty; 1669 defer reply.deinit(allocator); 1670 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1671 try writeU32(&reply, allocator, remote_id); 1672 try writeU32(&reply, allocator, reason); 1673 try writeStringField(&reply, allocator, description); 1674 try writeStringField(&reply, allocator, ""); // language tag 1675 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1676 } 1677 1678 const RequestKind = enum { shell, exec }; 1679 1680 /// Returns the kind of session request if this triggered one, else null. 1681 fn handleChannelRequest( 1682 io: std.Io, 1683 allocator: std.mem.Allocator, 1684 sc_cipher: *Cipher, 1685 writer: *std.Io.Writer, 1686 ch: *Channel, 1687 packet: []const u8, 1688 pending_exec: *?[]u8, 1689 ) !?RequestKind { 1690 // byte SSH_MSG_CHANNEL_REQUEST 1691 // uint32 recipient_channel (== our local_id) 1692 // string request_type 1693 // boolean want_reply 1694 // …request-specific data 1695 var r = std.Io.Reader.fixed(packet[1..]); 1696 const recipient_channel = try r.takeInt(u32, .big); 1697 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1698 const req_type = try takeStringField(allocator, &r, 64); 1699 defer allocator.free(req_type); 1700 const want_reply = (try r.takeByte()) != 0; 1701 1702 if (std.mem.eql(u8, req_type, "pty-req")) { 1703 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1704 // uint32 height px, string modes 1705 const term = try takeStringField(allocator, &r, 64); 1706 defer allocator.free(term); 1707 ch.pty = try takePtySize(&r); 1708 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1709 return null; 1710 } 1711 1712 if (std.mem.eql(u8, req_type, "env")) { 1713 // ignore environment variables silently (we don't pass them anywhere) 1714 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1715 return null; 1716 } 1717 1718 if (std.mem.eql(u8, req_type, "window-change")) { 1719 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1720 const sz = try takePtySize(&r); 1721 if (ch.pty != null) ch.pty = sz; 1722 // spec: window-change MUST NOT request a reply, but accept either 1723 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1724 return null; 1725 } 1726 1727 if (std.mem.eql(u8, req_type, "shell")) { 1728 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1729 return .shell; 1730 } 1731 1732 if (std.mem.eql(u8, req_type, "exec")) { 1733 // capture the command string for the handler to inspect 1734 const cmd = try takeStringField(allocator, &r, 4096); 1735 if (pending_exec.*) |old| allocator.free(old); 1736 pending_exec.* = cmd; 1737 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1738 return .exec; 1739 } 1740 1741 // unknown request kind — fail it 1742 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1743 return null; 1744 } 1745 1746 fn replyChannelRequest( 1747 io: std.Io, 1748 allocator: std.mem.Allocator, 1749 sc_cipher: *Cipher, 1750 writer: *std.Io.Writer, 1751 ch: *Channel, 1752 want_reply: bool, 1753 success: bool, 1754 ) !void { 1755 if (!want_reply) return; 1756 var reply: std.ArrayList(u8) = .empty; 1757 defer reply.deinit(allocator); 1758 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1759 try writeU32(&reply, allocator, ch.remote_id); 1760 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1761 } 1762 1763 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1764 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1765 // uint32 recipient_channel 1766 // uint32 bytes_to_add 1767 var r = std.Io.Reader.fixed(packet[1..]); 1768 const recipient_channel = try r.takeInt(u32, .big); 1769 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1770 const add = try r.takeInt(u32, .big); 1771 ch.remote_window +|= add; 1772 } 1773 1774 fn discardChannelData( 1775 io: std.Io, 1776 allocator: std.mem.Allocator, 1777 sc_cipher: *Cipher, 1778 writer: *std.Io.Writer, 1779 ch: *Channel, 1780 packet: []const u8, 1781 extended: bool, 1782 ) !void { 1783 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1784 // uint32 recipient_channel 1785 // [if extended: uint32 type_code] 1786 // string data 1787 const payload = try parseChannelData(packet, extended, ch.local_id); 1788 const data_len: u32 = @intCast(payload.len); 1789 1790 if (data_len > ch.local_window) return error.WindowExceeded; 1791 ch.local_window -= data_len; 1792 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1793 } 1794 1795 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1796 if (packet.len < 1) return error.EmptyPacket; 1797 var r = std.Io.Reader.fixed(packet[1..]); 1798 const recipient_channel = try r.takeInt(u32, .big); 1799 if (recipient_channel != expected_channel) return error.UnknownChannel; 1800 if (extended) { 1801 const data_type = try r.takeInt(u32, .big); 1802 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1803 } 1804 const data_len = try r.takeInt(u32, .big); 1805 // catches both data_len > remaining (would otherwise be a bounds-check 1806 // panic on the slice) and trailing junk after the declared payload. 1807 if (data_len != r.buffered().len) return error.InvalidChannelData; 1808 return r.buffered(); 1809 } 1810 1811 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1812 if (packet.len < 1) return error.EmptyPacket; 1813 var r = std.Io.Reader.fixed(packet[1..]); 1814 const recipient_channel = try r.takeInt(u32, .big); 1815 if (recipient_channel != expected_channel) return error.UnknownChannel; 1816 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1817 } 1818 1819 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1820 /// of the initial value. Used both for the pre-session discard path and by 1821 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1822 fn maybeRefillRecvWindow( 1823 io: std.Io, 1824 allocator: std.mem.Allocator, 1825 sc_cipher: *Cipher, 1826 writer: *std.Io.Writer, 1827 ch: *Channel, 1828 ) !void { 1829 if (ch.local_window >= initial_recv_window / 2) return; 1830 const add = initial_recv_window - ch.local_window; 1831 ch.local_window += add; 1832 var adj: std.ArrayList(u8) = .empty; 1833 defer adj.deinit(allocator); 1834 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1835 try writeU32(&adj, allocator, ch.remote_id); 1836 try writeU32(&adj, allocator, add); 1837 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1838 } 1839 1840 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1841 var bytes: [4]u8 = undefined; 1842 std.mem.writeInt(u32, &bytes, value, .big); 1843 try buf.appendSlice(allocator, &bytes); 1844 } 1845