╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
252 const public = try takeString(&private, 64); 253 const secret = try takeString(&private, 128); 254 if (secret.len != Ed25519.SecretKey.encoded_length) return error.InvalidHostKey; 255 _ = try takeString(&private, 1024); // comment 256 257 // padded with 1, 2, 3 and so on to the cipher's block size, 8 for none 258 if (private_section.len % 8 != 0) return error.InvalidHostKey; 259 for (private.buffered(), 1..) |byte, i| { 260 if (byte != i) return error.InvalidHostKey; 261 } 262 263 // the outer public key must be the same key 264 if (!std.mem.eql(u8, try takeString(&outer, 64), "ssh-ed25519") or 265 !std.mem.eql(u8, try takeString(&outer, 64), public) or 266 outer.bufferedLen() != 0) return error.InvalidHostKey; 267 268 // the secret is seed || public. rebuild it from the seed so a file 269 // whose halves disagree is rejected in every build mode. 270 const keypair = try Ed25519.KeyPair.generateDeterministic(secret[0..Ed25519.KeyPair.seed_length].*); 271 if (!std.mem.eql(u8, secret, &keypair.secret_key.bytes) or 272 !std.mem.eql(u8, public, &keypair.public_key.bytes)) return error.InvalidHostKey; 273 return .{ .keypair = keypair }; 274 } 275 276 /// what `ssh` shows a user on first connect 277 pub fn fingerprint(self: HostKey, allocator: std.mem.Allocator) ![fingerprint_len]u8 { 278 var blob: std.ArrayList(u8) = .empty; 279 defer blob.deinit(allocator); 280 try self.appendPublicBlob(&blob, allocator); 281 return formatFingerprint(blob.items); 282 } 283 284 /// SSH wire-format ed25519 public key blob (used as K_S in the hash and 285 /// returned in KEX_ECDH_REPLY): string "ssh-ed25519" || string pubkey. 286 pub fn appendPublicBlob(self: HostKey, buf: *std.ArrayList(u8), allocator: std.mem.Allocator) !void { 287 try writeStringField(buf, allocator, "ssh-ed25519"); 288 try writeStringField(buf, allocator, &self.keypair.public_key.bytes); 289 } 290 291 /// SSH wire-format signature blob: string "ssh-ed25519" || string sig. 292 fn appendSignatureBlob(self: HostKey, buf: *std.ArrayList(u8), allocator: std.mem.Allocator, message: []const u8) !void { 293 const sig = try self.keypair.sign(message, null); 294 const sig_bytes = sig.toBytes(); 295 try writeStringField(buf, allocator, "ssh-ed25519"); 296 try writeStringField(buf, allocator, &sig_bytes); 297 } 298 }; 299 300 // --------------------------------------------------------------------------- 301 // public session API 302 // --------------------------------------------------------------------------- 303 304 /// what the client wants to do on this channel. 305 pub const Request = union(enum) { 306 shell: Shell, 307 exec: Exec, 308 309 pub const Shell = struct { 310 /// pty info if a pty-req arrived before the shell 311 pty: ?PtySize, 312 /// false if a non-empty NO_COLOR env value arrived before the shell 313 color: bool, 314 }; 315 316 pub const Exec = struct { 317 command: []const u8, 318 /// the GIT_PROTOCOL env value, if one arrived before the exec 319 git_protocol: ?[]const u8, 320 }; 321 }; 322 323 /// next thing that arrived from the client. 324 pub const Event = union(enum) { 325 data: []u8, // CHANNEL_DATA payload — caller owns and must free via sess.conn.allocator 326 resize: PtySize, // window-change request 327 eof, // peer sent CHANNEL_EOF: no more input, but we may still write 328 close, // peer sent CHANNEL_CLOSE, or the transport hit EOF 329 }; 330 331 /// per-connection transport state: the byte stream, both ciphers, and what a 332 /// rekey needs. built once after the initial KEX and threaded through the 333 /// auth and channel layers. 334 pub const Conn = struct { 335 io: std.Io, 336 allocator: std.mem.Allocator, 337 reader: *std.Io.Reader, 338 writer: *std.Io.Writer, 339 cs_cipher: Cipher, 340 sc_cipher: Cipher, 341 rekey: RekeyState, 342 idle: *IdleState, 343 // set only while the TUI waits to resolve a lone escape key 344 read_timeout: std.Io.Timeout = .none, 345 // teardown ran to the peer's EOF, so nothing more can be said 346 drained: bool = false, 347 348 fn writePacket(self: *Conn, parts: []const []const u8) !void { 349 self.idle.waiting.store(true, .release); 350 defer self.idle.waiting.store(false, .release); 351 try self.sc_cipher.writePacket(self.io, self.writer, parts); 352 // a peer that keeps reading is alive 353 _ = self.idle.activity.fetchAdd(1, .acq_rel); 354 } 355 356 fn readPacket(self: *Conn) ![]u8 { 357 self.idle.waiting.store(true, .release); 358 defer self.idle.waiting.store(false, .release); 359 if (self.read_timeout != .none and !try self.cs_cipher.hasBufferedPacket(self.reader)) { 360 // peek keeps partial packets in the reader if the timer wins. 361 // join both tasks before consuming bytes or changing cipher state. 362 const Result = union(enum) { ready: anyerror!void, timeout: std.Io.Cancelable!void }; 363 var results: [2]Result = undefined; 364 var select = std.Io.Select(Result).init(self.io, &results); 365 defer select.cancelDiscard(); 366 try select.concurrent(.ready, Cipher.peekPacket, .{ &self.cs_cipher, self.reader }); 367 try select.concurrent(.timeout, std.Io.Timeout.sleep, .{ self.read_timeout, self.io }); 368 switch (try select.await()) { 369 .ready => |result| try result, 370 .timeout => |result| { 371 try result; 372 return error.Timeout; 373 }, 374 } 375 } 376 return self.cs_cipher.readPacket(self.allocator, self.reader); 377 } 378 }; 379 380 // how long a peer probe waits for a packet that may already be on its way 381 const probe_timeout: std.Io.Timeout = .{ .duration = .{ .raw = .fromMilliseconds(1), .clock = .awake } }; 382 383 /// session bridge handed to the consumer's handleSession callback. exposes a 384 /// pumped event API plus a byte-write API; the byte stream goes out as 385 /// CHANNEL_DATA packets respecting the channel's flow-control window. 386 pub const SessionCtx = struct { 387 conn: *Conn, 388 channel: *Channel, 389 /// SHA256 fingerprint of the pubkey this session authenticated with, 390 /// formatted as "SHA256:<base64-no-padding>" — same value the openssh 391 /// client logs as `Offering public key: ED25519 SHA256:…`. consumers 392 /// can use it as a stable per-key identity. 393 fingerprint: [fingerprint_len]u8, 394 /// the SSH wire-format blob of that pubkey 395 public_key: []const u8 = "", 396 closed: bool = false, 397 // what a SessionReader or SessionWriter actually hit. kept apart so a 398 // cleanup write can't replace the cause of a failed read. 399 read_err: ?anyerror = null, 400 write_err: ?anyerror = null, 401 402 // shared state for the packet pump. incoming CHANNEL_DATA bytes 403 // accumulate in incoming_buffer (already-consumed prefix tracked by 404 // incoming_start) until drained via SessionReader or nextEvent. 405 incoming_buffer: std.ArrayList(u8) = .empty, 406 incoming_start: usize = 0, 407 // peer sent CHANNEL_EOF — no more input arrives, but the channel stays 408 // open and we may keep writing (RFC 4254 §5.3) 409 incoming_eof: bool = false, 410 // peer sent CHANNEL_CLOSE, or the transport died — the channel is gone 411 remote_closed: bool = false, 412 // .eof is handed to the caller once; later pumps wait for the close 413 eof_reported: bool = false, 414 // resize seen by the background pump, returned by the next nextEvent call 415 pending_resize: ?PtySize = null, 416 417 pub fn deinit(self: *SessionCtx) void { 418 self.incoming_buffer.deinit(self.conn.allocator); 419 } 420 421 /// whether the client is gone. a push spends its transaction writing 422 /// rather than reading, so a peer that hung up has to be pumped for. one 423 /// pending packet is processed, which is where a close is seen. 424 pub fn peerGone(self: *SessionCtx) bool { 425 if (self.closed or self.remote_closed) return true; 426 self.conn.read_timeout = probe_timeout.toDeadline(self.conn.io); 427 defer self.conn.read_timeout = .none; 428 self.processOneBackgroundPacket() catch |err| switch (err) { 429 error.Timeout => return false, 430 else => { 431 // the session reports this cause rather than the cancellation 432 self.read_err = err; 433 return true; 434 }, 435 }; 436 return self.remote_closed; 437 } 438 439 /// the std.Io adapters can only report ReadFailed or WriteFailed. recover 440 /// what the session hit. 441 pub fn underlyingError(self: *const SessionCtx, err: anyerror) anyerror { 442 return switch (err) { 443 error.ReadFailed => self.read_err orelse err, 444 error.WriteFailed => self.write_err orelse err, 445 else => err, 446 }; 447 } 448 449 fn failRead(self: *SessionCtx, err: anyerror) error{ReadFailed} { 450 self.read_err = err; 451 return error.ReadFailed; 452 } 453 454 fn failWrite(self: *SessionCtx, err: anyerror) error{WriteFailed} { 455 self.write_err = err; 456 return error.WriteFailed; 457 } 458 459 fn incomingBytes(self: *const SessionCtx) []const u8 { 460 return self.incoming_buffer.items[self.incoming_start..]; 461 } 462 463 // mark n incoming bytes as consumed; the buffer is recycled once empty 464 fn consumeIncoming(self: *SessionCtx, n: usize) void { 465 self.incoming_start += n; 466 if (self.incoming_start == self.incoming_buffer.items.len) { 467 self.incoming_buffer.clearRetainingCapacity(); 468 self.incoming_start = 0; 469 } 470 } 471 472 // append to the incoming buffer, first compacting away the consumed 473 // prefix so the buffer only ever holds unread bytes. bounded by the 474 // receive window, which is never credited past max_incoming_buffered. 475 fn appendIncoming(self: *SessionCtx, payload: []const u8) !void { 476 if (self.incoming_start > 0) { 477 const remaining = self.incoming_buffer.items.len - self.incoming_start; 478 std.mem.copyForwards(u8, self.incoming_buffer.items[0..remaining], self.incoming_buffer.items[self.incoming_start..]); 479 self.incoming_buffer.shrinkRetainingCapacity(remaining); 480 self.incoming_start = 0; 481 } 482 try self.incoming_buffer.appendSlice(self.conn.allocator, payload); 483 } 484 485 /// interactive sessions idle legitimately; tell the host's idle 486 /// watchdog to stand down for the rest of this connection. 487 pub fn exemptFromIdleTimeout(self: *SessionCtx) void { 488 self.conn.idle.exempt.store(true, .release); 489 } 490 491 /// pump SSH packets until something interesting (data / resize / close) 492 /// arrives. background traffic (window adjusts, env requests, etc.) is 493 /// handled silently. drains the same incoming state as SessionReader, 494 /// so a session should consume through one or the other, not both. 495 pub fn nextEvent(self: *SessionCtx) !Event { 496 while (true) { 497 if (self.pending_resize) |sz| { 498 self.pending_resize = null; 499 return .{ .resize = sz }; 500 } 501 if (self.incomingBytes().len > 0) { 502 // hand the buffered bytes to the caller (caller owns) 503 const payload = try self.conn.allocator.dupe(u8, self.incomingBytes()); 504 errdefer self.conn.allocator.free(payload); 505 self.consumeIncoming(payload.len); 506 try self.maybeRefillRecvWindowForBufferedInput(); 507 return .{ .data = payload }; 508 } 509 if (self.remote_closed) return .close; 510 if (self.incoming_eof and !self.eof_reported) { 511 self.eof_reported = true; 512 return .eof; 513 } 514 try self.processOneBackgroundPacket(); 515 } 516 } 517 518 /// ship bytes to the client's stdout as one or more CHANNEL_DATA packets, 519 /// respecting the peer's max-packet size. if the remote window is 520 /// exhausted, pump incoming SSH packets until a WINDOW_ADJUST arrives 521 /// (background packets are processed for their side effects — incoming 522 /// CHANNEL_DATA goes into incoming_buffer for a future SessionReader). 523 pub fn writeBytes(self: *SessionCtx, bytes: []const u8) !void { 524 const conn = self.conn; 525 526 // byte SSH_MSG_CHANNEL_DATA, uint32 recipient_channel, uint32 data length 527 var header: [9]u8 = undefined; 528 header[0] = SSH_MSG_CHANNEL_DATA; 529 std.mem.writeInt(u32, header[1..5], self.channel.remote_id, .big); 530 531 var rest = bytes; 532 while (rest.len > 0) { 533 if (self.closed or self.remote_closed) return error.RemoteClosed; 534 while (self.channel.remote_window == 0) { 535 if (self.remote_closed) return error.RemoteClosed; 536 try self.processOneBackgroundPacket(); 537 } 538 // also clamp to our own max so the chunk fits writePacket's buffer 539 const cap = @min(rest.len, self.channel.max_packet, self.channel.remote_window, max_packet_size); 540 const chunk_len: u32 = @intCast(cap); 541 542 std.mem.writeInt(u32, header[5..9], chunk_len, .big); 543 try conn.writePacket(&.{ &header, rest[0..chunk_len] }); 544 545 self.channel.remote_window -= chunk_len; 546 rest = rest[chunk_len..]; 547 } 548 } 549 550 /// the session's packet pump: process exactly one SSH packet for side 551 /// effects only. CHANNEL_DATA payloads accumulate in incoming_buffer; 552 /// CHANNEL_EOF/CLOSE flips incoming_eof; WINDOW_ADJUST updates the 553 /// channel state; window-change is stashed in pending_resize; other 554 /// channel/global requests get a polite failure. driven by nextEvent, 555 /// SessionReader, and writeBytes (waiting for send-window). 556 fn processOneBackgroundPacket(self: *SessionCtx) !void { 557 const conn = self.conn; 558 const packet = readSessionPacket(conn) catch |err| switch (err) { 559 error.EndOfStream => { 560 self.incoming_eof = true; 561 self.remote_closed = true; 562 return; 563 }, 564 else => return err, 565 }; 566 defer conn.allocator.free(packet); 567 568 switch (packet[0]) { 569 SSH_MSG_CHANNEL_DATA => { 570 const payload = try parseChannelData(packet, false, self.channel.local_id); 571 const data_len: u32 = @intCast(payload.len); 572 if (data_len > self.channel.local_window) return error.WindowExceeded; 573 self.channel.local_window -= data_len; 574 try self.appendIncoming(payload); 575 try self.maybeRefillRecvWindowForBufferedInput(); 576 }, 577 SSH_MSG_CHANNEL_EXTENDED_DATA => { 578 // discarded, but the window is still credited against what the 579 // incoming buffer can take, since CHANNEL_DATA may be sitting 580 // in it unread 581 try discardChannelData(self.channel, packet, true); 582 try self.maybeRefillRecvWindowForBufferedInput(); 583 }, 584 SSH_MSG_CHANNEL_WINDOW_ADJUST => try handleWindowAdjust(self.channel, packet), 585 SSH_MSG_CHANNEL_REQUEST => { 586 var r = std.Io.Reader.fixed(packet[1..]); 587 const recipient_channel = try r.takeInt(u32, .big); 588 if (recipient_channel != self.channel.local_id) return error.UnknownChannel; 589 const req_type = try takeString(&r, 64); 590 const want_reply = (try r.takeByte()) != 0; 591 if (std.mem.eql(u8, req_type, "window-change")) { 592 const sz = try takePtySize(&r); 593 if (self.channel.pty != null) self.channel.pty = sz; 594 self.pending_resize = sz; 595 try replyChannelRequest(conn, self.channel, want_reply, true); 596 } else { 597 // other mid-session channel requests aren't honored — fail them 598 try replyChannelRequest(conn, self.channel, want_reply, false); 599 } 600 }, 601 SSH_MSG_CHANNEL_EOF => { 602 try parseChannelId(packet, self.channel.local_id); 603 self.incoming_eof = true; 604 }, 605 SSH_MSG_CHANNEL_CLOSE => { 606 try parseChannelId(packet, self.channel.local_id); 607 self.incoming_eof = true; 608 self.remote_closed = true; 609 try sendChannelMessage(conn, self.channel, SSH_MSG_CHANNEL_CLOSE); 610 }, 611 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 612 // refused, so a multiplexing client doesn't wait on it 613 SSH_MSG_CHANNEL_OPEN => _ = try handleChannelOpen(conn, packet, true), 614 // RFC 4252 §5.1: silently ignored once authenticated 615 SSH_MSG_USERAUTH_REQUEST => {}, 616 else => try sendUnimplemented(conn), 617 } 618 } 619 620 fn maybeRefillRecvWindowForBufferedInput(self: *SessionCtx) !void { 621 if (self.remote_closed or self.closed) return; 622 // credit only what the incoming buffer can still take 623 const buffered: u32 = @intCast(self.incomingBytes().len); 624 try maybeRefillRecvWindow(self.conn, self.channel, max_incoming_buffered - buffered); 625 } 626 627 /// signal the consumer's exit status and tear the channel down. 628 pub fn exit(self: *SessionCtx, status: u32) !void { 629 if (self.closed) return; 630 self.closed = true; 631 const conn = self.conn; 632 conn.idle.closing.store(true, .release); 633 634 // a peer CLOSE is acknowledged by the packet pump. don't send data, 635 // exit-status, or EOF after that acknowledgement. 636 if (!self.remote_closed) { 637 // exit-status request (informational; client uses it as the 638 // command's exit code) 639 { 640 var req: std.ArrayList(u8) = .empty; 641 defer req.deinit(conn.allocator); 642 try req.append(conn.allocator, SSH_MSG_CHANNEL_REQUEST); 643 try writeU32(&req, conn.allocator, self.channel.remote_id); 644 try writeStringField(&req, conn.allocator, "exit-status"); 645 try req.append(conn.allocator, 0); // want_reply MUST be false 646 try writeU32(&req, conn.allocator, status); 647 try conn.writePacket(&.{req.items}); 648 } 649 650 // EOF then CLOSE 651 try sendChannelMessage(conn, self.channel, SSH_MSG_CHANNEL_EOF); 652 try sendChannelMessage(conn, self.channel, SSH_MSG_CHANNEL_CLOSE); 653 } 654 drainConnection(conn); 655 } 656 }; 657 658 fn drainConnection(conn: *Conn) void { 659 conn.idle.closing.store(true, .release); 660 // read and discard until the peer closes (TCP FIN) before letting the 661 // caller close the socket. a git client, after our CHANNEL_CLOSE, still 662 // sends its own CHANNEL_CLOSE and SSH_MSG_DISCONNECT before closing; if 663 // we close with those unread, Linux sends RST instead of FIN, which the 664 // client reports as "Connection reset by peer" and treats as a failed 665 // push even though the ref updated. draining to EOF leaves nothing 666 // unread, so we send a clean FIN. the bytes don't matter, and the host's 667 // watchdog bounds how long a peer can keep this going. 668 _ = conn.reader.discardRemaining() catch {}; 669 conn.drained = true; 670 } 671 672 /// std.Io.Writer adapter that ships bytes to a SessionCtx as CHANNEL_DATA. 673 /// useful for plugging the session into anything that wants a *std.Io.Writer 674 /// (e.g. xitui.StreamTerminal). 675 pub const SessionWriter = struct { 676 interface: std.Io.Writer, 677 sess: *SessionCtx, 678 679 pub fn init(sess: *SessionCtx, buffer: []u8) SessionWriter { 680 return .{ 681 .interface = .{ 682 .vtable = &.{ .drain = drain }, 683 .buffer = buffer, 684 }, 685 .sess = sess, 686 }; 687 } 688 689 fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { 690 const self: *SessionWriter = @fieldParentPtr("interface", w); 691 692 // first ship anything already accumulated in the Writer's buffer 693 const buffered = w.buffered(); 694 self.sess.writeBytes(buffered) catch |err| return self.sess.failWrite(err); 695 696 // then ship the bytes passed in directly. data[0..len-1] are written 697 // once each; data[len-1] is written `splat` times (this is how the 698 // Writer interface represents fan-out / repeated patterns). 699 var extra: usize = 0; 700 for (data[0 .. data.len - 1]) |chunk| { 701 self.sess.writeBytes(chunk) catch |err| return self.sess.failWrite(err); 702 extra += chunk.len; 703 } 704 const pattern = data[data.len - 1]; 705 for (0..splat) |_| { 706 self.sess.writeBytes(pattern) catch |err| return self.sess.failWrite(err); 707 extra += pattern.len; 708 } 709 710 // consume tells the Writer how many bytes (buffered + data) were 711 // processed and clears w.end. it returns the count attributed to 712 // data, which is what `write` propagates back to the caller. 713 return w.consume(buffered.len + extra); 714 } 715 }; 716 717 /// std.Io.Reader adapter that drains incoming CHANNEL_DATA from a SessionCtx. 718 /// when the consumer reads beyond what's buffered, runs the SSH packet loop 719 /// (via processOneBackgroundPacket) until more bytes arrive or the peer 720 /// closes the channel. 721 pub const SessionReader = struct { 722 interface: std.Io.Reader, 723 sess: *SessionCtx, 724 725 pub fn init(sess: *SessionCtx, buffer: []u8) SessionReader { 726 return .{ 727 .interface = .{ 728 .vtable = &.{ .stream = stream }, 729 .buffer = buffer, 730 .seek = 0, 731 .end = 0, 732 }, 733 .sess = sess, 734 }; 735 } 736 737 fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { 738 const self: *SessionReader = @fieldParentPtr("interface", r); 739 740 // wait for data to arrive (or EOF) 741 while (self.sess.incomingBytes().len == 0) { 742 if (self.sess.incoming_eof) return error.EndOfStream; 743 self.sess.processOneBackgroundPacket() catch |err| return self.sess.failRead(err); 744 } 745 746 // drain as much buffered input as the limit allows, in one go 747 const chunk = limit.sliceConst(self.sess.incomingBytes()); 748 const written = try w.write(chunk); 749 750 self.sess.consumeIncoming(written); 751 self.sess.maybeRefillRecvWindowForBufferedInput() catch |err| return self.sess.failRead(err); 752 753 return written; 754 } 755 }; 756 757 // --------------------------------------------------------------------------- 758 // public entry point 759 // --------------------------------------------------------------------------- 760 761 /// `handler` must be a pointer to a struct with a method: 762 /// pub fn handleSession(self, sess: *SessionCtx, request: Request) anyerror!void 763 /// invoked once the channel is open and a shell/exec request has arrived. 764 /// 765 /// `reader` and `writer` are the bidirectional byte stream. `idle` is kept 766 /// current for the host's watchdog. 767 pub fn handleConnection( 768 io: std.Io, 769 allocator: std.mem.Allocator, 770 reader: *std.Io.Reader, 771 writer: *std.Io.Writer, 772 host_key: *const HostKey, 773 idle: *IdleState, 774 handler: anytype, 775 ) !void { 776 const client_version = try exchangeVersions(allocator, reader, writer); 777 defer allocator.free(client_version); 778 779 var conn = try runKex(io, allocator, reader, writer, host_key, client_version, idle); 780 defer std.crypto.secureZero(u8, std.mem.asBytes(&conn.cs_cipher)); 781 defer std.crypto.secureZero(u8, std.mem.asBytes(&conn.sc_cipher)); 782 783 authAndRunChannels(&conn, handler) catch |err| { 784 disconnectOnError(&conn, err); 785 return err; 786 }; 787 } 788 789 fn authAndRunChannels(conn: *Conn, handler: anytype) !void { 790 const client_key = try runAuth(conn); 791 defer conn.allocator.free(client_key.blob); 792 try runChannelLayer(conn, &client_key, handler); 793 } 794 795 /// tell the peer why we're hanging up (RFC 4253 §11.1), best effort. protocol 796 /// errors are named for whoever is debugging the client. 797 fn disconnectOnError(conn: *Conn, err: anyerror) void { 798 if (conn.drained) return; 799 const reason: u32, const description: []const u8 = switch (err) { 800 // the peer hung up first, or the transport is broken 801 error.EndOfStream, error.ReadFailed, error.WriteFailed => return, 802 error.MacVerificationFailed => .{ SSH_DISCONNECT_MAC_ERROR, @errorName(err) }, 803 error.OutOfMemory, error.Canceled => .{ SSH_DISCONNECT_BY_APPLICATION, "server error" }, 804 else => .{ SSH_DISCONNECT_PROTOCOL_ERROR, @errorName(err) }, 805 }; 806 807 disconnect(conn, reason, description) catch {}; 808 } 809 810 fn disconnect(conn: *Conn, reason: u32, description: []const u8) !void { 811 var buf: std.ArrayList(u8) = .empty; 812 defer buf.deinit(conn.allocator); 813 try buf.append(conn.allocator, SSH_MSG_DISCONNECT); 814 try writeU32(&buf, conn.allocator, reason); 815 try writeStringField(&buf, conn.allocator, description); 816 try writeStringField(&buf, conn.allocator, ""); // language tag 817 try conn.writePacket(&.{buf.items}); 818 } 819 820 // --------------------------------------------------------------------------- 821 // version exchange (RFC 4253 §4.2) 822 // --------------------------------------------------------------------------- 823 824 fn exchangeVersions( 825 allocator: std.mem.Allocator, 826 reader: *std.Io.Reader, 827 writer: *std.Io.Writer, 828 ) ![]u8 { 829 try writer.writeAll(server_version ++ "\r\n"); 830 try writer.flush(); 831 832 // the spec allows the client to send comment lines before its banner; 833 // skip anything that isn't an "SSH-2.0-…" / "SSH-1.99-…" line, up to a cap 834 // so a garbage-spewing peer can't hold the connection open forever. 835 var lines: u32 = 0; 836 while (lines < max_banner_lines) : (lines += 1) { 837 const line = (try reader.takeDelimiter('\n')) orelse return error.UnexpectedEof; 838 const trimmed = if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; 839 if (std.mem.startsWith(u8, trimmed, "SSH-2.0-") or std.mem.startsWith(u8, trimmed, "SSH-1.99-")) { 840 return try allocator.dupe(u8, trimmed); 841 } 842 } 843 return error.TooManyBannerLines; 844 } 845 846 // --------------------------------------------------------------------------- 847 // binary packet codec, unencrypted form (RFC 4253 §6) 848 // --------------------------------------------------------------------------- 849 850 pub fn writePlainPacket(io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 851 const block: usize = 8; 852 const initial_pad = block - ((5 + payload.len) % block); 853 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 854 const packet_len: u32 = @intCast(1 + payload.len + padding_len); 855 856 try writer.writeInt(u32, packet_len, .big); 857 try writer.writeByte(padding_len); 858 try writer.writeAll(payload); 859 860 var padding: [255]u8 = undefined; 861 io.random(padding[0..padding_len]); 862 try writer.writeAll(padding[0..padding_len]); 863 try writer.flush(); 864 } 865 866 pub fn readPlainPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 867 const packet_len = try reader.takeInt(u32, .big); 868 if (packet_len < 8 or packet_len > max_packet_len) return error.InvalidPacketLength; 869 const padding_len = try reader.takeByte(); 870 if (padding_len < 4 or @as(u32, padding_len) + 1 > packet_len) return error.InvalidPadding; 871 const payload_len = packet_len - 1 - @as(u32, padding_len); 872 // a payload starts with its message type 873 if (payload_len == 0) return error.EmptyPacket; 874 875 const payload = try reader.readAlloc(allocator, payload_len); 876 errdefer allocator.free(payload); 877 try reader.discardAll(padding_len); 878 return payload; 879 } 880 881 // IGNORE/DEBUG/UNIMPLEMENTED may arrive at any time (RFC 4253 §11); skip 882 // them wherever a specific message is expected 883 fn isIgnorableMsg(msg_type: u8) bool { 884 return msg_type == SSH_MSG_IGNORE or msg_type == SSH_MSG_UNIMPLEMENTED or msg_type == SSH_MSG_DEBUG; 885 } 886 887 /// packets handled during the plaintext phase — each direction's cipher picks 888 /// up its sequence number where that direction left off. 889 pub const PlainSeqs = struct { read: u64 = 0, written: u64 = 0 }; 890 891 // transport for KEX packets: the initial exchange runs in plaintext, a rekey 892 // runs under the current session ciphers. 893 pub const KexTransport = union(enum) { 894 plain: *PlainSeqs, 895 encrypted: struct { cs: *Cipher, sc: *Cipher }, 896 897 // read one packet, skipping ignorable messages — unless strict kex is in 898 // force, which bans them mid-handshake 899 pub fn readPacket(self: KexTransport, allocator: std.mem.Allocator, reader: *std.Io.Reader, strict: bool) ![]u8 { 900 while (true) { 901 const packet = switch (self) { 902 .plain => |seqs| packet: { 903 const packet = try readPlainPacket(allocator, reader); 904 seqs.read += 1; 905 break :packet packet; 906 }, 907 .encrypted => |ciphers| try ciphers.cs.readPacket(allocator, reader), 908 }; 909 if (isIgnorableMsg(packet[0])) { 910 allocator.free(packet); 911 if (strict) return error.StrictKexViolation; 912 continue; 913 } 914 return packet; 915 } 916 } 917 918 fn writePacket(self: KexTransport, io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 919 switch (self) { 920 .plain => |seqs| { 921 try writePlainPacket(io, writer, payload); 922 seqs.written += 1; 923 }, 924 .encrypted => |ciphers| try ciphers.sc.writePacket(io, writer, &.{payload}), 925 } 926 } 927 }; 928 929 // read one encrypted packet for the auth and channel layers, transparently 930 // skipping ignorable messages and servicing client-initiated rekeys. 931 pub fn readSessionPacket(conn: *Conn) ![]u8 { 932 while (true) { 933 const packet = try conn.readPacket(); 934 if (isIgnorableMsg(packet[0])) { 935 conn.allocator.free(packet); 936 continue; 937 } 938 // the peer is hanging up (RFC 4253 §11.1). same end of the packet 939 // stream as a transport close, so callers handle both the same way. 940 if (packet[0] == SSH_MSG_DISCONNECT) { 941 conn.allocator.free(packet); 942 return error.EndOfStream; 943 } 944 if (packet[0] == SSH_MSG_KEXINIT) { 945 defer conn.allocator.free(packet); 946 _ = conn.idle.activity.fetchAdd(1, .acq_rel); 947 try runRekey(conn, packet); 948 continue; 949 } 950 _ = conn.idle.activity.fetchAdd(1, .acq_rel); 951 return packet; 952 } 953 } 954 955 /// RFC 4253 §11.4 — an unrecognized message must be answered with 956 /// SSH_MSG_UNIMPLEMENTED carrying the offending packet's sequence number. 957 fn sendUnimplemented(conn: *Conn) !void { 958 var packet: [5]u8 = undefined; 959 packet[0] = SSH_MSG_UNIMPLEMENTED; 960 // the read already advanced past the packet we're rejecting 961 std.mem.writeInt(u32, packet[1..5], @truncate(conn.cs_cipher.seq - 1), .big); 962 try conn.writePacket(&.{&packet}); 963 } 964 965 // --------------------------------------------------------------------------- 966 // SSH field encoders / decoders (RFC 4251 §5) 967 // --------------------------------------------------------------------------- 968 969 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 970 var len_bytes: [4]u8 = undefined; 971 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 972 try buf.appendSlice(allocator, &len_bytes); 973 try buf.appendSlice(allocator, bytes); 974 } 975 976 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 977 var total: usize = 0; 978 for (names, 0..) |name, i| { 979 if (i > 0) total += 1; // comma separator 980 total += name.len; 981 } 982 var len_bytes: [4]u8 = undefined; 983 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 984 try buf.appendSlice(allocator, &len_bytes); 985 for (names, 0..) |name, i| { 986 if (i > 0) try buf.append(allocator, ','); 987 try buf.appendSlice(allocator, name); 988 } 989 } 990 991 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 992 /// our use (X25519 shared secret) the value is always non-negative, so we 993 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 994 /// the most-significant byte is set (to keep it parsed as positive). 995 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 996 var start: usize = 0; 997 while (start < bytes.len and bytes[start] == 0) start += 1; 998 const trimmed = bytes[start..]; 999 if (trimmed.len == 0) { 1000 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 1001 return; 1002 } 1003 const prepend = (trimmed[0] & 0x80) != 0; 1004 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 1005 var len_bytes: [4]u8 = undefined; 1006 std.mem.writeInt(u32, &len_bytes, out_len, .big); 1007 try buf.appendSlice(allocator, &len_bytes); 1008 if (prepend) try buf.append(allocator, 0); 1009 try buf.appendSlice(allocator, trimmed); 1010 } 1011 1012 /// a string field's bytes, borrowed from the packet behind a fixed reader 1013 pub fn takeString(reader: *std.Io.Reader, max_len: u32) ![]const u8 { 1014 const len = try reader.takeInt(u32, .big); 1015 if (len > max_len) return error.FieldTooLarge; 1016 return reader.take(len); 1017 } 1018 1019 // the first name in the peer's preference list that we also support (RFC 1020 // 4253 §7.1) 1021 fn firstCommonName(peer_names: []const u8, our_names: []const []const u8) ?[]const u8 { 1022 var iter = std.mem.splitScalar(u8, peer_names, ','); 1023 while (iter.next()) |name| { 1024 for (our_names) |ours| { 1025 if (std.mem.eql(u8, name, ours)) return ours; 1026 } 1027 } 1028 return null; 1029 } 1030 1031 // --------------------------------------------------------------------------- 1032 // KEXINIT (RFC 4253 §7.1) 1033 // --------------------------------------------------------------------------- 1034 1035 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 1036 1037 // strict kex markers (Terrapin / CVE-2023-48795 mitigation). pseudo-algorithms 1038 // carried in the initial KEXINIT's kex list: we advertise the -s form, the 1039 // client advertises the -c form. they are never selected as an actual kex 1040 // algorithm because the matcher only picks from our_kex_algos. 1041 pub const kex_strict_server = "kex-strict-s-v00@openssh.com"; 1042 pub const kex_strict_client = "kex-strict-c-v00@openssh.com"; 1043 // the client asks for EXT_INFO after the initial NEWKEYS (RFC 8308) 1044 pub const ext_info_client = "ext-info-c"; 1045 1046 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 1047 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 1048 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 1049 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 1050 pub const our_userauth_algos = [_][]const u8{ "ssh-ed25519", "rsa-sha2-512", "rsa-sha2-256", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384" }; 1051 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 1052 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 1053 const our_compression = [_][]const u8{"none"}; 1054 1055 /// build a KEXINIT payload with the given algorithm name-lists 1056 pub fn buildKexInit( 1057 io: std.Io, 1058 allocator: std.mem.Allocator, 1059 kex_algos: []const []const u8, 1060 host_key_algos: []const []const u8, 1061 ciphers: []const []const u8, 1062 ) ![]u8 { 1063 var buf: std.ArrayList(u8) = .empty; 1064 errdefer buf.deinit(allocator); 1065 1066 try buf.append(allocator, SSH_MSG_KEXINIT); 1067 1068 var cookie: [16]u8 = undefined; 1069 io.random(&cookie); 1070 try buf.appendSlice(allocator, &cookie); 1071 1072 try writeNameList(&buf, allocator, kex_algos); 1073 try writeNameList(&buf, allocator, host_key_algos); 1074 try writeNameList(&buf, allocator, ciphers); // c->s 1075 try writeNameList(&buf, allocator, ciphers); // s->c 1076 try writeNameList(&buf, allocator, &our_macs); 1077 try writeNameList(&buf, allocator, &our_macs); 1078 try writeNameList(&buf, allocator, &our_compression); 1079 try writeNameList(&buf, allocator, &our_compression); 1080 try writeNameList(&buf, allocator, &.{}); // langs c->s 1081 try writeNameList(&buf, allocator, &.{}); // langs s->c 1082 try buf.append(allocator, 0); // first_kex_packet_follows = false 1083 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 1084 1085 return try buf.toOwnedSlice(allocator); 1086 } 1087 1088 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 1089 return buildKexInit(io, allocator, &(our_kex_algos ++ [_][]const u8{kex_strict_server}), &our_host_key_algos, &our_ciphers); 1090 } 1091 1092 // the name-lists borrow from the KEXINIT payload 1093 const ParsedKexInit = struct { 1094 kex_algos: []const u8, 1095 host_key_algos: []const u8, 1096 cs_cipher: []const u8, 1097 sc_cipher: []const u8, 1098 first_kex_packet_follows: bool, 1099 }; 1100 1101 fn parseClientKexInit(payload: []const u8) !ParsedKexInit { 1102 if (payload.len < 1 + 16) return error.KexInitTruncated; 1103 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 1104 1105 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 1106 1107 const kex_algos = try takeString(&reader, max_name_list_len); 1108 const host_key_algos = try takeString(&reader, max_name_list_len); 1109 const cs_cipher = try takeString(&reader, max_name_list_len); 1110 const sc_cipher = try takeString(&reader, max_name_list_len); 1111 1112 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 1113 for (0..6) |_| _ = try takeString(&reader, max_name_list_len); 1114 const first_kex_packet_follows = (try reader.takeByte()) != 0; 1115 _ = try reader.takeInt(u32, .big); // reserved 1116 1117 return .{ 1118 .kex_algos = kex_algos, 1119 .host_key_algos = host_key_algos, 1120 .cs_cipher = cs_cipher, 1121 .sc_cipher = sc_cipher, 1122 .first_kex_packet_follows = first_kex_packet_follows, 1123 }; 1124 } 1125 1126 // --------------------------------------------------------------------------- 1127 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 1128 // --------------------------------------------------------------------------- 1129 1130 fn runKex( 1131 io: std.Io, 1132 allocator: std.mem.Allocator, 1133 reader: *std.Io.Reader, 1134 writer: *std.Io.Writer, 1135 host_key: *const HostKey, 1136 client_version: []const u8, 1137 idle: *IdleState, 1138 ) !Conn { 1139 var seqs: PlainSeqs = .{}; 1140 const transport = KexTransport{ .plain = &seqs }; 1141 1142 // exchange KEXINITs 1143 const server_kex_init = try buildServerKexInit(io, allocator); 1144 defer allocator.free(server_kex_init); 1145 try transport.writePacket(io, writer, server_kex_init); 1146 1147 const client_kex_init = try transport.readPacket(allocator, reader, false); 1148 defer allocator.free(client_kex_init); 1149 1150 const parsed = try parseClientKexInit(client_kex_init); 1151 1152 // strict kex: when the client advertises it, its KEXINIT must be the 1153 // first packet, ignorable messages are banned until NEWKEYS, and both 1154 // seqnos reset to 0 after every NEWKEYS. 1155 const strict = firstCommonName(parsed.kex_algos, &.{kex_strict_client}) != null; 1156 if (strict and seqs.read != 1) return error.StrictKexViolation; 1157 const ext_info = firstCommonName(parsed.kex_algos, &.{ext_info_client}) != null; 1158 1159 var keys: SessionKeys = undefined; 1160 defer std.crypto.secureZero(u8, std.mem.asBytes(&keys)); 1161 const session_id = try exchangeKeys( 1162 io, 1163 allocator, 1164 reader, 1165 writer, 1166 transport, 1167 strict, 1168 host_key, 1169 client_version, 1170 client_kex_init, 1171 server_kex_init, 1172 &parsed, 1173 null, 1174 &keys, 1175 ); 1176 1177 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com. 1178 // each cipher continues its own direction's count; the read side 1179 // includes any skipped IGNORE/DEBUG packets. 1180 var conn: Conn = .{ 1181 .io = io, 1182 .allocator = allocator, 1183 .reader = reader, 1184 .writer = writer, 1185 .cs_cipher = .init(&keys.cs_enc, if (strict) 0 else seqs.read), 1186 .sc_cipher = .init(&keys.sc_enc, if (strict) 0 else seqs.written), 1187 .rekey = .{ 1188 .host_key = host_key, 1189 .client_version = client_version, 1190 .session_id = session_id, 1191 .strict = strict, 1192 }, 1193 .idle = idle, 1194 }; 1195 if (ext_info) try sendExtInfo(&conn); 1196 return conn; 1197 } 1198 1199 // advertise server-sig-algs so clients will offer rsa-sha2 keys (RFC 8308 §3.1) 1200 fn sendExtInfo(conn: *Conn) !void { 1201 var buf: std.ArrayList(u8) = .empty; 1202 defer buf.deinit(conn.allocator); 1203 try buf.append(conn.allocator, SSH_MSG_EXT_INFO); 1204 try writeU32(&buf, conn.allocator, 1); // one extension 1205 try writeStringField(&buf, conn.allocator, "server-sig-algs"); 1206 try writeNameList(&buf, conn.allocator, &our_userauth_algos); 1207 try conn.writePacket(&.{buf.items}); 1208 } 1209 1210 /// everything needed to service a client-initiated rekey mid-session. 1211 const RekeyState = struct { 1212 host_key: *const HostKey, 1213 client_version: []const u8, 1214 session_id: [Sha256.digest_length]u8, 1215 strict: bool, 1216 }; 1217 1218 // service a rekey whose triggering KEXINIT payload has just been read: run 1219 // the whole exchange under the current keys, then swap the new keys into 1220 // both ciphers in place. 1221 fn runRekey(conn: *Conn, client_kex_init: []const u8) !void { 1222 const parsed = try parseClientKexInit(client_kex_init); 1223 1224 // the exchange reads and writes through the ciphers directly 1225 conn.idle.waiting.store(true, .release); 1226 defer conn.idle.waiting.store(false, .release); 1227 1228 const server_kex_init = try buildServerKexInit(conn.io, conn.allocator); 1229 defer conn.allocator.free(server_kex_init); 1230 try conn.sc_cipher.writePacket(conn.io, conn.writer, &.{server_kex_init}); 1231 1232 var keys: SessionKeys = undefined; 1233 defer std.crypto.secureZero(u8, std.mem.asBytes(&keys)); 1234 _ = try exchangeKeys( 1235 conn.io, 1236 conn.allocator, 1237 conn.reader, 1238 conn.writer, 1239 .{ .encrypted = .{ .cs = &conn.cs_cipher, .sc = &conn.sc_cipher } }, 1240 false, // strict kex message rules apply to the initial exchange only 1241 conn.rekey.host_key, 1242 conn.rekey.client_version, 1243 client_kex_init, 1244 server_kex_init, 1245 &parsed, 1246 &conn.rekey.session_id, 1247 &keys, 1248 ); 1249 1250 // seqnos continue across a rekey unless strict kex was negotiated, 1251 // which resets them after every NEWKEYS 1252 conn.cs_cipher = .init(&keys.cs_enc, if (conn.rekey.strict) 0 else conn.cs_cipher.seq); 1253 conn.sc_cipher = .init(&keys.sc_enc, if (conn.rekey.strict) 0 else conn.sc_cipher.seq); 1254 } 1255 1256 // the KEX core shared by the initial exchange and rekeys: pick algorithms, 1257 // run the (hybrid) ECDH round trip, exchange NEWKEYS, derive keys. both 1258 // KEXINIT payloads have already been exchanged by the caller, which also owns 1259 // `parsed`; the client's raw payload comes along too because the exchange hash 1260 // covers it verbatim. session_id is null on the initial exchange (where it 1261 // becomes the exchange hash) and the original session id on a rekey. fills 1262 // `keys` and returns the exchange hash. 1263 fn exchangeKeys( 1264 io: std.Io, 1265 allocator: std.mem.Allocator, 1266 reader: *std.Io.Reader, 1267 writer: *std.Io.Writer, 1268 transport: KexTransport, 1269 strict: bool, 1270 host_key: *const HostKey, 1271 client_version: []const u8, 1272 client_kex_init: []const u8, 1273 server_kex_init: []const u8, 1274 parsed: *const ParsedKexInit, 1275 session_id: ?*const [Sha256.digest_length]u8, 1276 keys: *SessionKeys, 1277 ) ![Sha256.digest_length]u8 { 1278 const kex_algo = firstCommonName(parsed.kex_algos, &our_kex_algos) orelse return error.NoCommonKexAlgorithm; 1279 if (firstCommonName(parsed.host_key_algos, &our_host_key_algos) == null) return error.NoCommonHostKeyAlgorithm; 1280 if (firstCommonName(parsed.cs_cipher, &our_ciphers) == null) return error.NoCommonCipher; 1281 if (firstCommonName(parsed.sc_cipher, &our_ciphers) == null) return error.NoCommonCipher; 1282 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 1283 1284 // a client may follow its KEXINIT with a kex packet for its guess. the 1285 // guess is right only when both sides' first kex and host key algorithms 1286 // match (RFC 4253 §7.1) — not when the client's first choice merely 1287 // happens to be kex_algo, so this compares against our list. a client 1288 // whose guess was wrong re-sends an init for the negotiated method. 1289 if (parsed.first_kex_packet_follows) { 1290 var kex_iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 1291 var host_key_iter = std.mem.splitScalar(u8, parsed.host_key_algos, ','); 1292 const guessed_right = std.mem.eql(u8, kex_iter.first(), our_kex_algos[0]) and 1293 std.mem.eql(u8, host_key_iter.first(), our_host_key_algos[0]); 1294 if (!guessed_right) { 1295 const wrong_guess = try transport.readPacket(allocator, reader, strict); 1296 allocator.free(wrong_guess); 1297 } 1298 } 1299 1300 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 1301 // wire shape, only the string size differs). 1302 const ecdh_init = try transport.readPacket(allocator, reader, strict); 1303 defer allocator.free(ecdh_init); 1304 if (ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 1305 1306 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 1307 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 1308 const client_blob = try takeString(&ecdh_init_reader, expected_client_len); 1309 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 1310 1311 // derive server reply blob (S_REPLY) + shared secret K. 1312 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 1313 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 1314 // K = SHA-256(K_MLKEM || K_X25519). 1315 var server_blob_buf: [hybrid_server_blob_len]u8 = undefined; 1316 var k: [Sha256.digest_length]u8 = undefined; 1317 defer std.crypto.secureZero(u8, &k); 1318 const server_blob: []const u8 = blk: { 1319 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 1320 var x25519_client_pub: [X25519.public_length]u8 = undefined; 1321 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 1322 var server_kp = X25519.KeyPair.generate(io); 1323 defer std.crypto.secureZero(u8, &server_kp.secret_key); 1324 var x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 1325 defer std.crypto.secureZero(u8, &x25519_shared); 1326 1327 if (!hybrid) { 1328 server_blob_buf[0..X25519.public_length].* = server_kp.public_key; 1329 k = x25519_shared; 1330 break :blk server_blob_buf[0..X25519.public_length]; 1331 } 1332 1333 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 1334 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 1335 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 1336 var encap = pq_pub.encaps(io); 1337 defer std.crypto.secureZero(u8, &encap.shared_secret); 1338 1339 server_blob_buf[0..MLKem768.ciphertext_length].* = encap.ciphertext; 1340 server_blob_buf[MLKem768.ciphertext_length..].* = server_kp.public_key; 1341 1342 var h = Sha256.init(.{}); 1343 defer std.crypto.secureZero(u8, std.mem.asBytes(&h)); 1344 h.update(&encap.shared_secret); 1345 h.update(&x25519_shared); 1346 h.final(&k); 1347 break :blk &server_blob_buf; 1348 }; 1349 1350 // build host key blob (K_S) 1351 var host_key_blob: std.ArrayList(u8) = .empty; 1352 defer host_key_blob.deinit(allocator); 1353 try host_key.appendPublicBlob(&host_key_blob, allocator); 1354 1355 // build exchange hash input and compute H 1356 const exchange_hash = try computeExchangeHash( 1357 allocator, 1358 client_version, 1359 server_version, 1360 client_kex_init, 1361 server_kex_init, 1362 host_key_blob.items, 1363 client_blob, 1364 server_blob, 1365 &k, 1366 hybrid, 1367 ); 1368 1369 // sign H with the host key, format as ssh signature blob 1370 var signature_blob: std.ArrayList(u8) = .empty; 1371 defer signature_blob.deinit(allocator); 1372 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 1373 1374 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 1375 var reply: std.ArrayList(u8) = .empty; 1376 defer reply.deinit(allocator); 1377 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 1378 try writeStringField(&reply, allocator, host_key_blob.items); 1379 try writeStringField(&reply, allocator, server_blob); 1380 try writeStringField(&reply, allocator, signature_blob.items); 1381 try transport.writePacket(io, writer, reply.items); 1382 1383 // NEWKEYS — both sides switch to the new keys after this is sent and 1384 // the peer's NEWKEYS is received. 1385 try transport.writePacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 1386 1387 const peer_newkeys = try transport.readPacket(allocator, reader, strict); 1388 defer allocator.free(peer_newkeys); 1389 if (peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 1390 1391 // derive session keys per RFC 4253 §7.2. only the encrypt keys are 1392 // needed for chacha20-poly1305 (no separate MAC/IV). 1393 try deriveSessionKeys(allocator, &k, &exchange_hash, if (session_id) |sid| sid else &exchange_hash, keys, hybrid); 1394 return exchange_hash; 1395 } 1396 1397 // --------------------------------------------------------------------------- 1398 // exchange hash (RFC 4253 §8, RFC 5656 §4) 1399 // --------------------------------------------------------------------------- 1400 1401 pub fn computeExchangeHash( 1402 allocator: std.mem.Allocator, 1403 client_version: []const u8, 1404 server_version_str: []const u8, 1405 client_kex_init: []const u8, 1406 server_kex_init: []const u8, 1407 host_key_blob: []const u8, 1408 client_ephemeral: []const u8, 1409 server_ephemeral: []const u8, 1410 shared_secret: []const u8, 1411 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1412 /// as a plain SSH string (length-prefixed bytes). 1413 k_is_string: bool, 1414 ) ![Sha256.digest_length]u8 { 1415 var buf: std.ArrayList(u8) = .empty; 1416 defer buf.deinit(allocator); 1417 defer std.crypto.secureZero(u8, buf.items); 1418 // reserved up front so a reallocation can't leave K behind 1419 try buf.ensureTotalCapacityPrecise(allocator, 8 * 4 + 1 + client_version.len + server_version_str.len + 1420 client_kex_init.len + server_kex_init.len + host_key_blob.len + client_ephemeral.len + 1421 server_ephemeral.len + shared_secret.len); 1422 1423 try writeStringField(&buf, allocator, client_version); 1424 try writeStringField(&buf, allocator, server_version_str); 1425 try writeStringField(&buf, allocator, client_kex_init); 1426 try writeStringField(&buf, allocator, server_kex_init); 1427 try writeStringField(&buf, allocator, host_key_blob); 1428 try writeStringField(&buf, allocator, client_ephemeral); 1429 try writeStringField(&buf, allocator, server_ephemeral); 1430 if (k_is_string) { 1431 try writeStringField(&buf, allocator, shared_secret); 1432 } else { 1433 try writeMpint(&buf, allocator, shared_secret); 1434 } 1435 1436 var hasher = Sha256.init(.{}); 1437 defer std.crypto.secureZero(u8, std.mem.asBytes(&hasher)); 1438 hasher.update(buf.items); 1439 return hasher.finalResult(); 1440 } 1441 1442 // --------------------------------------------------------------------------- 1443 // key derivation (RFC 4253 §7.2) 1444 // --------------------------------------------------------------------------- 1445 1446 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1447 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1448 // blocks chained per RFC 4253. 1449 pub const SessionKeys = struct { 1450 cs_enc: [64]u8, 1451 sc_enc: [64]u8, 1452 }; 1453 1454 pub fn deriveSessionKeys( 1455 allocator: std.mem.Allocator, 1456 shared_secret: []const u8, 1457 exchange_hash: []const u8, 1458 session_id: []const u8, 1459 out: *SessionKeys, 1460 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1461 k_is_string: bool, 1462 ) !void { 1463 // pre-build the K || H prefix once; reused for every derivation 1464 var prefix: std.ArrayList(u8) = .empty; 1465 defer prefix.deinit(allocator); 1466 defer std.crypto.secureZero(u8, prefix.items); 1467 // reserved up front so a reallocation can't leave K behind 1468 try prefix.ensureTotalCapacityPrecise(allocator, 4 + 1 + shared_secret.len + exchange_hash.len); 1469 if (k_is_string) { 1470 try writeStringField(&prefix, allocator, shared_secret); 1471 } else { 1472 try writeMpint(&prefix, allocator, shared_secret); 1473 } 1474 try prefix.appendSlice(allocator, exchange_hash); 1475 1476 deriveKey(prefix.items, 'C', session_id, &out.cs_enc); 1477 deriveKey(prefix.items, 'D', session_id, &out.sc_enc); 1478 } 1479 1480 fn deriveKey( 1481 prefix: []const u8, // K || H, already encoded 1482 letter: u8, 1483 session_id: []const u8, 1484 out: *[2 * Sha256.digest_length]u8, 1485 ) void { 1486 // a finished context still holds its digest and last input block 1487 // K_1 = HASH(K || H || letter || session_id) 1488 var first = Sha256.init(.{}); 1489 defer std.crypto.secureZero(u8, std.mem.asBytes(&first)); 1490 first.update(prefix); 1491 first.update(&.{letter}); 1492 first.update(session_id); 1493 first.final(out[0..Sha256.digest_length]); 1494 1495 // K_2 = HASH(K || H || K_1) 1496 var second = Sha256.init(.{}); 1497 defer std.crypto.secureZero(u8, std.mem.asBytes(&second)); 1498 second.update(prefix); 1499 second.update(out[0..Sha256.digest_length]); 1500 second.final(out[Sha256.digest_length..]); 1501 } 1502 1503 // --------------------------------------------------------------------------- 1504 // chacha20-poly1305@openssh.com packet codec 1505 // --------------------------------------------------------------------------- 1506 // 1507 // per openssh's PROTOCOL.chacha20poly1305: 1508 // K_2 = first 32 bytes of key material — encrypts the packet body 1509 // K_1 = next 32 bytes — encrypts the 4-byte length field 1510 // nonce = 64-bit big-endian sequence number 1511 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1512 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1513 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1514 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1515 // 1516 // padding is computed on the body alone (padding_length byte + payload + 1517 // padding) — the 4-byte length field is excluded from alignment. body must 1518 // be a multiple of 8 bytes; minimum padding 4 bytes. 1519 1520 pub const Cipher = struct { 1521 main_key: [32]u8, // K_2 1522 header_key: [32]u8, // K_1 1523 // wider than the 32-bit wire seqno, so a peer that never rekeys fails the 1524 // mac at 2^32 packets instead of wrapping into nonce reuse 1525 seq: u64, 1526 1527 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1528 return .{ 1529 .main_key = key_material[0..32].*, 1530 .header_key = key_material[32..64].*, 1531 .seq = initial_seq, 1532 }; 1533 } 1534 1535 fn makeNonce(seq: u64) [8]u8 { 1536 var nonce: [8]u8 = undefined; 1537 std.mem.writeInt(u64, &nonce, seq, .big); 1538 return nonce; 1539 } 1540 1541 fn bodyLength(self: *const Cipher, enc_length: *const [4]u8) !u32 { 1542 var plain: [4]u8 = undefined; 1543 ChaCha20.xor(&plain, enc_length, 0, self.header_key, makeNonce(self.seq)); 1544 const len = std.mem.readInt(u32, &plain, .big); 1545 if (len < 8 or len > max_packet_len or len % 8 != 0) return error.InvalidPacketLength; 1546 return len; 1547 } 1548 1549 fn peekPacket(self: *const Cipher, reader: *std.Io.Reader) !void { 1550 const len = 4 + (try self.bodyLength(try reader.peekArray(4))) + Poly1305.mac_length; 1551 if (len > reader.buffer.len) return error.ReadBufferTooSmall; 1552 _ = try reader.peek(len); 1553 } 1554 1555 fn hasBufferedPacket(self: *const Cipher, reader: *std.Io.Reader) !bool { 1556 const bytes = reader.buffered(); 1557 if (bytes.len < 4) return false; 1558 return bytes.len >= 4 + (try self.bodyLength(bytes[0..4])) + Poly1305.mac_length; 1559 } 1560 1561 /// the payload is the concatenation of `parts` 1562 pub fn writePacket( 1563 self: *Cipher, 1564 io: std.Io, 1565 writer: *std.Io.Writer, 1566 parts: []const []const u8, 1567 ) !void { 1568 var payload_len: usize = 0; 1569 for (parts) |part| payload_len += part.len; 1570 1571 const block: usize = 8; 1572 const initial_pad = block - ((1 + payload_len) % block); 1573 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1574 const body_len = 1 + payload_len + padding_len; 1575 if (body_len > max_packet_len) return error.PacketTooLarge; 1576 1577 const nonce = makeNonce(self.seq); 1578 1579 // encrypted length || body || mac, contiguous so the packet goes out 1580 // in one write. stack-allocated to avoid a heap alloc on every packet. 1581 var packet_buf: [packet_buffer_size]u8 = undefined; 1582 const packet = packet_buf[0 .. 4 + body_len + Poly1305.mac_length]; 1583 const enc_length = packet[0..4]; 1584 const body = packet[4..][0..body_len]; 1585 1586 // plaintext body = padding_length || payload || random padding 1587 body[0] = padding_len; 1588 var end: usize = 1; 1589 for (parts) |part| { 1590 @memcpy(body[end..][0..part.len], part); 1591 end += part.len; 1592 } 1593 io.random(body[end..]); 1594 1595 // encrypt body in place with counter=1 1596 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1597 1598 // encrypt length field with header key, counter=0 1599 std.mem.writeInt(u32, enc_length, @intCast(body_len), .big); 1600 ChaCha20.xor(enc_length, enc_length, 0, self.header_key, nonce); 1601 1602 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1603 var poly_key: [Poly1305.key_length]u8 = undefined; 1604 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1605 1606 // mac over encrypted_length || encrypted_body 1607 var poly = Poly1305.init(&poly_key); 1608 poly.update(packet[0 .. 4 + body_len]); 1609 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1610 1611 try writer.writeAll(packet); 1612 try writer.flush(); 1613 1614 self.seq += 1; 1615 } 1616 1617 pub fn readPacket( 1618 self: *Cipher, 1619 allocator: std.mem.Allocator, 1620 reader: *std.Io.Reader, 1621 ) ![]u8 { 1622 const nonce = makeNonce(self.seq); 1623 1624 var enc_length: [4]u8 = undefined; 1625 try reader.readSliceAll(&enc_length); 1626 1627 const body_len = try self.bodyLength(&enc_length); 1628 1629 // the body allocation becomes the returned payload, so a packet only 1630 // ever costs one allocation 1631 const body = try allocator.alloc(u8, body_len); 1632 errdefer allocator.free(body); 1633 try reader.readSliceAll(body); 1634 1635 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1636 try reader.readSliceAll(&tag_recv); 1637 1638 var poly_key: [Poly1305.key_length]u8 = undefined; 1639 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1640 1641 var poly = Poly1305.init(&poly_key); 1642 poly.update(&enc_length); 1643 poly.update(body); 1644 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1645 poly.final(&tag_computed); 1646 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1647 return error.MacVerificationFailed; 1648 } 1649 1650 // decrypt the body in place 1651 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1652 1653 const padding_len = body[0]; 1654 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1655 const payload_len = body_len - 1 - @as(u32, padding_len); 1656 // a payload starts with its message type 1657 if (payload_len == 0) return error.EmptyPacket; 1658 1659 // shift the payload over the padding_length byte, then release the 1660 // trailing padding (caller owns the result) 1661 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1662 const payload = try allocator.realloc(body, payload_len); 1663 1664 self.seq += 1; 1665 return payload; 1666 } 1667 }; 1668 1669 // --------------------------------------------------------------------------- 1670 // post-KEX: service request + user authentication (RFC 4252) 1671 // --------------------------------------------------------------------------- 1672 1673 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1674 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1675 /// `Offering public key: … SHA256:…`. 1676 pub const fingerprint_len = 50; 1677 1678 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1679 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1680 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1681 var digest: [Sha256.digest_length]u8 = undefined; 1682 Sha256.hash(pubkey_blob, &digest, .{}); 1683 1684 var out: [fingerprint_len]u8 = undefined; 1685 @memcpy(out[0..7], "SHA256:"); 1686 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1687 std.debug.assert(encoded.len == fingerprint_len - 7); 1688 return out; 1689 } 1690 1691 /// the pubkey a client authenticated with 1692 const ClientKey = struct { 1693 fingerprint: [fingerprint_len]u8, 1694 /// owned by the connection's allocator 1695 blob: []const u8, 1696 }; 1697 1698 fn runAuth(conn: *Conn) !ClientKey { 1699 const allocator = conn.allocator; 1700 1701 // step 1: service request for ssh-userauth → service accept 1702 { 1703 const req = try readSessionPacket(conn); 1704 defer allocator.free(req); 1705 if (req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1706 1707 var req_reader = std.Io.Reader.fixed(req[1..]); 1708 const service = try takeString(&req_reader, 64); 1709 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1710 1711 var accept: std.ArrayList(u8) = .empty; 1712 defer accept.deinit(allocator); 1713 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1714 try writeStringField(&accept, allocator, "ssh-userauth"); 1715 try conn.writePacket(&.{accept.items}); 1716 } 1717 1718 // step 2: USERAUTH loop until SUCCESS. accept any supported key whose 1719 // signature verifies against the offered pubkey. 1720 var auth_attempts: u32 = 0; 1721 while (true) { 1722 const req = try readSessionPacket(conn); 1723 defer allocator.free(req); 1724 if (req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1725 1726 // every request counts, probes included, so a client can't loop here 1727 // forever 1728 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1729 auth_attempts += 1; 1730 1731 var req_reader = std.Io.Reader.fixed(req[1..]); 1732 const user_name = try takeString(&req_reader, 256); 1733 const service_name = try takeString(&req_reader, 64); 1734 const method = try takeString(&req_reader, 64); 1735 1736 // RFC 4252 §5: the server must verify the requested service 1737 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1738 try sendUserauthFailure(conn); 1739 continue; 1740 } 1741 1742 if (!std.mem.eql(u8, method, "publickey")) { 1743 try sendUserauthFailure(conn); 1744 continue; 1745 } 1746 1747 const has_signature = (try req_reader.takeByte()) != 0; 1748 const algo = try takeString(&req_reader, 64); 1749 const pubkey_blob = try takeString(&req_reader, 4096); 1750 1751 if (firstCommonName(algo, &our_userauth_algos) == null) { 1752 try sendUserauthFailure(conn); 1753 continue; 1754 } 1755 1756 if (!has_signature) { 1757 // probe — tell the client this key is acceptable so it'll send 1758 // the signed version next. 1759 var pk_ok: std.ArrayList(u8) = .empty; 1760 defer pk_ok.deinit(allocator); 1761 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1762 try writeStringField(&pk_ok, allocator, algo); 1763 try writeStringField(&pk_ok, allocator, pubkey_blob); 1764 try conn.writePacket(&.{pk_ok.items}); 1765 continue; 1766 } 1767 1768 // has signature — verify it 1769 const signature_blob = try takeString(&req_reader, 1024); 1770 1771 const ok = verifyUserauthSignature( 1772 allocator, 1773 &conn.rekey.session_id, 1774 user_name, 1775 service_name, 1776 algo, 1777 pubkey_blob, 1778 signature_blob, 1779 ) catch |err| switch (err) { 1780 error.OutOfMemory => return err, 1781 // a malformed key or signature blob 1782 else => false, 1783 }; 1784 1785 if (!ok) { 1786 try sendUserauthFailure(conn); 1787 continue; 1788 } 1789 1790 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1791 return .{ .fingerprint = formatFingerprint(pubkey_blob), .blob = try allocator.dupe(u8, pubkey_blob) }; 1792 } 1793 } 1794 1795 fn sendUserauthFailure(conn: *Conn) !void { 1796 var buf: std.ArrayList(u8) = .empty; 1797 defer buf.deinit(conn.allocator); 1798 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1799 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1800 try buf.append(conn.allocator, 0); // partial_success = false 1801 try conn.writePacket(&.{buf.items}); 1802 } 1803 1804 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1805 /// used by the server to recompute the signed input for verification 1806 pub fn appendPublickeySignedData( 1807 buf: *std.ArrayList(u8), 1808 allocator: std.mem.Allocator, 1809 session_id: []const u8, 1810 user_name: []const u8, 1811 service_name: []const u8, 1812 algo: []const u8, 1813 pubkey_blob: []const u8, 1814 ) !void { 1815 try writeStringField(buf, allocator, session_id); 1816 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1817 try writeStringField(buf, allocator, user_name); 1818 try writeStringField(buf, allocator, service_name); 1819 try writeStringField(buf, allocator, "publickey"); 1820 try buf.append(allocator, 1); 1821 try writeStringField(buf, allocator, algo); 1822 try writeStringField(buf, allocator, pubkey_blob); 1823 } 1824 1825 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1826 // verify the supplied signature against them. 1827 fn verifyUserauthSignature( 1828 allocator: std.mem.Allocator, 1829 session_id: *const [Sha256.digest_length]u8, 1830 user_name: []const u8, 1831 service_name: []const u8, 1832 algo: []const u8, 1833 pubkey_blob: []const u8, 1834 signature_blob: []const u8, 1835 ) !bool { 1836 var signed: std.ArrayList(u8) = .empty; 1837 defer signed.deinit(allocator); 1838 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1839 1840 if (std.mem.eql(u8, algo, "ssh-ed25519")) return verifyEd25519(pubkey_blob, signature_blob, signed.items); 1841 if (std.mem.eql(u8, algo, "rsa-sha2-512")) return verifyRsa(Sha512, algo, pubkey_blob, signature_blob, signed.items); 1842 if (std.mem.eql(u8, algo, "rsa-sha2-256")) return verifyRsa(Sha256, algo, pubkey_blob, signature_blob, signed.items); 1843 if (std.mem.eql(u8, algo, "ecdsa-sha2-nistp256")) return verifyEcdsa(ecdsa.EcdsaP256Sha256, "nistp256", pubkey_blob, signature_blob, signed.items); 1844 if (std.mem.eql(u8, algo, "ecdsa-sha2-nistp384")) return verifyEcdsa(ecdsa.EcdsaP384Sha384, "nistp384", pubkey_blob, signature_blob, signed.items); 1845 return false; 1846 } 1847 1848 fn verifyEd25519(pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1849 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1850 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1851 const pk_algo = try takeString(&pubkey_reader, 64); 1852 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1853 const raw_pubkey = try takeString(&pubkey_reader, 64); 1854 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1855 // the fingerprint hashes the whole blob, so it must hold nothing else 1856 if (pubkey_reader.bufferedLen() != 0) return false; 1857 1858 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1859 var sig_reader = std.Io.Reader.fixed(signature_blob); 1860 const sig_algo = try takeString(&sig_reader, 64); 1861 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1862 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1863 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1864 1865 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1866 @memcpy(&pubkey_bytes, raw_pubkey); 1867 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1868 @memcpy(&sig_bytes, raw_sig); 1869 1870 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1871 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1872 sig.verify(signed, pk) catch return false; 1873 return true; 1874 } 1875 1876 fn verifyRsa(comptime Hash: type, algo: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1877 // parse pubkey_blob: string "ssh-rsa" || mpint e || mpint n 1878 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1879 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), "ssh-rsa")) return false; 1880 // the fingerprint hashes the whole blob, so one key must have one encoding 1881 const e = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1882 const n = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1883 if (pubkey_reader.bufferedLen() != 0) return false; 1884 1885 // parse signature_blob: string algo || string sig 1886 var sig_reader = std.Io.Reader.fixed(signature_blob); 1887 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1888 const sig = try takeString(&sig_reader, 1024); 1889 if (sig.len != n.len) return false; 1890 1891 const pk = rsa.PublicKey.fromBytes(e, n) catch return false; 1892 switch (n.len) { 1893 inline 256, 384, 512 => |len| { 1894 rsa.PKCS1v1_5Signature.verify(len, sig[0..len], signed, pk, Hash) catch return false; 1895 return true; 1896 }, 1897 else => return false, 1898 } 1899 } 1900 1901 fn verifyEcdsa(comptime Ecdsa: type, comptime curve: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1902 const algo = "ecdsa-sha2-" ++ curve; 1903 // parse pubkey_blob: string algo || string curve || string point 1904 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1905 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), algo)) return false; 1906 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), curve)) return false; 1907 const point = try takeString(&pubkey_reader, 256); 1908 // the fingerprint hashes the whole blob, so it must hold nothing else 1909 if (pubkey_reader.bufferedLen() != 0) return false; 1910 1911 // parse signature_blob: string algo || string (mpint r || mpint s) 1912 var sig_reader = std.Io.Reader.fixed(signature_blob); 1913 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1914 var rs_reader = std.Io.Reader.fixed(try takeString(&sig_reader, 256)); 1915 const r = canonicalMpintMagnitude(try takeString(&rs_reader, 128)) orelse return false; 1916 const s = canonicalMpintMagnitude(try takeString(&rs_reader, 128)) orelse return false; 1917 if (rs_reader.bufferedLen() != 0) return false; 1918 1919 // r and s become fixed-width big-endian halves of the signature 1920 const half = Ecdsa.Signature.encoded_length / 2; 1921 if (r.len > half or s.len > half) return false; 1922 var sig_bytes: [Ecdsa.Signature.encoded_length]u8 = @splat(0); 1923 @memcpy(sig_bytes[half - r.len .. half], r); 1924 @memcpy(sig_bytes[2 * half - s.len ..], s); 1925 1926 const pk = Ecdsa.PublicKey.fromSec1(point) catch return false; 1927 Ecdsa.Signature.fromBytes(sig_bytes).verify(signed, pk) catch return false; 1928 return true; 1929 } 1930 1931 // the unsigned bytes of a positive mpint in its shortest encoding (RFC 4251 1932 // §5), or null for zero, negative, or padded encodings 1933 fn canonicalMpintMagnitude(bytes: []const u8) ?[]const u8 { 1934 if (bytes.len == 0 or bytes[0] & 0x80 != 0) return null; 1935 if (bytes[0] != 0) return bytes; 1936 if (bytes.len < 2 or bytes[1] & 0x80 == 0) return null; 1937 return bytes[1..]; 1938 } 1939 1940 // --------------------------------------------------------------------------- 1941 // connection layer (RFC 4254): channels, requests, data, flow control 1942 // --------------------------------------------------------------------------- 1943 1944 const Channel = struct { 1945 local_id: u32, 1946 remote_id: u32, 1947 local_window: u32, // bytes peer may still send us before we adjust 1948 remote_window: u32, // bytes we may still send to peer before they adjust 1949 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1950 pty: ?PtySize = null, 1951 // value of GIT_PROTOCOL, one of the two env variables we keep 1952 git_protocol_buf: [64]u8 = undefined, 1953 git_protocol_len: ?usize = null, 1954 // false when NO_COLOR is set, the other env variable we keep 1955 color: bool = true, 1956 }; 1957 1958 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1959 1960 // take the uint32 width/height cell counts of a pty-req or window-change, 1961 // bounded before either initial rendering or a resize can allocate grids. 1962 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1963 fn takePtySize(r: *std.Io.Reader) !PtySize { 1964 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1965 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1966 return .{ 1967 .width_cells = @intCast(width), 1968 .height_cells = @intCast(height), 1969 }; 1970 } 1971 1972 fn runChannelLayer( 1973 conn: *Conn, 1974 client_key: *const ClientKey, 1975 handler: anytype, 1976 ) !void { 1977 const allocator = conn.allocator; 1978 var channel: ?Channel = null; 1979 1980 while (true) { 1981 const packet = try readSessionPacket(conn); 1982 defer allocator.free(packet); 1983 const msg_type = packet[0]; 1984 1985 switch (msg_type) { 1986 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1987 1988 SSH_MSG_CHANNEL_OPEN => { 1989 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1990 }, 1991 1992 SSH_MSG_CHANNEL_REQUEST => { 1993 const ch = if (channel) |*c| c else return error.UnknownChannel; 1994 const start_request = try handleChannelRequest(conn, ch, packet); 1995 // the request borrows from the packet, which outlives the session 1996 if (start_request) |request| { 1997 // any key authenticates, so the deadline holds until here 1998 conn.idle.session_started.store(true, .release); 1999 var sess = SessionCtx{ 2000 .conn = conn, 2001 .channel = ch, 2002 .fingerprint = client_key.fingerprint, 2003 .public_key = client_key.blob, 2004 }; 2005 defer sess.deinit(); 2006 handler.handleSession(&sess, request) catch |session_err| { 2007 // a failed read leaves the protocol unusable, so the 2008 // disconnect names it instead of a clean close 2009 if (sess.read_err) |read_err| return read_err; 2010 // try to send a non-zero exit status before closing 2011 sess.exit(1) catch {}; 2012 return sess.underlyingError(session_err); 2013 }; 2014 if (!sess.closed) try sess.exit(0); 2015 return; 2016 } 2017 }, 2018 2019 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 2020 const ch = if (channel) |*c| c else return error.UnknownChannel; 2021 try handleWindowAdjust(ch, packet); 2022 }, 2023 2024 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 2025 const ch = if (channel) |*c| c else return error.UnknownChannel; 2026 // before shell/exec the client shouldn't be sending data, but 2027 // some clients are chatty; discard and refill window. nothing 2028 // is buffered yet, so the whole window is available to credit. 2029 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 2030 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 2031 }, 2032 2033 SSH_MSG_CHANNEL_EOF => { 2034 const ch = if (channel) |*c| c else return error.UnknownChannel; 2035 try parseChannelId(packet, ch.local_id); 2036 }, 2037 2038 SSH_MSG_CHANNEL_CLOSE => { 2039 const ch = if (channel) |*c| c else return error.UnknownChannel; 2040 try parseChannelId(packet, ch.local_id); 2041 try sendChannelMessage(conn, ch, SSH_MSG_CHANNEL_CLOSE); 2042 drainConnection(conn); 2043 return; 2044 }, 2045 2046 // RFC 4252 §5.1: silently ignored once authenticated 2047 SSH_MSG_USERAUTH_REQUEST => {}, 2048 else => try sendUnimplemented(conn), 2049 } 2050 } 2051 } 2052 2053 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 2054 // byte SSH_MSG_GLOBAL_REQUEST 2055 // string request_name 2056 // boolean want_reply 2057 // …request-specific data we ignore 2058 var r = std.Io.Reader.fixed(packet[1..]); 2059 _ = try takeString(&r, 256); 2060 const want_reply = (try r.takeByte()) != 0; 2061 if (want_reply) { 2062 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2063 } 2064 } 2065 2066 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2067 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2068 /// return null. 2069 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 2070 // byte SSH_MSG_CHANNEL_OPEN 2071 // string channel_type 2072 // uint32 sender_channel (peer's id) 2073 // uint32 initial_window 2074 // uint32 max_packet 2075 var r = std.Io.Reader.fixed(packet[1..]); 2076 const ch_type = try takeString(&r, 64); 2077 const remote_id = try r.takeInt(u32, .big); 2078 const initial_window = try r.takeInt(u32, .big); 2079 const max_packet = try r.takeInt(u32, .big); 2080 2081 if (has_channel) { 2082 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 2083 return null; 2084 } 2085 2086 if (!std.mem.eql(u8, ch_type, "session")) { 2087 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2088 return null; 2089 } 2090 2091 // a zero max_packet would leave writeBytes looping without progress 2092 if (max_packet == 0) { 2093 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2094 return null; 2095 } 2096 2097 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2098 var reply: [17]u8 = undefined; 2099 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2100 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2101 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2102 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2103 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2104 try conn.writePacket(&.{&reply}); 2105 2106 return .{ 2107 .local_id = local_id, 2108 .remote_id = remote_id, 2109 .local_window = initial_recv_window, 2110 .remote_window = initial_window, 2111 .max_packet = max_packet, 2112 }; 2113 } 2114 2115 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2116 const allocator = conn.allocator; 2117 2118 var reply: std.ArrayList(u8) = .empty; 2119 defer reply.deinit(allocator); 2120 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2121 try writeU32(&reply, allocator, remote_id); 2122 try writeU32(&reply, allocator, reason); 2123 try writeStringField(&reply, allocator, description); 2124 try writeStringField(&reply, allocator, ""); // language tag 2125 try conn.writePacket(&.{reply.items}); 2126 } 2127 2128 /// returns the session request if this one triggered it, else null. an exec 2129 /// command borrows from `packet`. 2130 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2131 // byte SSH_MSG_CHANNEL_REQUEST 2132 // uint32 recipient_channel (== our local_id) 2133 // string request_type 2134 // boolean want_reply 2135 // …request-specific data 2136 var r = std.Io.Reader.fixed(packet[1..]); 2137 const recipient_channel = try r.takeInt(u32, .big); 2138 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2139 const req_type = try takeString(&r, 64); 2140 const want_reply = (try r.takeByte()) != 0; 2141 2142 if (std.mem.eql(u8, req_type, "pty-req")) { 2143 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2144 // uint32 height px, string modes 2145 _ = try takeString(&r, 64); 2146 ch.pty = try takePtySize(&r); 2147 try replyChannelRequest(conn, ch, want_reply, true); 2148 return null; 2149 } 2150 2151 if (std.mem.eql(u8, req_type, "env")) { 2152 // string name, string value. the rest are ignored silently. 2153 const name = try takeString(&r, max_packet_len); 2154 const value = try takeString(&r, max_packet_len); 2155 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2156 @memcpy(ch.git_protocol_buf[0..value.len], value); 2157 ch.git_protocol_len = value.len; 2158 } else if (std.mem.eql(u8, name, "NO_COLOR")) { 2159 ch.color = value.len == 0; 2160 } 2161 try replyChannelRequest(conn, ch, want_reply, true); 2162 return null; 2163 } 2164 2165 if (std.mem.eql(u8, req_type, "window-change")) { 2166 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2167 const sz = try takePtySize(&r); 2168 if (ch.pty != null) ch.pty = sz; 2169 // spec: window-change MUST NOT request a reply, but accept either 2170 try replyChannelRequest(conn, ch, want_reply, true); 2171 return null; 2172 } 2173 2174 if (std.mem.eql(u8, req_type, "shell")) { 2175 try replyChannelRequest(conn, ch, want_reply, true); 2176 return .{ .shell = .{ .pty = ch.pty, .color = ch.color } }; 2177 } 2178 2179 if (std.mem.eql(u8, req_type, "exec")) { 2180 // capture the command string for the handler to inspect 2181 const cmd = try takeString(&r, 4096); 2182 try replyChannelRequest(conn, ch, want_reply, true); 2183 return .{ .exec = .{ 2184 .command = cmd, 2185 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2186 } }; 2187 } 2188 2189 // unknown request kind — fail it 2190 try replyChannelRequest(conn, ch, want_reply, false); 2191 return null; 2192 } 2193 2194 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2195 if (!want_reply) return; 2196 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2197 } 2198 2199 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2200 var packet: [5]u8 = undefined; 2201 packet[0] = msg_type; 2202 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2203 try conn.writePacket(&.{&packet}); 2204 } 2205 2206 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2207 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2208 // uint32 recipient_channel 2209 // uint32 bytes_to_add 2210 var r = std.Io.Reader.fixed(packet[1..]); 2211 const recipient_channel = try r.takeInt(u32, .big); 2212 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2213 const add = try r.takeInt(u32, .big); 2214 ch.remote_window +|= add; 2215 } 2216 2217 // charge a payload's bytes against the receive window without keeping them. 2218 // the caller credits the window back, choosing the budget that suits it. 2219 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2220 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2221 // uint32 recipient_channel 2222 // [if extended: uint32 type_code] 2223 // string data 2224 const payload = try parseChannelData(packet, extended, ch.local_id); 2225 const data_len: u32 = @intCast(payload.len); 2226 2227 if (data_len > ch.local_window) return error.WindowExceeded; 2228 ch.local_window -= data_len; 2229 } 2230 2231 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2232 if (packet.len < 1) return error.EmptyPacket; 2233 var r = std.Io.Reader.fixed(packet[1..]); 2234 const recipient_channel = try r.takeInt(u32, .big); 2235 if (recipient_channel != expected_channel) return error.UnknownChannel; 2236 if (extended) { 2237 const data_type = try r.takeInt(u32, .big); 2238 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2239 } 2240 const data_len = try r.takeInt(u32, .big); 2241 // catches both data_len > remaining (would otherwise be a bounds-check 2242 // panic on the slice) and trailing junk after the declared payload. 2243 if (data_len != r.buffered().len) return error.InvalidChannelData; 2244 return r.buffered(); 2245 } 2246 2247 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2248 var r = std.Io.Reader.fixed(packet[1..]); 2249 const recipient_channel = try r.takeInt(u32, .big); 2250 if (recipient_channel != expected_channel) return error.UnknownChannel; 2251 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2252 } 2253 2254 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2255 /// of `budget`, the credit we're willing to have outstanding. used both for 2256 /// the pre-session discard path and by SessionCtx after it consumes a 2257 /// CHANNEL_DATA payload. 2258 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2259 if (ch.local_window >= budget / 2) return; 2260 const add = budget - ch.local_window; 2261 ch.local_window += add; 2262 var packet: [9]u8 = undefined; 2263 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2264 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2265 std.mem.writeInt(u32, packet[5..9], add, .big); 2266 try conn.writePacket(&.{&packet}); 2267 } 2268 2269 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2270 var bytes: [4]u8 = undefined; 2271 std.mem.writeInt(u32, &bytes, value, .big); 2272 try buf.appendSlice(allocator, &bytes); 2273 } 2274 2275 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2276 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2277 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2278 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2279 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2280 }) |case| { 2281 var bytes: [8]u8 = undefined; 2282 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2283 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2284 var reader = std.Io.Reader.fixed(&bytes); 2285 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2286 } 2287 } 2288 2289 test "channel close before shell or exec is acknowledged" { 2290 const io = std.testing.io; 2291 const allocator = std.testing.allocator; 2292 const key: [64]u8 = @splat(0x5a); 2293 var encoded: [256]u8 = undefined; 2294 var encoded_writer = std.Io.Writer.fixed(&encoded); 2295 var sender = Cipher.init(&key, 0); 2296 var open: std.ArrayList(u8) = .empty; 2297 defer open.deinit(allocator); 2298 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2299 try writeStringField(&open, allocator, "session"); 2300 try writeU32(&open, allocator, 7); 2301 try writeU32(&open, allocator, 32768); 2302 try writeU32(&open, allocator, 32768); 2303 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2304 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2305 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2306 var output: [256]u8 = undefined; 2307 var writer = std.Io.Writer.fixed(&output); 2308 var idle = IdleState{}; 2309 var conn = Conn{ 2310 .io = io, 2311 .allocator = allocator, 2312 .reader = &reader, 2313 .writer = &writer, 2314 .cs_cipher = Cipher.init(&key, 0), 2315 .sc_cipher = Cipher.init(&key, 0), 2316 .rekey = undefined, 2317 .idle = &idle, 2318 }; 2319 const Handler = struct { 2320 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2321 return error.UnexpectedSession; 2322 } 2323 }; 2324 var handler = Handler{}; 2325 try runChannelLayer(&conn, &.{ .fingerprint = @splat(0), .blob = "" }, &handler); 2326 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2327 var receiver = Cipher.init(&key, 0); 2328 const confirmation = try receiver.readPacket(allocator, &output_reader); 2329 defer allocator.free(confirmation); 2330 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2331 const close = try receiver.readPacket(allocator, &output_reader); 2332 defer allocator.free(close); 2333 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2334 try std.testing.expectEqual(0, output_reader.buffered().len); 2335 } 2336