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