╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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) !?Channel { 2036 const allocator = conn.allocator; 2037 2038 // byte SSH_MSG_CHANNEL_OPEN 2039 // string channel_type 2040 // uint32 sender_channel (peer's id) 2041 // uint32 initial_window 2042 // uint32 max_packet 2043 var r = std.Io.Reader.fixed(packet[1..]); 2044 const ch_type = try takeString(&r, 64); 2045 const remote_id = try r.takeInt(u32, .big); 2046 const initial_window = try r.takeInt(u32, .big); 2047 const max_packet = try r.takeInt(u32, .big); 2048 2049 if (!std.mem.eql(u8, ch_type, "session")) { 2050 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2051 return null; 2052 } 2053 2054 // a zero max_packet would leave writeChannel looping without progress 2055 if (max_packet == 0) { 2056 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2057 return null; 2058 } 2059 2060 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2061 var reply: std.ArrayList(u8) = .empty; 2062 defer reply.deinit(allocator); 2063 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 2064 try writeU32(&reply, allocator, remote_id); 2065 try writeU32(&reply, allocator, local_id); 2066 try writeU32(&reply, allocator, initial_recv_window); 2067 try writeU32(&reply, allocator, max_packet_size); 2068 try conn.writePacket(&.{reply.items}); 2069 2070 return .{ 2071 .local_id = local_id, 2072 .remote_id = remote_id, 2073 .local_window = initial_recv_window, 2074 .remote_window = initial_window, 2075 .max_packet = max_packet, 2076 }; 2077 } 2078 2079 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 2080 const allocator = conn.allocator; 2081 2082 // recover the sender_channel field from the CHANNEL_OPEN packet so we 2083 // address the failure to the correct id 2084 var r = std.Io.Reader.fixed(open_packet[1..]); 2085 const ch_type_len = try r.takeInt(u32, .big); 2086 try r.discardAll(ch_type_len); 2087 const remote_id = try r.takeInt(u32, .big); 2088 2089 var reply: std.ArrayList(u8) = .empty; 2090 defer reply.deinit(allocator); 2091 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2092 try writeU32(&reply, allocator, remote_id); 2093 try writeU32(&reply, allocator, reason); 2094 try writeStringField(&reply, allocator, description); 2095 try writeStringField(&reply, allocator, ""); // language tag 2096 try conn.writePacket(&.{reply.items}); 2097 } 2098 2099 /// returns the session request if this one triggered it, else null. an exec 2100 /// command borrows from `packet`. 2101 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2102 // byte SSH_MSG_CHANNEL_REQUEST 2103 // uint32 recipient_channel (== our local_id) 2104 // string request_type 2105 // boolean want_reply 2106 // …request-specific data 2107 var r = std.Io.Reader.fixed(packet[1..]); 2108 const recipient_channel = try r.takeInt(u32, .big); 2109 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2110 const req_type = try takeString(&r, 64); 2111 const want_reply = (try r.takeByte()) != 0; 2112 2113 if (std.mem.eql(u8, req_type, "pty-req")) { 2114 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2115 // uint32 height px, string modes 2116 _ = try takeString(&r, 64); 2117 ch.pty = try takePtySize(&r); 2118 try replyChannelRequest(conn, ch, want_reply, true); 2119 return null; 2120 } 2121 2122 if (std.mem.eql(u8, req_type, "env")) { 2123 // string name, string value. the rest are ignored silently. 2124 const name = try takeString(&r, max_packet_len); 2125 const value = try takeString(&r, max_packet_len); 2126 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2127 @memcpy(ch.git_protocol_buf[0..value.len], value); 2128 ch.git_protocol_len = value.len; 2129 } 2130 try replyChannelRequest(conn, ch, want_reply, true); 2131 return null; 2132 } 2133 2134 if (std.mem.eql(u8, req_type, "window-change")) { 2135 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2136 const sz = try takePtySize(&r); 2137 if (ch.pty != null) ch.pty = sz; 2138 // spec: window-change MUST NOT request a reply, but accept either 2139 try replyChannelRequest(conn, ch, want_reply, true); 2140 return null; 2141 } 2142 2143 if (std.mem.eql(u8, req_type, "shell")) { 2144 try replyChannelRequest(conn, ch, want_reply, true); 2145 return .{ .shell = ch.pty }; 2146 } 2147 2148 if (std.mem.eql(u8, req_type, "exec")) { 2149 // capture the command string for the handler to inspect 2150 const cmd = try takeString(&r, 4096); 2151 try replyChannelRequest(conn, ch, want_reply, true); 2152 return .{ .exec = .{ 2153 .command = cmd, 2154 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2155 } }; 2156 } 2157 2158 // unknown request kind — fail it 2159 try replyChannelRequest(conn, ch, want_reply, false); 2160 return null; 2161 } 2162 2163 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2164 if (!want_reply) return; 2165 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2166 } 2167 2168 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2169 var packet: [5]u8 = undefined; 2170 packet[0] = msg_type; 2171 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2172 try conn.writePacket(&.{&packet}); 2173 } 2174 2175 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2176 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2177 // uint32 recipient_channel 2178 // uint32 bytes_to_add 2179 var r = std.Io.Reader.fixed(packet[1..]); 2180 const recipient_channel = try r.takeInt(u32, .big); 2181 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2182 const add = try r.takeInt(u32, .big); 2183 ch.remote_window +|= add; 2184 } 2185 2186 // charge a payload's bytes against the receive window without keeping them. 2187 // the caller credits the window back, choosing the budget that suits it. 2188 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2189 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2190 // uint32 recipient_channel 2191 // [if extended: uint32 type_code] 2192 // string data 2193 const payload = try parseChannelData(packet, extended, ch.local_id); 2194 const data_len: u32 = @intCast(payload.len); 2195 2196 if (data_len > ch.local_window) return error.WindowExceeded; 2197 ch.local_window -= data_len; 2198 } 2199 2200 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2201 if (packet.len < 1) return error.EmptyPacket; 2202 var r = std.Io.Reader.fixed(packet[1..]); 2203 const recipient_channel = try r.takeInt(u32, .big); 2204 if (recipient_channel != expected_channel) return error.UnknownChannel; 2205 if (extended) { 2206 const data_type = try r.takeInt(u32, .big); 2207 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2208 } 2209 const data_len = try r.takeInt(u32, .big); 2210 // catches both data_len > remaining (would otherwise be a bounds-check 2211 // panic on the slice) and trailing junk after the declared payload. 2212 if (data_len != r.buffered().len) return error.InvalidChannelData; 2213 return r.buffered(); 2214 } 2215 2216 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2217 if (packet.len < 1) return error.EmptyPacket; 2218 var r = std.Io.Reader.fixed(packet[1..]); 2219 const recipient_channel = try r.takeInt(u32, .big); 2220 if (recipient_channel != expected_channel) return error.UnknownChannel; 2221 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2222 } 2223 2224 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2225 /// of `budget`, the credit we're willing to have outstanding. used both for 2226 /// the pre-session discard path and by SessionCtx after it consumes a 2227 /// CHANNEL_DATA payload. 2228 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2229 if (ch.local_window >= budget / 2) return; 2230 const add = budget - ch.local_window; 2231 ch.local_window += add; 2232 var adj: std.ArrayList(u8) = .empty; 2233 defer adj.deinit(conn.allocator); 2234 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2235 try writeU32(&adj, conn.allocator, ch.remote_id); 2236 try writeU32(&adj, conn.allocator, add); 2237 try conn.writePacket(&.{adj.items}); 2238 } 2239 2240 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2241 var bytes: [4]u8 = undefined; 2242 std.mem.writeInt(u32, &bytes, value, .big); 2243 try buf.appendSlice(allocator, &bytes); 2244 } 2245 2246 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2247 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2248 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2249 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2250 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2251 }) |case| { 2252 var bytes: [8]u8 = undefined; 2253 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2254 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2255 var reader = std.Io.Reader.fixed(&bytes); 2256 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2257 } 2258 } 2259 2260 test "channel close before shell or exec is acknowledged" { 2261 const io = std.testing.io; 2262 const allocator = std.testing.allocator; 2263 const key = [_]u8{0x5a} ** 64; 2264 var encoded: [256]u8 = undefined; 2265 var encoded_writer = std.Io.Writer.fixed(&encoded); 2266 var sender = Cipher.init(&key, 0); 2267 var open: std.ArrayList(u8) = .empty; 2268 defer open.deinit(allocator); 2269 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2270 try writeStringField(&open, allocator, "session"); 2271 try writeU32(&open, allocator, 7); 2272 try writeU32(&open, allocator, 32768); 2273 try writeU32(&open, allocator, 32768); 2274 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2275 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2276 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2277 var output: [256]u8 = undefined; 2278 var writer = std.Io.Writer.fixed(&output); 2279 var conn = Conn{ 2280 .io = io, 2281 .allocator = allocator, 2282 .reader = &reader, 2283 .writer = &writer, 2284 .cs_cipher = Cipher.init(&key, 0), 2285 .sc_cipher = Cipher.init(&key, 0), 2286 .rekey = undefined, 2287 }; 2288 const Handler = struct { 2289 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2290 return error.UnexpectedSession; 2291 } 2292 }; 2293 var handler = Handler{}; 2294 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2295 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2296 var receiver = Cipher.init(&key, 0); 2297 const confirmation = try receiver.readPacket(allocator, &output_reader); 2298 defer allocator.free(confirmation); 2299 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2300 const close = try receiver.readPacket(allocator, &output_reader); 2301 defer allocator.free(close); 2302 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2303 try std.testing.expectEqual(0, output_reader.buffered().len); 2304 } 2305