╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1881 // byte SSH_MSG_CHANNEL_OPEN 1882 // string channel_type 1883 // uint32 sender_channel (peer's id) 1884 // uint32 initial_window 1885 // uint32 max_packet 1886 var r = std.Io.Reader.fixed(packet[1..]); 1887 const ch_type = try takeStringField(allocator, &r, 64); 1888 defer allocator.free(ch_type); 1889 const remote_id = try r.takeInt(u32, .big); 1890 const initial_window = try r.takeInt(u32, .big); 1891 const max_packet = try r.takeInt(u32, .big); 1892 1893 if (!std.mem.eql(u8, ch_type, "session")) { 1894 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1895 return null; 1896 } 1897 1898 // a zero max_packet would leave writeChannel looping without progress 1899 if (max_packet == 0) { 1900 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1901 return null; 1902 } 1903 1904 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1905 var reply: std.ArrayList(u8) = .empty; 1906 defer reply.deinit(allocator); 1907 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1908 try writeU32(&reply, allocator, remote_id); 1909 try writeU32(&reply, allocator, local_id); 1910 try writeU32(&reply, allocator, initial_recv_window); 1911 try writeU32(&reply, allocator, max_packet_size); 1912 try conn.writePacket(reply.items); 1913 1914 return .{ 1915 .local_id = local_id, 1916 .remote_id = remote_id, 1917 .local_window = initial_recv_window, 1918 .remote_window = initial_window, 1919 .max_packet = max_packet, 1920 }; 1921 } 1922 1923 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1924 const allocator = conn.allocator; 1925 1926 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1927 // address the failure to the correct id 1928 var r = std.Io.Reader.fixed(open_packet[1..]); 1929 const ch_type_len = try r.takeInt(u32, .big); 1930 try r.discardAll(ch_type_len); 1931 const remote_id = try r.takeInt(u32, .big); 1932 1933 var reply: std.ArrayList(u8) = .empty; 1934 defer reply.deinit(allocator); 1935 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1936 try writeU32(&reply, allocator, remote_id); 1937 try writeU32(&reply, allocator, reason); 1938 try writeStringField(&reply, allocator, description); 1939 try writeStringField(&reply, allocator, ""); // language tag 1940 try conn.writePacket(reply.items); 1941 } 1942 1943 /// returns the session request if this one triggered it, else null. an exec 1944 /// command is owned by `pending_exec`, which outlives the packet it arrived in. 1945 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8, pending_exec: *?[]u8) !?Request { 1946 const allocator = conn.allocator; 1947 1948 // byte SSH_MSG_CHANNEL_REQUEST 1949 // uint32 recipient_channel (== our local_id) 1950 // string request_type 1951 // boolean want_reply 1952 // …request-specific data 1953 var r = std.Io.Reader.fixed(packet[1..]); 1954 const recipient_channel = try r.takeInt(u32, .big); 1955 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1956 const req_type = try takeStringField(allocator, &r, 64); 1957 defer allocator.free(req_type); 1958 const want_reply = (try r.takeByte()) != 0; 1959 1960 if (std.mem.eql(u8, req_type, "pty-req")) { 1961 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1962 // uint32 height px, string modes 1963 const term = try takeStringField(allocator, &r, 64); 1964 defer allocator.free(term); 1965 ch.pty = try takePtySize(&r); 1966 try replyChannelRequest(conn, ch, want_reply, true); 1967 return null; 1968 } 1969 1970 if (std.mem.eql(u8, req_type, "env")) { 1971 // ignore environment variables silently (we don't pass them anywhere) 1972 try replyChannelRequest(conn, ch, want_reply, true); 1973 return null; 1974 } 1975 1976 if (std.mem.eql(u8, req_type, "window-change")) { 1977 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1978 const sz = try takePtySize(&r); 1979 if (ch.pty != null) ch.pty = sz; 1980 // spec: window-change MUST NOT request a reply, but accept either 1981 try replyChannelRequest(conn, ch, want_reply, true); 1982 return null; 1983 } 1984 1985 if (std.mem.eql(u8, req_type, "shell")) { 1986 try replyChannelRequest(conn, ch, want_reply, true); 1987 return .{ .shell = ch.pty }; 1988 } 1989 1990 if (std.mem.eql(u8, req_type, "exec")) { 1991 // capture the command string for the handler to inspect 1992 const cmd = try takeStringField(allocator, &r, 4096); 1993 if (pending_exec.*) |old| allocator.free(old); 1994 pending_exec.* = cmd; 1995 try replyChannelRequest(conn, ch, want_reply, true); 1996 return .{ .exec = cmd }; 1997 } 1998 1999 // unknown request kind — fail it 2000 try replyChannelRequest(conn, ch, want_reply, false); 2001 return null; 2002 } 2003 2004 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2005 if (!want_reply) return; 2006 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2007 } 2008 2009 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2010 var packet: [5]u8 = undefined; 2011 packet[0] = msg_type; 2012 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2013 try conn.writePacket(&packet); 2014 } 2015 2016 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2017 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2018 // uint32 recipient_channel 2019 // uint32 bytes_to_add 2020 var r = std.Io.Reader.fixed(packet[1..]); 2021 const recipient_channel = try r.takeInt(u32, .big); 2022 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2023 const add = try r.takeInt(u32, .big); 2024 ch.remote_window +|= add; 2025 } 2026 2027 // charge a payload's bytes against the receive window without keeping them. 2028 // the caller credits the window back, choosing the budget that suits it. 2029 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2030 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2031 // uint32 recipient_channel 2032 // [if extended: uint32 type_code] 2033 // string data 2034 const payload = try parseChannelData(packet, extended, ch.local_id); 2035 const data_len: u32 = @intCast(payload.len); 2036 2037 if (data_len > ch.local_window) return error.WindowExceeded; 2038 ch.local_window -= data_len; 2039 } 2040 2041 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2042 if (packet.len < 1) return error.EmptyPacket; 2043 var r = std.Io.Reader.fixed(packet[1..]); 2044 const recipient_channel = try r.takeInt(u32, .big); 2045 if (recipient_channel != expected_channel) return error.UnknownChannel; 2046 if (extended) { 2047 const data_type = try r.takeInt(u32, .big); 2048 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2049 } 2050 const data_len = try r.takeInt(u32, .big); 2051 // catches both data_len > remaining (would otherwise be a bounds-check 2052 // panic on the slice) and trailing junk after the declared payload. 2053 if (data_len != r.buffered().len) return error.InvalidChannelData; 2054 return r.buffered(); 2055 } 2056 2057 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2058 if (packet.len < 1) return error.EmptyPacket; 2059 var r = std.Io.Reader.fixed(packet[1..]); 2060 const recipient_channel = try r.takeInt(u32, .big); 2061 if (recipient_channel != expected_channel) return error.UnknownChannel; 2062 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2063 } 2064 2065 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2066 /// of `budget`, the credit we're willing to have outstanding. used both for 2067 /// the pre-session discard path and by SessionCtx after it consumes a 2068 /// CHANNEL_DATA payload. 2069 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2070 if (ch.local_window >= budget / 2) return; 2071 const add = budget - ch.local_window; 2072 ch.local_window += add; 2073 var adj: std.ArrayList(u8) = .empty; 2074 defer adj.deinit(conn.allocator); 2075 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2076 try writeU32(&adj, conn.allocator, ch.remote_id); 2077 try writeU32(&adj, conn.allocator, add); 2078 try conn.writePacket(adj.items); 2079 } 2080 2081 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2082 var bytes: [4]u8 = undefined; 2083 std.mem.writeInt(u32, &bytes, value, .big); 2084 try buf.appendSlice(allocator, &bytes); 2085 } 2086 2087 test "pty dimensions have bounded axes and area, preserving normal and zero sizes" { 2088 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2089 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2090 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2091 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2092 }) |case| { 2093 var bytes: [8]u8 = undefined; 2094 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2095 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2096 var reader = std.Io.Reader.fixed(&bytes); 2097 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2098 } 2099 } 2100 2101 test "channel close before shell or exec is acknowledged" { 2102 const io = std.testing.io; 2103 const allocator = std.testing.allocator; 2104 const key = [_]u8{0x5a} ** 64; 2105 var encoded: [256]u8 = undefined; 2106 var encoded_writer = std.Io.Writer.fixed(&encoded); 2107 var sender = Cipher.init(&key, 0); 2108 var open: std.ArrayList(u8) = .empty; 2109 defer open.deinit(allocator); 2110 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2111 try writeStringField(&open, allocator, "session"); 2112 try writeU32(&open, allocator, 7); 2113 try writeU32(&open, allocator, 32768); 2114 try writeU32(&open, allocator, 32768); 2115 try sender.writePacket(io, &encoded_writer, open.items); 2116 try sender.writePacket(io, &encoded_writer, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }); 2117 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2118 var output: [256]u8 = undefined; 2119 var writer = std.Io.Writer.fixed(&output); 2120 var conn = Conn{ 2121 .io = io, 2122 .allocator = allocator, 2123 .reader = &reader, 2124 .writer = &writer, 2125 .cs_cipher = Cipher.init(&key, 0), 2126 .sc_cipher = Cipher.init(&key, 0), 2127 .rekey = undefined, 2128 }; 2129 const Handler = struct { 2130 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2131 return error.UnexpectedSession; 2132 } 2133 }; 2134 var handler = Handler{}; 2135 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2136 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2137 var receiver = Cipher.init(&key, 0); 2138 const confirmation = try receiver.readPacket(allocator, &output_reader); 2139 defer allocator.free(confirmation); 2140 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2141 const close = try receiver.readPacket(allocator, &output_reader); 2142 defer allocator.free(close); 2143 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2144 try std.testing.expectEqual(0, output_reader.buffered().len); 2145 } 2146