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