╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1588 1589 // mac over encrypted_length || encrypted_body 1590 var poly = Poly1305.init(&poly_key); 1591 poly.update(packet[0 .. 4 + body_len]); 1592 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1593 1594 try writer.writeAll(packet); 1595 try writer.flush(); 1596 1597 self.seq += 1; 1598 } 1599 1600 pub fn readPacket( 1601 self: *Cipher, 1602 allocator: std.mem.Allocator, 1603 reader: *std.Io.Reader, 1604 ) ![]u8 { 1605 const nonce = makeNonce(self.seq); 1606 1607 var enc_length: [4]u8 = undefined; 1608 try reader.readSliceAll(&enc_length); 1609 1610 const body_len = try self.bodyLength(&enc_length); 1611 1612 // the body allocation becomes the returned payload, so a packet only 1613 // ever costs one allocation 1614 const body = try allocator.alloc(u8, body_len); 1615 errdefer allocator.free(body); 1616 try reader.readSliceAll(body); 1617 1618 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1619 try reader.readSliceAll(&tag_recv); 1620 1621 var poly_key: [Poly1305.key_length]u8 = undefined; 1622 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1623 1624 var poly = Poly1305.init(&poly_key); 1625 poly.update(&enc_length); 1626 poly.update(body); 1627 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1628 poly.final(&tag_computed); 1629 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1630 return error.MacVerificationFailed; 1631 } 1632 1633 // decrypt the body in place 1634 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1635 1636 const padding_len = body[0]; 1637 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1638 const payload_len = body_len - 1 - @as(u32, padding_len); 1639 // a payload starts with its message type 1640 if (payload_len == 0) return error.EmptyPacket; 1641 1642 // shift the payload over the padding_length byte, then release the 1643 // trailing padding (caller owns the result) 1644 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1645 const payload = try allocator.realloc(body, payload_len); 1646 1647 self.seq += 1; 1648 return payload; 1649 } 1650 }; 1651 1652 // --------------------------------------------------------------------------- 1653 // post-KEX: service request + user authentication (RFC 4252) 1654 // --------------------------------------------------------------------------- 1655 1656 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1657 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1658 /// `Offering public key: … SHA256:…`. 1659 pub const fingerprint_len = 50; 1660 1661 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1662 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1663 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1664 var digest: [Sha256.digest_length]u8 = undefined; 1665 Sha256.hash(pubkey_blob, &digest, .{}); 1666 1667 var out: [fingerprint_len]u8 = undefined; 1668 @memcpy(out[0..7], "SHA256:"); 1669 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1670 std.debug.assert(encoded.len == fingerprint_len - 7); 1671 return out; 1672 } 1673 1674 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1675 const allocator = conn.allocator; 1676 1677 // step 1: service request for ssh-userauth → service accept 1678 { 1679 const req = try readSessionPacket(conn); 1680 defer allocator.free(req); 1681 if (req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1682 1683 var req_reader = std.Io.Reader.fixed(req[1..]); 1684 const service = try takeString(&req_reader, 64); 1685 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1686 1687 var accept: std.ArrayList(u8) = .empty; 1688 defer accept.deinit(allocator); 1689 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1690 try writeStringField(&accept, allocator, "ssh-userauth"); 1691 try conn.writePacket(&.{accept.items}); 1692 } 1693 1694 // step 2: USERAUTH loop until SUCCESS. accept any supported key whose 1695 // signature verifies against the offered pubkey. 1696 var auth_attempts: u32 = 0; 1697 while (true) { 1698 const req = try readSessionPacket(conn); 1699 defer allocator.free(req); 1700 if (req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1701 1702 // every request counts, probes included, so a client can't loop here 1703 // forever 1704 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1705 auth_attempts += 1; 1706 1707 var req_reader = std.Io.Reader.fixed(req[1..]); 1708 const user_name = try takeString(&req_reader, 256); 1709 const service_name = try takeString(&req_reader, 64); 1710 const method = try takeString(&req_reader, 64); 1711 1712 // RFC 4252 §5: the server must verify the requested service 1713 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1714 try sendUserauthFailure(conn); 1715 continue; 1716 } 1717 1718 if (!std.mem.eql(u8, method, "publickey")) { 1719 try sendUserauthFailure(conn); 1720 continue; 1721 } 1722 1723 const has_signature = (try req_reader.takeByte()) != 0; 1724 const algo = try takeString(&req_reader, 64); 1725 const pubkey_blob = try takeString(&req_reader, 4096); 1726 1727 if (firstCommonName(algo, &our_userauth_algos) == null) { 1728 try sendUserauthFailure(conn); 1729 continue; 1730 } 1731 1732 if (!has_signature) { 1733 // probe — tell the client this key is acceptable so it'll send 1734 // the signed version next. 1735 var pk_ok: std.ArrayList(u8) = .empty; 1736 defer pk_ok.deinit(allocator); 1737 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1738 try writeStringField(&pk_ok, allocator, algo); 1739 try writeStringField(&pk_ok, allocator, pubkey_blob); 1740 try conn.writePacket(&.{pk_ok.items}); 1741 continue; 1742 } 1743 1744 // has signature — verify it 1745 const signature_blob = try takeString(&req_reader, 1024); 1746 1747 const ok = verifyUserauthSignature( 1748 allocator, 1749 &conn.rekey.session_id, 1750 user_name, 1751 service_name, 1752 algo, 1753 pubkey_blob, 1754 signature_blob, 1755 ) catch |err| switch (err) { 1756 error.OutOfMemory => return err, 1757 // a malformed key or signature blob 1758 else => false, 1759 }; 1760 1761 if (!ok) { 1762 try sendUserauthFailure(conn); 1763 continue; 1764 } 1765 1766 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1767 return formatFingerprint(pubkey_blob); 1768 } 1769 } 1770 1771 fn sendUserauthFailure(conn: *Conn) !void { 1772 var buf: std.ArrayList(u8) = .empty; 1773 defer buf.deinit(conn.allocator); 1774 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1775 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1776 try buf.append(conn.allocator, 0); // partial_success = false 1777 try conn.writePacket(&.{buf.items}); 1778 } 1779 1780 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1781 /// used by the server to recompute the signed input for verification 1782 pub fn appendPublickeySignedData( 1783 buf: *std.ArrayList(u8), 1784 allocator: std.mem.Allocator, 1785 session_id: []const u8, 1786 user_name: []const u8, 1787 service_name: []const u8, 1788 algo: []const u8, 1789 pubkey_blob: []const u8, 1790 ) !void { 1791 try writeStringField(buf, allocator, session_id); 1792 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1793 try writeStringField(buf, allocator, user_name); 1794 try writeStringField(buf, allocator, service_name); 1795 try writeStringField(buf, allocator, "publickey"); 1796 try buf.append(allocator, 1); 1797 try writeStringField(buf, allocator, algo); 1798 try writeStringField(buf, allocator, pubkey_blob); 1799 } 1800 1801 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1802 // verify the supplied signature against them. 1803 fn verifyUserauthSignature( 1804 allocator: std.mem.Allocator, 1805 session_id: *const [Sha256.digest_length]u8, 1806 user_name: []const u8, 1807 service_name: []const u8, 1808 algo: []const u8, 1809 pubkey_blob: []const u8, 1810 signature_blob: []const u8, 1811 ) !bool { 1812 var signed: std.ArrayList(u8) = .empty; 1813 defer signed.deinit(allocator); 1814 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1815 1816 if (std.mem.eql(u8, algo, "ssh-ed25519")) return verifyEd25519(pubkey_blob, signature_blob, signed.items); 1817 if (std.mem.eql(u8, algo, "rsa-sha2-512")) return verifyRsa(Sha512, algo, pubkey_blob, signature_blob, signed.items); 1818 if (std.mem.eql(u8, algo, "rsa-sha2-256")) return verifyRsa(Sha256, algo, pubkey_blob, signature_blob, signed.items); 1819 return false; 1820 } 1821 1822 fn verifyEd25519(pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1823 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1824 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1825 const pk_algo = try takeString(&pubkey_reader, 64); 1826 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1827 const raw_pubkey = try takeString(&pubkey_reader, 64); 1828 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1829 // the fingerprint hashes the whole blob, so it must hold nothing else 1830 if (pubkey_reader.bufferedLen() != 0) return false; 1831 1832 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1833 var sig_reader = std.Io.Reader.fixed(signature_blob); 1834 const sig_algo = try takeString(&sig_reader, 64); 1835 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1836 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1837 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1838 1839 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1840 @memcpy(&pubkey_bytes, raw_pubkey); 1841 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1842 @memcpy(&sig_bytes, raw_sig); 1843 1844 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1845 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1846 sig.verify(signed, pk) catch return false; 1847 return true; 1848 } 1849 1850 fn verifyRsa(comptime Hash: type, algo: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1851 // parse pubkey_blob: string "ssh-rsa" || mpint e || mpint n 1852 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1853 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), "ssh-rsa")) return false; 1854 // the fingerprint hashes the whole blob, so one key must have one encoding 1855 const e = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1856 const n = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1857 if (pubkey_reader.bufferedLen() != 0) return false; 1858 1859 // parse signature_blob: string algo || string sig 1860 var sig_reader = std.Io.Reader.fixed(signature_blob); 1861 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1862 const sig = try takeString(&sig_reader, 1024); 1863 if (sig.len != n.len) return false; 1864 1865 const pk = rsa.PublicKey.fromBytes(e, n) catch return false; 1866 switch (n.len) { 1867 inline 256, 384, 512 => |len| { 1868 rsa.PKCS1v1_5Signature.verify(len, sig[0..len].*, signed, pk, Hash) catch return false; 1869 return true; 1870 }, 1871 else => return false, 1872 } 1873 } 1874 1875 // the unsigned bytes of a positive mpint in its shortest encoding (RFC 4251 1876 // §5), or null for zero, negative, or padded encodings 1877 fn canonicalMpintMagnitude(bytes: []const u8) ?[]const u8 { 1878 if (bytes.len == 0 or bytes[0] & 0x80 != 0) return null; 1879 if (bytes[0] != 0) return bytes; 1880 if (bytes.len < 2 or bytes[1] & 0x80 == 0) return null; 1881 return bytes[1..]; 1882 } 1883 1884 // --------------------------------------------------------------------------- 1885 // connection layer (RFC 4254): channels, requests, data, flow control 1886 // --------------------------------------------------------------------------- 1887 1888 const Channel = struct { 1889 local_id: u32, 1890 remote_id: u32, 1891 local_window: u32, // bytes peer may still send us before we adjust 1892 remote_window: u32, // bytes we may still send to peer before they adjust 1893 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1894 pty: ?PtySize = null, 1895 // value of GIT_PROTOCOL, the one env variable we keep 1896 git_protocol_buf: [64]u8 = undefined, 1897 git_protocol_len: ?usize = null, 1898 }; 1899 1900 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1901 1902 // take the uint32 width/height cell counts of a pty-req or window-change, 1903 // bounded before either initial rendering or a resize can allocate grids. 1904 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1905 fn takePtySize(r: *std.Io.Reader) !PtySize { 1906 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1907 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1908 return .{ 1909 .width_cells = @intCast(width), 1910 .height_cells = @intCast(height), 1911 }; 1912 } 1913 1914 fn runChannelLayer( 1915 conn: *Conn, 1916 fingerprint: *const [fingerprint_len]u8, 1917 handler: anytype, 1918 ) !void { 1919 const allocator = conn.allocator; 1920 var channel: ?Channel = null; 1921 1922 while (true) { 1923 const packet = try readSessionPacket(conn); 1924 defer allocator.free(packet); 1925 const msg_type = packet[0]; 1926 1927 switch (msg_type) { 1928 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1929 1930 SSH_MSG_CHANNEL_OPEN => { 1931 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1932 }, 1933 1934 SSH_MSG_CHANNEL_REQUEST => { 1935 const ch = if (channel) |*c| c else return error.UnknownChannel; 1936 const start_request = try handleChannelRequest(conn, ch, packet); 1937 // the request borrows from the packet, which outlives the session 1938 if (start_request) |request| { 1939 // any key authenticates, so the deadline holds until here 1940 conn.idle.session_started.store(true, .release); 1941 var sess = SessionCtx{ 1942 .conn = conn, 1943 .channel = ch, 1944 .fingerprint = fingerprint.*, 1945 }; 1946 defer sess.deinit(); 1947 handler.handleSession(&sess, request) catch |session_err| { 1948 // a failed read leaves the protocol unusable, so the 1949 // disconnect names it instead of a clean close 1950 if (sess.read_err) |read_err| return read_err; 1951 // try to send a non-zero exit status before closing 1952 sess.exit(1) catch {}; 1953 return sess.underlyingError(session_err); 1954 }; 1955 if (!sess.closed) try sess.exit(0); 1956 return; 1957 } 1958 }, 1959 1960 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1961 const ch = if (channel) |*c| c else return error.UnknownChannel; 1962 try handleWindowAdjust(ch, packet); 1963 }, 1964 1965 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1966 const ch = if (channel) |*c| c else return error.UnknownChannel; 1967 // before shell/exec the client shouldn't be sending data, but 1968 // some clients are chatty; discard and refill window. nothing 1969 // is buffered yet, so the whole window is available to credit. 1970 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1971 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1972 }, 1973 1974 SSH_MSG_CHANNEL_EOF => { 1975 const ch = if (channel) |*c| c else return error.UnknownChannel; 1976 try parseChannelId(packet, ch.local_id); 1977 }, 1978 1979 SSH_MSG_CHANNEL_CLOSE => { 1980 const ch = if (channel) |*c| c else return error.UnknownChannel; 1981 try parseChannelId(packet, ch.local_id); 1982 try sendChannelMessage(conn, ch, SSH_MSG_CHANNEL_CLOSE); 1983 drainConnection(conn); 1984 return; 1985 }, 1986 1987 // RFC 4252 §5.1: silently ignored once authenticated 1988 SSH_MSG_USERAUTH_REQUEST => {}, 1989 else => try sendUnimplemented(conn), 1990 } 1991 } 1992 } 1993 1994 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1995 // byte SSH_MSG_GLOBAL_REQUEST 1996 // string request_name 1997 // boolean want_reply 1998 // …request-specific data we ignore 1999 var r = std.Io.Reader.fixed(packet[1..]); 2000 _ = try takeString(&r, 256); 2001 const want_reply = (try r.takeByte()) != 0; 2002 if (want_reply) { 2003 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2004 } 2005 } 2006 2007 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2008 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2009 /// return null. 2010 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 2011 // byte SSH_MSG_CHANNEL_OPEN 2012 // string channel_type 2013 // uint32 sender_channel (peer's id) 2014 // uint32 initial_window 2015 // uint32 max_packet 2016 var r = std.Io.Reader.fixed(packet[1..]); 2017 const ch_type = try takeString(&r, 64); 2018 const remote_id = try r.takeInt(u32, .big); 2019 const initial_window = try r.takeInt(u32, .big); 2020 const max_packet = try r.takeInt(u32, .big); 2021 2022 if (has_channel) { 2023 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 2024 return null; 2025 } 2026 2027 if (!std.mem.eql(u8, ch_type, "session")) { 2028 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2029 return null; 2030 } 2031 2032 // a zero max_packet would leave writeBytes looping without progress 2033 if (max_packet == 0) { 2034 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2035 return null; 2036 } 2037 2038 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2039 var reply: [17]u8 = undefined; 2040 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2041 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2042 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2043 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2044 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2045 try conn.writePacket(&.{&reply}); 2046 2047 return .{ 2048 .local_id = local_id, 2049 .remote_id = remote_id, 2050 .local_window = initial_recv_window, 2051 .remote_window = initial_window, 2052 .max_packet = max_packet, 2053 }; 2054 } 2055 2056 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2057 const allocator = conn.allocator; 2058 2059 var reply: std.ArrayList(u8) = .empty; 2060 defer reply.deinit(allocator); 2061 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2062 try writeU32(&reply, allocator, remote_id); 2063 try writeU32(&reply, allocator, reason); 2064 try writeStringField(&reply, allocator, description); 2065 try writeStringField(&reply, allocator, ""); // language tag 2066 try conn.writePacket(&.{reply.items}); 2067 } 2068 2069 /// returns the session request if this one triggered it, else null. an exec 2070 /// command borrows from `packet`. 2071 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2072 // byte SSH_MSG_CHANNEL_REQUEST 2073 // uint32 recipient_channel (== our local_id) 2074 // string request_type 2075 // boolean want_reply 2076 // …request-specific data 2077 var r = std.Io.Reader.fixed(packet[1..]); 2078 const recipient_channel = try r.takeInt(u32, .big); 2079 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2080 const req_type = try takeString(&r, 64); 2081 const want_reply = (try r.takeByte()) != 0; 2082 2083 if (std.mem.eql(u8, req_type, "pty-req")) { 2084 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2085 // uint32 height px, string modes 2086 _ = try takeString(&r, 64); 2087 ch.pty = try takePtySize(&r); 2088 try replyChannelRequest(conn, ch, want_reply, true); 2089 return null; 2090 } 2091 2092 if (std.mem.eql(u8, req_type, "env")) { 2093 // string name, string value. the rest are ignored silently. 2094 const name = try takeString(&r, max_packet_len); 2095 const value = try takeString(&r, max_packet_len); 2096 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2097 @memcpy(ch.git_protocol_buf[0..value.len], value); 2098 ch.git_protocol_len = value.len; 2099 } 2100 try replyChannelRequest(conn, ch, want_reply, true); 2101 return null; 2102 } 2103 2104 if (std.mem.eql(u8, req_type, "window-change")) { 2105 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2106 const sz = try takePtySize(&r); 2107 if (ch.pty != null) ch.pty = sz; 2108 // spec: window-change MUST NOT request a reply, but accept either 2109 try replyChannelRequest(conn, ch, want_reply, true); 2110 return null; 2111 } 2112 2113 if (std.mem.eql(u8, req_type, "shell")) { 2114 try replyChannelRequest(conn, ch, want_reply, true); 2115 return .{ .shell = ch.pty }; 2116 } 2117 2118 if (std.mem.eql(u8, req_type, "exec")) { 2119 // capture the command string for the handler to inspect 2120 const cmd = try takeString(&r, 4096); 2121 try replyChannelRequest(conn, ch, want_reply, true); 2122 return .{ .exec = .{ 2123 .command = cmd, 2124 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2125 } }; 2126 } 2127 2128 // unknown request kind — fail it 2129 try replyChannelRequest(conn, ch, want_reply, false); 2130 return null; 2131 } 2132 2133 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2134 if (!want_reply) return; 2135 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2136 } 2137 2138 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2139 var packet: [5]u8 = undefined; 2140 packet[0] = msg_type; 2141 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2142 try conn.writePacket(&.{&packet}); 2143 } 2144 2145 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2146 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2147 // uint32 recipient_channel 2148 // uint32 bytes_to_add 2149 var r = std.Io.Reader.fixed(packet[1..]); 2150 const recipient_channel = try r.takeInt(u32, .big); 2151 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2152 const add = try r.takeInt(u32, .big); 2153 ch.remote_window +|= add; 2154 } 2155 2156 // charge a payload's bytes against the receive window without keeping them. 2157 // the caller credits the window back, choosing the budget that suits it. 2158 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2159 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2160 // uint32 recipient_channel 2161 // [if extended: uint32 type_code] 2162 // string data 2163 const payload = try parseChannelData(packet, extended, ch.local_id); 2164 const data_len: u32 = @intCast(payload.len); 2165 2166 if (data_len > ch.local_window) return error.WindowExceeded; 2167 ch.local_window -= data_len; 2168 } 2169 2170 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2171 if (packet.len < 1) return error.EmptyPacket; 2172 var r = std.Io.Reader.fixed(packet[1..]); 2173 const recipient_channel = try r.takeInt(u32, .big); 2174 if (recipient_channel != expected_channel) return error.UnknownChannel; 2175 if (extended) { 2176 const data_type = try r.takeInt(u32, .big); 2177 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2178 } 2179 const data_len = try r.takeInt(u32, .big); 2180 // catches both data_len > remaining (would otherwise be a bounds-check 2181 // panic on the slice) and trailing junk after the declared payload. 2182 if (data_len != r.buffered().len) return error.InvalidChannelData; 2183 return r.buffered(); 2184 } 2185 2186 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2187 var r = std.Io.Reader.fixed(packet[1..]); 2188 const recipient_channel = try r.takeInt(u32, .big); 2189 if (recipient_channel != expected_channel) return error.UnknownChannel; 2190 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2191 } 2192 2193 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2194 /// of `budget`, the credit we're willing to have outstanding. used both for 2195 /// the pre-session discard path and by SessionCtx after it consumes a 2196 /// CHANNEL_DATA payload. 2197 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2198 if (ch.local_window >= budget / 2) return; 2199 const add = budget - ch.local_window; 2200 ch.local_window += add; 2201 var packet: [9]u8 = undefined; 2202 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2203 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2204 std.mem.writeInt(u32, packet[5..9], add, .big); 2205 try conn.writePacket(&.{&packet}); 2206 } 2207 2208 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2209 var bytes: [4]u8 = undefined; 2210 std.mem.writeInt(u32, &bytes, value, .big); 2211 try buf.appendSlice(allocator, &bytes); 2212 } 2213 2214 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2215 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2216 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2217 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2218 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2219 }) |case| { 2220 var bytes: [8]u8 = undefined; 2221 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2222 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2223 var reader = std.Io.Reader.fixed(&bytes); 2224 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2225 } 2226 } 2227 2228 test "channel close before shell or exec is acknowledged" { 2229 const io = std.testing.io; 2230 const allocator = std.testing.allocator; 2231 const key = [_]u8{0x5a} ** 64; 2232 var encoded: [256]u8 = undefined; 2233 var encoded_writer = std.Io.Writer.fixed(&encoded); 2234 var sender = Cipher.init(&key, 0); 2235 var open: std.ArrayList(u8) = .empty; 2236 defer open.deinit(allocator); 2237 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2238 try writeStringField(&open, allocator, "session"); 2239 try writeU32(&open, allocator, 7); 2240 try writeU32(&open, allocator, 32768); 2241 try writeU32(&open, allocator, 32768); 2242 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2243 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2244 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2245 var output: [256]u8 = undefined; 2246 var writer = std.Io.Writer.fixed(&output); 2247 var idle = IdleState{}; 2248 var conn = Conn{ 2249 .io = io, 2250 .allocator = allocator, 2251 .reader = &reader, 2252 .writer = &writer, 2253 .cs_cipher = Cipher.init(&key, 0), 2254 .sc_cipher = Cipher.init(&key, 0), 2255 .rekey = undefined, 2256 .idle = &idle, 2257 }; 2258 const Handler = struct { 2259 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2260 return error.UnexpectedSession; 2261 } 2262 }; 2263 var handler = Handler{}; 2264 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2265 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2266 var receiver = Cipher.init(&key, 0); 2267 const confirmation = try receiver.readPacket(allocator, &output_reader); 2268 defer allocator.free(confirmation); 2269 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2270 const close = try receiver.readPacket(allocator, &output_reader); 2271 defer allocator.free(close); 2272 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2273 try std.testing.expectEqual(0, output_reader.buffered().len); 2274 } 2275