╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1923 1924 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1925 1926 // take the uint32 width/height cell counts of a pty-req or window-change, 1927 // bounded before either initial rendering or a resize can allocate grids. 1928 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1929 fn takePtySize(r: *std.Io.Reader) !PtySize { 1930 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1931 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1932 return .{ 1933 .width_cells = @intCast(width), 1934 .height_cells = @intCast(height), 1935 }; 1936 } 1937 1938 fn runChannelLayer( 1939 conn: *Conn, 1940 client_key: *const ClientKey, 1941 handler: anytype, 1942 ) !void { 1943 const allocator = conn.allocator; 1944 var channel: ?Channel = null; 1945 1946 while (true) { 1947 const packet = try readSessionPacket(conn); 1948 defer allocator.free(packet); 1949 const msg_type = packet[0]; 1950 1951 switch (msg_type) { 1952 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1953 1954 SSH_MSG_CHANNEL_OPEN => { 1955 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1956 }, 1957 1958 SSH_MSG_CHANNEL_REQUEST => { 1959 const ch = if (channel) |*c| c else return error.UnknownChannel; 1960 const start_request = try handleChannelRequest(conn, ch, packet); 1961 // the request borrows from the packet, which outlives the session 1962 if (start_request) |request| { 1963 // any key authenticates, so the deadline holds until here 1964 conn.idle.session_started.store(true, .release); 1965 var sess = SessionCtx{ 1966 .conn = conn, 1967 .channel = ch, 1968 .fingerprint = client_key.fingerprint, 1969 .public_key = client_key.blob, 1970 }; 1971 defer sess.deinit(); 1972 handler.handleSession(&sess, request) catch |session_err| { 1973 // a failed read leaves the protocol unusable, so the 1974 // disconnect names it instead of a clean close 1975 if (sess.read_err) |read_err| return read_err; 1976 // try to send a non-zero exit status before closing 1977 sess.exit(1) catch {}; 1978 return sess.underlyingError(session_err); 1979 }; 1980 if (!sess.closed) try sess.exit(0); 1981 return; 1982 } 1983 }, 1984 1985 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1986 const ch = if (channel) |*c| c else return error.UnknownChannel; 1987 try handleWindowAdjust(ch, packet); 1988 }, 1989 1990 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1991 const ch = if (channel) |*c| c else return error.UnknownChannel; 1992 // before shell/exec the client shouldn't be sending data, but 1993 // some clients are chatty; discard and refill window. nothing 1994 // is buffered yet, so the whole window is available to credit. 1995 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1996 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1997 }, 1998 1999 SSH_MSG_CHANNEL_EOF => { 2000 const ch = if (channel) |*c| c else return error.UnknownChannel; 2001 try parseChannelId(packet, ch.local_id); 2002 }, 2003 2004 SSH_MSG_CHANNEL_CLOSE => { 2005 const ch = if (channel) |*c| c else return error.UnknownChannel; 2006 try parseChannelId(packet, ch.local_id); 2007 try sendChannelMessage(conn, ch, SSH_MSG_CHANNEL_CLOSE); 2008 drainConnection(conn); 2009 return; 2010 }, 2011 2012 // RFC 4252 §5.1: silently ignored once authenticated 2013 SSH_MSG_USERAUTH_REQUEST => {}, 2014 else => try sendUnimplemented(conn), 2015 } 2016 } 2017 } 2018 2019 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 2020 // byte SSH_MSG_GLOBAL_REQUEST 2021 // string request_name 2022 // boolean want_reply 2023 // …request-specific data we ignore 2024 var r = std.Io.Reader.fixed(packet[1..]); 2025 _ = try takeString(&r, 256); 2026 const want_reply = (try r.takeByte()) != 0; 2027 if (want_reply) { 2028 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2029 } 2030 } 2031 2032 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2033 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2034 /// return null. 2035 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 2036 // byte SSH_MSG_CHANNEL_OPEN 2037 // string channel_type 2038 // uint32 sender_channel (peer's id) 2039 // uint32 initial_window 2040 // uint32 max_packet 2041 var r = std.Io.Reader.fixed(packet[1..]); 2042 const ch_type = try takeString(&r, 64); 2043 const remote_id = try r.takeInt(u32, .big); 2044 const initial_window = try r.takeInt(u32, .big); 2045 const max_packet = try r.takeInt(u32, .big); 2046 2047 if (has_channel) { 2048 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 2049 return null; 2050 } 2051 2052 if (!std.mem.eql(u8, ch_type, "session")) { 2053 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2054 return null; 2055 } 2056 2057 // a zero max_packet would leave writeBytes looping without progress 2058 if (max_packet == 0) { 2059 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2060 return null; 2061 } 2062 2063 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2064 var reply: [17]u8 = undefined; 2065 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2066 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2067 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2068 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2069 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2070 try conn.writePacket(&.{&reply}); 2071 2072 return .{ 2073 .local_id = local_id, 2074 .remote_id = remote_id, 2075 .local_window = initial_recv_window, 2076 .remote_window = initial_window, 2077 .max_packet = max_packet, 2078 }; 2079 } 2080 2081 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2082 const allocator = conn.allocator; 2083 2084 var reply: std.ArrayList(u8) = .empty; 2085 defer reply.deinit(allocator); 2086 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2087 try writeU32(&reply, allocator, remote_id); 2088 try writeU32(&reply, allocator, reason); 2089 try writeStringField(&reply, allocator, description); 2090 try writeStringField(&reply, allocator, ""); // language tag 2091 try conn.writePacket(&.{reply.items}); 2092 } 2093 2094 /// returns the session request if this one triggered it, else null. an exec 2095 /// command borrows from `packet`. 2096 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2097 // byte SSH_MSG_CHANNEL_REQUEST 2098 // uint32 recipient_channel (== our local_id) 2099 // string request_type 2100 // boolean want_reply 2101 // …request-specific data 2102 var r = std.Io.Reader.fixed(packet[1..]); 2103 const recipient_channel = try r.takeInt(u32, .big); 2104 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2105 const req_type = try takeString(&r, 64); 2106 const want_reply = (try r.takeByte()) != 0; 2107 2108 if (std.mem.eql(u8, req_type, "pty-req")) { 2109 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2110 // uint32 height px, string modes 2111 _ = try takeString(&r, 64); 2112 ch.pty = try takePtySize(&r); 2113 try replyChannelRequest(conn, ch, want_reply, true); 2114 return null; 2115 } 2116 2117 if (std.mem.eql(u8, req_type, "env")) { 2118 // string name, string value. the rest are ignored silently. 2119 const name = try takeString(&r, max_packet_len); 2120 const value = try takeString(&r, max_packet_len); 2121 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2122 @memcpy(ch.git_protocol_buf[0..value.len], value); 2123 ch.git_protocol_len = value.len; 2124 } else if (std.mem.eql(u8, name, "NO_COLOR")) { 2125 ch.color = value.len == 0; 2126 } 2127 try replyChannelRequest(conn, ch, want_reply, true); 2128 return null; 2129 } 2130 2131 if (std.mem.eql(u8, req_type, "window-change")) { 2132 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2133 const sz = try takePtySize(&r); 2134 if (ch.pty != null) ch.pty = sz; 2135 // spec: window-change MUST NOT request a reply, but accept either 2136 try replyChannelRequest(conn, ch, want_reply, true); 2137 return null; 2138 } 2139 2140 if (std.mem.eql(u8, req_type, "shell")) { 2141 try replyChannelRequest(conn, ch, want_reply, true); 2142 return .{ .shell = .{ .pty = ch.pty, .color = ch.color } }; 2143 } 2144 2145 if (std.mem.eql(u8, req_type, "exec")) { 2146 // capture the command string for the handler to inspect 2147 const cmd = try takeString(&r, 4096); 2148 try replyChannelRequest(conn, ch, want_reply, true); 2149 return .{ .exec = .{ 2150 .command = cmd, 2151 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2152 } }; 2153 } 2154 2155 // unknown request kind — fail it 2156 try replyChannelRequest(conn, ch, want_reply, false); 2157 return null; 2158 } 2159 2160 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2161 if (!want_reply) return; 2162 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2163 } 2164 2165 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2166 var packet: [5]u8 = undefined; 2167 packet[0] = msg_type; 2168 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2169 try conn.writePacket(&.{&packet}); 2170 } 2171 2172 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2173 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2174 // uint32 recipient_channel 2175 // uint32 bytes_to_add 2176 var r = std.Io.Reader.fixed(packet[1..]); 2177 const recipient_channel = try r.takeInt(u32, .big); 2178 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2179 const add = try r.takeInt(u32, .big); 2180 ch.remote_window +|= add; 2181 } 2182 2183 // charge a payload's bytes against the receive window without keeping them. 2184 // the caller credits the window back, choosing the budget that suits it. 2185 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2186 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2187 // uint32 recipient_channel 2188 // [if extended: uint32 type_code] 2189 // string data 2190 const payload = try parseChannelData(packet, extended, ch.local_id); 2191 const data_len: u32 = @intCast(payload.len); 2192 2193 if (data_len > ch.local_window) return error.WindowExceeded; 2194 ch.local_window -= data_len; 2195 } 2196 2197 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2198 if (packet.len < 1) return error.EmptyPacket; 2199 var r = std.Io.Reader.fixed(packet[1..]); 2200 const recipient_channel = try r.takeInt(u32, .big); 2201 if (recipient_channel != expected_channel) return error.UnknownChannel; 2202 if (extended) { 2203 const data_type = try r.takeInt(u32, .big); 2204 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2205 } 2206 const data_len = try r.takeInt(u32, .big); 2207 // catches both data_len > remaining (would otherwise be a bounds-check 2208 // panic on the slice) and trailing junk after the declared payload. 2209 if (data_len != r.buffered().len) return error.InvalidChannelData; 2210 return r.buffered(); 2211 } 2212 2213 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2214 var r = std.Io.Reader.fixed(packet[1..]); 2215 const recipient_channel = try r.takeInt(u32, .big); 2216 if (recipient_channel != expected_channel) return error.UnknownChannel; 2217 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2218 } 2219 2220 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2221 /// of `budget`, the credit we're willing to have outstanding. used both for 2222 /// the pre-session discard path and by SessionCtx after it consumes a 2223 /// CHANNEL_DATA payload. 2224 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2225 if (ch.local_window >= budget / 2) return; 2226 const add = budget - ch.local_window; 2227 ch.local_window += add; 2228 var packet: [9]u8 = undefined; 2229 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2230 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2231 std.mem.writeInt(u32, packet[5..9], add, .big); 2232 try conn.writePacket(&.{&packet}); 2233 } 2234 2235 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2236 var bytes: [4]u8 = undefined; 2237 std.mem.writeInt(u32, &bytes, value, .big); 2238 try buf.appendSlice(allocator, &bytes); 2239 } 2240 2241 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2242 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2243 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2244 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2245 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2246 }) |case| { 2247 var bytes: [8]u8 = undefined; 2248 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2249 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2250 var reader = std.Io.Reader.fixed(&bytes); 2251 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2252 } 2253 } 2254 2255 test "channel close before shell or exec is acknowledged" { 2256 const io = std.testing.io; 2257 const allocator = std.testing.allocator; 2258 const key: [64]u8 = @splat(0x5a); 2259 var encoded: [256]u8 = undefined; 2260 var encoded_writer = std.Io.Writer.fixed(&encoded); 2261 var sender = Cipher.init(&key, 0); 2262 var open: std.ArrayList(u8) = .empty; 2263 defer open.deinit(allocator); 2264 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2265 try writeStringField(&open, allocator, "session"); 2266 try writeU32(&open, allocator, 7); 2267 try writeU32(&open, allocator, 32768); 2268 try writeU32(&open, allocator, 32768); 2269 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2270 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2271 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2272 var output: [256]u8 = undefined; 2273 var writer = std.Io.Writer.fixed(&output); 2274 var idle = IdleState{}; 2275 var conn = Conn{ 2276 .io = io, 2277 .allocator = allocator, 2278 .reader = &reader, 2279 .writer = &writer, 2280 .cs_cipher = Cipher.init(&key, 0), 2281 .sc_cipher = Cipher.init(&key, 0), 2282 .rekey = undefined, 2283 .idle = &idle, 2284 }; 2285 const Handler = struct { 2286 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2287 return error.UnexpectedSession; 2288 } 2289 }; 2290 var handler = Handler{}; 2291 try runChannelLayer(&conn, &.{ .fingerprint = @splat(0), .blob = "" }, &handler); 2292 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2293 var receiver = Cipher.init(&key, 0); 2294 const confirmation = try receiver.readPacket(allocator, &output_reader); 2295 defer allocator.free(confirmation); 2296 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2297 const close = try receiver.readPacket(allocator, &output_reader); 2298 defer allocator.free(close); 2299 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2300 try std.testing.expectEqual(0, output_reader.buffered().len); 2301 } 2302