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