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