╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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