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