╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1290 self.seq = seq; 1291 } 1292 1293 fn makeNonce(seq: u64) [8]u8 { 1294 var nonce: [8]u8 = undefined; 1295 std.mem.writeInt(u64, &nonce, seq, .big); 1296 return nonce; 1297 } 1298 1299 pub fn writePacket( 1300 self: *Cipher, 1301 io: std.Io, 1302 allocator: std.mem.Allocator, 1303 writer: *std.Io.Writer, 1304 payload: []const u8, 1305 ) !void { 1306 const block: usize = 8; 1307 const initial_pad = block - ((1 + payload.len) % block); 1308 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1309 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1310 1311 const nonce = makeNonce(self.seq); 1312 1313 // plaintext body = padding_length || payload || random padding 1314 const body = try allocator.alloc(u8, body_len); 1315 defer allocator.free(body); 1316 body[0] = padding_len; 1317 @memcpy(body[1 .. 1 + payload.len], payload); 1318 io.random(body[1 + payload.len ..]); 1319 1320 // encrypt body in place with counter=1 1321 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1322 1323 // encrypt length field with header key, counter=0 1324 var enc_length: [4]u8 = undefined; 1325 var length_plain: [4]u8 = undefined; 1326 std.mem.writeInt(u32, &length_plain, body_len, .big); 1327 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1328 1329 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1330 var poly_key: [Poly1305.key_length]u8 = undefined; 1331 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1332 1333 // mac over encrypted_length || encrypted_body 1334 var poly = Poly1305.init(&poly_key); 1335 poly.update(&enc_length); 1336 poly.update(body); 1337 var tag: [Poly1305.mac_length]u8 = undefined; 1338 poly.final(&tag); 1339 1340 try writer.writeAll(&enc_length); 1341 try writer.writeAll(body); 1342 try writer.writeAll(&tag); 1343 try writer.flush(); 1344 1345 self.seq += 1; 1346 } 1347 1348 pub fn readPacket( 1349 self: *Cipher, 1350 allocator: std.mem.Allocator, 1351 reader: *std.Io.Reader, 1352 ) ![]u8 { 1353 const nonce = makeNonce(self.seq); 1354 1355 var enc_length: [4]u8 = undefined; 1356 try reader.readSliceAll(&enc_length); 1357 1358 var length_plain: [4]u8 = undefined; 1359 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1360 const body_len = std.mem.readInt(u32, &length_plain, .big); 1361 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1362 1363 const enc_body = try allocator.alloc(u8, body_len); 1364 defer allocator.free(enc_body); 1365 try reader.readSliceAll(enc_body); 1366 1367 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1368 try reader.readSliceAll(&tag_recv); 1369 1370 var poly_key: [Poly1305.key_length]u8 = undefined; 1371 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1372 1373 var poly = Poly1305.init(&poly_key); 1374 poly.update(&enc_length); 1375 poly.update(enc_body); 1376 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1377 poly.final(&tag_computed); 1378 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1379 return error.MacVerificationFailed; 1380 } 1381 1382 // decrypt the body in place, then copy out the payload (caller owns) 1383 ChaCha20.xor(enc_body, enc_body, 1, self.main_key, nonce); 1384 1385 const padding_len = enc_body[0]; 1386 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1387 const payload_len = body_len - 1 - @as(u32, padding_len); 1388 1389 const payload = try allocator.dupe(u8, enc_body[1 .. 1 + payload_len]); 1390 1391 self.seq += 1; 1392 if (self.idle) |idle| _ = idle.activity.fetchAdd(1, .monotonic); 1393 return payload; 1394 } 1395 }; 1396 1397 // --------------------------------------------------------------------------- 1398 // post-KEX: service request + user authentication (RFC 4252) 1399 // --------------------------------------------------------------------------- 1400 1401 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1402 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1403 /// `Offering public key: … SHA256:…`. 1404 pub const fingerprint_len = 50; 1405 1406 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1407 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1408 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1409 var digest: [Sha256.digest_length]u8 = undefined; 1410 Sha256.hash(pubkey_blob, &digest, .{}); 1411 1412 var out: [fingerprint_len]u8 = undefined; 1413 @memcpy(out[0..7], "SHA256:"); 1414 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1415 std.debug.assert(encoded.len == fingerprint_len - 7); 1416 return out; 1417 } 1418 1419 fn runAuth( 1420 io: std.Io, 1421 allocator: std.mem.Allocator, 1422 reader: *std.Io.Reader, 1423 writer: *std.Io.Writer, 1424 cs_cipher: *Cipher, 1425 sc_cipher: *Cipher, 1426 rekey: *const RekeyState, 1427 ) ![fingerprint_len]u8 { 1428 // step 1: service request for ssh-userauth → service accept 1429 { 1430 const req = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1431 defer allocator.free(req); 1432 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1433 1434 var req_reader = std.Io.Reader.fixed(req[1..]); 1435 const service = try takeStringField(allocator, &req_reader, 64); 1436 defer allocator.free(service); 1437 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1438 1439 var accept: std.ArrayList(u8) = .empty; 1440 defer accept.deinit(allocator); 1441 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1442 try writeStringField(&accept, allocator, "ssh-userauth"); 1443 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1444 } 1445 1446 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1447 // signature verifies against the offered pubkey. 1448 var auth_attempts: u32 = 0; 1449 while (true) { 1450 const req = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1451 defer allocator.free(req); 1452 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1453 1454 var req_reader = std.Io.Reader.fixed(req[1..]); 1455 const user_name = try takeStringField(allocator, &req_reader, 256); 1456 defer allocator.free(user_name); 1457 const service_name = try takeStringField(allocator, &req_reader, 64); 1458 defer allocator.free(service_name); 1459 const method = try takeStringField(allocator, &req_reader, 64); 1460 defer allocator.free(method); 1461 1462 // RFC 4252 §5: the server must verify the requested service 1463 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1464 auth_attempts += 1; 1465 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1466 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1467 continue; 1468 } 1469 1470 if (!std.mem.eql(u8, method, "publickey")) { 1471 auth_attempts += 1; 1472 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1473 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1474 continue; 1475 } 1476 1477 const has_signature = (try req_reader.takeByte()) != 0; 1478 const algo = try takeStringField(allocator, &req_reader, 64); 1479 defer allocator.free(algo); 1480 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1481 defer allocator.free(pubkey_blob); 1482 1483 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1484 auth_attempts += 1; 1485 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1486 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1487 continue; 1488 } 1489 1490 if (!has_signature) { 1491 // probes count as attempts so a client can't loop here forever 1492 auth_attempts += 1; 1493 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1494 // probe — tell the client this key is acceptable so it'll send 1495 // the signed version next. 1496 var pk_ok: std.ArrayList(u8) = .empty; 1497 defer pk_ok.deinit(allocator); 1498 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1499 try writeStringField(&pk_ok, allocator, algo); 1500 try writeStringField(&pk_ok, allocator, pubkey_blob); 1501 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1502 continue; 1503 } 1504 1505 // has signature — verify it 1506 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1507 defer allocator.free(signature_blob); 1508 1509 const ok = verifyUserauthSignature( 1510 allocator, 1511 &rekey.session_id, 1512 user_name, 1513 service_name, 1514 algo, 1515 pubkey_blob, 1516 signature_blob, 1517 ) catch false; 1518 1519 if (!ok) { 1520 auth_attempts += 1; 1521 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1522 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1523 continue; 1524 } 1525 1526 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1527 return formatFingerprint(pubkey_blob); 1528 } 1529 } 1530 1531 fn sendUserauthFailure( 1532 io: std.Io, 1533 allocator: std.mem.Allocator, 1534 sc_cipher: *Cipher, 1535 writer: *std.Io.Writer, 1536 ) !void { 1537 var buf: std.ArrayList(u8) = .empty; 1538 defer buf.deinit(allocator); 1539 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1540 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1541 try buf.append(allocator, 0); // partial_success = false 1542 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1543 } 1544 1545 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1546 /// Used by the server to recompute the signed input for verification 1547 pub fn appendPublickeySignedData( 1548 buf: *std.ArrayList(u8), 1549 allocator: std.mem.Allocator, 1550 session_id: []const u8, 1551 user_name: []const u8, 1552 service_name: []const u8, 1553 algo: []const u8, 1554 pubkey_blob: []const u8, 1555 ) !void { 1556 try writeStringField(buf, allocator, session_id); 1557 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1558 try writeStringField(buf, allocator, user_name); 1559 try writeStringField(buf, allocator, service_name); 1560 try writeStringField(buf, allocator, "publickey"); 1561 try buf.append(allocator, 1); 1562 try writeStringField(buf, allocator, algo); 1563 try writeStringField(buf, allocator, pubkey_blob); 1564 } 1565 1566 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1567 // verify the supplied signature against them. 1568 fn verifyUserauthSignature( 1569 allocator: std.mem.Allocator, 1570 session_id: *const [Sha256.digest_length]u8, 1571 user_name: []const u8, 1572 service_name: []const u8, 1573 algo: []const u8, 1574 pubkey_blob: []const u8, 1575 signature_blob: []const u8, 1576 ) !bool { 1577 var signed: std.ArrayList(u8) = .empty; 1578 defer signed.deinit(allocator); 1579 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1580 1581 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1582 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1583 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1584 defer allocator.free(pk_algo); 1585 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1586 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1587 defer allocator.free(raw_pubkey); 1588 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1589 1590 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1591 var sig_reader = std.Io.Reader.fixed(signature_blob); 1592 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1593 defer allocator.free(sig_algo); 1594 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1595 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1596 defer allocator.free(raw_sig); 1597 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1598 1599 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1600 @memcpy(&pubkey_bytes, raw_pubkey); 1601 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1602 @memcpy(&sig_bytes, raw_sig); 1603 1604 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1605 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1606 sig.verify(signed.items, pk) catch return false; 1607 return true; 1608 } 1609 1610 // --------------------------------------------------------------------------- 1611 // connection layer (RFC 4254): channels, requests, data, flow control 1612 // --------------------------------------------------------------------------- 1613 1614 const Channel = struct { 1615 local_id: u32, 1616 remote_id: u32, 1617 local_window: u32, // bytes peer may still send us before we adjust 1618 remote_window: u32, // bytes we may still send to peer before they adjust 1619 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1620 pty: ?PtySize = null, 1621 }; 1622 1623 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1624 1625 // take the uint32 width/height cell counts of a pty-req or window-change, 1626 // clamped to u16 1627 fn takePtySize(r: *std.Io.Reader) !PtySize { 1628 const width = try r.takeInt(u32, .big); 1629 const height = try r.takeInt(u32, .big); 1630 return .{ 1631 .width_cells = @intCast(@min(width, 0xFFFF)), 1632 .height_cells = @intCast(@min(height, 0xFFFF)), 1633 }; 1634 } 1635 1636 fn runChannelLayer( 1637 io: std.Io, 1638 allocator: std.mem.Allocator, 1639 reader: *std.Io.Reader, 1640 writer: *std.Io.Writer, 1641 cs_cipher: *Cipher, 1642 sc_cipher: *Cipher, 1643 rekey: *const RekeyState, 1644 fingerprint: *const [fingerprint_len]u8, 1645 handler: anytype, 1646 ) !void { 1647 var channel: ?Channel = null; 1648 var pending_exec: ?[]u8 = null; 1649 defer if (pending_exec) |s| allocator.free(s); 1650 1651 while (true) { 1652 const packet = try readSessionPacket(io, allocator, reader, writer, cs_cipher, sc_cipher, rekey); 1653 defer allocator.free(packet); 1654 if (packet.len < 1) return error.EmptyPacket; 1655 const msg_type = packet[0]; 1656 1657 switch (msg_type) { 1658 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1659 1660 SSH_MSG_CHANNEL_OPEN => { 1661 if (channel != null) { 1662 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1663 continue; 1664 } 1665 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1666 }, 1667 1668 SSH_MSG_CHANNEL_REQUEST => { 1669 const ch = if (channel) |*c| c else continue; 1670 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1671 if (start_request) |req_kind| { 1672 const request: Request = switch (req_kind) { 1673 .shell => .{ .shell = ch.pty }, 1674 .exec => .{ .exec = pending_exec.? }, 1675 }; 1676 var sess = SessionCtx{ 1677 .io = io, 1678 .allocator = allocator, 1679 .reader = reader, 1680 .writer = writer, 1681 .cs_cipher = cs_cipher, 1682 .sc_cipher = sc_cipher, 1683 .rekey = rekey, 1684 .channel = ch, 1685 .fingerprint = fingerprint.*, 1686 }; 1687 defer sess.deinit(); 1688 handler.handleSession(&sess, request) catch |session_err| { 1689 // try to send a non-zero exit status before closing 1690 sess.exit(1) catch {}; 1691 return session_err; 1692 }; 1693 if (!sess.closed) try sess.exit(0); 1694 return; 1695 } 1696 }, 1697 1698 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1699 const ch = if (channel) |*c| c else continue; 1700 try handleWindowAdjust(ch, packet); 1701 }, 1702 1703 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1704 const ch = if (channel) |*c| c else continue; 1705 // before shell/exec the client shouldn't be sending data, but 1706 // some clients are chatty; discard and refill window. 1707 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1708 }, 1709 1710 SSH_MSG_CHANNEL_EOF => { 1711 if (channel) |*c| try parseChannelId(packet, c.local_id); 1712 }, 1713 1714 SSH_MSG_CHANNEL_CLOSE => { 1715 if (channel) |*c| try parseChannelId(packet, c.local_id); 1716 return; 1717 }, 1718 1719 else => {}, // ignore unknown messages 1720 } 1721 } 1722 } 1723 1724 fn handleGlobalRequest( 1725 io: std.Io, 1726 allocator: std.mem.Allocator, 1727 sc_cipher: *Cipher, 1728 writer: *std.Io.Writer, 1729 packet: []const u8, 1730 ) !void { 1731 // byte SSH_MSG_GLOBAL_REQUEST 1732 // string request_name 1733 // boolean want_reply 1734 // …request-specific data we ignore 1735 var r = std.Io.Reader.fixed(packet[1..]); 1736 const name = try takeStringField(allocator, &r, 256); 1737 defer allocator.free(name); 1738 const want_reply = (try r.takeByte()) != 0; 1739 if (want_reply) { 1740 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1741 } 1742 } 1743 1744 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1745 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1746 /// return null. 1747 fn handleChannelOpen( 1748 io: std.Io, 1749 allocator: std.mem.Allocator, 1750 sc_cipher: *Cipher, 1751 writer: *std.Io.Writer, 1752 packet: []const u8, 1753 ) !?Channel { 1754 // byte SSH_MSG_CHANNEL_OPEN 1755 // string channel_type 1756 // uint32 sender_channel (peer's id) 1757 // uint32 initial_window 1758 // uint32 max_packet 1759 var r = std.Io.Reader.fixed(packet[1..]); 1760 const ch_type = try takeStringField(allocator, &r, 64); 1761 defer allocator.free(ch_type); 1762 const remote_id = try r.takeInt(u32, .big); 1763 const initial_window = try r.takeInt(u32, .big); 1764 const max_packet = try r.takeInt(u32, .big); 1765 1766 if (!std.mem.eql(u8, ch_type, "session")) { 1767 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1768 return null; 1769 } 1770 1771 // a zero max_packet would leave writeChannel looping without progress 1772 if (max_packet == 0) { 1773 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1774 return null; 1775 } 1776 1777 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1778 var reply: std.ArrayList(u8) = .empty; 1779 defer reply.deinit(allocator); 1780 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1781 try writeU32(&reply, allocator, remote_id); 1782 try writeU32(&reply, allocator, local_id); 1783 try writeU32(&reply, allocator, initial_recv_window); 1784 try writeU32(&reply, allocator, max_packet_size); 1785 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1786 1787 return .{ 1788 .local_id = local_id, 1789 .remote_id = remote_id, 1790 .local_window = initial_recv_window, 1791 .remote_window = initial_window, 1792 .max_packet = max_packet, 1793 }; 1794 } 1795 1796 fn sendChannelOpenFailure( 1797 io: std.Io, 1798 allocator: std.mem.Allocator, 1799 sc_cipher: *Cipher, 1800 writer: *std.Io.Writer, 1801 open_packet: []const u8, 1802 reason: u32, 1803 description: []const u8, 1804 ) !void { 1805 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1806 // address the failure to the correct id 1807 var r = std.Io.Reader.fixed(open_packet[1..]); 1808 const ch_type_len = try r.takeInt(u32, .big); 1809 try r.discardAll(ch_type_len); 1810 const remote_id = try r.takeInt(u32, .big); 1811 1812 var reply: std.ArrayList(u8) = .empty; 1813 defer reply.deinit(allocator); 1814 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1815 try writeU32(&reply, allocator, remote_id); 1816 try writeU32(&reply, allocator, reason); 1817 try writeStringField(&reply, allocator, description); 1818 try writeStringField(&reply, allocator, ""); // language tag 1819 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1820 } 1821 1822 const RequestKind = enum { shell, exec }; 1823 1824 /// Returns the kind of session request if this triggered one, else null. 1825 fn handleChannelRequest( 1826 io: std.Io, 1827 allocator: std.mem.Allocator, 1828 sc_cipher: *Cipher, 1829 writer: *std.Io.Writer, 1830 ch: *Channel, 1831 packet: []const u8, 1832 pending_exec: *?[]u8, 1833 ) !?RequestKind { 1834 // byte SSH_MSG_CHANNEL_REQUEST 1835 // uint32 recipient_channel (== our local_id) 1836 // string request_type 1837 // boolean want_reply 1838 // …request-specific data 1839 var r = std.Io.Reader.fixed(packet[1..]); 1840 const recipient_channel = try r.takeInt(u32, .big); 1841 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1842 const req_type = try takeStringField(allocator, &r, 64); 1843 defer allocator.free(req_type); 1844 const want_reply = (try r.takeByte()) != 0; 1845 1846 if (std.mem.eql(u8, req_type, "pty-req")) { 1847 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1848 // uint32 height px, string modes 1849 const term = try takeStringField(allocator, &r, 64); 1850 defer allocator.free(term); 1851 ch.pty = try takePtySize(&r); 1852 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1853 return null; 1854 } 1855 1856 if (std.mem.eql(u8, req_type, "env")) { 1857 // ignore environment variables silently (we don't pass them anywhere) 1858 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1859 return null; 1860 } 1861 1862 if (std.mem.eql(u8, req_type, "window-change")) { 1863 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1864 const sz = try takePtySize(&r); 1865 if (ch.pty != null) ch.pty = sz; 1866 // spec: window-change MUST NOT request a reply, but accept either 1867 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1868 return null; 1869 } 1870 1871 if (std.mem.eql(u8, req_type, "shell")) { 1872 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1873 return .shell; 1874 } 1875 1876 if (std.mem.eql(u8, req_type, "exec")) { 1877 // capture the command string for the handler to inspect 1878 const cmd = try takeStringField(allocator, &r, 4096); 1879 if (pending_exec.*) |old| allocator.free(old); 1880 pending_exec.* = cmd; 1881 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1882 return .exec; 1883 } 1884 1885 // unknown request kind — fail it 1886 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1887 return null; 1888 } 1889 1890 fn replyChannelRequest( 1891 io: std.Io, 1892 allocator: std.mem.Allocator, 1893 sc_cipher: *Cipher, 1894 writer: *std.Io.Writer, 1895 ch: *Channel, 1896 want_reply: bool, 1897 success: bool, 1898 ) !void { 1899 if (!want_reply) return; 1900 var reply: std.ArrayList(u8) = .empty; 1901 defer reply.deinit(allocator); 1902 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1903 try writeU32(&reply, allocator, ch.remote_id); 1904 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1905 } 1906 1907 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1908 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1909 // uint32 recipient_channel 1910 // uint32 bytes_to_add 1911 var r = std.Io.Reader.fixed(packet[1..]); 1912 const recipient_channel = try r.takeInt(u32, .big); 1913 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1914 const add = try r.takeInt(u32, .big); 1915 ch.remote_window +|= add; 1916 } 1917 1918 fn discardChannelData( 1919 io: std.Io, 1920 allocator: std.mem.Allocator, 1921 sc_cipher: *Cipher, 1922 writer: *std.Io.Writer, 1923 ch: *Channel, 1924 packet: []const u8, 1925 extended: bool, 1926 ) !void { 1927 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1928 // uint32 recipient_channel 1929 // [if extended: uint32 type_code] 1930 // string data 1931 const payload = try parseChannelData(packet, extended, ch.local_id); 1932 const data_len: u32 = @intCast(payload.len); 1933 1934 if (data_len > ch.local_window) return error.WindowExceeded; 1935 ch.local_window -= data_len; 1936 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1937 } 1938 1939 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1940 if (packet.len < 1) return error.EmptyPacket; 1941 var r = std.Io.Reader.fixed(packet[1..]); 1942 const recipient_channel = try r.takeInt(u32, .big); 1943 if (recipient_channel != expected_channel) return error.UnknownChannel; 1944 if (extended) { 1945 const data_type = try r.takeInt(u32, .big); 1946 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1947 } 1948 const data_len = try r.takeInt(u32, .big); 1949 // catches both data_len > remaining (would otherwise be a bounds-check 1950 // panic on the slice) and trailing junk after the declared payload. 1951 if (data_len != r.buffered().len) return error.InvalidChannelData; 1952 return r.buffered(); 1953 } 1954 1955 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1956 if (packet.len < 1) return error.EmptyPacket; 1957 var r = std.Io.Reader.fixed(packet[1..]); 1958 const recipient_channel = try r.takeInt(u32, .big); 1959 if (recipient_channel != expected_channel) return error.UnknownChannel; 1960 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1961 } 1962 1963 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1964 /// of the initial value. Used both for the pre-session discard path and by 1965 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1966 fn maybeRefillRecvWindow( 1967 io: std.Io, 1968 allocator: std.mem.Allocator, 1969 sc_cipher: *Cipher, 1970 writer: *std.Io.Writer, 1971 ch: *Channel, 1972 ) !void { 1973 if (ch.local_window >= initial_recv_window / 2) return; 1974 const add = initial_recv_window - ch.local_window; 1975 ch.local_window += add; 1976 var adj: std.ArrayList(u8) = .empty; 1977 defer adj.deinit(allocator); 1978 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1979 try writeU32(&adj, allocator, ch.remote_id); 1980 try writeU32(&adj, allocator, add); 1981 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1982 } 1983 1984 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1985 var bytes: [4]u8 = undefined; 1986 std.mem.writeInt(u32, &bytes, value, .big); 1987 try buf.appendSlice(allocator, &bytes); 1988 } 1989