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