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