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