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