╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1660 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1661 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1662 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1663 defer allocator.free(pk_algo); 1664 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1665 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1666 defer allocator.free(raw_pubkey); 1667 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1668 1669 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1670 var sig_reader = std.Io.Reader.fixed(signature_blob); 1671 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1672 defer allocator.free(sig_algo); 1673 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1674 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1675 defer allocator.free(raw_sig); 1676 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1677 1678 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1679 @memcpy(&pubkey_bytes, raw_pubkey); 1680 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1681 @memcpy(&sig_bytes, raw_sig); 1682 1683 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1684 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1685 sig.verify(signed.items, pk) catch return false; 1686 return true; 1687 } 1688 1689 // --------------------------------------------------------------------------- 1690 // connection layer (RFC 4254): channels, requests, data, flow control 1691 // --------------------------------------------------------------------------- 1692 1693 const Channel = struct { 1694 local_id: u32, 1695 remote_id: u32, 1696 local_window: u32, // bytes peer may still send us before we adjust 1697 remote_window: u32, // bytes we may still send to peer before they adjust 1698 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1699 pty: ?PtySize = null, 1700 }; 1701 1702 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1703 1704 // take the uint32 width/height cell counts of a pty-req or window-change, 1705 // clamped to u16 1706 fn takePtySize(r: *std.Io.Reader) !PtySize { 1707 const width = try r.takeInt(u32, .big); 1708 const height = try r.takeInt(u32, .big); 1709 return .{ 1710 .width_cells = @intCast(@min(width, 0xFFFF)), 1711 .height_cells = @intCast(@min(height, 0xFFFF)), 1712 }; 1713 } 1714 1715 fn runChannelLayer( 1716 conn: *Conn, 1717 fingerprint: *const [fingerprint_len]u8, 1718 handler: anytype, 1719 ) !void { 1720 const allocator = conn.allocator; 1721 var channel: ?Channel = null; 1722 var pending_exec: ?[]u8 = null; 1723 defer if (pending_exec) |s| allocator.free(s); 1724 1725 while (true) { 1726 const packet = try readSessionPacket(conn); 1727 defer allocator.free(packet); 1728 if (packet.len < 1) return error.EmptyPacket; 1729 const msg_type = packet[0]; 1730 1731 switch (msg_type) { 1732 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1733 1734 SSH_MSG_CHANNEL_OPEN => { 1735 if (channel != null) { 1736 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1737 continue; 1738 } 1739 channel = try handleChannelOpen(conn, packet) orelse continue; 1740 }, 1741 1742 SSH_MSG_CHANNEL_REQUEST => { 1743 const ch = if (channel) |*c| c else continue; 1744 const start_request = try handleChannelRequest(conn, ch, packet, &pending_exec); 1745 if (start_request) |request| { 1746 var sess = SessionCtx{ 1747 .conn = conn, 1748 .channel = ch, 1749 .fingerprint = fingerprint.*, 1750 }; 1751 defer sess.deinit(); 1752 handler.handleSession(&sess, request) catch |session_err| { 1753 // try to send a non-zero exit status before closing 1754 sess.exit(1) catch {}; 1755 return session_err; 1756 }; 1757 if (!sess.closed) try sess.exit(0); 1758 return; 1759 } 1760 }, 1761 1762 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1763 const ch = if (channel) |*c| c else continue; 1764 try handleWindowAdjust(ch, packet); 1765 }, 1766 1767 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1768 const ch = if (channel) |*c| c else continue; 1769 // before shell/exec the client shouldn't be sending data, but 1770 // some clients are chatty; discard and refill window. 1771 try discardChannelData(conn, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1772 }, 1773 1774 SSH_MSG_CHANNEL_EOF => { 1775 if (channel) |*c| try parseChannelId(packet, c.local_id); 1776 }, 1777 1778 SSH_MSG_CHANNEL_CLOSE => { 1779 if (channel) |*c| try parseChannelId(packet, c.local_id); 1780 return; 1781 }, 1782 1783 else => try sendUnimplemented(conn), 1784 } 1785 } 1786 } 1787 1788 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1789 // byte SSH_MSG_GLOBAL_REQUEST 1790 // string request_name 1791 // boolean want_reply 1792 // …request-specific data we ignore 1793 var r = std.Io.Reader.fixed(packet[1..]); 1794 const name = try takeStringField(conn.allocator, &r, 256); 1795 defer conn.allocator.free(name); 1796 const want_reply = (try r.takeByte()) != 0; 1797 if (want_reply) { 1798 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1799 } 1800 } 1801 1802 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 1803 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 1804 /// return null. 1805 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 1806 const allocator = conn.allocator; 1807 1808 // byte SSH_MSG_CHANNEL_OPEN 1809 // string channel_type 1810 // uint32 sender_channel (peer's id) 1811 // uint32 initial_window 1812 // uint32 max_packet 1813 var r = std.Io.Reader.fixed(packet[1..]); 1814 const ch_type = try takeStringField(allocator, &r, 64); 1815 defer allocator.free(ch_type); 1816 const remote_id = try r.takeInt(u32, .big); 1817 const initial_window = try r.takeInt(u32, .big); 1818 const max_packet = try r.takeInt(u32, .big); 1819 1820 if (!std.mem.eql(u8, ch_type, "session")) { 1821 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1822 return null; 1823 } 1824 1825 // a zero max_packet would leave writeChannel looping without progress 1826 if (max_packet == 0) { 1827 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1828 return null; 1829 } 1830 1831 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1832 var reply: std.ArrayList(u8) = .empty; 1833 defer reply.deinit(allocator); 1834 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1835 try writeU32(&reply, allocator, remote_id); 1836 try writeU32(&reply, allocator, local_id); 1837 try writeU32(&reply, allocator, initial_recv_window); 1838 try writeU32(&reply, allocator, max_packet_size); 1839 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1840 1841 return .{ 1842 .local_id = local_id, 1843 .remote_id = remote_id, 1844 .local_window = initial_recv_window, 1845 .remote_window = initial_window, 1846 .max_packet = max_packet, 1847 }; 1848 } 1849 1850 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1851 const allocator = conn.allocator; 1852 1853 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1854 // address the failure to the correct id 1855 var r = std.Io.Reader.fixed(open_packet[1..]); 1856 const ch_type_len = try r.takeInt(u32, .big); 1857 try r.discardAll(ch_type_len); 1858 const remote_id = try r.takeInt(u32, .big); 1859 1860 var reply: std.ArrayList(u8) = .empty; 1861 defer reply.deinit(allocator); 1862 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1863 try writeU32(&reply, allocator, remote_id); 1864 try writeU32(&reply, allocator, reason); 1865 try writeStringField(&reply, allocator, description); 1866 try writeStringField(&reply, allocator, ""); // language tag 1867 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1868 } 1869 1870 /// returns the session request if this one triggered it, else null. an exec 1871 /// command is owned by `pending_exec`, which outlives the packet it arrived in. 1872 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8, pending_exec: *?[]u8) !?Request { 1873 const allocator = conn.allocator; 1874 1875 // byte SSH_MSG_CHANNEL_REQUEST 1876 // uint32 recipient_channel (== our local_id) 1877 // string request_type 1878 // boolean want_reply 1879 // …request-specific data 1880 var r = std.Io.Reader.fixed(packet[1..]); 1881 const recipient_channel = try r.takeInt(u32, .big); 1882 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1883 const req_type = try takeStringField(allocator, &r, 64); 1884 defer allocator.free(req_type); 1885 const want_reply = (try r.takeByte()) != 0; 1886 1887 if (std.mem.eql(u8, req_type, "pty-req")) { 1888 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1889 // uint32 height px, string modes 1890 const term = try takeStringField(allocator, &r, 64); 1891 defer allocator.free(term); 1892 ch.pty = try takePtySize(&r); 1893 try replyChannelRequest(conn, ch, want_reply, true); 1894 return null; 1895 } 1896 1897 if (std.mem.eql(u8, req_type, "env")) { 1898 // ignore environment variables silently (we don't pass them anywhere) 1899 try replyChannelRequest(conn, ch, want_reply, true); 1900 return null; 1901 } 1902 1903 if (std.mem.eql(u8, req_type, "window-change")) { 1904 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1905 const sz = try takePtySize(&r); 1906 if (ch.pty != null) ch.pty = sz; 1907 // spec: window-change MUST NOT request a reply, but accept either 1908 try replyChannelRequest(conn, ch, want_reply, true); 1909 return null; 1910 } 1911 1912 if (std.mem.eql(u8, req_type, "shell")) { 1913 try replyChannelRequest(conn, ch, want_reply, true); 1914 return .{ .shell = ch.pty }; 1915 } 1916 1917 if (std.mem.eql(u8, req_type, "exec")) { 1918 // capture the command string for the handler to inspect 1919 const cmd = try takeStringField(allocator, &r, 4096); 1920 if (pending_exec.*) |old| allocator.free(old); 1921 pending_exec.* = cmd; 1922 try replyChannelRequest(conn, ch, want_reply, true); 1923 return .{ .exec = cmd }; 1924 } 1925 1926 // unknown request kind — fail it 1927 try replyChannelRequest(conn, ch, want_reply, false); 1928 return null; 1929 } 1930 1931 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 1932 if (!want_reply) return; 1933 var reply: std.ArrayList(u8) = .empty; 1934 defer reply.deinit(conn.allocator); 1935 try reply.append(conn.allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1936 try writeU32(&reply, conn.allocator, ch.remote_id); 1937 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1938 } 1939 1940 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1941 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1942 // uint32 recipient_channel 1943 // uint32 bytes_to_add 1944 var r = std.Io.Reader.fixed(packet[1..]); 1945 const recipient_channel = try r.takeInt(u32, .big); 1946 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1947 const add = try r.takeInt(u32, .big); 1948 ch.remote_window +|= add; 1949 } 1950 1951 fn discardChannelData(conn: *Conn, ch: *Channel, packet: []const u8, extended: bool) !void { 1952 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1953 // uint32 recipient_channel 1954 // [if extended: uint32 type_code] 1955 // string data 1956 const payload = try parseChannelData(packet, extended, ch.local_id); 1957 const data_len: u32 = @intCast(payload.len); 1958 1959 if (data_len > ch.local_window) return error.WindowExceeded; 1960 ch.local_window -= data_len; 1961 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1962 } 1963 1964 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1965 if (packet.len < 1) return error.EmptyPacket; 1966 var r = std.Io.Reader.fixed(packet[1..]); 1967 const recipient_channel = try r.takeInt(u32, .big); 1968 if (recipient_channel != expected_channel) return error.UnknownChannel; 1969 if (extended) { 1970 const data_type = try r.takeInt(u32, .big); 1971 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1972 } 1973 const data_len = try r.takeInt(u32, .big); 1974 // catches both data_len > remaining (would otherwise be a bounds-check 1975 // panic on the slice) and trailing junk after the declared payload. 1976 if (data_len != r.buffered().len) return error.InvalidChannelData; 1977 return r.buffered(); 1978 } 1979 1980 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1981 if (packet.len < 1) return error.EmptyPacket; 1982 var r = std.Io.Reader.fixed(packet[1..]); 1983 const recipient_channel = try r.takeInt(u32, .big); 1984 if (recipient_channel != expected_channel) return error.UnknownChannel; 1985 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1986 } 1987 1988 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1989 /// of `budget`, the credit we're willing to have outstanding. used both for 1990 /// the pre-session discard path and by SessionCtx after it consumes a 1991 /// CHANNEL_DATA payload. 1992 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 1993 if (ch.local_window >= budget / 2) return; 1994 const add = budget - ch.local_window; 1995 ch.local_window += add; 1996 var adj: std.ArrayList(u8) = .empty; 1997 defer adj.deinit(conn.allocator); 1998 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1999 try writeU32(&adj, conn.allocator, ch.remote_id); 2000 try writeU32(&adj, conn.allocator, add); 2001 try conn.sc_cipher.writePacket(conn.io, conn.writer, adj.items); 2002 } 2003 2004 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2005 var bytes: [4]u8 = undefined; 2006 std.mem.writeInt(u32, &bytes, value, .big); 2007 try buf.appendSlice(allocator, &bytes); 2008 } 2009