╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1773 defer allocator.free(packet); 1774 if (packet.len < 1) return error.EmptyPacket; 1775 const msg_type = packet[0]; 1776 1777 switch (msg_type) { 1778 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1779 1780 SSH_MSG_CHANNEL_OPEN => { 1781 if (channel != null) { 1782 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1783 continue; 1784 } 1785 channel = try handleChannelOpen(conn, packet) orelse continue; 1786 }, 1787 1788 SSH_MSG_CHANNEL_REQUEST => { 1789 const ch = if (channel) |*c| c else continue; 1790 const start_request = try handleChannelRequest(conn, ch, packet, &pending_exec); 1791 if (start_request) |request| { 1792 var sess = SessionCtx{ 1793 .conn = conn, 1794 .channel = ch, 1795 .fingerprint = fingerprint.*, 1796 }; 1797 defer sess.deinit(); 1798 handler.handleSession(&sess, request) catch |session_err| { 1799 // try to send a non-zero exit status before closing 1800 sess.exit(1) catch {}; 1801 return session_err; 1802 }; 1803 if (!sess.closed) try sess.exit(0); 1804 return; 1805 } 1806 }, 1807 1808 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1809 const ch = if (channel) |*c| c else continue; 1810 try handleWindowAdjust(ch, packet); 1811 }, 1812 1813 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1814 const ch = if (channel) |*c| c else continue; 1815 // before shell/exec the client shouldn't be sending data, but 1816 // some clients are chatty; discard and refill window. nothing 1817 // is buffered yet, so the whole window is available to credit. 1818 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1819 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1820 }, 1821 1822 SSH_MSG_CHANNEL_EOF => { 1823 if (channel) |*c| try parseChannelId(packet, c.local_id); 1824 }, 1825 1826 SSH_MSG_CHANNEL_CLOSE => { 1827 if (channel) |*c| { 1828 try parseChannelId(packet, c.local_id); 1829 try sendChannelMessage(conn, c, SSH_MSG_CHANNEL_CLOSE); 1830 drainConnection(conn); 1831 } 1832 return; 1833 }, 1834 1835 else => try sendUnimplemented(conn), 1836 } 1837 } 1838 } 1839 1840 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1841 // byte SSH_MSG_GLOBAL_REQUEST 1842 // string request_name 1843 // boolean want_reply 1844 // …request-specific data we ignore 1845 var r = std.Io.Reader.fixed(packet[1..]); 1846 const name = try takeStringField(conn.allocator, &r, 256); 1847 defer conn.allocator.free(name); 1848 const want_reply = (try r.takeByte()) != 0; 1849 if (want_reply) { 1850 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1851 } 1852 } 1853 1854 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 1855 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 1856 /// return null. 1857 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 1858 const allocator = conn.allocator; 1859 1860 // byte SSH_MSG_CHANNEL_OPEN 1861 // string channel_type 1862 // uint32 sender_channel (peer's id) 1863 // uint32 initial_window 1864 // uint32 max_packet 1865 var r = std.Io.Reader.fixed(packet[1..]); 1866 const ch_type = try takeStringField(allocator, &r, 64); 1867 defer allocator.free(ch_type); 1868 const remote_id = try r.takeInt(u32, .big); 1869 const initial_window = try r.takeInt(u32, .big); 1870 const max_packet = try r.takeInt(u32, .big); 1871 1872 if (!std.mem.eql(u8, ch_type, "session")) { 1873 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1874 return null; 1875 } 1876 1877 // a zero max_packet would leave writeChannel looping without progress 1878 if (max_packet == 0) { 1879 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1880 return null; 1881 } 1882 1883 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1884 var reply: std.ArrayList(u8) = .empty; 1885 defer reply.deinit(allocator); 1886 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1887 try writeU32(&reply, allocator, remote_id); 1888 try writeU32(&reply, allocator, local_id); 1889 try writeU32(&reply, allocator, initial_recv_window); 1890 try writeU32(&reply, allocator, max_packet_size); 1891 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1892 1893 return .{ 1894 .local_id = local_id, 1895 .remote_id = remote_id, 1896 .local_window = initial_recv_window, 1897 .remote_window = initial_window, 1898 .max_packet = max_packet, 1899 }; 1900 } 1901 1902 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1903 const allocator = conn.allocator; 1904 1905 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1906 // address the failure to the correct id 1907 var r = std.Io.Reader.fixed(open_packet[1..]); 1908 const ch_type_len = try r.takeInt(u32, .big); 1909 try r.discardAll(ch_type_len); 1910 const remote_id = try r.takeInt(u32, .big); 1911 1912 var reply: std.ArrayList(u8) = .empty; 1913 defer reply.deinit(allocator); 1914 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1915 try writeU32(&reply, allocator, remote_id); 1916 try writeU32(&reply, allocator, reason); 1917 try writeStringField(&reply, allocator, description); 1918 try writeStringField(&reply, allocator, ""); // language tag 1919 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1920 } 1921 1922 /// returns the session request if this one triggered it, else null. an exec 1923 /// command is owned by `pending_exec`, which outlives the packet it arrived in. 1924 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8, pending_exec: *?[]u8) !?Request { 1925 const allocator = conn.allocator; 1926 1927 // byte SSH_MSG_CHANNEL_REQUEST 1928 // uint32 recipient_channel (== our local_id) 1929 // string request_type 1930 // boolean want_reply 1931 // …request-specific data 1932 var r = std.Io.Reader.fixed(packet[1..]); 1933 const recipient_channel = try r.takeInt(u32, .big); 1934 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1935 const req_type = try takeStringField(allocator, &r, 64); 1936 defer allocator.free(req_type); 1937 const want_reply = (try r.takeByte()) != 0; 1938 1939 if (std.mem.eql(u8, req_type, "pty-req")) { 1940 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1941 // uint32 height px, string modes 1942 const term = try takeStringField(allocator, &r, 64); 1943 defer allocator.free(term); 1944 ch.pty = try takePtySize(&r); 1945 try replyChannelRequest(conn, ch, want_reply, true); 1946 return null; 1947 } 1948 1949 if (std.mem.eql(u8, req_type, "env")) { 1950 // ignore environment variables silently (we don't pass them anywhere) 1951 try replyChannelRequest(conn, ch, want_reply, true); 1952 return null; 1953 } 1954 1955 if (std.mem.eql(u8, req_type, "window-change")) { 1956 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1957 const sz = try takePtySize(&r); 1958 if (ch.pty != null) ch.pty = sz; 1959 // spec: window-change MUST NOT request a reply, but accept either 1960 try replyChannelRequest(conn, ch, want_reply, true); 1961 return null; 1962 } 1963 1964 if (std.mem.eql(u8, req_type, "shell")) { 1965 try replyChannelRequest(conn, ch, want_reply, true); 1966 return .{ .shell = ch.pty }; 1967 } 1968 1969 if (std.mem.eql(u8, req_type, "exec")) { 1970 // capture the command string for the handler to inspect 1971 const cmd = try takeStringField(allocator, &r, 4096); 1972 if (pending_exec.*) |old| allocator.free(old); 1973 pending_exec.* = cmd; 1974 try replyChannelRequest(conn, ch, want_reply, true); 1975 return .{ .exec = cmd }; 1976 } 1977 1978 // unknown request kind — fail it 1979 try replyChannelRequest(conn, ch, want_reply, false); 1980 return null; 1981 } 1982 1983 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 1984 if (!want_reply) return; 1985 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1986 } 1987 1988 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 1989 var packet: [5]u8 = undefined; 1990 packet[0] = msg_type; 1991 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 1992 try conn.sc_cipher.writePacket(conn.io, conn.writer, &packet); 1993 } 1994 1995 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1996 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1997 // uint32 recipient_channel 1998 // uint32 bytes_to_add 1999 var r = std.Io.Reader.fixed(packet[1..]); 2000 const recipient_channel = try r.takeInt(u32, .big); 2001 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2002 const add = try r.takeInt(u32, .big); 2003 ch.remote_window +|= add; 2004 } 2005 2006 // charge a payload's bytes against the receive window without keeping them. 2007 // the caller credits the window back, choosing the budget that suits it. 2008 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2009 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2010 // uint32 recipient_channel 2011 // [if extended: uint32 type_code] 2012 // string data 2013 const payload = try parseChannelData(packet, extended, ch.local_id); 2014 const data_len: u32 = @intCast(payload.len); 2015 2016 if (data_len > ch.local_window) return error.WindowExceeded; 2017 ch.local_window -= data_len; 2018 } 2019 2020 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2021 if (packet.len < 1) return error.EmptyPacket; 2022 var r = std.Io.Reader.fixed(packet[1..]); 2023 const recipient_channel = try r.takeInt(u32, .big); 2024 if (recipient_channel != expected_channel) return error.UnknownChannel; 2025 if (extended) { 2026 const data_type = try r.takeInt(u32, .big); 2027 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2028 } 2029 const data_len = try r.takeInt(u32, .big); 2030 // catches both data_len > remaining (would otherwise be a bounds-check 2031 // panic on the slice) and trailing junk after the declared payload. 2032 if (data_len != r.buffered().len) return error.InvalidChannelData; 2033 return r.buffered(); 2034 } 2035 2036 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2037 if (packet.len < 1) return error.EmptyPacket; 2038 var r = std.Io.Reader.fixed(packet[1..]); 2039 const recipient_channel = try r.takeInt(u32, .big); 2040 if (recipient_channel != expected_channel) return error.UnknownChannel; 2041 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2042 } 2043 2044 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2045 /// of `budget`, the credit we're willing to have outstanding. used both for 2046 /// the pre-session discard path and by SessionCtx after it consumes a 2047 /// CHANNEL_DATA payload. 2048 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2049 if (ch.local_window >= budget / 2) return; 2050 const add = budget - ch.local_window; 2051 ch.local_window += add; 2052 var adj: std.ArrayList(u8) = .empty; 2053 defer adj.deinit(conn.allocator); 2054 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2055 try writeU32(&adj, conn.allocator, ch.remote_id); 2056 try writeU32(&adj, conn.allocator, add); 2057 try conn.sc_cipher.writePacket(conn.io, conn.writer, adj.items); 2058 } 2059 2060 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2061 var bytes: [4]u8 = undefined; 2062 std.mem.writeInt(u32, &bytes, value, .big); 2063 try buf.appendSlice(allocator, &bytes); 2064 } 2065 2066 test "pty dimensions have bounded axes and area, preserving normal and zero sizes" { 2067 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2068 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2069 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2070 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2071 }) |case| { 2072 var bytes: [8]u8 = undefined; 2073 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2074 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2075 var reader = std.Io.Reader.fixed(&bytes); 2076 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2077 } 2078 } 2079 2080 test "channel close before shell or exec is acknowledged" { 2081 const io = std.testing.io; 2082 const allocator = std.testing.allocator; 2083 const key = [_]u8{0x5a} ** 64; 2084 var encoded: [256]u8 = undefined; 2085 var encoded_writer = std.Io.Writer.fixed(&encoded); 2086 var sender = Cipher.init(&key, 0); 2087 var open: std.ArrayList(u8) = .empty; 2088 defer open.deinit(allocator); 2089 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2090 try writeStringField(&open, allocator, "session"); 2091 try writeU32(&open, allocator, 7); 2092 try writeU32(&open, allocator, 32768); 2093 try writeU32(&open, allocator, 32768); 2094 try sender.writePacket(io, &encoded_writer, open.items); 2095 try sender.writePacket(io, &encoded_writer, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }); 2096 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2097 var output: [256]u8 = undefined; 2098 var writer = std.Io.Writer.fixed(&output); 2099 var conn = Conn{ 2100 .io = io, 2101 .allocator = allocator, 2102 .reader = &reader, 2103 .writer = &writer, 2104 .cs_cipher = Cipher.init(&key, 0), 2105 .sc_cipher = Cipher.init(&key, 0), 2106 .rekey = undefined, 2107 }; 2108 const Handler = struct { 2109 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2110 return error.UnexpectedSession; 2111 } 2112 }; 2113 var handler = Handler{}; 2114 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2115 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2116 var receiver = Cipher.init(&key, 0); 2117 const confirmation = try receiver.readPacket(allocator, &output_reader); 2118 defer allocator.free(confirmation); 2119 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2120 const close = try receiver.readPacket(allocator, &output_reader); 2121 defer allocator.free(close); 2122 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2123 try std.testing.expectEqual(0, output_reader.buffered().len); 2124 } 2125