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