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