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