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