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