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