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