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