╭ 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 const SSH_MSG_DISCONNECT: u8 = 1; 57 const SSH_MSG_SERVICE_REQUEST: u8 = 5; 58 const SSH_MSG_SERVICE_ACCEPT: u8 = 6; 59 const SSH_MSG_KEXINIT: u8 = 20; 60 const SSH_MSG_NEWKEYS: u8 = 21; 61 const SSH_MSG_KEX_ECDH_INIT: u8 = 30; 62 const SSH_MSG_KEX_ECDH_REPLY: u8 = 31; 63 const SSH_MSG_USERAUTH_REQUEST: u8 = 50; 64 const SSH_MSG_USERAUTH_FAILURE: u8 = 51; 65 const SSH_MSG_USERAUTH_SUCCESS: u8 = 52; 66 const SSH_MSG_USERAUTH_PK_OK: u8 = 60; // method-specific name for publickey 67 const SSH_MSG_GLOBAL_REQUEST: u8 = 80; 68 const SSH_MSG_REQUEST_SUCCESS: u8 = 81; 69 const SSH_MSG_REQUEST_FAILURE: u8 = 82; 70 const SSH_MSG_CHANNEL_OPEN: u8 = 90; 71 const SSH_MSG_CHANNEL_OPEN_CONFIRMATION: u8 = 91; 72 const SSH_MSG_CHANNEL_OPEN_FAILURE: u8 = 92; 73 const SSH_MSG_CHANNEL_WINDOW_ADJUST: u8 = 93; 74 const SSH_MSG_CHANNEL_DATA: u8 = 94; 75 const SSH_MSG_CHANNEL_EXTENDED_DATA: u8 = 95; 76 const SSH_MSG_CHANNEL_EOF: u8 = 96; 77 const SSH_MSG_CHANNEL_CLOSE: u8 = 97; 78 const SSH_MSG_CHANNEL_REQUEST: u8 = 98; 79 const SSH_MSG_CHANNEL_SUCCESS: u8 = 99; 80 const SSH_MSG_CHANNEL_FAILURE: u8 = 100; 81 82 const SSH_DISCONNECT_PROTOCOL_ERROR: u32 = 2; 83 84 // SSH_OPEN_* reason codes for CHANNEL_OPEN_FAILURE 85 const SSH_OPEN_RESOURCE_SHORTAGE: u32 = 4; 86 const SSH_OPEN_UNKNOWN_CHANNEL_TYPE: u32 = 3; 87 88 // data type code for CHANNEL_EXTENDED_DATA (stderr) 89 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 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 pub fn handleConnection( 545 io: std.Io, 546 allocator: std.mem.Allocator, 547 stream: std.Io.net.Stream, 548 host_key: *const HostKey, 549 handler: anytype, 550 ) !void { 551 var recv_buf: [4096]u8 = undefined; 552 var send_buf: [4096]u8 = undefined; 553 var stream_reader = stream.reader(io, &recv_buf); 554 var stream_writer = stream.writer(io, &send_buf); 555 const reader = &stream_reader.interface; 556 const writer = &stream_writer.interface; 557 558 const client_version = try exchangeVersions(allocator, reader, writer); 559 defer allocator.free(client_version); 560 561 const kex = try runKex(io, allocator, reader, writer, host_key, client_version); 562 563 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com. 564 // both sides started counting packet seqnos at 0; KEXINIT, KEX_ECDH and 565 // NEWKEYS used seqno 0/1/2, so the first encrypted packet uses seqno 3. 566 var cs_cipher = Cipher.init(&kex.cs_key, 3); 567 var sc_cipher = Cipher.init(&kex.sc_key, 3); 568 569 const fingerprint = try runAuth(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &kex.session_id); 570 571 try runChannelLayer(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &fingerprint, handler); 572 } 573 574 // --------------------------------------------------------------------------- 575 // version exchange (RFC 4253 §4.2) 576 // --------------------------------------------------------------------------- 577 578 fn exchangeVersions( 579 allocator: std.mem.Allocator, 580 reader: *std.Io.Reader, 581 writer: *std.Io.Writer, 582 ) ![]u8 { 583 try writer.writeAll(server_version ++ "\r\n"); 584 try writer.flush(); 585 586 // the spec allows the client to send arbitrary comment lines before its 587 // banner; skip anything that isn't an "SSH-2.0-…" / "SSH-1.99-…" line. 588 while (true) { 589 const line = (try reader.takeDelimiter('\n')) orelse return error.UnexpectedEof; 590 const trimmed = if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; 591 if (std.mem.startsWith(u8, trimmed, "SSH-2.0-") or std.mem.startsWith(u8, trimmed, "SSH-1.99-")) { 592 return try allocator.dupe(u8, trimmed); 593 } 594 } 595 } 596 597 // --------------------------------------------------------------------------- 598 // binary packet codec, unencrypted form (RFC 4253 §6) 599 // --------------------------------------------------------------------------- 600 601 fn writePlainPacket(io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 602 const block: usize = 8; 603 const initial_pad = block - ((5 + payload.len) % block); 604 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 605 const packet_len: u32 = @intCast(1 + payload.len + padding_len); 606 607 try writer.writeInt(u32, packet_len, .big); 608 try writer.writeByte(padding_len); 609 try writer.writeAll(payload); 610 611 var padding: [255]u8 = undefined; 612 io.random(padding[0..padding_len]); 613 try writer.writeAll(padding[0..padding_len]); 614 try writer.flush(); 615 } 616 617 fn readPlainPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 618 const packet_len = try reader.takeInt(u32, .big); 619 if (packet_len < 8 or packet_len > max_packet_len) return error.InvalidPacketLength; 620 const padding_len = try reader.takeByte(); 621 if (padding_len < 4 or @as(u32, padding_len) + 1 > packet_len) return error.InvalidPadding; 622 const payload_len = packet_len - 1 - @as(u32, padding_len); 623 624 const payload = try reader.readAlloc(allocator, payload_len); 625 errdefer allocator.free(payload); 626 try reader.discardAll(padding_len); 627 return payload; 628 } 629 630 // --------------------------------------------------------------------------- 631 // SSH field encoders / decoders (RFC 4251 §5) 632 // --------------------------------------------------------------------------- 633 634 fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 635 var len_bytes: [4]u8 = undefined; 636 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 637 try buf.appendSlice(allocator, &len_bytes); 638 try buf.appendSlice(allocator, bytes); 639 } 640 641 fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 642 var total: usize = 0; 643 for (names, 0..) |name, i| { 644 if (i > 0) total += 1; // comma separator 645 total += name.len; 646 } 647 var len_bytes: [4]u8 = undefined; 648 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 649 try buf.appendSlice(allocator, &len_bytes); 650 for (names, 0..) |name, i| { 651 if (i > 0) try buf.append(allocator, ','); 652 try buf.appendSlice(allocator, name); 653 } 654 } 655 656 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 657 /// our use (X25519 shared secret) the value is always non-negative, so we 658 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 659 /// the most-significant byte is set (to keep it parsed as positive). 660 fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 661 var start: usize = 0; 662 while (start < bytes.len and bytes[start] == 0) start += 1; 663 const trimmed = bytes[start..]; 664 if (trimmed.len == 0) { 665 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 666 return; 667 } 668 const prepend = (trimmed[0] & 0x80) != 0; 669 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 670 var len_bytes: [4]u8 = undefined; 671 std.mem.writeInt(u32, &len_bytes, out_len, .big); 672 try buf.appendSlice(allocator, &len_bytes); 673 if (prepend) try buf.append(allocator, 0); 674 try buf.appendSlice(allocator, trimmed); 675 } 676 677 fn takeStringField(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_len: u32) ![]u8 { 678 const len = try reader.takeInt(u32, .big); 679 if (len > max_len) return error.FieldTooLarge; 680 return try reader.readAlloc(allocator, len); 681 } 682 683 fn nameListContainsAny(haystack: []const u8, our_options: []const []const u8) bool { 684 var iter = std.mem.splitScalar(u8, haystack, ','); 685 while (iter.next()) |name| { 686 for (our_options) |opt| { 687 if (std.mem.eql(u8, name, opt)) return true; 688 } 689 } 690 return false; 691 } 692 693 // --------------------------------------------------------------------------- 694 // KEXINIT (RFC 4253 §7.1) 695 // --------------------------------------------------------------------------- 696 697 const our_kex_algos = [_][]const u8{ "curve25519-sha256", "curve25519-sha256@libssh.org" }; 698 const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 699 const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 700 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 701 const our_compression = [_][]const u8{"none"}; 702 703 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 704 var buf: std.ArrayList(u8) = .empty; 705 errdefer buf.deinit(allocator); 706 707 try buf.append(allocator, SSH_MSG_KEXINIT); 708 709 var cookie: [16]u8 = undefined; 710 io.random(&cookie); 711 try buf.appendSlice(allocator, &cookie); 712 713 try writeNameList(&buf, allocator, &our_kex_algos); 714 try writeNameList(&buf, allocator, &our_host_key_algos); 715 try writeNameList(&buf, allocator, &our_ciphers); // c->s 716 try writeNameList(&buf, allocator, &our_ciphers); // s->c 717 try writeNameList(&buf, allocator, &our_macs); 718 try writeNameList(&buf, allocator, &our_macs); 719 try writeNameList(&buf, allocator, &our_compression); 720 try writeNameList(&buf, allocator, &our_compression); 721 try writeNameList(&buf, allocator, &.{}); // langs c->s 722 try writeNameList(&buf, allocator, &.{}); // langs s->c 723 try buf.append(allocator, 0); // first_kex_packet_follows = false 724 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 725 726 return try buf.toOwnedSlice(allocator); 727 } 728 729 const ParsedKexInit = struct { 730 kex_algos: []u8, 731 host_key_algos: []u8, 732 cs_cipher: []u8, 733 sc_cipher: []u8, 734 735 fn deinit(self: ParsedKexInit, allocator: std.mem.Allocator) void { 736 allocator.free(self.kex_algos); 737 allocator.free(self.host_key_algos); 738 allocator.free(self.cs_cipher); 739 allocator.free(self.sc_cipher); 740 } 741 }; 742 743 fn parseClientKexInit(allocator: std.mem.Allocator, payload: []const u8) !ParsedKexInit { 744 if (payload.len < 1 + 16) return error.KexInitTruncated; 745 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 746 747 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 748 749 const kex_algos = try takeStringField(allocator, &reader, max_name_list_len); 750 errdefer allocator.free(kex_algos); 751 const host_key_algos = try takeStringField(allocator, &reader, max_name_list_len); 752 errdefer allocator.free(host_key_algos); 753 const cs_cipher = try takeStringField(allocator, &reader, max_name_list_len); 754 errdefer allocator.free(cs_cipher); 755 const sc_cipher = try takeStringField(allocator, &reader, max_name_list_len); 756 errdefer allocator.free(sc_cipher); 757 758 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 759 for (0..6) |_| { 760 const len = try reader.takeInt(u32, .big); 761 if (len > max_name_list_len) return error.FieldTooLarge; 762 try reader.discardAll(len); 763 } 764 _ = try reader.takeByte(); // first_kex_packet_follows 765 _ = try reader.takeInt(u32, .big); // reserved 766 767 return .{ 768 .kex_algos = kex_algos, 769 .host_key_algos = host_key_algos, 770 .cs_cipher = cs_cipher, 771 .sc_cipher = sc_cipher, 772 }; 773 } 774 775 // --------------------------------------------------------------------------- 776 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 777 // --------------------------------------------------------------------------- 778 779 const KexResult = struct { 780 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 781 sc_key: [64]u8, // server → client cipher key material 782 session_id: [Sha256.digest_length]u8, 783 }; 784 785 fn runKex( 786 io: std.Io, 787 allocator: std.mem.Allocator, 788 reader: *std.Io.Reader, 789 writer: *std.Io.Writer, 790 host_key: *const HostKey, 791 client_version: []const u8, 792 ) !KexResult { 793 // exchange KEXINITs 794 const server_kex_init = try buildServerKexInit(io, allocator); 795 defer allocator.free(server_kex_init); 796 try writePlainPacket(io, writer, server_kex_init); 797 798 const client_kex_init = try readPlainPacket(allocator, reader); 799 defer allocator.free(client_kex_init); 800 801 var parsed = try parseClientKexInit(allocator, client_kex_init); 802 defer parsed.deinit(allocator); 803 804 if (!nameListContainsAny(parsed.kex_algos, &our_kex_algos)) return error.NoCommonKexAlgorithm; 805 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 806 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 807 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 808 809 // receive KEX_ECDH_INIT — client's ephemeral curve25519 pubkey 810 const ecdh_init = try readPlainPacket(allocator, reader); 811 defer allocator.free(ecdh_init); 812 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 813 814 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 815 const client_ephemeral_alloc = try takeStringField(allocator, &ecdh_init_reader, X25519.public_length); 816 defer allocator.free(client_ephemeral_alloc); 817 if (client_ephemeral_alloc.len != X25519.public_length) return error.InvalidEphemeralKey; 818 var client_ephemeral: [X25519.public_length]u8 = undefined; 819 @memcpy(&client_ephemeral, client_ephemeral_alloc); 820 821 // our ephemeral keypair + shared secret 822 const server_ephemeral_kp = X25519.KeyPair.generate(io); 823 const shared_secret = try X25519.scalarmult(server_ephemeral_kp.secret_key, client_ephemeral); 824 825 // build host key blob (K_S) 826 var host_key_blob: std.ArrayList(u8) = .empty; 827 defer host_key_blob.deinit(allocator); 828 try host_key.appendPublicBlob(&host_key_blob, allocator); 829 830 // build exchange hash input and compute H 831 const exchange_hash = try computeExchangeHash( 832 allocator, 833 client_version, 834 server_version, 835 client_kex_init, 836 server_kex_init, 837 host_key_blob.items, 838 &client_ephemeral, 839 &server_ephemeral_kp.public_key, 840 &shared_secret, 841 ); 842 843 // sign H with the host key, format as ssh signature blob 844 var signature_blob: std.ArrayList(u8) = .empty; 845 defer signature_blob.deinit(allocator); 846 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 847 848 // build & send KEX_ECDH_REPLY 849 var reply: std.ArrayList(u8) = .empty; 850 defer reply.deinit(allocator); 851 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 852 try writeStringField(&reply, allocator, host_key_blob.items); 853 try writeStringField(&reply, allocator, &server_ephemeral_kp.public_key); 854 try writeStringField(&reply, allocator, signature_blob.items); 855 try writePlainPacket(io, writer, reply.items); 856 857 // NEWKEYS — both sides switch to encrypted mode after this is sent and 858 // the peer's NEWKEYS is received. 859 try writePlainPacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 860 861 const peer_newkeys = try readPlainPacket(allocator, reader); 862 defer allocator.free(peer_newkeys); 863 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 864 865 // derive session keys per RFC 4253 §7.2. session_id == H for the first 866 // KEX. K is encoded as mpint in each derivation input. only the encrypt 867 // keys are needed for chacha20-poly1305 (no separate MAC/IV). 868 var keys: SessionKeys = undefined; 869 try deriveSessionKeys(allocator, &shared_secret, &exchange_hash, &exchange_hash, &keys); 870 871 return .{ 872 .cs_key = keys.cs_enc, 873 .sc_key = keys.sc_enc, 874 .session_id = exchange_hash, 875 }; 876 } 877 878 // --------------------------------------------------------------------------- 879 // exchange hash (RFC 4253 §8, RFC 5656 §4) 880 // --------------------------------------------------------------------------- 881 882 fn computeExchangeHash( 883 allocator: std.mem.Allocator, 884 client_version: []const u8, 885 server_version_str: []const u8, 886 client_kex_init: []const u8, 887 server_kex_init: []const u8, 888 host_key_blob: []const u8, 889 client_ephemeral: []const u8, 890 server_ephemeral: []const u8, 891 shared_secret: []const u8, 892 ) ![Sha256.digest_length]u8 { 893 var buf: std.ArrayList(u8) = .empty; 894 defer buf.deinit(allocator); 895 896 try writeStringField(&buf, allocator, client_version); 897 try writeStringField(&buf, allocator, server_version_str); 898 try writeStringField(&buf, allocator, client_kex_init); 899 try writeStringField(&buf, allocator, server_kex_init); 900 try writeStringField(&buf, allocator, host_key_blob); 901 try writeStringField(&buf, allocator, client_ephemeral); 902 try writeStringField(&buf, allocator, server_ephemeral); 903 try writeMpint(&buf, allocator, shared_secret); 904 905 var hasher = Sha256.init(.{}); 906 hasher.update(buf.items); 907 return hasher.finalResult(); 908 } 909 910 // --------------------------------------------------------------------------- 911 // key derivation (RFC 4253 §7.2) 912 // --------------------------------------------------------------------------- 913 914 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 915 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 916 // blocks chained per RFC 4253. 917 const SessionKeys = struct { 918 cs_iv: [16]u8, 919 sc_iv: [16]u8, 920 cs_enc: [64]u8, 921 sc_enc: [64]u8, 922 }; 923 924 fn deriveSessionKeys( 925 allocator: std.mem.Allocator, 926 shared_secret: []const u8, 927 exchange_hash: []const u8, 928 session_id: []const u8, 929 out: *SessionKeys, 930 ) !void { 931 // pre-build the K || H prefix once; reused for every derivation 932 var prefix: std.ArrayList(u8) = .empty; 933 defer prefix.deinit(allocator); 934 try writeMpint(&prefix, allocator, shared_secret); 935 try prefix.appendSlice(allocator, exchange_hash); 936 937 try deriveKey(allocator, prefix.items, 'A', session_id, &out.cs_iv); 938 try deriveKey(allocator, prefix.items, 'B', session_id, &out.sc_iv); 939 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 940 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 941 } 942 943 fn deriveKey( 944 allocator: std.mem.Allocator, 945 prefix: []const u8, // K || H, already encoded 946 letter: u8, 947 session_id: []const u8, 948 out: []u8, 949 ) !void { 950 // first block: HASH(K || H || letter || session_id) 951 var first_block: [Sha256.digest_length]u8 = undefined; 952 { 953 var hasher = Sha256.init(.{}); 954 hasher.update(prefix); 955 hasher.update(&[_]u8{letter}); 956 hasher.update(session_id); 957 first_block = hasher.finalResult(); 958 } 959 const first_copy = @min(out.len, first_block.len); 960 @memcpy(out[0..first_copy], first_block[0..first_copy]); 961 962 // chain additional blocks if requested length exceeds one hash: 963 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 964 var chained: std.ArrayList(u8) = .empty; 965 defer chained.deinit(allocator); 966 try chained.appendSlice(allocator, first_block[0..]); 967 968 var produced: usize = first_copy; 969 while (produced < out.len) { 970 var hasher = Sha256.init(.{}); 971 hasher.update(prefix); 972 hasher.update(chained.items); 973 const block = hasher.finalResult(); 974 const copy_len = @min(out.len - produced, block.len); 975 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 976 produced += copy_len; 977 try chained.appendSlice(allocator, block[0..]); 978 } 979 } 980 981 // --------------------------------------------------------------------------- 982 // chacha20-poly1305@openssh.com packet codec 983 // --------------------------------------------------------------------------- 984 // 985 // per openssh's PROTOCOL.chacha20poly1305: 986 // K_2 = first 32 bytes of key material — encrypts the packet body 987 // K_1 = next 32 bytes — encrypts the 4-byte length field 988 // nonce = 64-bit big-endian sequence number 989 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 990 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 991 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 992 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 993 // 994 // padding is computed on the body alone (padding_length byte + payload + 995 // padding) — the 4-byte length field is excluded from alignment. body must 996 // be a multiple of 8 bytes; minimum padding 4 bytes. 997 998 const Cipher = struct { 999 main_key: [32]u8, // K_2 1000 header_key: [32]u8, // K_1 1001 seq: u64, 1002 1003 fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1004 return .{ 1005 .main_key = key_material[0..32].*, 1006 .header_key = key_material[32..64].*, 1007 .seq = initial_seq, 1008 }; 1009 } 1010 1011 fn makeNonce(seq: u64) [8]u8 { 1012 var nonce: [8]u8 = undefined; 1013 std.mem.writeInt(u64, &nonce, seq, .big); 1014 return nonce; 1015 } 1016 1017 fn writePacket( 1018 self: *Cipher, 1019 io: std.Io, 1020 allocator: std.mem.Allocator, 1021 writer: *std.Io.Writer, 1022 payload: []const u8, 1023 ) !void { 1024 const block: usize = 8; 1025 const initial_pad = block - ((1 + payload.len) % block); 1026 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1027 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1028 1029 const nonce = makeNonce(self.seq); 1030 1031 // plaintext body = padding_length || payload || random padding 1032 const body = try allocator.alloc(u8, body_len); 1033 defer allocator.free(body); 1034 body[0] = padding_len; 1035 @memcpy(body[1 .. 1 + payload.len], payload); 1036 io.random(body[1 + payload.len ..]); 1037 1038 // encrypt body in place with counter=1 1039 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1040 1041 // encrypt length field with header key, counter=0 1042 var enc_length: [4]u8 = undefined; 1043 var length_plain: [4]u8 = undefined; 1044 std.mem.writeInt(u32, &length_plain, body_len, .big); 1045 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1046 1047 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1048 var poly_key: [Poly1305.key_length]u8 = undefined; 1049 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1050 1051 // mac over encrypted_length || encrypted_body 1052 const mac_input = try allocator.alloc(u8, 4 + body_len); 1053 defer allocator.free(mac_input); 1054 @memcpy(mac_input[0..4], &enc_length); 1055 @memcpy(mac_input[4..], body); 1056 var tag: [Poly1305.mac_length]u8 = undefined; 1057 Poly1305.create(&tag, mac_input, &poly_key); 1058 1059 try writer.writeAll(&enc_length); 1060 try writer.writeAll(body); 1061 try writer.writeAll(&tag); 1062 try writer.flush(); 1063 1064 self.seq += 1; 1065 } 1066 1067 fn readPacket( 1068 self: *Cipher, 1069 allocator: std.mem.Allocator, 1070 reader: *std.Io.Reader, 1071 ) ![]u8 { 1072 const nonce = makeNonce(self.seq); 1073 1074 var enc_length: [4]u8 = undefined; 1075 try reader.readSliceAll(&enc_length); 1076 1077 var length_plain: [4]u8 = undefined; 1078 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1079 const body_len = std.mem.readInt(u32, &length_plain, .big); 1080 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1081 1082 const enc_body = try allocator.alloc(u8, body_len); 1083 defer allocator.free(enc_body); 1084 try reader.readSliceAll(enc_body); 1085 1086 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1087 try reader.readSliceAll(&tag_recv); 1088 1089 var poly_key: [Poly1305.key_length]u8 = undefined; 1090 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1091 1092 const mac_input = try allocator.alloc(u8, 4 + body_len); 1093 defer allocator.free(mac_input); 1094 @memcpy(mac_input[0..4], &enc_length); 1095 @memcpy(mac_input[4..], enc_body); 1096 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1097 Poly1305.create(&tag_computed, mac_input, &poly_key); 1098 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1099 return error.MacVerificationFailed; 1100 } 1101 1102 // decrypt body in place into a separate buffer (caller owns) 1103 const body = try allocator.alloc(u8, body_len); 1104 errdefer allocator.free(body); 1105 ChaCha20.xor(body, enc_body, 1, self.main_key, nonce); 1106 1107 const padding_len = body[0]; 1108 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1109 const payload_len = body_len - 1 - @as(u32, padding_len); 1110 1111 const payload = try allocator.dupe(u8, body[1 .. 1 + payload_len]); 1112 allocator.free(body); 1113 1114 self.seq += 1; 1115 return payload; 1116 } 1117 }; 1118 1119 // --------------------------------------------------------------------------- 1120 // post-KEX: service request + user authentication (RFC 4252) 1121 // --------------------------------------------------------------------------- 1122 1123 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1124 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1125 /// `Offering public key: … SHA256:…`. 1126 pub const fingerprint_len = 50; 1127 1128 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1129 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1130 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1131 var digest: [Sha256.digest_length]u8 = undefined; 1132 Sha256.hash(pubkey_blob, &digest, .{}); 1133 1134 var out: [fingerprint_len]u8 = undefined; 1135 @memcpy(out[0..7], "SHA256:"); 1136 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1137 std.debug.assert(encoded.len == fingerprint_len - 7); 1138 return out; 1139 } 1140 1141 fn runAuth( 1142 io: std.Io, 1143 allocator: std.mem.Allocator, 1144 reader: *std.Io.Reader, 1145 writer: *std.Io.Writer, 1146 cs_cipher: *Cipher, 1147 sc_cipher: *Cipher, 1148 session_id: *const [Sha256.digest_length]u8, 1149 ) ![fingerprint_len]u8 { 1150 // step 1: service request for ssh-userauth → service accept 1151 { 1152 const req = try cs_cipher.readPacket(allocator, reader); 1153 defer allocator.free(req); 1154 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1155 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1156 return error.RekeyUnsupported; 1157 } 1158 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1159 1160 var req_reader = std.Io.Reader.fixed(req[1..]); 1161 const service = try takeStringField(allocator, &req_reader, 64); 1162 defer allocator.free(service); 1163 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1164 1165 var accept: std.ArrayList(u8) = .empty; 1166 defer accept.deinit(allocator); 1167 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1168 try writeStringField(&accept, allocator, "ssh-userauth"); 1169 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1170 } 1171 1172 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1173 // signature verifies against the offered pubkey. 1174 var auth_attempts: u32 = 0; 1175 while (true) { 1176 const req = try cs_cipher.readPacket(allocator, reader); 1177 defer allocator.free(req); 1178 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1179 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1180 return error.RekeyUnsupported; 1181 } 1182 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1183 1184 var req_reader = std.Io.Reader.fixed(req[1..]); 1185 const user_name = try takeStringField(allocator, &req_reader, 256); 1186 defer allocator.free(user_name); 1187 const service_name = try takeStringField(allocator, &req_reader, 64); 1188 defer allocator.free(service_name); 1189 const method = try takeStringField(allocator, &req_reader, 64); 1190 defer allocator.free(method); 1191 1192 if (!std.mem.eql(u8, method, "publickey")) { 1193 auth_attempts += 1; 1194 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1195 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1196 continue; 1197 } 1198 1199 const has_signature = (try req_reader.takeByte()) != 0; 1200 const algo = try takeStringField(allocator, &req_reader, 64); 1201 defer allocator.free(algo); 1202 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1203 defer allocator.free(pubkey_blob); 1204 1205 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1206 auth_attempts += 1; 1207 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1208 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1209 continue; 1210 } 1211 1212 if (!has_signature) { 1213 // probe — tell the client this key is acceptable so it'll send 1214 // the signed version next. 1215 var pk_ok: std.ArrayList(u8) = .empty; 1216 defer pk_ok.deinit(allocator); 1217 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1218 try writeStringField(&pk_ok, allocator, algo); 1219 try writeStringField(&pk_ok, allocator, pubkey_blob); 1220 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1221 continue; 1222 } 1223 1224 // has signature — verify it 1225 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1226 defer allocator.free(signature_blob); 1227 1228 const ok = verifyUserauthSignature( 1229 allocator, 1230 session_id, 1231 user_name, 1232 service_name, 1233 algo, 1234 pubkey_blob, 1235 signature_blob, 1236 ) catch false; 1237 1238 if (!ok) { 1239 auth_attempts += 1; 1240 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1241 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1242 continue; 1243 } 1244 1245 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1246 return formatFingerprint(pubkey_blob); 1247 } 1248 } 1249 1250 fn sendUserauthFailure( 1251 io: std.Io, 1252 allocator: std.mem.Allocator, 1253 sc_cipher: *Cipher, 1254 writer: *std.Io.Writer, 1255 ) !void { 1256 var buf: std.ArrayList(u8) = .empty; 1257 defer buf.deinit(allocator); 1258 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1259 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1260 try buf.append(allocator, 0); // partial_success = false 1261 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1262 } 1263 1264 fn sendDisconnect( 1265 io: std.Io, 1266 allocator: std.mem.Allocator, 1267 sc_cipher: *Cipher, 1268 writer: *std.Io.Writer, 1269 description: []const u8, 1270 ) !void { 1271 var buf: std.ArrayList(u8) = .empty; 1272 defer buf.deinit(allocator); 1273 try buf.append(allocator, SSH_MSG_DISCONNECT); 1274 try writeU32(&buf, allocator, SSH_DISCONNECT_PROTOCOL_ERROR); 1275 try writeStringField(&buf, allocator, description); 1276 try writeStringField(&buf, allocator, ""); 1277 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1278 } 1279 1280 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1281 // verify the supplied signature against them. 1282 fn verifyUserauthSignature( 1283 allocator: std.mem.Allocator, 1284 session_id: *const [Sha256.digest_length]u8, 1285 user_name: []const u8, 1286 service_name: []const u8, 1287 algo: []const u8, 1288 pubkey_blob: []const u8, 1289 signature_blob: []const u8, 1290 ) !bool { 1291 // signed data: 1292 // string session_id 1293 // byte SSH_MSG_USERAUTH_REQUEST 1294 // string user_name 1295 // string service_name 1296 // string "publickey" 1297 // bool TRUE 1298 // string algo 1299 // string pubkey 1300 var signed: std.ArrayList(u8) = .empty; 1301 defer signed.deinit(allocator); 1302 try writeStringField(&signed, allocator, session_id); 1303 try signed.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1304 try writeStringField(&signed, allocator, user_name); 1305 try writeStringField(&signed, allocator, service_name); 1306 try writeStringField(&signed, allocator, "publickey"); 1307 try signed.append(allocator, 1); 1308 try writeStringField(&signed, allocator, algo); 1309 try writeStringField(&signed, allocator, pubkey_blob); 1310 1311 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1312 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1313 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1314 defer allocator.free(pk_algo); 1315 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1316 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1317 defer allocator.free(raw_pubkey); 1318 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1319 1320 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1321 var sig_reader = std.Io.Reader.fixed(signature_blob); 1322 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1323 defer allocator.free(sig_algo); 1324 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1325 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1326 defer allocator.free(raw_sig); 1327 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1328 1329 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1330 @memcpy(&pubkey_bytes, raw_pubkey); 1331 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1332 @memcpy(&sig_bytes, raw_sig); 1333 1334 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1335 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1336 sig.verify(signed.items, pk) catch return false; 1337 return true; 1338 } 1339 1340 // --------------------------------------------------------------------------- 1341 // connection layer (RFC 4254): channels, requests, data, flow control 1342 // --------------------------------------------------------------------------- 1343 1344 const Channel = struct { 1345 local_id: u32, 1346 remote_id: u32, 1347 local_window: u32, // bytes peer may still send us before we adjust 1348 remote_window: u32, // bytes we may still send to peer before they adjust 1349 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1350 eof_received: bool = false, 1351 pty: ?PtySize = null, 1352 }; 1353 1354 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1355 1356 fn runChannelLayer( 1357 io: std.Io, 1358 allocator: std.mem.Allocator, 1359 reader: *std.Io.Reader, 1360 writer: *std.Io.Writer, 1361 cs_cipher: *Cipher, 1362 sc_cipher: *Cipher, 1363 fingerprint: *const [fingerprint_len]u8, 1364 handler: anytype, 1365 ) !void { 1366 var channel: ?Channel = null; 1367 var pending_exec: ?[]u8 = null; 1368 defer if (pending_exec) |s| allocator.free(s); 1369 1370 while (true) { 1371 const packet = try cs_cipher.readPacket(allocator, reader); 1372 defer allocator.free(packet); 1373 if (packet.len < 1) return error.EmptyPacket; 1374 const msg_type = packet[0]; 1375 1376 switch (msg_type) { 1377 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1378 1379 SSH_MSG_KEXINIT => { 1380 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1381 return error.RekeyUnsupported; 1382 }, 1383 1384 SSH_MSG_CHANNEL_OPEN => { 1385 if (channel != null) { 1386 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1387 continue; 1388 } 1389 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1390 }, 1391 1392 SSH_MSG_CHANNEL_REQUEST => { 1393 const ch = if (channel) |*c| c else continue; 1394 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1395 if (start_request) |req_kind| { 1396 const request: Request = switch (req_kind) { 1397 .shell => .{ .shell = ch.pty }, 1398 .exec => .{ .exec = pending_exec.? }, 1399 }; 1400 var sess = SessionCtx{ 1401 .io = io, 1402 .allocator = allocator, 1403 .reader = reader, 1404 .writer = writer, 1405 .cs_cipher = cs_cipher, 1406 .sc_cipher = sc_cipher, 1407 .channel = ch, 1408 .fingerprint = fingerprint.*, 1409 }; 1410 defer sess.deinit(); 1411 handler.handleSession(&sess, request) catch |session_err| { 1412 // try to send a non-zero exit status before closing 1413 sess.exit(1) catch {}; 1414 return session_err; 1415 }; 1416 if (!sess.closed) try sess.exit(0); 1417 return; 1418 } 1419 }, 1420 1421 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1422 const ch = if (channel) |*c| c else continue; 1423 try handleWindowAdjust(ch, packet); 1424 }, 1425 1426 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1427 const ch = if (channel) |*c| c else continue; 1428 // before shell/exec the client shouldn't be sending data, but 1429 // some clients are chatty; discard and refill window. 1430 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1431 }, 1432 1433 SSH_MSG_CHANNEL_EOF => { 1434 if (channel) |*c| { 1435 try parseChannelId(packet, c.local_id); 1436 c.eof_received = true; 1437 } 1438 }, 1439 1440 SSH_MSG_CHANNEL_CLOSE => { 1441 if (channel) |*c| try parseChannelId(packet, c.local_id); 1442 return; 1443 }, 1444 1445 else => {}, // ignore unknown messages 1446 } 1447 } 1448 } 1449 1450 fn handleGlobalRequest( 1451 io: std.Io, 1452 allocator: std.mem.Allocator, 1453 sc_cipher: *Cipher, 1454 writer: *std.Io.Writer, 1455 packet: []const u8, 1456 ) !void { 1457 // byte SSH_MSG_GLOBAL_REQUEST 1458 // string request_name 1459 // boolean want_reply 1460 // …request-specific data we ignore 1461 var r = std.Io.Reader.fixed(packet[1..]); 1462 const name = try takeStringField(allocator, &r, 256); 1463 defer allocator.free(name); 1464 const want_reply = (try r.takeByte()) != 0; 1465 if (want_reply) { 1466 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1467 } 1468 } 1469 1470 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1471 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1472 /// return null. 1473 fn handleChannelOpen( 1474 io: std.Io, 1475 allocator: std.mem.Allocator, 1476 sc_cipher: *Cipher, 1477 writer: *std.Io.Writer, 1478 packet: []const u8, 1479 ) !?Channel { 1480 // byte SSH_MSG_CHANNEL_OPEN 1481 // string channel_type 1482 // uint32 sender_channel (peer's id) 1483 // uint32 initial_window 1484 // uint32 max_packet 1485 var r = std.Io.Reader.fixed(packet[1..]); 1486 const ch_type = try takeStringField(allocator, &r, 64); 1487 defer allocator.free(ch_type); 1488 const remote_id = try r.takeInt(u32, .big); 1489 const initial_window = try r.takeInt(u32, .big); 1490 const max_packet = try r.takeInt(u32, .big); 1491 1492 if (!std.mem.eql(u8, ch_type, "session")) { 1493 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1494 return null; 1495 } 1496 1497 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1498 var reply: std.ArrayList(u8) = .empty; 1499 defer reply.deinit(allocator); 1500 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1501 try writeU32(&reply, allocator, remote_id); 1502 try writeU32(&reply, allocator, local_id); 1503 try writeU32(&reply, allocator, initial_recv_window); 1504 try writeU32(&reply, allocator, max_packet_size); 1505 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1506 1507 return .{ 1508 .local_id = local_id, 1509 .remote_id = remote_id, 1510 .local_window = initial_recv_window, 1511 .remote_window = initial_window, 1512 .max_packet = max_packet, 1513 }; 1514 } 1515 1516 fn sendChannelOpenFailure( 1517 io: std.Io, 1518 allocator: std.mem.Allocator, 1519 sc_cipher: *Cipher, 1520 writer: *std.Io.Writer, 1521 open_packet: []const u8, 1522 reason: u32, 1523 description: []const u8, 1524 ) !void { 1525 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1526 // address the failure to the correct id 1527 var r = std.Io.Reader.fixed(open_packet[1..]); 1528 const ch_type_len = try r.takeInt(u32, .big); 1529 try r.discardAll(ch_type_len); 1530 const remote_id = try r.takeInt(u32, .big); 1531 1532 var reply: std.ArrayList(u8) = .empty; 1533 defer reply.deinit(allocator); 1534 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1535 try writeU32(&reply, allocator, remote_id); 1536 try writeU32(&reply, allocator, reason); 1537 try writeStringField(&reply, allocator, description); 1538 try writeStringField(&reply, allocator, ""); // language tag 1539 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1540 } 1541 1542 const RequestKind = enum { shell, exec }; 1543 1544 /// Returns the kind of session request if this triggered one, else null. 1545 fn handleChannelRequest( 1546 io: std.Io, 1547 allocator: std.mem.Allocator, 1548 sc_cipher: *Cipher, 1549 writer: *std.Io.Writer, 1550 ch: *Channel, 1551 packet: []const u8, 1552 pending_exec: *?[]u8, 1553 ) !?RequestKind { 1554 // byte SSH_MSG_CHANNEL_REQUEST 1555 // uint32 recipient_channel (== our local_id) 1556 // string request_type 1557 // boolean want_reply 1558 // …request-specific data 1559 var r = std.Io.Reader.fixed(packet[1..]); 1560 const recipient_channel = try r.takeInt(u32, .big); 1561 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1562 const req_type = try takeStringField(allocator, &r, 64); 1563 defer allocator.free(req_type); 1564 const want_reply = (try r.takeByte()) != 0; 1565 1566 if (std.mem.eql(u8, req_type, "pty-req")) { 1567 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1568 // uint32 height px, string modes 1569 const term = try takeStringField(allocator, &r, 64); 1570 defer allocator.free(term); 1571 const width = try r.takeInt(u32, .big); 1572 const height = try r.takeInt(u32, .big); 1573 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1574 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1575 return null; 1576 } 1577 1578 if (std.mem.eql(u8, req_type, "env")) { 1579 // ignore environment variables silently (we don't pass them anywhere) 1580 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1581 return null; 1582 } 1583 1584 if (std.mem.eql(u8, req_type, "window-change")) { 1585 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1586 const width = try r.takeInt(u32, .big); 1587 const height = try r.takeInt(u32, .big); 1588 if (ch.pty != null) { 1589 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1590 } 1591 // spec: window-change MUST NOT request a reply, but accept either 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, "shell")) { 1597 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1598 return .shell; 1599 } 1600 1601 if (std.mem.eql(u8, req_type, "exec")) { 1602 // capture the command string for the handler to inspect 1603 const cmd = try takeStringField(allocator, &r, 4096); 1604 if (pending_exec.*) |old| allocator.free(old); 1605 pending_exec.* = cmd; 1606 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1607 return .exec; 1608 } 1609 1610 // unknown request kind — fail it 1611 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1612 return null; 1613 } 1614 1615 fn replyChannelRequest( 1616 io: std.Io, 1617 allocator: std.mem.Allocator, 1618 sc_cipher: *Cipher, 1619 writer: *std.Io.Writer, 1620 ch: *Channel, 1621 want_reply: bool, 1622 success: bool, 1623 ) !void { 1624 if (!want_reply) return; 1625 var reply: std.ArrayList(u8) = .empty; 1626 defer reply.deinit(allocator); 1627 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1628 try writeU32(&reply, allocator, ch.remote_id); 1629 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1630 } 1631 1632 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1633 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1634 // uint32 recipient_channel 1635 // uint32 bytes_to_add 1636 var r = std.Io.Reader.fixed(packet[1..]); 1637 const recipient_channel = try r.takeInt(u32, .big); 1638 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1639 const add = try r.takeInt(u32, .big); 1640 ch.remote_window +|= add; 1641 } 1642 1643 fn discardChannelData( 1644 io: std.Io, 1645 allocator: std.mem.Allocator, 1646 sc_cipher: *Cipher, 1647 writer: *std.Io.Writer, 1648 ch: *Channel, 1649 packet: []const u8, 1650 extended: bool, 1651 ) !void { 1652 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1653 // uint32 recipient_channel 1654 // [if extended: uint32 type_code] 1655 // string data 1656 const payload = try parseChannelData(packet, extended, ch.local_id); 1657 const data_len: u32 = @intCast(payload.len); 1658 1659 if (data_len > ch.local_window) return error.WindowExceeded; 1660 ch.local_window -= data_len; 1661 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1662 } 1663 1664 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1665 if (packet.len < 1) return error.EmptyPacket; 1666 var r = std.Io.Reader.fixed(packet[1..]); 1667 const recipient_channel = try r.takeInt(u32, .big); 1668 if (recipient_channel != expected_channel) return error.UnknownChannel; 1669 if (extended) { 1670 const data_type = try r.takeInt(u32, .big); 1671 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1672 } 1673 const data_len = try r.takeInt(u32, .big); 1674 // catches both data_len > remaining (would otherwise be a bounds-check 1675 // panic on the slice) and trailing junk after the declared payload. 1676 if (data_len != r.buffered().len) return error.InvalidChannelData; 1677 return r.buffered(); 1678 } 1679 1680 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1681 if (packet.len < 1) return error.EmptyPacket; 1682 var r = std.Io.Reader.fixed(packet[1..]); 1683 const recipient_channel = try r.takeInt(u32, .big); 1684 if (recipient_channel != expected_channel) return error.UnknownChannel; 1685 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1686 } 1687 1688 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1689 /// of the initial value. Used both for the pre-session discard path and by 1690 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1691 fn maybeRefillRecvWindow( 1692 io: std.Io, 1693 allocator: std.mem.Allocator, 1694 sc_cipher: *Cipher, 1695 writer: *std.Io.Writer, 1696 ch: *Channel, 1697 ) !void { 1698 if (ch.local_window >= initial_recv_window / 2) return; 1699 const add = initial_recv_window - ch.local_window; 1700 ch.local_window += add; 1701 var adj: std.ArrayList(u8) = .empty; 1702 defer adj.deinit(allocator); 1703 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1704 try writeU32(&adj, allocator, ch.remote_id); 1705 try writeU32(&adj, allocator, add); 1706 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1707 } 1708 1709 fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1710 var bytes: [4]u8 = undefined; 1711 std.mem.writeInt(u32, &bytes, value, .big); 1712 try buf.appendSlice(allocator, &bytes); 1713 } 1714