╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1771 } 1772 1773 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1774 return formatFingerprint(pubkey_blob); 1775 } 1776 } 1777 1778 fn sendUserauthFailure(conn: *Conn) !void { 1779 var buf: std.ArrayList(u8) = .empty; 1780 defer buf.deinit(conn.allocator); 1781 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1782 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1783 try buf.append(conn.allocator, 0); // partial_success = false 1784 try conn.writePacket(&.{buf.items}); 1785 } 1786 1787 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1788 /// used by the server to recompute the signed input for verification 1789 pub fn appendPublickeySignedData( 1790 buf: *std.ArrayList(u8), 1791 allocator: std.mem.Allocator, 1792 session_id: []const u8, 1793 user_name: []const u8, 1794 service_name: []const u8, 1795 algo: []const u8, 1796 pubkey_blob: []const u8, 1797 ) !void { 1798 try writeStringField(buf, allocator, session_id); 1799 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1800 try writeStringField(buf, allocator, user_name); 1801 try writeStringField(buf, allocator, service_name); 1802 try writeStringField(buf, allocator, "publickey"); 1803 try buf.append(allocator, 1); 1804 try writeStringField(buf, allocator, algo); 1805 try writeStringField(buf, allocator, pubkey_blob); 1806 } 1807 1808 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1809 // verify the supplied signature against them. 1810 fn verifyUserauthSignature( 1811 allocator: std.mem.Allocator, 1812 session_id: *const [Sha256.digest_length]u8, 1813 user_name: []const u8, 1814 service_name: []const u8, 1815 algo: []const u8, 1816 pubkey_blob: []const u8, 1817 signature_blob: []const u8, 1818 ) !bool { 1819 var signed: std.ArrayList(u8) = .empty; 1820 defer signed.deinit(allocator); 1821 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1822 1823 if (std.mem.eql(u8, algo, "ssh-ed25519")) return verifyEd25519(pubkey_blob, signature_blob, signed.items); 1824 if (std.mem.eql(u8, algo, "rsa-sha2-512")) return verifyRsa(Sha512, algo, pubkey_blob, signature_blob, signed.items); 1825 if (std.mem.eql(u8, algo, "rsa-sha2-256")) return verifyRsa(Sha256, algo, pubkey_blob, signature_blob, signed.items); 1826 return false; 1827 } 1828 1829 fn verifyEd25519(pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1830 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1831 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1832 const pk_algo = try takeString(&pubkey_reader, 64); 1833 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1834 const raw_pubkey = try takeString(&pubkey_reader, 64); 1835 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1836 // the fingerprint hashes the whole blob, so it must hold nothing else 1837 if (pubkey_reader.bufferedLen() != 0) return false; 1838 1839 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1840 var sig_reader = std.Io.Reader.fixed(signature_blob); 1841 const sig_algo = try takeString(&sig_reader, 64); 1842 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1843 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1844 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1845 1846 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1847 @memcpy(&pubkey_bytes, raw_pubkey); 1848 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1849 @memcpy(&sig_bytes, raw_sig); 1850 1851 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1852 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1853 sig.verify(signed, pk) catch return false; 1854 return true; 1855 } 1856 1857 fn verifyRsa(comptime Hash: type, algo: []const u8, pubkey_blob: []const u8, signature_blob: []const u8, signed: []const u8) !bool { 1858 // parse pubkey_blob: string "ssh-rsa" || mpint e || mpint n 1859 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1860 if (!std.mem.eql(u8, try takeString(&pubkey_reader, 64), "ssh-rsa")) return false; 1861 // the fingerprint hashes the whole blob, so one key must have one encoding 1862 const e = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1863 const n = canonicalMpintMagnitude(try takeString(&pubkey_reader, 1024)) orelse return false; 1864 if (pubkey_reader.bufferedLen() != 0) return false; 1865 1866 // parse signature_blob: string algo || string sig 1867 var sig_reader = std.Io.Reader.fixed(signature_blob); 1868 if (!std.mem.eql(u8, try takeString(&sig_reader, 64), algo)) return false; 1869 const sig = try takeString(&sig_reader, 1024); 1870 if (sig.len != n.len) return false; 1871 1872 const pk = rsa.PublicKey.fromBytes(e, n) catch return false; 1873 switch (n.len) { 1874 inline 256, 384, 512 => |len| { 1875 rsa.PKCS1v1_5Signature.verify(len, sig[0..len].*, signed, pk, Hash) catch return false; 1876 return true; 1877 }, 1878 else => return false, 1879 } 1880 } 1881 1882 // the unsigned bytes of a positive mpint in its shortest encoding (RFC 4251 1883 // §5), or null for zero, negative, or padded encodings 1884 fn canonicalMpintMagnitude(bytes: []const u8) ?[]const u8 { 1885 if (bytes.len == 0 or bytes[0] & 0x80 != 0) return null; 1886 if (bytes[0] != 0) return bytes; 1887 if (bytes.len < 2 or bytes[1] & 0x80 == 0) return null; 1888 return bytes[1..]; 1889 } 1890 1891 // --------------------------------------------------------------------------- 1892 // connection layer (RFC 4254): channels, requests, data, flow control 1893 // --------------------------------------------------------------------------- 1894 1895 const Channel = struct { 1896 local_id: u32, 1897 remote_id: u32, 1898 local_window: u32, // bytes peer may still send us before we adjust 1899 remote_window: u32, // bytes we may still send to peer before they adjust 1900 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1901 pty: ?PtySize = null, 1902 // value of GIT_PROTOCOL, one of the two env variables we keep 1903 git_protocol_buf: [64]u8 = undefined, 1904 git_protocol_len: ?usize = null, 1905 // false when NO_COLOR is set, the other env variable we keep 1906 color: bool = true, 1907 }; 1908 1909 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1910 1911 // take the uint32 width/height cell counts of a pty-req or window-change, 1912 // bounded before either initial rendering or a resize can allocate grids. 1913 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1914 fn takePtySize(r: *std.Io.Reader) !PtySize { 1915 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1916 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1917 return .{ 1918 .width_cells = @intCast(width), 1919 .height_cells = @intCast(height), 1920 }; 1921 } 1922 1923 fn runChannelLayer( 1924 conn: *Conn, 1925 fingerprint: *const [fingerprint_len]u8, 1926 handler: anytype, 1927 ) !void { 1928 const allocator = conn.allocator; 1929 var channel: ?Channel = null; 1930 1931 while (true) { 1932 const packet = try readSessionPacket(conn); 1933 defer allocator.free(packet); 1934 const msg_type = packet[0]; 1935 1936 switch (msg_type) { 1937 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1938 1939 SSH_MSG_CHANNEL_OPEN => { 1940 channel = try handleChannelOpen(conn, packet, channel != null) orelse continue; 1941 }, 1942 1943 SSH_MSG_CHANNEL_REQUEST => { 1944 const ch = if (channel) |*c| c else return error.UnknownChannel; 1945 const start_request = try handleChannelRequest(conn, ch, packet); 1946 // the request borrows from the packet, which outlives the session 1947 if (start_request) |request| { 1948 // any key authenticates, so the deadline holds until here 1949 conn.idle.session_started.store(true, .release); 1950 var sess = SessionCtx{ 1951 .conn = conn, 1952 .channel = ch, 1953 .fingerprint = fingerprint.*, 1954 }; 1955 defer sess.deinit(); 1956 handler.handleSession(&sess, request) catch |session_err| { 1957 // a failed read leaves the protocol unusable, so the 1958 // disconnect names it instead of a clean close 1959 if (sess.read_err) |read_err| return read_err; 1960 // try to send a non-zero exit status before closing 1961 sess.exit(1) catch {}; 1962 return sess.underlyingError(session_err); 1963 }; 1964 if (!sess.closed) try sess.exit(0); 1965 return; 1966 } 1967 }, 1968 1969 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1970 const ch = if (channel) |*c| c else return error.UnknownChannel; 1971 try handleWindowAdjust(ch, packet); 1972 }, 1973 1974 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1975 const ch = if (channel) |*c| c else return error.UnknownChannel; 1976 // before shell/exec the client shouldn't be sending data, but 1977 // some clients are chatty; discard and refill window. nothing 1978 // is buffered yet, so the whole window is available to credit. 1979 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1980 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1981 }, 1982 1983 SSH_MSG_CHANNEL_EOF => { 1984 const ch = if (channel) |*c| c else return error.UnknownChannel; 1985 try parseChannelId(packet, ch.local_id); 1986 }, 1987 1988 SSH_MSG_CHANNEL_CLOSE => { 1989 const ch = if (channel) |*c| c else return error.UnknownChannel; 1990 try parseChannelId(packet, ch.local_id); 1991 try sendChannelMessage(conn, ch, SSH_MSG_CHANNEL_CLOSE); 1992 drainConnection(conn); 1993 return; 1994 }, 1995 1996 // RFC 4252 §5.1: silently ignored once authenticated 1997 SSH_MSG_USERAUTH_REQUEST => {}, 1998 else => try sendUnimplemented(conn), 1999 } 2000 } 2001 } 2002 2003 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 2004 // byte SSH_MSG_GLOBAL_REQUEST 2005 // string request_name 2006 // boolean want_reply 2007 // …request-specific data we ignore 2008 var r = std.Io.Reader.fixed(packet[1..]); 2009 _ = try takeString(&r, 256); 2010 const want_reply = (try r.takeByte()) != 0; 2011 if (want_reply) { 2012 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2013 } 2014 } 2015 2016 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2017 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2018 /// return null. 2019 fn handleChannelOpen(conn: *Conn, packet: []const u8, has_channel: bool) !?Channel { 2020 // byte SSH_MSG_CHANNEL_OPEN 2021 // string channel_type 2022 // uint32 sender_channel (peer's id) 2023 // uint32 initial_window 2024 // uint32 max_packet 2025 var r = std.Io.Reader.fixed(packet[1..]); 2026 const ch_type = try takeString(&r, 64); 2027 const remote_id = try r.takeInt(u32, .big); 2028 const initial_window = try r.takeInt(u32, .big); 2029 const max_packet = try r.takeInt(u32, .big); 2030 2031 if (has_channel) { 2032 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 2033 return null; 2034 } 2035 2036 if (!std.mem.eql(u8, ch_type, "session")) { 2037 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2038 return null; 2039 } 2040 2041 // a zero max_packet would leave writeBytes looping without progress 2042 if (max_packet == 0) { 2043 try sendChannelOpenFailure(conn, remote_id, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2044 return null; 2045 } 2046 2047 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2048 var reply: [17]u8 = undefined; 2049 reply[0] = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; 2050 std.mem.writeInt(u32, reply[1..5], remote_id, .big); 2051 std.mem.writeInt(u32, reply[5..9], local_id, .big); 2052 std.mem.writeInt(u32, reply[9..13], initial_recv_window, .big); 2053 std.mem.writeInt(u32, reply[13..17], max_packet_size, .big); 2054 try conn.writePacket(&.{&reply}); 2055 2056 return .{ 2057 .local_id = local_id, 2058 .remote_id = remote_id, 2059 .local_window = initial_recv_window, 2060 .remote_window = initial_window, 2061 .max_packet = max_packet, 2062 }; 2063 } 2064 2065 fn sendChannelOpenFailure(conn: *Conn, remote_id: u32, reason: u32, description: []const u8) !void { 2066 const allocator = conn.allocator; 2067 2068 var reply: std.ArrayList(u8) = .empty; 2069 defer reply.deinit(allocator); 2070 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2071 try writeU32(&reply, allocator, remote_id); 2072 try writeU32(&reply, allocator, reason); 2073 try writeStringField(&reply, allocator, description); 2074 try writeStringField(&reply, allocator, ""); // language tag 2075 try conn.writePacket(&.{reply.items}); 2076 } 2077 2078 /// returns the session request if this one triggered it, else null. an exec 2079 /// command borrows from `packet`. 2080 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2081 // byte SSH_MSG_CHANNEL_REQUEST 2082 // uint32 recipient_channel (== our local_id) 2083 // string request_type 2084 // boolean want_reply 2085 // …request-specific data 2086 var r = std.Io.Reader.fixed(packet[1..]); 2087 const recipient_channel = try r.takeInt(u32, .big); 2088 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2089 const req_type = try takeString(&r, 64); 2090 const want_reply = (try r.takeByte()) != 0; 2091 2092 if (std.mem.eql(u8, req_type, "pty-req")) { 2093 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2094 // uint32 height px, string modes 2095 _ = try takeString(&r, 64); 2096 ch.pty = try takePtySize(&r); 2097 try replyChannelRequest(conn, ch, want_reply, true); 2098 return null; 2099 } 2100 2101 if (std.mem.eql(u8, req_type, "env")) { 2102 // string name, string value. the rest are ignored silently. 2103 const name = try takeString(&r, max_packet_len); 2104 const value = try takeString(&r, max_packet_len); 2105 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2106 @memcpy(ch.git_protocol_buf[0..value.len], value); 2107 ch.git_protocol_len = value.len; 2108 } else if (std.mem.eql(u8, name, "NO_COLOR")) { 2109 ch.color = value.len == 0; 2110 } 2111 try replyChannelRequest(conn, ch, want_reply, true); 2112 return null; 2113 } 2114 2115 if (std.mem.eql(u8, req_type, "window-change")) { 2116 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2117 const sz = try takePtySize(&r); 2118 if (ch.pty != null) ch.pty = sz; 2119 // spec: window-change MUST NOT request a reply, but accept either 2120 try replyChannelRequest(conn, ch, want_reply, true); 2121 return null; 2122 } 2123 2124 if (std.mem.eql(u8, req_type, "shell")) { 2125 try replyChannelRequest(conn, ch, want_reply, true); 2126 return .{ .shell = .{ .pty = ch.pty, .color = ch.color } }; 2127 } 2128 2129 if (std.mem.eql(u8, req_type, "exec")) { 2130 // capture the command string for the handler to inspect 2131 const cmd = try takeString(&r, 4096); 2132 try replyChannelRequest(conn, ch, want_reply, true); 2133 return .{ .exec = .{ 2134 .command = cmd, 2135 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2136 } }; 2137 } 2138 2139 // unknown request kind — fail it 2140 try replyChannelRequest(conn, ch, want_reply, false); 2141 return null; 2142 } 2143 2144 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2145 if (!want_reply) return; 2146 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2147 } 2148 2149 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2150 var packet: [5]u8 = undefined; 2151 packet[0] = msg_type; 2152 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2153 try conn.writePacket(&.{&packet}); 2154 } 2155 2156 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2157 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2158 // uint32 recipient_channel 2159 // uint32 bytes_to_add 2160 var r = std.Io.Reader.fixed(packet[1..]); 2161 const recipient_channel = try r.takeInt(u32, .big); 2162 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2163 const add = try r.takeInt(u32, .big); 2164 ch.remote_window +|= add; 2165 } 2166 2167 // charge a payload's bytes against the receive window without keeping them. 2168 // the caller credits the window back, choosing the budget that suits it. 2169 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2170 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2171 // uint32 recipient_channel 2172 // [if extended: uint32 type_code] 2173 // string data 2174 const payload = try parseChannelData(packet, extended, ch.local_id); 2175 const data_len: u32 = @intCast(payload.len); 2176 2177 if (data_len > ch.local_window) return error.WindowExceeded; 2178 ch.local_window -= data_len; 2179 } 2180 2181 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2182 if (packet.len < 1) return error.EmptyPacket; 2183 var r = std.Io.Reader.fixed(packet[1..]); 2184 const recipient_channel = try r.takeInt(u32, .big); 2185 if (recipient_channel != expected_channel) return error.UnknownChannel; 2186 if (extended) { 2187 const data_type = try r.takeInt(u32, .big); 2188 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2189 } 2190 const data_len = try r.takeInt(u32, .big); 2191 // catches both data_len > remaining (would otherwise be a bounds-check 2192 // panic on the slice) and trailing junk after the declared payload. 2193 if (data_len != r.buffered().len) return error.InvalidChannelData; 2194 return r.buffered(); 2195 } 2196 2197 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2198 var r = std.Io.Reader.fixed(packet[1..]); 2199 const recipient_channel = try r.takeInt(u32, .big); 2200 if (recipient_channel != expected_channel) return error.UnknownChannel; 2201 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2202 } 2203 2204 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2205 /// of `budget`, the credit we're willing to have outstanding. used both for 2206 /// the pre-session discard path and by SessionCtx after it consumes a 2207 /// CHANNEL_DATA payload. 2208 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2209 if (ch.local_window >= budget / 2) return; 2210 const add = budget - ch.local_window; 2211 ch.local_window += add; 2212 var packet: [9]u8 = undefined; 2213 packet[0] = SSH_MSG_CHANNEL_WINDOW_ADJUST; 2214 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2215 std.mem.writeInt(u32, packet[5..9], add, .big); 2216 try conn.writePacket(&.{&packet}); 2217 } 2218 2219 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2220 var bytes: [4]u8 = undefined; 2221 std.mem.writeInt(u32, &bytes, value, .big); 2222 try buf.appendSlice(allocator, &bytes); 2223 } 2224 2225 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2226 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2227 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2228 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2229 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2230 }) |case| { 2231 var bytes: [8]u8 = undefined; 2232 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2233 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2234 var reader = std.Io.Reader.fixed(&bytes); 2235 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2236 } 2237 } 2238 2239 test "channel close before shell or exec is acknowledged" { 2240 const io = std.testing.io; 2241 const allocator = std.testing.allocator; 2242 const key = [_]u8{0x5a} ** 64; 2243 var encoded: [256]u8 = undefined; 2244 var encoded_writer = std.Io.Writer.fixed(&encoded); 2245 var sender = Cipher.init(&key, 0); 2246 var open: std.ArrayList(u8) = .empty; 2247 defer open.deinit(allocator); 2248 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2249 try writeStringField(&open, allocator, "session"); 2250 try writeU32(&open, allocator, 7); 2251 try writeU32(&open, allocator, 32768); 2252 try writeU32(&open, allocator, 32768); 2253 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2254 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2255 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2256 var output: [256]u8 = undefined; 2257 var writer = std.Io.Writer.fixed(&output); 2258 var idle = IdleState{}; 2259 var conn = Conn{ 2260 .io = io, 2261 .allocator = allocator, 2262 .reader = &reader, 2263 .writer = &writer, 2264 .cs_cipher = Cipher.init(&key, 0), 2265 .sc_cipher = Cipher.init(&key, 0), 2266 .rekey = undefined, 2267 .idle = &idle, 2268 }; 2269 const Handler = struct { 2270 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2271 return error.UnexpectedSession; 2272 } 2273 }; 2274 var handler = Handler{}; 2275 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2276 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2277 var receiver = Cipher.init(&key, 0); 2278 const confirmation = try receiver.readPacket(allocator, &output_reader); 2279 defer allocator.free(confirmation); 2280 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2281 const close = try receiver.readPacket(allocator, &output_reader); 2282 defer allocator.free(close); 2283 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2284 try std.testing.expectEqual(0, output_reader.buffered().len); 2285 } 2286