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