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