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