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