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