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