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