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