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