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