╭ 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 // RFC 4252 §5.1: silently ignored once authenticated 467 SSH_MSG_USERAUTH_REQUEST => {}, 468 else => try sendUnimplemented(conn), 469 } 470 } 471 472 fn maybeRefillRecvWindowForBufferedInput(self: *SessionCtx) !void { 473 if (self.remote_closed or self.closed) return; 474 // credit only what the incoming buffer can still take 475 const buffered: u32 = @intCast(self.incomingBytes().len); 476 try maybeRefillRecvWindow(self.conn, self.channel, max_incoming_buffered - buffered); 477 } 478 479 /// signal the consumer's exit status and tear the channel down. 480 pub fn exit(self: *SessionCtx, status: u32) !void { 481 if (self.closed) return; 482 self.closed = true; 483 const conn = self.conn; 484 if (conn.idle) |idle| idle.closing.store(true, .release); 485 486 // a peer CLOSE is acknowledged by the packet pump. don't send data, 487 // exit-status, or EOF after that acknowledgement. 488 if (!self.remote_closed) { 489 // exit-status request (informational; client uses it as the 490 // command's exit code) 491 { 492 var req: std.ArrayList(u8) = .empty; 493 defer req.deinit(conn.allocator); 494 try req.append(conn.allocator, SSH_MSG_CHANNEL_REQUEST); 495 try writeU32(&req, conn.allocator, self.channel.remote_id); 496 try writeStringField(&req, conn.allocator, "exit-status"); 497 try req.append(conn.allocator, 0); // want_reply MUST be false 498 try writeU32(&req, conn.allocator, status); 499 try conn.writePacket(req.items); 500 } 501 502 // EOF then CLOSE 503 try sendChannelMessage(conn, self.channel, SSH_MSG_CHANNEL_EOF); 504 try sendChannelMessage(conn, self.channel, SSH_MSG_CHANNEL_CLOSE); 505 } 506 drainConnection(conn); 507 } 508 }; 509 510 fn drainConnection(conn: *Conn) void { 511 if (conn.idle) |idle| idle.closing.store(true, .release); 512 // read and discard until the peer closes (TCP FIN) before letting the 513 // caller close the socket. a git client, after our CHANNEL_CLOSE, still 514 // sends its own CHANNEL_CLOSE and SSH_MSG_DISCONNECT before closing; if 515 // we close with those unread, Linux sends RST instead of FIN, which the 516 // client reports as "Connection reset by peer" and treats as a failed 517 // push even though the ref updated. draining to EOF leaves nothing 518 // unread, so we send a clean FIN. the bytes don't matter, and the host's 519 // watchdog bounds how long a peer can keep this going. 520 _ = conn.reader.discardRemaining() catch {}; 521 conn.drained = true; 522 } 523 524 /// std.Io.Writer adapter that ships bytes to a SessionCtx as CHANNEL_DATA. 525 /// useful for plugging the session into anything that wants a *std.Io.Writer 526 /// (e.g. xitui.StreamTerminal). 527 pub const SessionWriter = struct { 528 interface: std.Io.Writer, 529 sess: *SessionCtx, 530 531 pub fn init(sess: *SessionCtx, buffer: []u8) SessionWriter { 532 return .{ 533 .interface = .{ 534 .vtable = &.{ .drain = drain }, 535 .buffer = buffer, 536 }, 537 .sess = sess, 538 }; 539 } 540 541 fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { 542 const self: *SessionWriter = @fieldParentPtr("interface", w); 543 544 // first ship anything already accumulated in the Writer's buffer 545 const buffered = w.buffered(); 546 if (buffered.len > 0) { 547 self.sess.writeBytes(buffered) catch |err| return self.sess.failWrite(err); 548 } 549 550 // then ship the bytes passed in directly. data[0..len-1] are written 551 // once each; data[len-1] is written `splat` times (this is how the 552 // Writer interface represents fan-out / repeated patterns). 553 var extra: usize = 0; 554 if (data.len > 1) { 555 for (data[0 .. data.len - 1]) |chunk| { 556 if (chunk.len == 0) continue; 557 self.sess.writeBytes(chunk) catch |err| return self.sess.failWrite(err); 558 extra += chunk.len; 559 } 560 } 561 if (data.len > 0) { 562 const pattern = data[data.len - 1]; 563 if (pattern.len > 0) { 564 var i: usize = 0; 565 while (i < splat) : (i += 1) { 566 self.sess.writeBytes(pattern) catch |err| return self.sess.failWrite(err); 567 extra += pattern.len; 568 } 569 } 570 } 571 572 // consume tells the Writer how many bytes (buffered + data) were 573 // processed and clears w.end. it returns the count attributed to 574 // data, which is what `write` propagates back to the caller. 575 return w.consume(buffered.len + extra); 576 } 577 }; 578 579 /// std.Io.Reader adapter that drains incoming CHANNEL_DATA from a SessionCtx. 580 /// when the consumer reads beyond what's buffered, runs the SSH packet loop 581 /// (via processOneBackgroundPacket) until more bytes arrive or the peer 582 /// closes the channel. 583 pub const SessionReader = struct { 584 interface: std.Io.Reader, 585 sess: *SessionCtx, 586 587 pub fn init(sess: *SessionCtx, buffer: []u8) SessionReader { 588 return .{ 589 .interface = .{ 590 .vtable = &.{ 591 .readVec = readVec, 592 .stream = stream, 593 }, 594 .buffer = buffer, 595 .seek = 0, 596 .end = 0, 597 }, 598 .sess = sess, 599 }; 600 } 601 602 fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { 603 const self: *SessionReader = @fieldParentPtr("interface", r); 604 605 // wait for data to arrive (or EOF) 606 while (self.sess.incomingBytes().len == 0) { 607 if (self.sess.incoming_eof) return error.EndOfStream; 608 self.sess.processOneBackgroundPacket() catch |err| return self.sess.failRead(err); 609 } 610 611 // drain as much buffered input as the limit allows, in one go 612 const chunk = limit.sliceConst(self.sess.incomingBytes()); 613 const written = try w.write(chunk); 614 615 self.sess.consumeIncoming(written); 616 self.sess.maybeRefillRecvWindowForBufferedInput() catch |err| return self.sess.failRead(err); 617 618 return written; 619 } 620 621 fn readVec(r: *std.Io.Reader, data: [][]u8) std.Io.Reader.Error!usize { 622 const self: *SessionReader = @fieldParentPtr("interface", r); 623 624 // wait until some input is buffered (or EOF) 625 while (self.sess.incomingBytes().len == 0) { 626 if (self.sess.incoming_eof) return error.EndOfStream; 627 self.sess.processOneBackgroundPacket() catch |err| return self.sess.failRead(err); 628 } 629 630 const src = self.sess.incomingBytes(); 631 632 // vtable.readVec contract: if data[0] is empty, write into r.buffer 633 // instead and return 0. without this branch the caller spins, 634 // calling readVec repeatedly with the same empty buffer. 635 if (data.len == 0 or data[0].len == 0) { 636 const dest = r.buffer[r.end..]; 637 if (dest.len == 0) return 0; 638 const copy = @min(dest.len, src.len); 639 @memcpy(dest[0..copy], src[0..copy]); 640 r.end += copy; 641 self.sess.consumeIncoming(copy); 642 self.sess.maybeRefillRecvWindowForBufferedInput() catch |err| return self.sess.failRead(err); 643 return 0; 644 } 645 646 const dest = data[0]; 647 const copy = @min(dest.len, src.len); 648 @memcpy(dest[0..copy], src[0..copy]); 649 self.sess.consumeIncoming(copy); 650 self.sess.maybeRefillRecvWindowForBufferedInput() catch |err| return self.sess.failRead(err); 651 return copy; 652 } 653 }; 654 655 // --------------------------------------------------------------------------- 656 // public entry point 657 // --------------------------------------------------------------------------- 658 659 /// `handler` must be a pointer to a struct with a method: 660 /// pub fn handleSession(self, sess: *SessionCtx, request: Request) anyerror!void 661 /// invoked once the channel is open and a shell/exec request has arrived. 662 /// 663 /// `reader` and `writer` are the bidirectional byte stream. `idle`, if 664 /// given, is kept current for the host's watchdog. 665 pub fn handleConnection( 666 io: std.Io, 667 allocator: std.mem.Allocator, 668 reader: *std.Io.Reader, 669 writer: *std.Io.Writer, 670 host_key: *const HostKey, 671 idle: ?*IdleState, 672 handler: anytype, 673 ) !void { 674 const client_version = try exchangeVersions(allocator, reader, writer); 675 defer allocator.free(client_version); 676 677 var kex = try runKex(io, allocator, reader, writer, host_key, client_version); 678 defer std.crypto.secureZero(u8, std.mem.asBytes(&kex)); 679 680 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com 681 var conn = Conn{ 682 .io = io, 683 .allocator = allocator, 684 .reader = reader, 685 .writer = writer, 686 .cs_cipher = Cipher.init(&kex.cs_key, kex.next_cs_seq), 687 .sc_cipher = Cipher.init(&kex.sc_key, kex.next_sc_seq), 688 .rekey = .{ 689 .host_key = host_key, 690 .client_version = client_version, 691 .session_id = kex.session_id, 692 .strict = kex.strict, 693 }, 694 .idle = idle, 695 }; 696 defer std.crypto.secureZero(u8, std.mem.asBytes(&conn.cs_cipher)); 697 defer std.crypto.secureZero(u8, std.mem.asBytes(&conn.sc_cipher)); 698 699 const fingerprint = runAuth(&conn) catch |err| { 700 disconnectOnError(&conn, err); 701 return err; 702 }; 703 704 runChannelLayer(&conn, &fingerprint, handler) catch |err| { 705 disconnectOnError(&conn, err); 706 return err; 707 }; 708 } 709 710 /// tell the peer why we're hanging up (RFC 4253 §11.1), best effort. protocol 711 /// errors are named for whoever is debugging the client. 712 fn disconnectOnError(conn: *Conn, err: anyerror) void { 713 if (conn.drained) return; 714 const reason: u32, const description: []const u8 = switch (err) { 715 // the peer hung up first, or the transport is broken 716 error.EndOfStream, error.ReadFailed, error.WriteFailed => return, 717 error.MacVerificationFailed => .{ SSH_DISCONNECT_MAC_ERROR, @errorName(err) }, 718 error.OutOfMemory, error.Canceled => .{ SSH_DISCONNECT_BY_APPLICATION, "server error" }, 719 else => .{ SSH_DISCONNECT_PROTOCOL_ERROR, @errorName(err) }, 720 }; 721 722 disconnect(conn, reason, description) catch {}; 723 } 724 725 fn disconnect(conn: *Conn, reason: u32, description: []const u8) !void { 726 var buf: std.ArrayList(u8) = .empty; 727 defer buf.deinit(conn.allocator); 728 try buf.append(conn.allocator, SSH_MSG_DISCONNECT); 729 try writeU32(&buf, conn.allocator, reason); 730 try writeStringField(&buf, conn.allocator, description); 731 try writeStringField(&buf, conn.allocator, ""); // language tag 732 try conn.writePacket(buf.items); 733 } 734 735 // --------------------------------------------------------------------------- 736 // version exchange (RFC 4253 §4.2) 737 // --------------------------------------------------------------------------- 738 739 fn exchangeVersions( 740 allocator: std.mem.Allocator, 741 reader: *std.Io.Reader, 742 writer: *std.Io.Writer, 743 ) ![]u8 { 744 try writer.writeAll(server_version ++ "\r\n"); 745 try writer.flush(); 746 747 // the spec allows the client to send comment lines before its banner; 748 // skip anything that isn't an "SSH-2.0-…" / "SSH-1.99-…" line, up to a cap 749 // so a garbage-spewing peer can't hold the connection open forever. 750 var lines: u32 = 0; 751 while (lines < max_banner_lines) : (lines += 1) { 752 const line = (try reader.takeDelimiter('\n')) orelse return error.UnexpectedEof; 753 const trimmed = if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; 754 if (std.mem.startsWith(u8, trimmed, "SSH-2.0-") or std.mem.startsWith(u8, trimmed, "SSH-1.99-")) { 755 return try allocator.dupe(u8, trimmed); 756 } 757 } 758 return error.TooManyBannerLines; 759 } 760 761 // --------------------------------------------------------------------------- 762 // binary packet codec, unencrypted form (RFC 4253 §6) 763 // --------------------------------------------------------------------------- 764 765 pub fn writePlainPacket(io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 766 const block: usize = 8; 767 const initial_pad = block - ((5 + payload.len) % block); 768 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 769 const packet_len: u32 = @intCast(1 + payload.len + padding_len); 770 771 try writer.writeInt(u32, packet_len, .big); 772 try writer.writeByte(padding_len); 773 try writer.writeAll(payload); 774 775 var padding: [255]u8 = undefined; 776 io.random(padding[0..padding_len]); 777 try writer.writeAll(padding[0..padding_len]); 778 try writer.flush(); 779 } 780 781 pub fn readPlainPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 782 const packet_len = try reader.takeInt(u32, .big); 783 if (packet_len < 8 or packet_len > max_packet_len) return error.InvalidPacketLength; 784 const padding_len = try reader.takeByte(); 785 if (padding_len < 4 or @as(u32, padding_len) + 1 > packet_len) return error.InvalidPadding; 786 const payload_len = packet_len - 1 - @as(u32, padding_len); 787 788 const payload = try reader.readAlloc(allocator, payload_len); 789 errdefer allocator.free(payload); 790 try reader.discardAll(padding_len); 791 return payload; 792 } 793 794 // IGNORE/DEBUG/UNIMPLEMENTED may arrive at any time (RFC 4253 §11); skip 795 // them wherever a specific message is expected 796 fn isIgnorableMsg(msg_type: u8) bool { 797 return msg_type == SSH_MSG_IGNORE or msg_type == SSH_MSG_UNIMPLEMENTED or msg_type == SSH_MSG_DEBUG; 798 } 799 800 /// packets handled during the plaintext phase — each direction's cipher picks 801 /// up its sequence number where that direction left off. 802 pub const PlainSeqs = struct { read: u64 = 0, written: u64 = 0 }; 803 804 // transport for KEX packets: the initial exchange runs in plaintext, a rekey 805 // runs under the current session ciphers. 806 pub const KexTransport = union(enum) { 807 plain: *PlainSeqs, 808 encrypted: struct { cs: *Cipher, sc: *Cipher }, 809 810 // read one packet, skipping ignorable messages — unless strict kex is in 811 // force, which bans them mid-handshake 812 pub fn readPacket(self: KexTransport, allocator: std.mem.Allocator, reader: *std.Io.Reader, strict: bool) ![]u8 { 813 while (true) { 814 const packet = switch (self) { 815 .plain => |seqs| packet: { 816 const packet = try readPlainPacket(allocator, reader); 817 seqs.read += 1; 818 break :packet packet; 819 }, 820 .encrypted => |ciphers| try ciphers.cs.readPacket(allocator, reader), 821 }; 822 if (packet.len >= 1 and isIgnorableMsg(packet[0])) { 823 allocator.free(packet); 824 if (strict) return error.StrictKexViolation; 825 continue; 826 } 827 return packet; 828 } 829 } 830 831 fn writePacket(self: KexTransport, io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 832 switch (self) { 833 .plain => |seqs| { 834 try writePlainPacket(io, writer, payload); 835 seqs.written += 1; 836 }, 837 .encrypted => |ciphers| try ciphers.sc.writePacket(io, writer, payload), 838 } 839 } 840 }; 841 842 // read one encrypted packet for the auth and channel layers, transparently 843 // skipping ignorable messages and servicing client-initiated rekeys. 844 pub fn readSessionPacket(conn: *Conn) ![]u8 { 845 while (true) { 846 const packet = try conn.readPacket(); 847 if (packet.len >= 1 and isIgnorableMsg(packet[0])) { 848 conn.allocator.free(packet); 849 continue; 850 } 851 // the peer is hanging up (RFC 4253 §11.1). same end of the packet 852 // stream as a transport close, so callers handle both the same way. 853 if (packet.len >= 1 and packet[0] == SSH_MSG_DISCONNECT) { 854 conn.allocator.free(packet); 855 return error.EndOfStream; 856 } 857 if (packet.len >= 1 and packet[0] == SSH_MSG_KEXINIT) { 858 defer conn.allocator.free(packet); 859 recordActivity(conn); 860 try runRekey(conn, packet); 861 continue; 862 } 863 recordActivity(conn); 864 return packet; 865 } 866 } 867 868 /// RFC 4253 §11.4 — an unrecognized message must be answered with 869 /// SSH_MSG_UNIMPLEMENTED carrying the offending packet's sequence number. 870 fn sendUnimplemented(conn: *Conn) !void { 871 var buf: std.ArrayList(u8) = .empty; 872 defer buf.deinit(conn.allocator); 873 try buf.append(conn.allocator, SSH_MSG_UNIMPLEMENTED); 874 // the read already advanced past the packet we're rejecting 875 try writeU32(&buf, conn.allocator, @truncate(conn.cs_cipher.seq - 1)); 876 try conn.writePacket(buf.items); 877 } 878 879 fn recordActivity(conn: *Conn) void { 880 if (conn.idle) |idle| _ = idle.activity.fetchAdd(1, .monotonic); 881 } 882 883 // --------------------------------------------------------------------------- 884 // SSH field encoders / decoders (RFC 4251 §5) 885 // --------------------------------------------------------------------------- 886 887 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 888 var len_bytes: [4]u8 = undefined; 889 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 890 try buf.appendSlice(allocator, &len_bytes); 891 try buf.appendSlice(allocator, bytes); 892 } 893 894 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 895 var total: usize = 0; 896 for (names, 0..) |name, i| { 897 if (i > 0) total += 1; // comma separator 898 total += name.len; 899 } 900 var len_bytes: [4]u8 = undefined; 901 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 902 try buf.appendSlice(allocator, &len_bytes); 903 for (names, 0..) |name, i| { 904 if (i > 0) try buf.append(allocator, ','); 905 try buf.appendSlice(allocator, name); 906 } 907 } 908 909 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 910 /// our use (X25519 shared secret) the value is always non-negative, so we 911 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 912 /// the most-significant byte is set (to keep it parsed as positive). 913 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 914 var start: usize = 0; 915 while (start < bytes.len and bytes[start] == 0) start += 1; 916 const trimmed = bytes[start..]; 917 if (trimmed.len == 0) { 918 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 919 return; 920 } 921 const prepend = (trimmed[0] & 0x80) != 0; 922 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 923 var len_bytes: [4]u8 = undefined; 924 std.mem.writeInt(u32, &len_bytes, out_len, .big); 925 try buf.appendSlice(allocator, &len_bytes); 926 if (prepend) try buf.append(allocator, 0); 927 try buf.appendSlice(allocator, trimmed); 928 } 929 930 /// a string field's bytes, borrowed from the packet behind a fixed reader 931 pub fn takeString(reader: *std.Io.Reader, max_len: u32) ![]const u8 { 932 const len = try reader.takeInt(u32, .big); 933 if (len > max_len) return error.FieldTooLarge; 934 return reader.take(len); 935 } 936 937 fn nameListContainsAny(haystack: []const u8, our_options: []const []const u8) bool { 938 var iter = std.mem.splitScalar(u8, haystack, ','); 939 while (iter.next()) |name| { 940 for (our_options) |opt| { 941 if (std.mem.eql(u8, name, opt)) return true; 942 } 943 } 944 return false; 945 } 946 947 // --------------------------------------------------------------------------- 948 // KEXINIT (RFC 4253 §7.1) 949 // --------------------------------------------------------------------------- 950 951 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 952 953 // strict kex markers (Terrapin / CVE-2023-48795 mitigation). pseudo-algorithms 954 // carried in the initial KEXINIT's kex list: we advertise the -s form, the 955 // client advertises the -c form. they are never selected as an actual kex 956 // algorithm because the matcher only picks from our_kex_algos. 957 pub const kex_strict_server = "kex-strict-s-v00@openssh.com"; 958 pub const kex_strict_client = "kex-strict-c-v00@openssh.com"; 959 960 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 961 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 962 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 963 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 964 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 965 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 966 const our_compression = [_][]const u8{"none"}; 967 968 /// build a KEXINIT payload with the given algorithm name-lists 969 pub fn buildKexInit( 970 io: std.Io, 971 allocator: std.mem.Allocator, 972 kex_algos: []const []const u8, 973 host_key_algos: []const []const u8, 974 ciphers: []const []const u8, 975 ) ![]u8 { 976 var buf: std.ArrayList(u8) = .empty; 977 errdefer buf.deinit(allocator); 978 979 try buf.append(allocator, SSH_MSG_KEXINIT); 980 981 var cookie: [16]u8 = undefined; 982 io.random(&cookie); 983 try buf.appendSlice(allocator, &cookie); 984 985 try writeNameList(&buf, allocator, kex_algos); 986 try writeNameList(&buf, allocator, host_key_algos); 987 try writeNameList(&buf, allocator, ciphers); // c->s 988 try writeNameList(&buf, allocator, ciphers); // s->c 989 try writeNameList(&buf, allocator, &our_macs); 990 try writeNameList(&buf, allocator, &our_macs); 991 try writeNameList(&buf, allocator, &our_compression); 992 try writeNameList(&buf, allocator, &our_compression); 993 try writeNameList(&buf, allocator, &.{}); // langs c->s 994 try writeNameList(&buf, allocator, &.{}); // langs s->c 995 try buf.append(allocator, 0); // first_kex_packet_follows = false 996 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 997 998 return try buf.toOwnedSlice(allocator); 999 } 1000 1001 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 1002 return buildKexInit(io, allocator, &(our_kex_algos ++ [_][]const u8{kex_strict_server}), &our_host_key_algos, &our_ciphers); 1003 } 1004 1005 // the name-lists borrow from the KEXINIT payload 1006 const ParsedKexInit = struct { 1007 kex_algos: []const u8, 1008 host_key_algos: []const u8, 1009 cs_cipher: []const u8, 1010 sc_cipher: []const u8, 1011 first_kex_packet_follows: bool, 1012 }; 1013 1014 fn parseClientKexInit(payload: []const u8) !ParsedKexInit { 1015 if (payload.len < 1 + 16) return error.KexInitTruncated; 1016 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 1017 1018 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 1019 1020 const kex_algos = try takeString(&reader, max_name_list_len); 1021 const host_key_algos = try takeString(&reader, max_name_list_len); 1022 const cs_cipher = try takeString(&reader, max_name_list_len); 1023 const sc_cipher = try takeString(&reader, max_name_list_len); 1024 1025 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 1026 for (0..6) |_| _ = try takeString(&reader, max_name_list_len); 1027 const first_kex_packet_follows = (try reader.takeByte()) != 0; 1028 _ = try reader.takeInt(u32, .big); // reserved 1029 1030 return .{ 1031 .kex_algos = kex_algos, 1032 .host_key_algos = host_key_algos, 1033 .cs_cipher = cs_cipher, 1034 .sc_cipher = sc_cipher, 1035 .first_kex_packet_follows = first_kex_packet_follows, 1036 }; 1037 } 1038 1039 // --------------------------------------------------------------------------- 1040 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 1041 // --------------------------------------------------------------------------- 1042 1043 const KexResult = struct { 1044 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 1045 sc_key: [64]u8, // server → client cipher key material 1046 session_id: [Sha256.digest_length]u8, 1047 next_cs_seq: u64, 1048 next_sc_seq: u64, 1049 strict: bool, 1050 }; 1051 1052 fn runKex( 1053 io: std.Io, 1054 allocator: std.mem.Allocator, 1055 reader: *std.Io.Reader, 1056 writer: *std.Io.Writer, 1057 host_key: *const HostKey, 1058 client_version: []const u8, 1059 ) !KexResult { 1060 var seqs: PlainSeqs = .{}; 1061 const transport = KexTransport{ .plain = &seqs }; 1062 1063 // exchange KEXINITs 1064 const server_kex_init = try buildServerKexInit(io, allocator); 1065 defer allocator.free(server_kex_init); 1066 try transport.writePacket(io, writer, server_kex_init); 1067 1068 const client_kex_init = try transport.readPacket(allocator, reader, false); 1069 defer allocator.free(client_kex_init); 1070 1071 const parsed = try parseClientKexInit(client_kex_init); 1072 1073 // strict kex: when the client advertises it, its KEXINIT must be the 1074 // first packet, ignorable messages are banned until NEWKEYS, and both 1075 // seqnos reset to 0 after every NEWKEYS. 1076 const strict = nameListContainsAny(parsed.kex_algos, &.{kex_strict_client}); 1077 if (strict and seqs.read != 1) return error.StrictKexViolation; 1078 1079 var negotiated = try exchangeKeys( 1080 io, 1081 allocator, 1082 reader, 1083 writer, 1084 transport, 1085 strict, 1086 host_key, 1087 client_version, 1088 client_kex_init, 1089 server_kex_init, 1090 &parsed, 1091 null, 1092 ); 1093 defer std.crypto.secureZero(u8, std.mem.asBytes(&negotiated.keys)); 1094 1095 return .{ 1096 .cs_key = negotiated.keys.cs_enc, 1097 .sc_key = negotiated.keys.sc_enc, 1098 .session_id = negotiated.exchange_hash, 1099 // each cipher continues its own direction's count; the read side 1100 // includes any skipped IGNORE/DEBUG packets. 1101 .next_cs_seq = if (strict) 0 else seqs.read, 1102 .next_sc_seq = if (strict) 0 else seqs.written, 1103 .strict = strict, 1104 }; 1105 } 1106 1107 /// everything needed to service a client-initiated rekey mid-session. 1108 const RekeyState = struct { 1109 host_key: *const HostKey, 1110 client_version: []const u8, 1111 session_id: [Sha256.digest_length]u8, 1112 strict: bool, 1113 }; 1114 1115 // service a rekey whose triggering KEXINIT payload has just been read: run 1116 // the whole exchange under the current keys, then swap the new keys into 1117 // both ciphers in place. 1118 fn runRekey(conn: *Conn, client_kex_init: []const u8) !void { 1119 const parsed = try parseClientKexInit(client_kex_init); 1120 1121 // the exchange reads and writes through the ciphers directly 1122 conn.setWaiting(true); 1123 defer conn.setWaiting(false); 1124 1125 const server_kex_init = try buildServerKexInit(conn.io, conn.allocator); 1126 defer conn.allocator.free(server_kex_init); 1127 try conn.sc_cipher.writePacket(conn.io, conn.writer, server_kex_init); 1128 1129 var negotiated = try exchangeKeys( 1130 conn.io, 1131 conn.allocator, 1132 conn.reader, 1133 conn.writer, 1134 .{ .encrypted = .{ .cs = &conn.cs_cipher, .sc = &conn.sc_cipher } }, 1135 false, // strict kex message rules apply to the initial exchange only 1136 conn.rekey.host_key, 1137 conn.rekey.client_version, 1138 client_kex_init, 1139 server_kex_init, 1140 &parsed, 1141 &conn.rekey.session_id, 1142 ); 1143 defer std.crypto.secureZero(u8, std.mem.asBytes(&negotiated.keys)); 1144 1145 // seqnos continue across a rekey unless strict kex was negotiated, 1146 // which resets them after every NEWKEYS 1147 conn.cs_cipher.setKeys(&negotiated.keys.cs_enc, if (conn.rekey.strict) 0 else conn.cs_cipher.seq); 1148 conn.sc_cipher.setKeys(&negotiated.keys.sc_enc, if (conn.rekey.strict) 0 else conn.sc_cipher.seq); 1149 } 1150 1151 const NegotiatedKeys = struct { 1152 keys: SessionKeys, 1153 exchange_hash: [Sha256.digest_length]u8, 1154 }; 1155 1156 // the KEX core shared by the initial exchange and rekeys: pick algorithms, 1157 // run the (hybrid) ECDH round trip, exchange NEWKEYS, derive keys. both 1158 // KEXINIT payloads have already been exchanged by the caller, which also owns 1159 // `parsed`; the client's raw payload comes along too because the exchange hash 1160 // covers it verbatim. session_id is null on the initial exchange (where it 1161 // becomes the exchange hash) and the original session id on a rekey. 1162 fn exchangeKeys( 1163 io: std.Io, 1164 allocator: std.mem.Allocator, 1165 reader: *std.Io.Reader, 1166 writer: *std.Io.Writer, 1167 transport: KexTransport, 1168 strict: bool, 1169 host_key: *const HostKey, 1170 client_version: []const u8, 1171 client_kex_init: []const u8, 1172 server_kex_init: []const u8, 1173 parsed: *const ParsedKexInit, 1174 session_id: ?*const [Sha256.digest_length]u8, 1175 ) !NegotiatedKeys { 1176 // pick the first kex algo in the client's preference list that we also 1177 // support (RFC 4253 §7.1.3). 1178 const kex_algo = blk: { 1179 var iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 1180 while (iter.next()) |name| { 1181 for (our_kex_algos) |opt| { 1182 if (std.mem.eql(u8, name, opt)) break :blk opt; 1183 } 1184 } 1185 return error.NoCommonKexAlgorithm; 1186 }; 1187 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 1188 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 1189 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 1190 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 1191 1192 // a client may follow its KEXINIT with a kex packet for its guess. the 1193 // guess is right only when both sides' first kex and host key algorithms 1194 // match (RFC 4253 §7.1) — not when the client's first choice merely 1195 // happens to be kex_algo, so this compares against our list. a client 1196 // whose guess was wrong re-sends an init for the negotiated method. 1197 if (parsed.first_kex_packet_follows) { 1198 var kex_iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 1199 var host_key_iter = std.mem.splitScalar(u8, parsed.host_key_algos, ','); 1200 const guessed_right = std.mem.eql(u8, kex_iter.first(), our_kex_algos[0]) and 1201 std.mem.eql(u8, host_key_iter.first(), our_host_key_algos[0]); 1202 if (!guessed_right) { 1203 const wrong_guess = try transport.readPacket(allocator, reader, strict); 1204 allocator.free(wrong_guess); 1205 } 1206 } 1207 1208 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 1209 // wire shape, only the string size differs). 1210 const ecdh_init = try transport.readPacket(allocator, reader, strict); 1211 defer allocator.free(ecdh_init); 1212 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 1213 1214 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 1215 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 1216 const client_blob = try takeString(&ecdh_init_reader, expected_client_len); 1217 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 1218 1219 // derive server reply blob (S_REPLY) + shared secret K. 1220 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 1221 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 1222 // K = SHA-256(K_MLKEM || K_X25519). 1223 var server_blob_buf: [hybrid_server_blob_len]u8 = undefined; 1224 var k: [Sha256.digest_length]u8 = undefined; 1225 defer std.crypto.secureZero(u8, &k); 1226 const server_blob: []const u8 = blk: { 1227 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 1228 var x25519_client_pub: [X25519.public_length]u8 = undefined; 1229 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 1230 var server_kp = X25519.KeyPair.generate(io); 1231 defer std.crypto.secureZero(u8, &server_kp.secret_key); 1232 var x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 1233 defer std.crypto.secureZero(u8, &x25519_shared); 1234 1235 if (!hybrid) { 1236 server_blob_buf[0..X25519.public_length].* = server_kp.public_key; 1237 k = x25519_shared; 1238 break :blk server_blob_buf[0..X25519.public_length]; 1239 } 1240 1241 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 1242 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 1243 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 1244 var encap = pq_pub.encaps(io); 1245 defer std.crypto.secureZero(u8, &encap.shared_secret); 1246 1247 server_blob_buf[0..MLKem768.ciphertext_length].* = encap.ciphertext; 1248 server_blob_buf[MLKem768.ciphertext_length..].* = server_kp.public_key; 1249 1250 var h = Sha256.init(.{}); 1251 defer std.crypto.secureZero(u8, std.mem.asBytes(&h)); 1252 h.update(&encap.shared_secret); 1253 h.update(&x25519_shared); 1254 h.final(&k); 1255 break :blk &server_blob_buf; 1256 }; 1257 1258 // build host key blob (K_S) 1259 var host_key_blob: std.ArrayList(u8) = .empty; 1260 defer host_key_blob.deinit(allocator); 1261 try host_key.appendPublicBlob(&host_key_blob, allocator); 1262 1263 // build exchange hash input and compute H 1264 const exchange_hash = try computeExchangeHash( 1265 allocator, 1266 client_version, 1267 server_version, 1268 client_kex_init, 1269 server_kex_init, 1270 host_key_blob.items, 1271 client_blob, 1272 server_blob, 1273 &k, 1274 hybrid, 1275 ); 1276 1277 // sign H with the host key, format as ssh signature blob 1278 var signature_blob: std.ArrayList(u8) = .empty; 1279 defer signature_blob.deinit(allocator); 1280 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 1281 1282 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 1283 var reply: std.ArrayList(u8) = .empty; 1284 defer reply.deinit(allocator); 1285 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 1286 try writeStringField(&reply, allocator, host_key_blob.items); 1287 try writeStringField(&reply, allocator, server_blob); 1288 try writeStringField(&reply, allocator, signature_blob.items); 1289 try transport.writePacket(io, writer, reply.items); 1290 1291 // NEWKEYS — both sides switch to the new keys after this is sent and 1292 // the peer's NEWKEYS is received. 1293 try transport.writePacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 1294 1295 const peer_newkeys = try transport.readPacket(allocator, reader, strict); 1296 defer allocator.free(peer_newkeys); 1297 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 1298 1299 // derive session keys per RFC 4253 §7.2. only the encrypt keys are 1300 // needed for chacha20-poly1305 (no separate MAC/IV). 1301 var keys: SessionKeys = undefined; 1302 defer std.crypto.secureZero(u8, std.mem.asBytes(&keys)); 1303 try deriveSessionKeys(allocator, &k, &exchange_hash, if (session_id) |sid| sid else &exchange_hash, &keys, hybrid); 1304 1305 return .{ .keys = keys, .exchange_hash = exchange_hash }; 1306 } 1307 1308 // --------------------------------------------------------------------------- 1309 // exchange hash (RFC 4253 §8, RFC 5656 §4) 1310 // --------------------------------------------------------------------------- 1311 1312 pub fn computeExchangeHash( 1313 allocator: std.mem.Allocator, 1314 client_version: []const u8, 1315 server_version_str: []const u8, 1316 client_kex_init: []const u8, 1317 server_kex_init: []const u8, 1318 host_key_blob: []const u8, 1319 client_ephemeral: []const u8, 1320 server_ephemeral: []const u8, 1321 shared_secret: []const u8, 1322 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1323 /// as a plain SSH string (length-prefixed bytes). 1324 k_is_string: bool, 1325 ) ![Sha256.digest_length]u8 { 1326 var buf: std.ArrayList(u8) = .empty; 1327 defer buf.deinit(allocator); 1328 defer std.crypto.secureZero(u8, buf.items); 1329 // reserved up front so a reallocation can't leave K behind 1330 try buf.ensureTotalCapacityPrecise(allocator, 8 * 4 + 1 + client_version.len + server_version_str.len + 1331 client_kex_init.len + server_kex_init.len + host_key_blob.len + client_ephemeral.len + 1332 server_ephemeral.len + shared_secret.len); 1333 1334 try writeStringField(&buf, allocator, client_version); 1335 try writeStringField(&buf, allocator, server_version_str); 1336 try writeStringField(&buf, allocator, client_kex_init); 1337 try writeStringField(&buf, allocator, server_kex_init); 1338 try writeStringField(&buf, allocator, host_key_blob); 1339 try writeStringField(&buf, allocator, client_ephemeral); 1340 try writeStringField(&buf, allocator, server_ephemeral); 1341 if (k_is_string) { 1342 try writeStringField(&buf, allocator, shared_secret); 1343 } else { 1344 try writeMpint(&buf, allocator, shared_secret); 1345 } 1346 1347 var hasher = Sha256.init(.{}); 1348 defer std.crypto.secureZero(u8, std.mem.asBytes(&hasher)); 1349 hasher.update(buf.items); 1350 return hasher.finalResult(); 1351 } 1352 1353 // --------------------------------------------------------------------------- 1354 // key derivation (RFC 4253 §7.2) 1355 // --------------------------------------------------------------------------- 1356 1357 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1358 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1359 // blocks chained per RFC 4253. 1360 pub const SessionKeys = struct { 1361 cs_enc: [64]u8, 1362 sc_enc: [64]u8, 1363 }; 1364 1365 pub fn deriveSessionKeys( 1366 allocator: std.mem.Allocator, 1367 shared_secret: []const u8, 1368 exchange_hash: []const u8, 1369 session_id: []const u8, 1370 out: *SessionKeys, 1371 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1372 k_is_string: bool, 1373 ) !void { 1374 // pre-build the K || H prefix once; reused for every derivation 1375 var prefix: std.ArrayList(u8) = .empty; 1376 defer prefix.deinit(allocator); 1377 defer std.crypto.secureZero(u8, prefix.items); 1378 // reserved up front so a reallocation can't leave K behind 1379 try prefix.ensureTotalCapacityPrecise(allocator, 4 + 1 + shared_secret.len + exchange_hash.len); 1380 if (k_is_string) { 1381 try writeStringField(&prefix, allocator, shared_secret); 1382 } else { 1383 try writeMpint(&prefix, allocator, shared_secret); 1384 } 1385 try prefix.appendSlice(allocator, exchange_hash); 1386 1387 deriveKey(prefix.items, 'C', session_id, &out.cs_enc); 1388 deriveKey(prefix.items, 'D', session_id, &out.sc_enc); 1389 } 1390 1391 fn deriveKey( 1392 prefix: []const u8, // K || H, already encoded 1393 letter: u8, 1394 session_id: []const u8, 1395 out: *[2 * Sha256.digest_length]u8, 1396 ) void { 1397 // a finished context still holds its digest and last input block 1398 // K_1 = HASH(K || H || letter || session_id) 1399 var first = Sha256.init(.{}); 1400 defer std.crypto.secureZero(u8, std.mem.asBytes(&first)); 1401 first.update(prefix); 1402 first.update(&.{letter}); 1403 first.update(session_id); 1404 first.final(out[0..Sha256.digest_length]); 1405 1406 // K_2 = HASH(K || H || K_1) 1407 var second = Sha256.init(.{}); 1408 defer std.crypto.secureZero(u8, std.mem.asBytes(&second)); 1409 second.update(prefix); 1410 second.update(out[0..Sha256.digest_length]); 1411 second.final(out[Sha256.digest_length..]); 1412 } 1413 1414 // --------------------------------------------------------------------------- 1415 // chacha20-poly1305@openssh.com packet codec 1416 // --------------------------------------------------------------------------- 1417 // 1418 // per openssh's PROTOCOL.chacha20poly1305: 1419 // K_2 = first 32 bytes of key material — encrypts the packet body 1420 // K_1 = next 32 bytes — encrypts the 4-byte length field 1421 // nonce = 64-bit big-endian sequence number 1422 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1423 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1424 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1425 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1426 // 1427 // padding is computed on the body alone (padding_length byte + payload + 1428 // padding) — the 4-byte length field is excluded from alignment. body must 1429 // be a multiple of 8 bytes; minimum padding 4 bytes. 1430 1431 pub const Cipher = struct { 1432 main_key: [32]u8, // K_2 1433 header_key: [32]u8, // K_1 1434 // wider than the 32-bit wire seqno, so a peer that never rekeys fails the 1435 // mac at 2^32 packets instead of wrapping into nonce reuse 1436 seq: u64, 1437 1438 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1439 return .{ 1440 .main_key = key_material[0..32].*, 1441 .header_key = key_material[32..64].*, 1442 .seq = initial_seq, 1443 }; 1444 } 1445 1446 /// swap in new key material after a rekey, leaving the rest of the 1447 /// cipher state alone 1448 fn setKeys(self: *Cipher, key_material: *const [64]u8, seq: u64) void { 1449 self.main_key = key_material[0..32].*; 1450 self.header_key = key_material[32..64].*; 1451 self.seq = seq; 1452 } 1453 1454 fn makeNonce(seq: u64) [8]u8 { 1455 var nonce: [8]u8 = undefined; 1456 std.mem.writeInt(u64, &nonce, seq, .big); 1457 return nonce; 1458 } 1459 1460 fn bodyLength(self: *const Cipher, enc_length: *const [4]u8) !u32 { 1461 var plain: [4]u8 = undefined; 1462 ChaCha20.xor(&plain, enc_length, 0, self.header_key, makeNonce(self.seq)); 1463 const len = std.mem.readInt(u32, &plain, .big); 1464 if (len < 8 or len > max_packet_len or len % 8 != 0) return error.InvalidPacketLength; 1465 return len; 1466 } 1467 1468 fn peekPacket(self: *const Cipher, reader: *std.Io.Reader) !void { 1469 const len = 4 + (try self.bodyLength(try reader.peekArray(4))) + Poly1305.mac_length; 1470 if (len > reader.buffer.len) return error.ReadBufferTooSmall; 1471 _ = try reader.peek(len); 1472 } 1473 1474 fn hasBufferedPacket(self: *const Cipher, reader: *std.Io.Reader) !bool { 1475 const bytes = reader.buffered(); 1476 if (bytes.len < 4) return false; 1477 return bytes.len >= 4 + (try self.bodyLength(bytes[0..4])) + Poly1305.mac_length; 1478 } 1479 1480 pub fn writePacket( 1481 self: *Cipher, 1482 io: std.Io, 1483 writer: *std.Io.Writer, 1484 payload: []const u8, 1485 ) !void { 1486 try self.writePacketVec(io, writer, &.{payload}); 1487 } 1488 1489 /// the payload is the concatenation of `parts` 1490 pub fn writePacketVec( 1491 self: *Cipher, 1492 io: std.Io, 1493 writer: *std.Io.Writer, 1494 parts: []const []const u8, 1495 ) !void { 1496 var payload_len: usize = 0; 1497 for (parts) |part| payload_len += part.len; 1498 1499 const block: usize = 8; 1500 const initial_pad = block - ((1 + payload_len) % block); 1501 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1502 const body_len = 1 + payload_len + padding_len; 1503 if (body_len > max_packet_len) return error.PacketTooLarge; 1504 1505 const nonce = makeNonce(self.seq); 1506 1507 // encrypted length || body || mac, contiguous so the packet goes out 1508 // in one write. stack-allocated to avoid a heap alloc on every packet. 1509 var packet_buf: [packet_buffer_size]u8 = undefined; 1510 const packet = packet_buf[0 .. 4 + body_len + Poly1305.mac_length]; 1511 const enc_length = packet[0..4]; 1512 const body = packet[4..][0..body_len]; 1513 1514 // plaintext body = padding_length || payload || random padding 1515 body[0] = padding_len; 1516 var end: usize = 1; 1517 for (parts) |part| { 1518 @memcpy(body[end..][0..part.len], part); 1519 end += part.len; 1520 } 1521 io.random(body[end..]); 1522 1523 // encrypt body in place with counter=1 1524 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1525 1526 // encrypt length field with header key, counter=0 1527 std.mem.writeInt(u32, enc_length, @intCast(body_len), .big); 1528 ChaCha20.xor(enc_length, enc_length, 0, self.header_key, nonce); 1529 1530 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1531 var poly_key: [Poly1305.key_length]u8 = undefined; 1532 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1533 1534 // mac over encrypted_length || encrypted_body 1535 var poly = Poly1305.init(&poly_key); 1536 poly.update(packet[0 .. 4 + body_len]); 1537 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1538 1539 try writer.writeAll(packet); 1540 try writer.flush(); 1541 1542 self.seq += 1; 1543 } 1544 1545 pub fn readPacket( 1546 self: *Cipher, 1547 allocator: std.mem.Allocator, 1548 reader: *std.Io.Reader, 1549 ) ![]u8 { 1550 const nonce = makeNonce(self.seq); 1551 1552 var enc_length: [4]u8 = undefined; 1553 try reader.readSliceAll(&enc_length); 1554 1555 const body_len = try self.bodyLength(&enc_length); 1556 1557 // the body allocation becomes the returned payload, so a packet only 1558 // ever costs one allocation 1559 const body = try allocator.alloc(u8, body_len); 1560 errdefer allocator.free(body); 1561 try reader.readSliceAll(body); 1562 1563 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1564 try reader.readSliceAll(&tag_recv); 1565 1566 var poly_key: [Poly1305.key_length]u8 = undefined; 1567 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1568 1569 var poly = Poly1305.init(&poly_key); 1570 poly.update(&enc_length); 1571 poly.update(body); 1572 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1573 poly.final(&tag_computed); 1574 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1575 return error.MacVerificationFailed; 1576 } 1577 1578 // decrypt the body in place 1579 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1580 1581 const padding_len = body[0]; 1582 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1583 const payload_len = body_len - 1 - @as(u32, padding_len); 1584 1585 // shift the payload over the padding_length byte, then release the 1586 // trailing padding (caller owns the result) 1587 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1588 const payload = try allocator.realloc(body, payload_len); 1589 1590 self.seq += 1; 1591 return payload; 1592 } 1593 }; 1594 1595 // --------------------------------------------------------------------------- 1596 // post-KEX: service request + user authentication (RFC 4252) 1597 // --------------------------------------------------------------------------- 1598 1599 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1600 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1601 /// `Offering public key: … SHA256:…`. 1602 pub const fingerprint_len = 50; 1603 1604 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1605 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1606 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1607 var digest: [Sha256.digest_length]u8 = undefined; 1608 Sha256.hash(pubkey_blob, &digest, .{}); 1609 1610 var out: [fingerprint_len]u8 = undefined; 1611 @memcpy(out[0..7], "SHA256:"); 1612 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1613 std.debug.assert(encoded.len == fingerprint_len - 7); 1614 return out; 1615 } 1616 1617 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1618 const allocator = conn.allocator; 1619 1620 // step 1: service request for ssh-userauth → service accept 1621 { 1622 const req = try readSessionPacket(conn); 1623 defer allocator.free(req); 1624 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1625 1626 var req_reader = std.Io.Reader.fixed(req[1..]); 1627 const service = try takeString(&req_reader, 64); 1628 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1629 1630 var accept: std.ArrayList(u8) = .empty; 1631 defer accept.deinit(allocator); 1632 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1633 try writeStringField(&accept, allocator, "ssh-userauth"); 1634 try conn.writePacket(accept.items); 1635 } 1636 1637 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1638 // signature verifies against the offered pubkey. 1639 var auth_attempts: u32 = 0; 1640 while (true) { 1641 const req = try readSessionPacket(conn); 1642 defer allocator.free(req); 1643 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1644 1645 // every request counts, probes included, so a client can't loop here 1646 // forever 1647 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1648 auth_attempts += 1; 1649 1650 var req_reader = std.Io.Reader.fixed(req[1..]); 1651 const user_name = try takeString(&req_reader, 256); 1652 const service_name = try takeString(&req_reader, 64); 1653 const method = try takeString(&req_reader, 64); 1654 1655 // RFC 4252 §5: the server must verify the requested service 1656 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1657 try sendUserauthFailure(conn); 1658 continue; 1659 } 1660 1661 if (!std.mem.eql(u8, method, "publickey")) { 1662 try sendUserauthFailure(conn); 1663 continue; 1664 } 1665 1666 const has_signature = (try req_reader.takeByte()) != 0; 1667 const algo = try takeString(&req_reader, 64); 1668 const pubkey_blob = try takeString(&req_reader, 4096); 1669 1670 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1671 try sendUserauthFailure(conn); 1672 continue; 1673 } 1674 1675 if (!has_signature) { 1676 // probe — tell the client this key is acceptable so it'll send 1677 // the signed version next. 1678 var pk_ok: std.ArrayList(u8) = .empty; 1679 defer pk_ok.deinit(allocator); 1680 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1681 try writeStringField(&pk_ok, allocator, algo); 1682 try writeStringField(&pk_ok, allocator, pubkey_blob); 1683 try conn.writePacket(pk_ok.items); 1684 continue; 1685 } 1686 1687 // has signature — verify it 1688 const signature_blob = try takeString(&req_reader, 1024); 1689 1690 const ok = verifyUserauthSignature( 1691 allocator, 1692 &conn.rekey.session_id, 1693 user_name, 1694 service_name, 1695 algo, 1696 pubkey_blob, 1697 signature_blob, 1698 ) catch |err| switch (err) { 1699 error.OutOfMemory => return err, 1700 // a malformed key or signature blob 1701 else => false, 1702 }; 1703 1704 if (!ok) { 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 // RFC 4252 §5.1: silently ignored once authenticated 1887 SSH_MSG_USERAUTH_REQUEST => {}, 1888 else => try sendUnimplemented(conn), 1889 } 1890 } 1891 } 1892 1893 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1894 // byte SSH_MSG_GLOBAL_REQUEST 1895 // string request_name 1896 // boolean want_reply 1897 // …request-specific data we ignore 1898 var r = std.Io.Reader.fixed(packet[1..]); 1899 _ = try takeString(&r, 256); 1900 const want_reply = (try r.takeByte()) != 0; 1901 if (want_reply) { 1902 try conn.writePacket(&[_]u8{SSH_MSG_REQUEST_FAILURE}); 1903 } 1904 } 1905 1906 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 1907 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 1908 /// return null. 1909 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 1910 const allocator = conn.allocator; 1911 1912 // byte SSH_MSG_CHANNEL_OPEN 1913 // string channel_type 1914 // uint32 sender_channel (peer's id) 1915 // uint32 initial_window 1916 // uint32 max_packet 1917 var r = std.Io.Reader.fixed(packet[1..]); 1918 const ch_type = try takeString(&r, 64); 1919 const remote_id = try r.takeInt(u32, .big); 1920 const initial_window = try r.takeInt(u32, .big); 1921 const max_packet = try r.takeInt(u32, .big); 1922 1923 if (!std.mem.eql(u8, ch_type, "session")) { 1924 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1925 return null; 1926 } 1927 1928 // a zero max_packet would leave writeChannel looping without progress 1929 if (max_packet == 0) { 1930 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1931 return null; 1932 } 1933 1934 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1935 var reply: std.ArrayList(u8) = .empty; 1936 defer reply.deinit(allocator); 1937 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1938 try writeU32(&reply, allocator, remote_id); 1939 try writeU32(&reply, allocator, local_id); 1940 try writeU32(&reply, allocator, initial_recv_window); 1941 try writeU32(&reply, allocator, max_packet_size); 1942 try conn.writePacket(reply.items); 1943 1944 return .{ 1945 .local_id = local_id, 1946 .remote_id = remote_id, 1947 .local_window = initial_recv_window, 1948 .remote_window = initial_window, 1949 .max_packet = max_packet, 1950 }; 1951 } 1952 1953 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1954 const allocator = conn.allocator; 1955 1956 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1957 // address the failure to the correct id 1958 var r = std.Io.Reader.fixed(open_packet[1..]); 1959 const ch_type_len = try r.takeInt(u32, .big); 1960 try r.discardAll(ch_type_len); 1961 const remote_id = try r.takeInt(u32, .big); 1962 1963 var reply: std.ArrayList(u8) = .empty; 1964 defer reply.deinit(allocator); 1965 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1966 try writeU32(&reply, allocator, remote_id); 1967 try writeU32(&reply, allocator, reason); 1968 try writeStringField(&reply, allocator, description); 1969 try writeStringField(&reply, allocator, ""); // language tag 1970 try conn.writePacket(reply.items); 1971 } 1972 1973 /// returns the session request if this one triggered it, else null. an exec 1974 /// command borrows from `packet`. 1975 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 1976 // byte SSH_MSG_CHANNEL_REQUEST 1977 // uint32 recipient_channel (== our local_id) 1978 // string request_type 1979 // boolean want_reply 1980 // …request-specific data 1981 var r = std.Io.Reader.fixed(packet[1..]); 1982 const recipient_channel = try r.takeInt(u32, .big); 1983 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1984 const req_type = try takeString(&r, 64); 1985 const want_reply = (try r.takeByte()) != 0; 1986 1987 if (std.mem.eql(u8, req_type, "pty-req")) { 1988 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1989 // uint32 height px, string modes 1990 _ = try takeString(&r, 64); 1991 ch.pty = try takePtySize(&r); 1992 try replyChannelRequest(conn, ch, want_reply, true); 1993 return null; 1994 } 1995 1996 if (std.mem.eql(u8, req_type, "env")) { 1997 // ignore environment variables silently (we don't pass them anywhere) 1998 try replyChannelRequest(conn, ch, want_reply, true); 1999 return null; 2000 } 2001 2002 if (std.mem.eql(u8, req_type, "window-change")) { 2003 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2004 const sz = try takePtySize(&r); 2005 if (ch.pty != null) ch.pty = sz; 2006 // spec: window-change MUST NOT request a reply, but accept either 2007 try replyChannelRequest(conn, ch, want_reply, true); 2008 return null; 2009 } 2010 2011 if (std.mem.eql(u8, req_type, "shell")) { 2012 try replyChannelRequest(conn, ch, want_reply, true); 2013 return .{ .shell = ch.pty }; 2014 } 2015 2016 if (std.mem.eql(u8, req_type, "exec")) { 2017 // capture the command string for the handler to inspect 2018 const cmd = try takeString(&r, 4096); 2019 try replyChannelRequest(conn, ch, want_reply, true); 2020 return .{ .exec = cmd }; 2021 } 2022 2023 // unknown request kind — fail it 2024 try replyChannelRequest(conn, ch, want_reply, false); 2025 return null; 2026 } 2027 2028 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2029 if (!want_reply) return; 2030 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2031 } 2032 2033 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2034 var packet: [5]u8 = undefined; 2035 packet[0] = msg_type; 2036 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2037 try conn.writePacket(&packet); 2038 } 2039 2040 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2041 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2042 // uint32 recipient_channel 2043 // uint32 bytes_to_add 2044 var r = std.Io.Reader.fixed(packet[1..]); 2045 const recipient_channel = try r.takeInt(u32, .big); 2046 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2047 const add = try r.takeInt(u32, .big); 2048 ch.remote_window +|= add; 2049 } 2050 2051 // charge a payload's bytes against the receive window without keeping them. 2052 // the caller credits the window back, choosing the budget that suits it. 2053 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2054 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2055 // uint32 recipient_channel 2056 // [if extended: uint32 type_code] 2057 // string data 2058 const payload = try parseChannelData(packet, extended, ch.local_id); 2059 const data_len: u32 = @intCast(payload.len); 2060 2061 if (data_len > ch.local_window) return error.WindowExceeded; 2062 ch.local_window -= data_len; 2063 } 2064 2065 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2066 if (packet.len < 1) return error.EmptyPacket; 2067 var r = std.Io.Reader.fixed(packet[1..]); 2068 const recipient_channel = try r.takeInt(u32, .big); 2069 if (recipient_channel != expected_channel) return error.UnknownChannel; 2070 if (extended) { 2071 const data_type = try r.takeInt(u32, .big); 2072 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2073 } 2074 const data_len = try r.takeInt(u32, .big); 2075 // catches both data_len > remaining (would otherwise be a bounds-check 2076 // panic on the slice) and trailing junk after the declared payload. 2077 if (data_len != r.buffered().len) return error.InvalidChannelData; 2078 return r.buffered(); 2079 } 2080 2081 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2082 if (packet.len < 1) return error.EmptyPacket; 2083 var r = std.Io.Reader.fixed(packet[1..]); 2084 const recipient_channel = try r.takeInt(u32, .big); 2085 if (recipient_channel != expected_channel) return error.UnknownChannel; 2086 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2087 } 2088 2089 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2090 /// of `budget`, the credit we're willing to have outstanding. used both for 2091 /// the pre-session discard path and by SessionCtx after it consumes a 2092 /// CHANNEL_DATA payload. 2093 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2094 if (ch.local_window >= budget / 2) return; 2095 const add = budget - ch.local_window; 2096 ch.local_window += add; 2097 var adj: std.ArrayList(u8) = .empty; 2098 defer adj.deinit(conn.allocator); 2099 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2100 try writeU32(&adj, conn.allocator, ch.remote_id); 2101 try writeU32(&adj, conn.allocator, add); 2102 try conn.writePacket(adj.items); 2103 } 2104 2105 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2106 var bytes: [4]u8 = undefined; 2107 std.mem.writeInt(u32, &bytes, value, .big); 2108 try buf.appendSlice(allocator, &bytes); 2109 } 2110 2111 test "pty dimensions have bounded axes and area, preserving normal and zero sizes" { 2112 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2113 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2114 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2115 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2116 }) |case| { 2117 var bytes: [8]u8 = undefined; 2118 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2119 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2120 var reader = std.Io.Reader.fixed(&bytes); 2121 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2122 } 2123 } 2124 2125 test "channel close before shell or exec is acknowledged" { 2126 const io = std.testing.io; 2127 const allocator = std.testing.allocator; 2128 const key = [_]u8{0x5a} ** 64; 2129 var encoded: [256]u8 = undefined; 2130 var encoded_writer = std.Io.Writer.fixed(&encoded); 2131 var sender = Cipher.init(&key, 0); 2132 var open: std.ArrayList(u8) = .empty; 2133 defer open.deinit(allocator); 2134 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2135 try writeStringField(&open, allocator, "session"); 2136 try writeU32(&open, allocator, 7); 2137 try writeU32(&open, allocator, 32768); 2138 try writeU32(&open, allocator, 32768); 2139 try sender.writePacket(io, &encoded_writer, open.items); 2140 try sender.writePacket(io, &encoded_writer, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }); 2141 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2142 var output: [256]u8 = undefined; 2143 var writer = std.Io.Writer.fixed(&output); 2144 var conn = Conn{ 2145 .io = io, 2146 .allocator = allocator, 2147 .reader = &reader, 2148 .writer = &writer, 2149 .cs_cipher = Cipher.init(&key, 0), 2150 .sc_cipher = Cipher.init(&key, 0), 2151 .rekey = undefined, 2152 }; 2153 const Handler = struct { 2154 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2155 return error.UnexpectedSession; 2156 } 2157 }; 2158 var handler = Handler{}; 2159 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2160 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2161 var receiver = Cipher.init(&key, 0); 2162 const confirmation = try receiver.readPacket(allocator, &output_reader); 2163 defer allocator.free(confirmation); 2164 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2165 const close = try receiver.readPacket(allocator, &output_reader); 2166 defer allocator.free(close); 2167 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2168 try std.testing.expectEqual(0, output_reader.buffered().len); 2169 } 2170