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