╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
698 if (packet.len >= 1 and isIgnorableMsg(packet[0])) { 699 allocator.free(packet); 700 continue; 701 } 702 if (packet.len >= 1 and packet[0] == SSH_MSG_KEXINIT) { 703 defer allocator.free(packet); 704 try runRekey(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey, packet); 705 continue; 706 } 707 return packet; 708 } 709 } 710 711 // --------------------------------------------------------------------------- 712 // SSH field encoders / decoders (RFC 4251 §5) 713 // --------------------------------------------------------------------------- 714 715 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 716 var len_bytes: [4]u8 = undefined; 717 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 718 try buf.appendSlice(allocator, &len_bytes); 719 try buf.appendSlice(allocator, bytes); 720 } 721 722 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 723 var total: usize = 0; 724 for (names, 0..) |name, i| { 725 if (i > 0) total += 1; // comma separator 726 total += name.len; 727 } 728 var len_bytes: [4]u8 = undefined; 729 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 730 try buf.appendSlice(allocator, &len_bytes); 731 for (names, 0..) |name, i| { 732 if (i > 0) try buf.append(allocator, ','); 733 try buf.appendSlice(allocator, name); 734 } 735 } 736 737 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 738 /// our use (X25519 shared secret) the value is always non-negative, so we 739 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 740 /// the most-significant byte is set (to keep it parsed as positive). 741 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 742 var start: usize = 0; 743 while (start < bytes.len and bytes[start] == 0) start += 1; 744 const trimmed = bytes[start..]; 745 if (trimmed.len == 0) { 746 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 747 return; 748 } 749 const prepend = (trimmed[0] & 0x80) != 0; 750 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 751 var len_bytes: [4]u8 = undefined; 752 std.mem.writeInt(u32, &len_bytes, out_len, .big); 753 try buf.appendSlice(allocator, &len_bytes); 754 if (prepend) try buf.append(allocator, 0); 755 try buf.appendSlice(allocator, trimmed); 756 } 757 758 pub fn takeStringField(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_len: u32) ![]u8 { 759 const len = try reader.takeInt(u32, .big); 760 if (len > max_len) return error.FieldTooLarge; 761 return try reader.readAlloc(allocator, len); 762 } 763 764 fn nameListContainsAny(haystack: []const u8, our_options: []const []const u8) bool { 765 var iter = std.mem.splitScalar(u8, haystack, ','); 766 while (iter.next()) |name| { 767 for (our_options) |opt| { 768 if (std.mem.eql(u8, name, opt)) return true; 769 } 770 } 771 return false; 772 } 773 774 // --------------------------------------------------------------------------- 775 // KEXINIT (RFC 4253 §7.1) 776 // --------------------------------------------------------------------------- 777 778 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 779 780 // strict kex markers (Terrapin / CVE-2023-48795 mitigation). pseudo-algorithms 781 // carried in the initial KEXINIT's kex list: we advertise the -s form, the 782 // client advertises the -c form. they are never selected as an actual kex 783 // algorithm because the matcher only picks from our_kex_algos. 784 pub const kex_strict_server = "kex-strict-s-v00@openssh.com"; 785 pub const kex_strict_client = "kex-strict-c-v00@openssh.com"; 786 787 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 788 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 789 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 790 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 791 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 792 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 793 const our_compression = [_][]const u8{"none"}; 794 795 /// Build a KEXINIT payload with the given algorithm name-lists 796 pub fn buildKexInit( 797 io: std.Io, 798 allocator: std.mem.Allocator, 799 kex_algos: []const []const u8, 800 host_key_algos: []const []const u8, 801 ciphers: []const []const u8, 802 ) ![]u8 { 803 var buf: std.ArrayList(u8) = .empty; 804 errdefer buf.deinit(allocator); 805 806 try buf.append(allocator, SSH_MSG_KEXINIT); 807 808 var cookie: [16]u8 = undefined; 809 io.random(&cookie); 810 try buf.appendSlice(allocator, &cookie); 811 812 try writeNameList(&buf, allocator, kex_algos); 813 try writeNameList(&buf, allocator, host_key_algos); 814 try writeNameList(&buf, allocator, ciphers); // c->s 815 try writeNameList(&buf, allocator, ciphers); // s->c 816 try writeNameList(&buf, allocator, &our_macs); 817 try writeNameList(&buf, allocator, &our_macs); 818 try writeNameList(&buf, allocator, &our_compression); 819 try writeNameList(&buf, allocator, &our_compression); 820 try writeNameList(&buf, allocator, &.{}); // langs c->s 821 try writeNameList(&buf, allocator, &.{}); // langs s->c 822 try buf.append(allocator, 0); // first_kex_packet_follows = false 823 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 824 825 return try buf.toOwnedSlice(allocator); 826 } 827 828 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 829 return buildKexInit(io, allocator, &(our_kex_algos ++ [_][]const u8{kex_strict_server}), &our_host_key_algos, &our_ciphers); 830 } 831 832 const ParsedKexInit = struct { 833 kex_algos: []u8, 834 host_key_algos: []u8, 835 cs_cipher: []u8, 836 sc_cipher: []u8, 837 838 fn deinit(self: ParsedKexInit, allocator: std.mem.Allocator) void { 839 allocator.free(self.kex_algos); 840 allocator.free(self.host_key_algos); 841 allocator.free(self.cs_cipher); 842 allocator.free(self.sc_cipher); 843 } 844 }; 845 846 fn parseClientKexInit(allocator: std.mem.Allocator, payload: []const u8) !ParsedKexInit { 847 if (payload.len < 1 + 16) return error.KexInitTruncated; 848 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 849 850 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 851 852 const kex_algos = try takeStringField(allocator, &reader, max_name_list_len); 853 errdefer allocator.free(kex_algos); 854 const host_key_algos = try takeStringField(allocator, &reader, max_name_list_len); 855 errdefer allocator.free(host_key_algos); 856 const cs_cipher = try takeStringField(allocator, &reader, max_name_list_len); 857 errdefer allocator.free(cs_cipher); 858 const sc_cipher = try takeStringField(allocator, &reader, max_name_list_len); 859 errdefer allocator.free(sc_cipher); 860 861 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 862 for (0..6) |_| { 863 const len = try reader.takeInt(u32, .big); 864 if (len > max_name_list_len) return error.FieldTooLarge; 865 try reader.discardAll(len); 866 } 867 _ = try reader.takeByte(); // first_kex_packet_follows 868 _ = try reader.takeInt(u32, .big); // reserved 869 870 return .{ 871 .kex_algos = kex_algos, 872 .host_key_algos = host_key_algos, 873 .cs_cipher = cs_cipher, 874 .sc_cipher = sc_cipher, 875 }; 876 } 877 878 // --------------------------------------------------------------------------- 879 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 880 // --------------------------------------------------------------------------- 881 882 const KexResult = struct { 883 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 884 sc_key: [64]u8, // server → client cipher key material 885 session_id: [Sha256.digest_length]u8, 886 next_cs_seq: u64, 887 next_sc_seq: u64, 888 strict: bool, 889 }; 890 891 fn runKex( 892 io: std.Io, 893 allocator: std.mem.Allocator, 894 reader: *std.Io.Reader, 895 writer: *std.Io.Writer, 896 host_key: *const HostKey, 897 client_version: []const u8, 898 ) !KexResult { 899 var client_seq: u64 = 0; 900 const transport = KexTransport{ .plain = &client_seq }; 901 902 // exchange KEXINITs 903 const server_kex_init = try buildServerKexInit(io, allocator); 904 defer allocator.free(server_kex_init); 905 try writePlainPacket(io, writer, server_kex_init); 906 907 const client_kex_init = try transport.readPacket(allocator, reader, false); 908 defer allocator.free(client_kex_init); 909 910 // strict kex: when the client advertises it, its KEXINIT must be the 911 // first packet, ignorable messages are banned until NEWKEYS, and both 912 // seqnos reset to 0 after every NEWKEYS. 913 const strict = strict: { 914 var parsed = try parseClientKexInit(allocator, client_kex_init); 915 defer parsed.deinit(allocator); 916 break :strict nameListContainsAny(parsed.kex_algos, &.{kex_strict_client}); 917 }; 918 if (strict and client_seq != 1) return error.StrictKexViolation; 919 920 const negotiated = try exchangeKeys( 921 io, 922 allocator, 923 reader, 924 writer, 925 transport, 926 strict, 927 host_key, 928 client_version, 929 client_kex_init, 930 server_kex_init, 931 null, 932 ); 933 934 return .{ 935 .cs_key = negotiated.keys.cs_enc, 936 .sc_key = negotiated.keys.sc_enc, 937 .session_id = negotiated.exchange_hash, 938 // the server sent exactly KEXINIT, KEX_ECDH_REPLY and NEWKEYS; the 939 // client's count includes any skipped IGNORE/DEBUG packets. 940 .next_cs_seq = if (strict) 0 else client_seq, 941 .next_sc_seq = if (strict) 0 else 3, 942 .strict = strict, 943 }; 944 } 945 946 /// everything needed to service a client-initiated rekey mid-session. 947 pub const RekeyState = struct { 948 host_key: *const HostKey, 949 client_version: []const u8, 950 session_id: [Sha256.digest_length]u8, 951 strict: bool, 952 }; 953 954 // service a rekey whose triggering KEXINIT payload has just been read: run 955 // the whole exchange under the current keys, then swap the new keys into 956 // both ciphers in place. 957 fn runRekey( 958 io: std.Io, 959 allocator: std.mem.Allocator, 960 reader: *std.Io.Reader, 961 writer: *std.Io.Writer, 962 cs_cipher: *Cipher, 963 sc_cipher: *Cipher, 964 rekey: *const RekeyState, 965 client_kex_init: []const u8, 966 ) !void { 967 const server_kex_init = try buildServerKexInit(io, allocator); 968 defer allocator.free(server_kex_init); 969 try sc_cipher.writePacket(io, writer, server_kex_init); 970 971 const negotiated = try exchangeKeys( 972 io, 973 allocator, 974 reader, 975 writer, 976 .{ .encrypted = .{ .cs = cs_cipher, .sc = sc_cipher } }, 977 false, 978 rekey.host_key, 979 rekey.client_version, 980 client_kex_init, 981 server_kex_init, 982 &rekey.session_id, 983 ); 984 985 // seqnos continue across a rekey unless strict kex was negotiated, 986 // which resets them after every NEWKEYS 987 cs_cipher.setKeys(&negotiated.keys.cs_enc, if (rekey.strict) 0 else cs_cipher.seq); 988 sc_cipher.setKeys(&negotiated.keys.sc_enc, if (rekey.strict) 0 else sc_cipher.seq); 989 } 990 991 const NegotiatedKeys = struct { 992 keys: SessionKeys, 993 exchange_hash: [Sha256.digest_length]u8, 994 }; 995 996 // the KEX core shared by the initial exchange and rekeys: pick algorithms, 997 // run the (hybrid) ECDH round trip, exchange NEWKEYS, derive keys. both 998 // KEXINIT payloads have already been exchanged by the caller. session_id is 999 // null on the initial exchange (where it becomes the exchange hash) and the 1000 // original session id on a rekey. 1001 fn exchangeKeys( 1002 io: std.Io, 1003 allocator: std.mem.Allocator, 1004 reader: *std.Io.Reader, 1005 writer: *std.Io.Writer, 1006 transport: KexTransport, 1007 strict: bool, 1008 host_key: *const HostKey, 1009 client_version: []const u8, 1010 client_kex_init: []const u8, 1011 server_kex_init: []const u8, 1012 session_id: ?*const [Sha256.digest_length]u8, 1013 ) !NegotiatedKeys { 1014 var parsed = try parseClientKexInit(allocator, client_kex_init); 1015 defer parsed.deinit(allocator); 1016 1017 // pick the first kex algo in the client's preference list that we also 1018 // support (RFC 4253 §7.1.3). 1019 const kex_algo = blk: { 1020 var iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 1021 while (iter.next()) |name| { 1022 for (our_kex_algos) |opt| { 1023 if (std.mem.eql(u8, name, opt)) break :blk opt; 1024 } 1025 } 1026 return error.NoCommonKexAlgorithm; 1027 }; 1028 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 1029 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 1030 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 1031 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 1032 1033 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 1034 // wire shape, only the string size differs). 1035 const ecdh_init = try transport.readPacket(allocator, reader, strict); 1036 defer allocator.free(ecdh_init); 1037 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 1038 1039 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 1040 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 1041 const client_blob = try takeStringField(allocator, &ecdh_init_reader, expected_client_len); 1042 defer allocator.free(client_blob); 1043 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 1044 1045 // derive server reply blob (S_REPLY) + shared secret K. 1046 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 1047 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 1048 // K = SHA-256(K_MLKEM || K_X25519). 1049 var server_blob: []u8 = undefined; 1050 var k: []u8 = undefined; 1051 { 1052 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 1053 var x25519_client_pub: [X25519.public_length]u8 = undefined; 1054 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 1055 const server_kp = X25519.KeyPair.generate(io); 1056 const x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 1057 1058 if (hybrid) { 1059 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 1060 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 1061 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 1062 const encap = pq_pub.encaps(io); 1063 1064 server_blob = try allocator.alloc(u8, hybrid_server_blob_len); 1065 @memcpy(server_blob[0..MLKem768.ciphertext_length], &encap.ciphertext); 1066 @memcpy(server_blob[MLKem768.ciphertext_length..], &server_kp.public_key); 1067 1068 var h = Sha256.init(.{}); 1069 h.update(&encap.shared_secret); 1070 h.update(&x25519_shared); 1071 k = try allocator.dupe(u8, &h.finalResult()); 1072 } else { 1073 server_blob = try allocator.dupe(u8, &server_kp.public_key); 1074 k = try allocator.dupe(u8, &x25519_shared); 1075 } 1076 } 1077 defer allocator.free(server_blob); 1078 defer allocator.free(k); 1079 1080 // build host key blob (K_S) 1081 var host_key_blob: std.ArrayList(u8) = .empty; 1082 defer host_key_blob.deinit(allocator); 1083 try host_key.appendPublicBlob(&host_key_blob, allocator); 1084 1085 // build exchange hash input and compute H 1086 const exchange_hash = try computeExchangeHash( 1087 allocator, 1088 client_version, 1089 server_version, 1090 client_kex_init, 1091 server_kex_init, 1092 host_key_blob.items, 1093 client_blob, 1094 server_blob, 1095 k, 1096 hybrid, 1097 ); 1098 1099 // sign H with the host key, format as ssh signature blob 1100 var signature_blob: std.ArrayList(u8) = .empty; 1101 defer signature_blob.deinit(allocator); 1102 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 1103 1104 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 1105 var reply: std.ArrayList(u8) = .empty; 1106 defer reply.deinit(allocator); 1107 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 1108 try writeStringField(&reply, allocator, host_key_blob.items); 1109 try writeStringField(&reply, allocator, server_blob); 1110 try writeStringField(&reply, allocator, signature_blob.items); 1111 try transport.writePacket(io, writer, reply.items); 1112 1113 // NEWKEYS — both sides switch to the new keys after this is sent and 1114 // the peer's NEWKEYS is received. 1115 try transport.writePacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 1116 1117 const peer_newkeys = try transport.readPacket(allocator, reader, strict); 1118 defer allocator.free(peer_newkeys); 1119 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 1120 1121 // derive session keys per RFC 4253 §7.2. only the encrypt keys are 1122 // needed for chacha20-poly1305 (no separate MAC/IV). 1123 var keys: SessionKeys = undefined; 1124 try deriveSessionKeys(allocator, k, &exchange_hash, if (session_id) |sid| sid else &exchange_hash, &keys, hybrid); 1125 1126 return .{ .keys = keys, .exchange_hash = exchange_hash }; 1127 } 1128 1129 // --------------------------------------------------------------------------- 1130 // exchange hash (RFC 4253 §8, RFC 5656 §4) 1131 // --------------------------------------------------------------------------- 1132 1133 pub fn computeExchangeHash( 1134 allocator: std.mem.Allocator, 1135 client_version: []const u8, 1136 server_version_str: []const u8, 1137 client_kex_init: []const u8, 1138 server_kex_init: []const u8, 1139 host_key_blob: []const u8, 1140 client_ephemeral: []const u8, 1141 server_ephemeral: []const u8, 1142 shared_secret: []const u8, 1143 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 1144 /// as a plain SSH string (length-prefixed bytes). 1145 k_is_string: bool, 1146 ) ![Sha256.digest_length]u8 { 1147 var buf: std.ArrayList(u8) = .empty; 1148 defer buf.deinit(allocator); 1149 1150 try writeStringField(&buf, allocator, client_version); 1151 try writeStringField(&buf, allocator, server_version_str); 1152 try writeStringField(&buf, allocator, client_kex_init); 1153 try writeStringField(&buf, allocator, server_kex_init); 1154 try writeStringField(&buf, allocator, host_key_blob); 1155 try writeStringField(&buf, allocator, client_ephemeral); 1156 try writeStringField(&buf, allocator, server_ephemeral); 1157 if (k_is_string) { 1158 try writeStringField(&buf, allocator, shared_secret); 1159 } else { 1160 try writeMpint(&buf, allocator, shared_secret); 1161 } 1162 1163 var hasher = Sha256.init(.{}); 1164 hasher.update(buf.items); 1165 return hasher.finalResult(); 1166 } 1167 1168 // --------------------------------------------------------------------------- 1169 // key derivation (RFC 4253 §7.2) 1170 // --------------------------------------------------------------------------- 1171 1172 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 1173 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 1174 // blocks chained per RFC 4253. 1175 pub const SessionKeys = struct { 1176 cs_enc: [64]u8, 1177 sc_enc: [64]u8, 1178 }; 1179 1180 pub fn deriveSessionKeys( 1181 allocator: std.mem.Allocator, 1182 shared_secret: []const u8, 1183 exchange_hash: []const u8, 1184 session_id: []const u8, 1185 out: *SessionKeys, 1186 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1187 k_is_string: bool, 1188 ) !void { 1189 // pre-build the K || H prefix once; reused for every derivation 1190 var prefix: std.ArrayList(u8) = .empty; 1191 defer prefix.deinit(allocator); 1192 if (k_is_string) { 1193 try writeStringField(&prefix, allocator, shared_secret); 1194 } else { 1195 try writeMpint(&prefix, allocator, shared_secret); 1196 } 1197 try prefix.appendSlice(allocator, exchange_hash); 1198 1199 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 1200 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 1201 } 1202 1203 fn deriveKey( 1204 allocator: std.mem.Allocator, 1205 prefix: []const u8, // K || H, already encoded 1206 letter: u8, 1207 session_id: []const u8, 1208 out: []u8, 1209 ) !void { 1210 // first block: HASH(K || H || letter || session_id) 1211 var first_block: [Sha256.digest_length]u8 = undefined; 1212 { 1213 var hasher = Sha256.init(.{}); 1214 hasher.update(prefix); 1215 hasher.update(&[_]u8{letter}); 1216 hasher.update(session_id); 1217 first_block = hasher.finalResult(); 1218 } 1219 const first_copy = @min(out.len, first_block.len); 1220 @memcpy(out[0..first_copy], first_block[0..first_copy]); 1221 1222 // chain additional blocks if requested length exceeds one hash: 1223 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 1224 var chained: std.ArrayList(u8) = .empty; 1225 defer chained.deinit(allocator); 1226 try chained.appendSlice(allocator, first_block[0..]); 1227 1228 var produced: usize = first_copy; 1229 while (produced < out.len) { 1230 var hasher = Sha256.init(.{}); 1231 hasher.update(prefix); 1232 hasher.update(chained.items); 1233 const block = hasher.finalResult(); 1234 const copy_len = @min(out.len - produced, block.len); 1235 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 1236 produced += copy_len; 1237 try chained.appendSlice(allocator, block[0..]); 1238 } 1239 } 1240 1241 // --------------------------------------------------------------------------- 1242 // chacha20-poly1305@openssh.com packet codec 1243 // --------------------------------------------------------------------------- 1244 // 1245 // per openssh's PROTOCOL.chacha20poly1305: 1246 // K_2 = first 32 bytes of key material — encrypts the packet body 1247 // K_1 = next 32 bytes — encrypts the 4-byte length field 1248 // nonce = 64-bit big-endian sequence number 1249 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1250 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1251 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1252 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1253 // 1254 // padding is computed on the body alone (padding_length byte + payload + 1255 // padding) — the 4-byte length field is excluded from alignment. body must 1256 // be a multiple of 8 bytes; minimum padding 4 bytes. 1257 1258 pub const Cipher = struct { 1259 main_key: [32]u8, // K_2 1260 header_key: [32]u8, // K_1 1261 seq: u64, 1262 idle: ?*IdleState = null, 1263 1264 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1265 return .{ 1266 .main_key = key_material[0..32].*, 1267 .header_key = key_material[32..64].*, 1268 .seq = initial_seq, 1269 }; 1270 } 1271 1272 /// swap in new key material after a rekey, leaving the rest of the 1273 /// cipher state alone 1274 fn setKeys(self: *Cipher, key_material: *const [64]u8, seq: u64) void { 1275 self.main_key = key_material[0..32].*; 1276 self.header_key = key_material[32..64].*; 1277 self.seq = seq; 1278 } 1279 1280 fn makeNonce(seq: u64) [8]u8 { 1281 var nonce: [8]u8 = undefined; 1282 std.mem.writeInt(u64, &nonce, seq, .big); 1283 return nonce; 1284 } 1285 1286 pub fn writePacket( 1287 self: *Cipher, 1288 io: std.Io, 1289 writer: *std.Io.Writer, 1290 payload: []const u8, 1291 ) !void { 1292 const block: usize = 8; 1293 const initial_pad = block - ((1 + payload.len) % block); 1294 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1295 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1296 1297 const nonce = makeNonce(self.seq); 1298 1299 // plaintext body = padding_length || payload || random padding. 1300 // stack-allocated to avoid a heap alloc on every packet. 1301 var body_buf: [max_packet_len]u8 = undefined; 1302 if (body_len > body_buf.len) return error.PacketTooLarge; 1303 const body = body_buf[0..body_len]; 1304 body[0] = padding_len; 1305 @memcpy(body[1 .. 1 + payload.len], payload); 1306 io.random(body[1 + payload.len ..]); 1307 1308 // encrypt body in place with counter=1 1309 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1310 1311 // encrypt length field with header key, counter=0 1312 var enc_length: [4]u8 = undefined; 1313 var length_plain: [4]u8 = undefined; 1314 std.mem.writeInt(u32, &length_plain, body_len, .big); 1315 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1316 1317 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1318 var poly_key: [Poly1305.key_length]u8 = undefined; 1319 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1320 1321 // mac over encrypted_length || encrypted_body 1322 var poly = Poly1305.init(&poly_key); 1323 poly.update(&enc_length); 1324 poly.update(body); 1325 var tag: [Poly1305.mac_length]u8 = undefined; 1326 poly.final(&tag); 1327 1328 try writer.writeAll(&enc_length); 1329 try writer.writeAll(body); 1330 try writer.writeAll(&tag); 1331 try writer.flush(); 1332 1333 self.seq += 1; 1334 } 1335 1336 pub fn readPacket( 1337 self: *Cipher, 1338 allocator: std.mem.Allocator, 1339 reader: *std.Io.Reader, 1340 ) ![]u8 { 1341 const nonce = makeNonce(self.seq); 1342 1343 var enc_length: [4]u8 = undefined; 1344 try reader.readSliceAll(&enc_length); 1345 1346 var length_plain: [4]u8 = undefined; 1347 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1348 const body_len = std.mem.readInt(u32, &length_plain, .big); 1349 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1350 1351 const enc_body = try allocator.alloc(u8, body_len); 1352 defer allocator.free(enc_body); 1353 try reader.readSliceAll(enc_body); 1354 1355 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1356 try reader.readSliceAll(&tag_recv); 1357 1358 var poly_key: [Poly1305.key_length]u8 = undefined; 1359 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1360 1361 var poly = Poly1305.init(&poly_key); 1362 poly.update(&enc_length); 1363 poly.update(enc_body); 1364 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1365 poly.final(&tag_computed); 1366 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1367 return error.MacVerificationFailed; 1368 } 1369 1370 // decrypt the body in place, then copy out the payload (caller owns) 1371 ChaCha20.xor(enc_body, enc_body, 1, self.main_key, nonce); 1372 1373 const padding_len = enc_body[0]; 1374 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1375 const payload_len = body_len - 1 - @as(u32, padding_len); 1376 1377 const payload = try allocator.dupe(u8, enc_body[1 .. 1 + payload_len]); 1378 1379 self.seq += 1; 1380 if (self.idle) |idle| _ = idle.activity.fetchAdd(1, .monotonic); 1381 return payload; 1382 } 1383 }; 1384 1385 // --------------------------------------------------------------------------- 1386 // post-KEX: service request + user authentication (RFC 4252) 1387 // --------------------------------------------------------------------------- 1388 1389 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1390 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1391 /// `Offering public key: … SHA256:…`. 1392 pub const fingerprint_len = 50; 1393 1394 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1395 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1396 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1397 var digest: [Sha256.digest_length]u8 = undefined; 1398 Sha256.hash(pubkey_blob, &digest, .{}); 1399 1400 var out: [fingerprint_len]u8 = undefined; 1401 @memcpy(out[0..7], "SHA256:"); 1402 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1403 std.debug.assert(encoded.len == fingerprint_len - 7); 1404 return out; 1405 } 1406 1407 fn runAuth( 1408 io: std.Io, 1409 allocator: std.mem.Allocator, 1410 reader: *std.Io.Reader, 1411 writer: *std.Io.Writer, 1412 cs_cipher: *Cipher, 1413 sc_cipher: *Cipher, 1414 rekey: *const RekeyState, 1415 ) ![fingerprint_len]u8 { 1416 // step 1: service request for ssh-userauth → service accept 1417 { 1418 const req = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1419 defer allocator.free(req); 1420 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1421 1422 var req_reader = std.Io.Reader.fixed(req[1..]); 1423 const service = try takeStringField(allocator, &req_reader, 64); 1424 defer allocator.free(service); 1425 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1426 1427 var accept: std.ArrayList(u8) = .empty; 1428 defer accept.deinit(allocator); 1429 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1430 try writeStringField(&accept, allocator, "ssh-userauth"); 1431 try sc_cipher.writePacket(io, writer, accept.items); 1432 } 1433 1434 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1435 // signature verifies against the offered pubkey. 1436 var auth_attempts: u32 = 0; 1437 while (true) { 1438 const req = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1439 defer allocator.free(req); 1440 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1441 1442 var req_reader = std.Io.Reader.fixed(req[1..]); 1443 const user_name = try takeStringField(allocator, &req_reader, 256); 1444 defer allocator.free(user_name); 1445 const service_name = try takeStringField(allocator, &req_reader, 64); 1446 defer allocator.free(service_name); 1447 const method = try takeStringField(allocator, &req_reader, 64); 1448 defer allocator.free(method); 1449 1450 // RFC 4252 §5: the server must verify the requested service 1451 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1452 auth_attempts += 1; 1453 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1454 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1455 continue; 1456 } 1457 1458 if (!std.mem.eql(u8, method, "publickey")) { 1459 auth_attempts += 1; 1460 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1461 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1462 continue; 1463 } 1464 1465 const has_signature = (try req_reader.takeByte()) != 0; 1466 const algo = try takeStringField(allocator, &req_reader, 64); 1467 defer allocator.free(algo); 1468 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1469 defer allocator.free(pubkey_blob); 1470 1471 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1472 auth_attempts += 1; 1473 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1474 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1475 continue; 1476 } 1477 1478 if (!has_signature) { 1479 // probes count as attempts so a client can't loop here forever 1480 auth_attempts += 1; 1481 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1482 // probe — tell the client this key is acceptable so it'll send 1483 // the signed version next. 1484 var pk_ok: std.ArrayList(u8) = .empty; 1485 defer pk_ok.deinit(allocator); 1486 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1487 try writeStringField(&pk_ok, allocator, algo); 1488 try writeStringField(&pk_ok, allocator, pubkey_blob); 1489 try sc_cipher.writePacket(io, writer, pk_ok.items); 1490 continue; 1491 } 1492 1493 // has signature — verify it 1494 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1495 defer allocator.free(signature_blob); 1496 1497 const ok = verifyUserauthSignature( 1498 allocator, 1499 &rekey.session_id, 1500 user_name, 1501 service_name, 1502 algo, 1503 pubkey_blob, 1504 signature_blob, 1505 ) catch false; 1506 1507 if (!ok) { 1508 auth_attempts += 1; 1509 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1510 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1511 continue; 1512 } 1513 1514 try sc_cipher.writePacket(io, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1515 return formatFingerprint(pubkey_blob); 1516 } 1517 } 1518 1519 fn sendUserauthFailure( 1520 io: std.Io, 1521 allocator: std.mem.Allocator, 1522 sc_cipher: *Cipher, 1523 writer: *std.Io.Writer, 1524 ) !void { 1525 var buf: std.ArrayList(u8) = .empty; 1526 defer buf.deinit(allocator); 1527 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1528 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1529 try buf.append(allocator, 0); // partial_success = false 1530 try sc_cipher.writePacket(io, writer, buf.items); 1531 } 1532 1533 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1534 /// Used by the server to recompute the signed input for verification 1535 pub fn appendPublickeySignedData( 1536 buf: *std.ArrayList(u8), 1537 allocator: std.mem.Allocator, 1538 session_id: []const u8, 1539 user_name: []const u8, 1540 service_name: []const u8, 1541 algo: []const u8, 1542 pubkey_blob: []const u8, 1543 ) !void { 1544 try writeStringField(buf, allocator, session_id); 1545 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1546 try writeStringField(buf, allocator, user_name); 1547 try writeStringField(buf, allocator, service_name); 1548 try writeStringField(buf, allocator, "publickey"); 1549 try buf.append(allocator, 1); 1550 try writeStringField(buf, allocator, algo); 1551 try writeStringField(buf, allocator, pubkey_blob); 1552 } 1553 1554 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1555 // verify the supplied signature against them. 1556 fn verifyUserauthSignature( 1557 allocator: std.mem.Allocator, 1558 session_id: *const [Sha256.digest_length]u8, 1559 user_name: []const u8, 1560 service_name: []const u8, 1561 algo: []const u8, 1562 pubkey_blob: []const u8, 1563 signature_blob: []const u8, 1564 ) !bool { 1565 var signed: std.ArrayList(u8) = .empty; 1566 defer signed.deinit(allocator); 1567 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1568 1569 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1570 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1571 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1572 defer allocator.free(pk_algo); 1573 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1574 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1575 defer allocator.free(raw_pubkey); 1576 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1577 1578 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1579 var sig_reader = std.Io.Reader.fixed(signature_blob); 1580 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1581 defer allocator.free(sig_algo); 1582 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1583 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1584 defer allocator.free(raw_sig); 1585 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1586 1587 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1588 @memcpy(&pubkey_bytes, raw_pubkey); 1589 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1590 @memcpy(&sig_bytes, raw_sig); 1591 1592 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1593 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1594 sig.verify(signed.items, pk) catch return false; 1595 return true; 1596 } 1597 1598 // --------------------------------------------------------------------------- 1599 // connection layer (RFC 4254): channels, requests, data, flow control 1600 // --------------------------------------------------------------------------- 1601 1602 const Channel = struct { 1603 local_id: u32, 1604 remote_id: u32, 1605 local_window: u32, // bytes peer may still send us before we adjust 1606 remote_window: u32, // bytes we may still send to peer before they adjust 1607 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1608 pty: ?PtySize = null, 1609 }; 1610 1611 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1612 1613 // take the uint32 width/height cell counts of a pty-req or window-change, 1614 // clamped to u16 1615 fn takePtySize(r: *std.Io.Reader) !PtySize { 1616 const width = try r.takeInt(u32, .big); 1617 const height = try r.takeInt(u32, .big); 1618 return .{ 1619 .width_cells = @intCast(@min(width, 0xFFFF)), 1620 .height_cells = @intCast(@min(height, 0xFFFF)), 1621 }; 1622 } 1623 1624 fn runChannelLayer( 1625 io: std.Io, 1626 allocator: std.mem.Allocator, 1627 reader: *std.Io.Reader, 1628 writer: *std.Io.Writer, 1629 cs_cipher: *Cipher, 1630 sc_cipher: *Cipher, 1631 rekey: *const RekeyState, 1632 fingerprint: *const [fingerprint_len]u8, 1633 handler: anytype, 1634 ) !void { 1635 var channel: ?Channel = null; 1636 var pending_exec: ?[]u8 = null; 1637 defer if (pending_exec) |s| allocator.free(s); 1638 1639 while (true) { 1640 const packet = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1641 defer allocator.free(packet); 1642 if (packet.len < 1) return error.EmptyPacket; 1643 const msg_type = packet[0]; 1644 1645 switch (msg_type) { 1646 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1647 1648 SSH_MSG_CHANNEL_OPEN => { 1649 if (channel != null) { 1650 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1651 continue; 1652 } 1653 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1654 }, 1655 1656 SSH_MSG_CHANNEL_REQUEST => { 1657 const ch = if (channel) |*c| c else continue; 1658 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1659 if (start_request) |req_kind| { 1660 const request: Request = switch (req_kind) { 1661 .shell => .{ .shell = ch.pty }, 1662 .exec => .{ .exec = pending_exec.? }, 1663 }; 1664 var sess = SessionCtx{ 1665 .io = io, 1666 .allocator = allocator, 1667 .reader = reader, 1668 .writer = writer, 1669 .cs_cipher = cs_cipher, 1670 .sc_cipher = sc_cipher, 1671 .rekey = rekey, 1672 .channel = ch, 1673 .fingerprint = fingerprint.*, 1674 }; 1675 defer sess.deinit(); 1676 handler.handleSession(&sess, request) catch |session_err| { 1677 // try to send a non-zero exit status before closing 1678 sess.exit(1) catch {}; 1679 return session_err; 1680 }; 1681 if (!sess.closed) try sess.exit(0); 1682 return; 1683 } 1684 }, 1685 1686 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1687 const ch = if (channel) |*c| c else continue; 1688 try handleWindowAdjust(ch, packet); 1689 }, 1690 1691 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1692 const ch = if (channel) |*c| c else continue; 1693 // before shell/exec the client shouldn't be sending data, but 1694 // some clients are chatty; discard and refill window. 1695 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1696 }, 1697 1698 SSH_MSG_CHANNEL_EOF => { 1699 if (channel) |*c| try parseChannelId(packet, c.local_id); 1700 }, 1701 1702 SSH_MSG_CHANNEL_CLOSE => { 1703 if (channel) |*c| try parseChannelId(packet, c.local_id); 1704 return; 1705 }, 1706 1707 else => {}, // ignore unknown messages 1708 } 1709 } 1710 } 1711 1712 fn handleGlobalRequest( 1713 io: std.Io, 1714 allocator: std.mem.Allocator, 1715 sc_cipher: *Cipher, 1716 writer: *std.Io.Writer, 1717 packet: []const u8, 1718 ) !void { 1719 // byte SSH_MSG_GLOBAL_REQUEST 1720 // string request_name 1721 // boolean want_reply 1722 // …request-specific data we ignore 1723 var r = std.Io.Reader.fixed(packet[1..]); 1724 const name = try takeStringField(allocator, &r, 256); 1725 defer allocator.free(name); 1726 const want_reply = (try r.takeByte()) != 0; 1727 if (want_reply) { 1728 try sc_cipher.writePacket(io, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1729 } 1730 } 1731 1732 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1733 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1734 /// return null. 1735 fn handleChannelOpen( 1736 io: std.Io, 1737 allocator: std.mem.Allocator, 1738 sc_cipher: *Cipher, 1739 writer: *std.Io.Writer, 1740 packet: []const u8, 1741 ) !?Channel { 1742 // byte SSH_MSG_CHANNEL_OPEN 1743 // string channel_type 1744 // uint32 sender_channel (peer's id) 1745 // uint32 initial_window 1746 // uint32 max_packet 1747 var r = std.Io.Reader.fixed(packet[1..]); 1748 const ch_type = try takeStringField(allocator, &r, 64); 1749 defer allocator.free(ch_type); 1750 const remote_id = try r.takeInt(u32, .big); 1751 const initial_window = try r.takeInt(u32, .big); 1752 const max_packet = try r.takeInt(u32, .big); 1753 1754 if (!std.mem.eql(u8, ch_type, "session")) { 1755 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1756 return null; 1757 } 1758 1759 // a zero max_packet would leave writeChannel looping without progress 1760 if (max_packet == 0) { 1761 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1762 return null; 1763 } 1764 1765 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1766 var reply: std.ArrayList(u8) = .empty; 1767 defer reply.deinit(allocator); 1768 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1769 try writeU32(&reply, allocator, remote_id); 1770 try writeU32(&reply, allocator, local_id); 1771 try writeU32(&reply, allocator, initial_recv_window); 1772 try writeU32(&reply, allocator, max_packet_size); 1773 try sc_cipher.writePacket(io, writer, reply.items); 1774 1775 return .{ 1776 .local_id = local_id, 1777 .remote_id = remote_id, 1778 .local_window = initial_recv_window, 1779 .remote_window = initial_window, 1780 .max_packet = max_packet, 1781 }; 1782 } 1783 1784 fn sendChannelOpenFailure( 1785 io: std.Io, 1786 allocator: std.mem.Allocator, 1787 sc_cipher: *Cipher, 1788 writer: *std.Io.Writer, 1789 open_packet: []const u8, 1790 reason: u32, 1791 description: []const u8, 1792 ) !void { 1793 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1794 // address the failure to the correct id 1795 var r = std.Io.Reader.fixed(open_packet[1..]); 1796 const ch_type_len = try r.takeInt(u32, .big); 1797 try r.discardAll(ch_type_len); 1798 const remote_id = try r.takeInt(u32, .big); 1799 1800 var reply: std.ArrayList(u8) = .empty; 1801 defer reply.deinit(allocator); 1802 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1803 try writeU32(&reply, allocator, remote_id); 1804 try writeU32(&reply, allocator, reason); 1805 try writeStringField(&reply, allocator, description); 1806 try writeStringField(&reply, allocator, ""); // language tag 1807 try sc_cipher.writePacket(io, writer, reply.items); 1808 } 1809 1810 const RequestKind = enum { shell, exec }; 1811 1812 /// Returns the kind of session request if this triggered one, else null. 1813 fn handleChannelRequest( 1814 io: std.Io, 1815 allocator: std.mem.Allocator, 1816 sc_cipher: *Cipher, 1817 writer: *std.Io.Writer, 1818 ch: *Channel, 1819 packet: []const u8, 1820 pending_exec: *?[]u8, 1821 ) !?RequestKind { 1822 // byte SSH_MSG_CHANNEL_REQUEST 1823 // uint32 recipient_channel (== our local_id) 1824 // string request_type 1825 // boolean want_reply 1826 // …request-specific data 1827 var r = std.Io.Reader.fixed(packet[1..]); 1828 const recipient_channel = try r.takeInt(u32, .big); 1829 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1830 const req_type = try takeStringField(allocator, &r, 64); 1831 defer allocator.free(req_type); 1832 const want_reply = (try r.takeByte()) != 0; 1833 1834 if (std.mem.eql(u8, req_type, "pty-req")) { 1835 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1836 // uint32 height px, string modes 1837 const term = try takeStringField(allocator, &r, 64); 1838 defer allocator.free(term); 1839 ch.pty = try takePtySize(&r); 1840 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1841 return null; 1842 } 1843 1844 if (std.mem.eql(u8, req_type, "env")) { 1845 // ignore environment variables silently (we don't pass them anywhere) 1846 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1847 return null; 1848 } 1849 1850 if (std.mem.eql(u8, req_type, "window-change")) { 1851 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1852 const sz = try takePtySize(&r); 1853 if (ch.pty != null) ch.pty = sz; 1854 // spec: window-change MUST NOT request a reply, but accept either 1855 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1856 return null; 1857 } 1858 1859 if (std.mem.eql(u8, req_type, "shell")) { 1860 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1861 return .shell; 1862 } 1863 1864 if (std.mem.eql(u8, req_type, "exec")) { 1865 // capture the command string for the handler to inspect 1866 const cmd = try takeStringField(allocator, &r, 4096); 1867 if (pending_exec.*) |old| allocator.free(old); 1868 pending_exec.* = cmd; 1869 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1870 return .exec; 1871 } 1872 1873 // unknown request kind — fail it 1874 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1875 return null; 1876 } 1877 1878 fn replyChannelRequest( 1879 io: std.Io, 1880 allocator: std.mem.Allocator, 1881 sc_cipher: *Cipher, 1882 writer: *std.Io.Writer, 1883 ch: *Channel, 1884 want_reply: bool, 1885 success: bool, 1886 ) !void { 1887 if (!want_reply) return; 1888 var reply: std.ArrayList(u8) = .empty; 1889 defer reply.deinit(allocator); 1890 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1891 try writeU32(&reply, allocator, ch.remote_id); 1892 try sc_cipher.writePacket(io, writer, reply.items); 1893 } 1894 1895 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1896 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1897 // uint32 recipient_channel 1898 // uint32 bytes_to_add 1899 var r = std.Io.Reader.fixed(packet[1..]); 1900 const recipient_channel = try r.takeInt(u32, .big); 1901 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1902 const add = try r.takeInt(u32, .big); 1903 ch.remote_window +|= add; 1904 } 1905 1906 fn discardChannelData( 1907 io: std.Io, 1908 allocator: std.mem.Allocator, 1909 sc_cipher: *Cipher, 1910 writer: *std.Io.Writer, 1911 ch: *Channel, 1912 packet: []const u8, 1913 extended: bool, 1914 ) !void { 1915 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1916 // uint32 recipient_channel 1917 // [if extended: uint32 type_code] 1918 // string data 1919 const payload = try parseChannelData(packet, extended, ch.local_id); 1920 const data_len: u32 = @intCast(payload.len); 1921 1922 if (data_len > ch.local_window) return error.WindowExceeded; 1923 ch.local_window -= data_len; 1924 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1925 } 1926 1927 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1928 if (packet.len < 1) return error.EmptyPacket; 1929 var r = std.Io.Reader.fixed(packet[1..]); 1930 const recipient_channel = try r.takeInt(u32, .big); 1931 if (recipient_channel != expected_channel) return error.UnknownChannel; 1932 if (extended) { 1933 const data_type = try r.takeInt(u32, .big); 1934 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1935 } 1936 const data_len = try r.takeInt(u32, .big); 1937 // catches both data_len > remaining (would otherwise be a bounds-check 1938 // panic on the slice) and trailing junk after the declared payload. 1939 if (data_len != r.buffered().len) return error.InvalidChannelData; 1940 return r.buffered(); 1941 } 1942 1943 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1944 if (packet.len < 1) return error.EmptyPacket; 1945 var r = std.Io.Reader.fixed(packet[1..]); 1946 const recipient_channel = try r.takeInt(u32, .big); 1947 if (recipient_channel != expected_channel) return error.UnknownChannel; 1948 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1949 } 1950 1951 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1952 /// of the initial value. Used both for the pre-session discard path and by 1953 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1954 fn maybeRefillRecvWindow( 1955 io: std.Io, 1956 allocator: std.mem.Allocator, 1957 sc_cipher: *Cipher, 1958 writer: *std.Io.Writer, 1959 ch: *Channel, 1960 ) !void { 1961 if (ch.local_window >= initial_recv_window / 2) return; 1962 const add = initial_recv_window - ch.local_window; 1963 ch.local_window += add; 1964 var adj: std.ArrayList(u8) = .empty; 1965 defer adj.deinit(allocator); 1966 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1967 try writeU32(&adj, allocator, ch.remote_id); 1968 try writeU32(&adj, allocator, add); 1969 try sc_cipher.writePacket(io, writer, adj.items); 1970 } 1971 1972 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1973 var bytes: [4]u8 = undefined; 1974 std.mem.writeInt(u32, &bytes, value, .big); 1975 try buf.appendSlice(allocator, &bytes); 1976 } 1977