╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
192 self.incoming_buffer.deinit(self.allocator); 193 } 194 195 /// pump SSH packets until something interesting (data / resize / close) 196 /// arrives. background traffic (window adjusts, env requests, etc.) is 197 /// handled silently. used by pumped-event consumers (e.g. the TUI path); 198 /// do not mix with SessionReader, which has its own packet pump. 199 pub fn nextEvent(self: *SessionCtx) !Event { 200 while (true) { 201 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch |err| switch (err) { 202 error.EndOfStream => { 203 self.closed = true; 204 return .close; 205 }, 206 else => return err, 207 }; 208 errdefer self.allocator.free(packet); 209 if (packet.len < 1) return error.EmptyPacket; 210 211 switch (packet[0]) { 212 SSH_MSG_CHANNEL_DATA => { 213 const payload = try parseChannelData(packet, false, self.channel.local_id); 214 const data_len: u32 = @intCast(payload.len); 215 if (data_len > self.channel.local_window) return error.WindowExceeded; 216 self.channel.local_window -= data_len; 217 try maybeRefillRecvWindow(self.io, self.allocator, self.sc_cipher, self.writer, self.channel); 218 // hand the payload bytes to the caller (caller owns) 219 const owned_payload = try self.allocator.dupe(u8, payload); 220 self.allocator.free(packet); 221 return .{ .data = owned_payload }; 222 }, 223 SSH_MSG_CHANNEL_EXTENDED_DATA => { 224 // stderr from the client is unusual; discard, but adjust window 225 try discardChannelData(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, packet, true); 226 self.allocator.free(packet); 227 }, 228 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 229 try handleWindowAdjust(self.channel, packet); 230 self.allocator.free(packet); 231 }, 232 SSH_MSG_KEXINIT => { 233 defer self.allocator.free(packet); 234 try sendDisconnect(self.io, self.allocator, self.sc_cipher, self.writer, "rekey is not supported"); 235 return error.RekeyUnsupported; 236 }, 237 SSH_MSG_CHANNEL_REQUEST => { 238 defer self.allocator.free(packet); 239 var r = std.Io.Reader.fixed(packet[1..]); 240 const recipient_channel = try r.takeInt(u32, .big); 241 if (recipient_channel != self.channel.local_id) return error.UnknownChannel; 242 const req_type = try takeStringField(self.allocator, &r, 64); 243 defer self.allocator.free(req_type); 244 const want_reply = (try r.takeByte()) != 0; 245 if (std.mem.eql(u8, req_type, "window-change")) { 246 const w = try r.takeInt(u32, .big); 247 const h = try r.takeInt(u32, .big); 248 const sz = PtySize{ 249 .width_cells = @intCast(@min(w, 0xFFFF)), 250 .height_cells = @intCast(@min(h, 0xFFFF)), 251 }; 252 if (self.channel.pty != null) self.channel.pty = sz; 253 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, true); 254 return .{ .resize = sz }; 255 } 256 // unknown / not interesting — fail it and keep going 257 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, false); 258 }, 259 SSH_MSG_CHANNEL_EOF, SSH_MSG_CHANNEL_CLOSE => { 260 try parseChannelId(packet, self.channel.local_id); 261 self.allocator.free(packet); 262 self.closed = true; 263 return .close; 264 }, 265 SSH_MSG_GLOBAL_REQUEST => { 266 try handleGlobalRequest(self.io, self.allocator, self.sc_cipher, self.writer, packet); 267 self.allocator.free(packet); 268 }, 269 else => self.allocator.free(packet), 270 } 271 } 272 } 273 274 /// send bytes to the client's stdout (CHANNEL_DATA). 275 pub fn writeBytes(self: *SessionCtx, bytes: []const u8) !void { 276 try self.writeChannel(bytes, false); 277 } 278 279 /// send bytes to the client's stderr (CHANNEL_EXTENDED_DATA). use this for 280 /// server messages on a git exec session, where stdout carries the pack 281 /// protocol and stray text breaks the client's pkt-line parser. 282 pub fn writeStderr(self: *SessionCtx, bytes: []const u8) !void { 283 try self.writeChannel(bytes, true); 284 } 285 286 /// ship bytes as one or more stdout CHANNEL_DATA (or stderr 287 /// CHANNEL_EXTENDED_DATA) packets, respecting the peer's max-packet size. 288 /// if the remote window is exhausted, pump incoming SSH packets until a 289 /// WINDOW_ADJUST arrives (background packets are processed for their side 290 /// effects — incoming CHANNEL_DATA goes into incoming_buffer for a future 291 /// SessionReader). 292 fn writeChannel(self: *SessionCtx, bytes: []const u8, extended: bool) !void { 293 var rest = bytes; 294 while (rest.len > 0) { 295 while (self.channel.remote_window == 0) { 296 if (self.incoming_eof) return error.RemoteClosed; 297 try self.processOneBackgroundPacket(); 298 } 299 const cap = @min(@min(rest.len, self.channel.max_packet), self.channel.remote_window); 300 const chunk_len: u32 = @intCast(cap); 301 302 var msg: std.ArrayList(u8) = .empty; 303 defer msg.deinit(self.allocator); 304 try msg.append(self.allocator, if (extended) SSH_MSG_CHANNEL_EXTENDED_DATA else SSH_MSG_CHANNEL_DATA); 305 try writeU32(&msg, self.allocator, self.channel.remote_id); 306 if (extended) try writeU32(&msg, self.allocator, SSH_EXTENDED_DATA_STDERR); 307 try writeStringField(&msg, self.allocator, rest[0..chunk_len]); 308 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, msg.items); 309 310 self.channel.remote_window -= chunk_len; 311 rest = rest[chunk_len..]; 312 } 313 } 314 315 /// process exactly one SSH packet for side effects only. CHANNEL_DATA 316 /// payloads accumulate in incoming_buffer; CHANNEL_EOF/CLOSE flips 317 /// incoming_eof; WINDOW_ADJUST updates the channel state; channel/global 318 /// requests get a polite failure. used both by SessionReader (waiting 319 /// for inbound bytes) and writeBytes (waiting for send-window). 320 fn processOneBackgroundPacket(self: *SessionCtx) !void { 321 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch |err| switch (err) { 322 error.EndOfStream => { 323 self.incoming_eof = true; 324 return; 325 }, 326 else => return err, 327 }; 328 defer self.allocator.free(packet); 329 if (packet.len < 1) return; 330 331 switch (packet[0]) { 332 SSH_MSG_CHANNEL_DATA => { 333 const payload = try parseChannelData(packet, false, self.channel.local_id); 334 const data_len: u32 = @intCast(payload.len); 335 if (data_len > self.channel.local_window) return error.WindowExceeded; 336 self.channel.local_window -= data_len; 337 if (payload.len > max_incoming_buffered - self.incoming_buffer.items.len) { 338 return error.IncomingBufferExceeded; 339 } 340 try self.incoming_buffer.appendSlice(self.allocator, payload); 341 try self.maybeRefillRecvWindowForBufferedInput(); 342 }, 343 SSH_MSG_CHANNEL_EXTENDED_DATA => { 344 try discardChannelData(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, packet, true); 345 }, 346 SSH_MSG_CHANNEL_WINDOW_ADJUST => try handleWindowAdjust(self.channel, packet), 347 SSH_MSG_KEXINIT => { 348 try sendDisconnect(self.io, self.allocator, self.sc_cipher, self.writer, "rekey is not supported"); 349 return error.RekeyUnsupported; 350 }, 351 SSH_MSG_CHANNEL_REQUEST => { 352 var r = std.Io.Reader.fixed(packet[1..]); 353 const recipient_channel = try r.takeInt(u32, .big); 354 if (recipient_channel != self.channel.local_id) return error.UnknownChannel; 355 const req_type = try takeStringField(self.allocator, &r, 64); 356 defer self.allocator.free(req_type); 357 const want_reply = (try r.takeByte()) != 0; 358 // mid-session channel requests aren't honored — fail them 359 try replyChannelRequest(self.io, self.allocator, self.sc_cipher, self.writer, self.channel, want_reply, false); 360 }, 361 SSH_MSG_CHANNEL_EOF, SSH_MSG_CHANNEL_CLOSE => { 362 try parseChannelId(packet, self.channel.local_id); 363 self.incoming_eof = true; 364 }, 365 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(self.io, self.allocator, self.sc_cipher, self.writer, packet), 366 else => {}, 367 } 368 } 369 370 fn maybeRefillRecvWindowForBufferedInput(self: *SessionCtx) !void { 371 if (self.incoming_buffer.items.len >= incoming_refill_threshold) return; 372 try maybeRefillRecvWindow(self.io, self.allocator, self.sc_cipher, self.writer, self.channel); 373 } 374 375 /// signal the consumer's exit status and tear the channel down. 376 pub fn exit(self: *SessionCtx, status: u32) !void { 377 if (self.closed) return; 378 self.closed = true; 379 380 // exit-status request (informational; client uses it as the 381 // command's exit code) 382 { 383 var req: std.ArrayList(u8) = .empty; 384 defer req.deinit(self.allocator); 385 try req.append(self.allocator, SSH_MSG_CHANNEL_REQUEST); 386 try writeU32(&req, self.allocator, self.channel.remote_id); 387 try writeStringField(&req, self.allocator, "exit-status"); 388 try req.append(self.allocator, 0); // want_reply MUST be false 389 try writeU32(&req, self.allocator, status); 390 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, req.items); 391 } 392 393 // EOF then CLOSE 394 var eof: std.ArrayList(u8) = .empty; 395 defer eof.deinit(self.allocator); 396 try eof.append(self.allocator, SSH_MSG_CHANNEL_EOF); 397 try writeU32(&eof, self.allocator, self.channel.remote_id); 398 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, eof.items); 399 400 var close: std.ArrayList(u8) = .empty; 401 defer close.deinit(self.allocator); 402 try close.append(self.allocator, SSH_MSG_CHANNEL_CLOSE); 403 try writeU32(&close, self.allocator, self.channel.remote_id); 404 try self.sc_cipher.writePacket(self.io, self.allocator, self.writer, close.items); 405 406 // read and discard until the peer closes (TCP FIN) before letting the 407 // caller close the socket. a git client, after our CHANNEL_CLOSE, still 408 // sends its own CHANNEL_CLOSE and SSH_MSG_DISCONNECT before closing; if 409 // we close with those unread, Linux sends RST instead of FIN, which the 410 // client reports as "Connection reset by peer" and treats as a failed 411 // push even though the ref updated. draining to EOF leaves nothing 412 // unread, so we send a clean FIN. we're tearing down, so the packet 413 // contents don't matter — just get them off the socket. 414 var drain_packets: u32 = 0; 415 while (drain_packets < max_exit_drain_packets) : (drain_packets += 1) { 416 const packet = self.cs_cipher.readPacket(self.allocator, self.reader) catch break; 417 self.allocator.free(packet); 418 } 419 } 420 }; 421 422 /// std.Io.Writer adapter that ships bytes to a SessionCtx as CHANNEL_DATA. 423 /// useful for plugging the session into anything that wants a *std.Io.Writer 424 /// (e.g. xitui.StreamTerminal). 425 pub const SessionWriter = struct { 426 interface: std.Io.Writer, 427 sess: *SessionCtx, 428 429 pub fn init(sess: *SessionCtx, buffer: []u8) SessionWriter { 430 return .{ 431 .interface = .{ 432 .vtable = &.{ .drain = drain }, 433 .buffer = buffer, 434 }, 435 .sess = sess, 436 }; 437 } 438 439 fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { 440 const self: *SessionWriter = @fieldParentPtr("interface", w); 441 442 // first ship anything already accumulated in the Writer's buffer 443 const buffered = w.buffered(); 444 if (buffered.len > 0) { 445 self.sess.writeBytes(buffered) catch return error.WriteFailed; 446 } 447 448 // then ship the bytes passed in directly. data[0..len-1] are written 449 // once each; data[len-1] is written `splat` times (this is how the 450 // Writer interface represents fan-out / repeated patterns). 451 var extra: usize = 0; 452 if (data.len > 1) { 453 for (data[0 .. data.len - 1]) |chunk| { 454 if (chunk.len == 0) continue; 455 self.sess.writeBytes(chunk) catch return error.WriteFailed; 456 extra += chunk.len; 457 } 458 } 459 if (data.len > 0) { 460 const pattern = data[data.len - 1]; 461 if (pattern.len > 0) { 462 var i: usize = 0; 463 while (i < splat) : (i += 1) { 464 self.sess.writeBytes(pattern) catch return error.WriteFailed; 465 extra += pattern.len; 466 } 467 } 468 } 469 470 // consume tells the Writer how many bytes (buffered + data) were 471 // processed and clears w.end. it returns the count attributed to 472 // data, which is what `write` propagates back to the caller. 473 return w.consume(buffered.len + extra); 474 } 475 }; 476 477 /// std.Io.Reader adapter that drains incoming CHANNEL_DATA from a SessionCtx. 478 /// when the consumer reads beyond what's buffered, runs the SSH packet loop 479 /// (via processOneBackgroundPacket) until more bytes arrive or the peer 480 /// closes the channel. 481 pub const SessionReader = struct { 482 interface: std.Io.Reader, 483 sess: *SessionCtx, 484 485 pub fn init(sess: *SessionCtx, buffer: []u8) SessionReader { 486 return .{ 487 .interface = .{ 488 .vtable = &.{ 489 .readVec = readVec, 490 .stream = stream, 491 }, 492 .buffer = buffer, 493 .seek = 0, 494 .end = 0, 495 }, 496 .sess = sess, 497 }; 498 } 499 500 fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize { 501 const self: *SessionReader = @fieldParentPtr("interface", r); 502 503 // wait for data to arrive (or EOF) 504 while (self.sess.incoming_buffer.items.len == 0) { 505 if (self.sess.incoming_eof) return error.EndOfStream; 506 self.sess.processOneBackgroundPacket() catch return error.ReadFailed; 507 } 508 509 // drain as much of incoming_buffer as the limit allows, in one go 510 const chunk = limit.sliceConst(self.sess.incoming_buffer.items); 511 const written = try w.write(chunk); 512 513 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, self.sess.incoming_buffer.items[written..]); 514 self.sess.incoming_buffer.shrinkRetainingCapacity(self.sess.incoming_buffer.items.len - written); 515 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 516 517 return written; 518 } 519 520 fn readVec(r: *std.Io.Reader, data: [][]u8) std.Io.Reader.Error!usize { 521 const self: *SessionReader = @fieldParentPtr("interface", r); 522 523 // wait until something is in incoming_buffer (or EOF) 524 while (self.sess.incoming_buffer.items.len == 0) { 525 if (self.sess.incoming_eof) return error.EndOfStream; 526 self.sess.processOneBackgroundPacket() catch return error.ReadFailed; 527 } 528 529 const src = self.sess.incoming_buffer.items; 530 531 // vtable.readVec contract: if data[0] is empty, write into r.buffer 532 // instead and return 0. without this branch the caller spins, 533 // calling readVec repeatedly with the same empty buffer. 534 if (data.len == 0 or data[0].len == 0) { 535 const dest = r.buffer[r.end..]; 536 if (dest.len == 0) return 0; 537 const copy = @min(dest.len, src.len); 538 @memcpy(dest[0..copy], src[0..copy]); 539 r.end += copy; 540 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, src[copy..]); 541 self.sess.incoming_buffer.shrinkRetainingCapacity(src.len - copy); 542 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 543 return 0; 544 } 545 546 const dest = data[0]; 547 const copy = @min(dest.len, src.len); 548 @memcpy(dest[0..copy], src[0..copy]); 549 std.mem.copyForwards(u8, self.sess.incoming_buffer.items, src[copy..]); 550 self.sess.incoming_buffer.shrinkRetainingCapacity(src.len - copy); 551 self.sess.maybeRefillRecvWindowForBufferedInput() catch return error.ReadFailed; 552 return copy; 553 } 554 }; 555 556 // --------------------------------------------------------------------------- 557 // public entry point 558 // --------------------------------------------------------------------------- 559 560 /// `handler` must be a pointer to a struct with a method: 561 /// pub fn handleSession(self, sess: *SessionCtx, request: Request) anyerror!void 562 /// invoked once the channel is open and a shell/exec request has arrived. 563 /// 564 /// `reader` and `writer` are the bidirectional byte stream 565 pub fn handleConnection( 566 io: std.Io, 567 allocator: std.mem.Allocator, 568 reader: *std.Io.Reader, 569 writer: *std.Io.Writer, 570 host_key: *const HostKey, 571 handler: anytype, 572 ) !void { 573 const client_version = try exchangeVersions(allocator, reader, writer); 574 defer allocator.free(client_version); 575 576 const kex = try runKex(io, allocator, reader, writer, host_key, client_version); 577 578 // post-KEX everything is encrypted with chacha20-poly1305@openssh.com. 579 // both sides started counting packet seqnos at 0; KEXINIT, KEX_ECDH and 580 // NEWKEYS used seqno 0/1/2, so the first encrypted packet uses seqno 3. 581 var cs_cipher = Cipher.init(&kex.cs_key, 3); 582 var sc_cipher = Cipher.init(&kex.sc_key, 3); 583 584 const fingerprint = try runAuth(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &kex.session_id); 585 586 try runChannelLayer(io, allocator, reader, writer, &cs_cipher, &sc_cipher, &fingerprint, handler); 587 } 588 589 // --------------------------------------------------------------------------- 590 // version exchange (RFC 4253 §4.2) 591 // --------------------------------------------------------------------------- 592 593 fn exchangeVersions( 594 allocator: std.mem.Allocator, 595 reader: *std.Io.Reader, 596 writer: *std.Io.Writer, 597 ) ![]u8 { 598 try writer.writeAll(server_version ++ "\r\n"); 599 try writer.flush(); 600 601 // the spec allows the client to send arbitrary comment lines before its 602 // banner; skip anything that isn't an "SSH-2.0-…" / "SSH-1.99-…" line. 603 while (true) { 604 const line = (try reader.takeDelimiter('\n')) orelse return error.UnexpectedEof; 605 const trimmed = if (line.len > 0 and line[line.len - 1] == '\r') line[0 .. line.len - 1] else line; 606 if (std.mem.startsWith(u8, trimmed, "SSH-2.0-") or std.mem.startsWith(u8, trimmed, "SSH-1.99-")) { 607 return try allocator.dupe(u8, trimmed); 608 } 609 } 610 } 611 612 // --------------------------------------------------------------------------- 613 // binary packet codec, unencrypted form (RFC 4253 §6) 614 // --------------------------------------------------------------------------- 615 616 pub fn writePlainPacket(io: std.Io, writer: *std.Io.Writer, payload: []const u8) !void { 617 const block: usize = 8; 618 const initial_pad = block - ((5 + payload.len) % block); 619 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 620 const packet_len: u32 = @intCast(1 + payload.len + padding_len); 621 622 try writer.writeInt(u32, packet_len, .big); 623 try writer.writeByte(padding_len); 624 try writer.writeAll(payload); 625 626 var padding: [255]u8 = undefined; 627 io.random(padding[0..padding_len]); 628 try writer.writeAll(padding[0..padding_len]); 629 try writer.flush(); 630 } 631 632 pub fn readPlainPacket(allocator: std.mem.Allocator, reader: *std.Io.Reader) ![]u8 { 633 const packet_len = try reader.takeInt(u32, .big); 634 if (packet_len < 8 or packet_len > max_packet_len) return error.InvalidPacketLength; 635 const padding_len = try reader.takeByte(); 636 if (padding_len < 4 or @as(u32, padding_len) + 1 > packet_len) return error.InvalidPadding; 637 const payload_len = packet_len - 1 - @as(u32, padding_len); 638 639 const payload = try reader.readAlloc(allocator, payload_len); 640 errdefer allocator.free(payload); 641 try reader.discardAll(padding_len); 642 return payload; 643 } 644 645 // --------------------------------------------------------------------------- 646 // SSH field encoders / decoders (RFC 4251 §5) 647 // --------------------------------------------------------------------------- 648 649 pub fn writeStringField(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 650 var len_bytes: [4]u8 = undefined; 651 std.mem.writeInt(u32, &len_bytes, @intCast(bytes.len), .big); 652 try buf.appendSlice(allocator, &len_bytes); 653 try buf.appendSlice(allocator, bytes); 654 } 655 656 pub fn writeNameList(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, names: []const []const u8) !void { 657 var total: usize = 0; 658 for (names, 0..) |name, i| { 659 if (i > 0) total += 1; // comma separator 660 total += name.len; 661 } 662 var len_bytes: [4]u8 = undefined; 663 std.mem.writeInt(u32, &len_bytes, @intCast(total), .big); 664 try buf.appendSlice(allocator, &len_bytes); 665 for (names, 0..) |name, i| { 666 if (i > 0) try buf.append(allocator, ','); 667 try buf.appendSlice(allocator, name); 668 } 669 } 670 671 /// SSH "mpint" — big-endian two's complement multi-precision integer. for 672 /// our use (X25519 shared secret) the value is always non-negative, so we 673 /// strip leading zero bytes, then prepend a single 0x00 if the high bit of 674 /// the most-significant byte is set (to keep it parsed as positive). 675 pub fn writeMpint(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, bytes: []const u8) !void { 676 var start: usize = 0; 677 while (start < bytes.len and bytes[start] == 0) start += 1; 678 const trimmed = bytes[start..]; 679 if (trimmed.len == 0) { 680 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); 681 return; 682 } 683 const prepend = (trimmed[0] & 0x80) != 0; 684 const out_len: u32 = @intCast(trimmed.len + @as(usize, @intFromBool(prepend))); 685 var len_bytes: [4]u8 = undefined; 686 std.mem.writeInt(u32, &len_bytes, out_len, .big); 687 try buf.appendSlice(allocator, &len_bytes); 688 if (prepend) try buf.append(allocator, 0); 689 try buf.appendSlice(allocator, trimmed); 690 } 691 692 pub fn takeStringField(allocator: std.mem.Allocator, reader: *std.Io.Reader, max_len: u32) ![]u8 { 693 const len = try reader.takeInt(u32, .big); 694 if (len > max_len) return error.FieldTooLarge; 695 return try reader.readAlloc(allocator, len); 696 } 697 698 fn nameListContainsAny(haystack: []const u8, our_options: []const []const u8) bool { 699 var iter = std.mem.splitScalar(u8, haystack, ','); 700 while (iter.next()) |name| { 701 for (our_options) |opt| { 702 if (std.mem.eql(u8, name, opt)) return true; 703 } 704 } 705 return false; 706 } 707 708 // --------------------------------------------------------------------------- 709 // KEXINIT (RFC 4253 §7.1) 710 // --------------------------------------------------------------------------- 711 712 pub const our_kex_algos = [_][]const u8{ "mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org" }; 713 714 const MLKem768 = std.crypto.kem.ml_kem.MLKem768; 715 const hybrid_client_blob_len = MLKem768.PublicKey.encoded_length + X25519.public_length; // 1216 716 const hybrid_server_blob_len = MLKem768.ciphertext_length + X25519.public_length; // 1120 717 pub const our_host_key_algos = [_][]const u8{"ssh-ed25519"}; 718 pub const our_ciphers = [_][]const u8{"chacha20-poly1305@openssh.com"}; 719 const our_macs = [_][]const u8{}; // none — implicit in the AEAD cipher 720 const our_compression = [_][]const u8{"none"}; 721 722 /// Build a KEXINIT payload with the given algorithm name-lists 723 pub fn buildKexInit( 724 io: std.Io, 725 allocator: std.mem.Allocator, 726 kex_algos: []const []const u8, 727 host_key_algos: []const []const u8, 728 ciphers: []const []const u8, 729 ) ![]u8 { 730 var buf: std.ArrayList(u8) = .empty; 731 errdefer buf.deinit(allocator); 732 733 try buf.append(allocator, SSH_MSG_KEXINIT); 734 735 var cookie: [16]u8 = undefined; 736 io.random(&cookie); 737 try buf.appendSlice(allocator, &cookie); 738 739 try writeNameList(&buf, allocator, kex_algos); 740 try writeNameList(&buf, allocator, host_key_algos); 741 try writeNameList(&buf, allocator, ciphers); // c->s 742 try writeNameList(&buf, allocator, ciphers); // s->c 743 try writeNameList(&buf, allocator, &our_macs); 744 try writeNameList(&buf, allocator, &our_macs); 745 try writeNameList(&buf, allocator, &our_compression); 746 try writeNameList(&buf, allocator, &our_compression); 747 try writeNameList(&buf, allocator, &.{}); // langs c->s 748 try writeNameList(&buf, allocator, &.{}); // langs s->c 749 try buf.append(allocator, 0); // first_kex_packet_follows = false 750 try buf.appendSlice(allocator, &[_]u8{ 0, 0, 0, 0 }); // reserved 751 752 return try buf.toOwnedSlice(allocator); 753 } 754 755 fn buildServerKexInit(io: std.Io, allocator: std.mem.Allocator) ![]u8 { 756 return buildKexInit(io, allocator, &our_kex_algos, &our_host_key_algos, &our_ciphers); 757 } 758 759 const ParsedKexInit = struct { 760 kex_algos: []u8, 761 host_key_algos: []u8, 762 cs_cipher: []u8, 763 sc_cipher: []u8, 764 765 fn deinit(self: ParsedKexInit, allocator: std.mem.Allocator) void { 766 allocator.free(self.kex_algos); 767 allocator.free(self.host_key_algos); 768 allocator.free(self.cs_cipher); 769 allocator.free(self.sc_cipher); 770 } 771 }; 772 773 fn parseClientKexInit(allocator: std.mem.Allocator, payload: []const u8) !ParsedKexInit { 774 if (payload.len < 1 + 16) return error.KexInitTruncated; 775 if (payload[0] != SSH_MSG_KEXINIT) return error.UnexpectedMessage; 776 777 var reader = std.Io.Reader.fixed(payload[1 + 16 ..]); // skip type + cookie 778 779 const kex_algos = try takeStringField(allocator, &reader, max_name_list_len); 780 errdefer allocator.free(kex_algos); 781 const host_key_algos = try takeStringField(allocator, &reader, max_name_list_len); 782 errdefer allocator.free(host_key_algos); 783 const cs_cipher = try takeStringField(allocator, &reader, max_name_list_len); 784 errdefer allocator.free(cs_cipher); 785 const sc_cipher = try takeStringField(allocator, &reader, max_name_list_len); 786 errdefer allocator.free(sc_cipher); 787 788 // skip c->s mac, s->c mac, c->s compress, s->c compress, lang c->s, lang s->c 789 for (0..6) |_| { 790 const len = try reader.takeInt(u32, .big); 791 if (len > max_name_list_len) return error.FieldTooLarge; 792 try reader.discardAll(len); 793 } 794 _ = try reader.takeByte(); // first_kex_packet_follows 795 _ = try reader.takeInt(u32, .big); // reserved 796 797 return .{ 798 .kex_algos = kex_algos, 799 .host_key_algos = host_key_algos, 800 .cs_cipher = cs_cipher, 801 .sc_cipher = sc_cipher, 802 }; 803 } 804 805 // --------------------------------------------------------------------------- 806 // KEX orchestration: KEXINIT → ECDH → NEWKEYS → key derivation 807 // --------------------------------------------------------------------------- 808 809 const KexResult = struct { 810 cs_key: [64]u8, // client → server cipher key material (K_2 || K_1) 811 sc_key: [64]u8, // server → client cipher key material 812 session_id: [Sha256.digest_length]u8, 813 }; 814 815 fn runKex( 816 io: std.Io, 817 allocator: std.mem.Allocator, 818 reader: *std.Io.Reader, 819 writer: *std.Io.Writer, 820 host_key: *const HostKey, 821 client_version: []const u8, 822 ) !KexResult { 823 // exchange KEXINITs 824 const server_kex_init = try buildServerKexInit(io, allocator); 825 defer allocator.free(server_kex_init); 826 try writePlainPacket(io, writer, server_kex_init); 827 828 const client_kex_init = try readPlainPacket(allocator, reader); 829 defer allocator.free(client_kex_init); 830 831 var parsed = try parseClientKexInit(allocator, client_kex_init); 832 defer parsed.deinit(allocator); 833 834 // pick the first kex algo in the client's preference list that we also 835 // support (RFC 4253 §7.1.3). 836 const kex_algo = blk: { 837 var iter = std.mem.splitScalar(u8, parsed.kex_algos, ','); 838 while (iter.next()) |name| { 839 for (our_kex_algos) |opt| { 840 if (std.mem.eql(u8, name, opt)) break :blk opt; 841 } 842 } 843 return error.NoCommonKexAlgorithm; 844 }; 845 if (!nameListContainsAny(parsed.host_key_algos, &our_host_key_algos)) return error.NoCommonHostKeyAlgorithm; 846 if (!nameListContainsAny(parsed.cs_cipher, &our_ciphers)) return error.NoCommonCipher; 847 if (!nameListContainsAny(parsed.sc_cipher, &our_ciphers)) return error.NoCommonCipher; 848 const hybrid = std.mem.eql(u8, kex_algo, "mlkem768x25519-sha256"); 849 850 // receive KEX_ECDH_INIT (mlkem768x25519 reuses message code 30 — same 851 // wire shape, only the string size differs). 852 const ecdh_init = try readPlainPacket(allocator, reader); 853 defer allocator.free(ecdh_init); 854 if (ecdh_init.len < 1 or ecdh_init[0] != SSH_MSG_KEX_ECDH_INIT) return error.UnexpectedMessage; 855 856 var ecdh_init_reader = std.Io.Reader.fixed(ecdh_init[1..]); 857 const expected_client_len: u32 = if (hybrid) hybrid_client_blob_len else X25519.public_length; 858 const client_blob = try takeStringField(allocator, &ecdh_init_reader, expected_client_len); 859 defer allocator.free(client_blob); 860 if (client_blob.len != expected_client_len) return error.InvalidEphemeralKey; 861 862 // derive server reply blob (S_REPLY) + shared secret K. 863 // ECDH: server_blob = X25519 server pub (32B); K = X25519(s, c_pub). 864 // hybrid: server_blob = MLKEM ciphertext (1088B) || X25519 server pub (32B); 865 // K = SHA-256(K_MLKEM || K_X25519). 866 var server_blob: []u8 = undefined; 867 var k: []u8 = undefined; 868 { 869 const x25519_offset: usize = if (hybrid) MLKem768.PublicKey.encoded_length else 0; 870 var x25519_client_pub: [X25519.public_length]u8 = undefined; 871 @memcpy(&x25519_client_pub, client_blob[x25519_offset..]); 872 const server_kp = X25519.KeyPair.generate(io); 873 const x25519_shared = try X25519.scalarmult(server_kp.secret_key, x25519_client_pub); 874 875 if (hybrid) { 876 var pq_pub_bytes: [MLKem768.PublicKey.encoded_length]u8 = undefined; 877 @memcpy(&pq_pub_bytes, client_blob[0..MLKem768.PublicKey.encoded_length]); 878 const pq_pub = try MLKem768.PublicKey.fromBytes(&pq_pub_bytes); 879 const encap = pq_pub.encaps(io); 880 881 server_blob = try allocator.alloc(u8, hybrid_server_blob_len); 882 @memcpy(server_blob[0..MLKem768.ciphertext_length], &encap.ciphertext); 883 @memcpy(server_blob[MLKem768.ciphertext_length..], &server_kp.public_key); 884 885 var h = Sha256.init(.{}); 886 h.update(&encap.shared_secret); 887 h.update(&x25519_shared); 888 k = try allocator.dupe(u8, &h.finalResult()); 889 } else { 890 server_blob = try allocator.dupe(u8, &server_kp.public_key); 891 k = try allocator.dupe(u8, &x25519_shared); 892 } 893 } 894 defer allocator.free(server_blob); 895 defer allocator.free(k); 896 897 // build host key blob (K_S) 898 var host_key_blob: std.ArrayList(u8) = .empty; 899 defer host_key_blob.deinit(allocator); 900 try host_key.appendPublicBlob(&host_key_blob, allocator); 901 902 // build exchange hash input and compute H 903 const exchange_hash = try computeExchangeHash( 904 allocator, 905 client_version, 906 server_version, 907 client_kex_init, 908 server_kex_init, 909 host_key_blob.items, 910 client_blob, 911 server_blob, 912 k, 913 hybrid, 914 ); 915 916 // sign H with the host key, format as ssh signature blob 917 var signature_blob: std.ArrayList(u8) = .empty; 918 defer signature_blob.deinit(allocator); 919 try host_key.appendSignatureBlob(&signature_blob, allocator, &exchange_hash); 920 921 // build & send KEX_ECDH_REPLY (msg code 31 reused as KEX_HYBRID_REPLY) 922 var reply: std.ArrayList(u8) = .empty; 923 defer reply.deinit(allocator); 924 try reply.append(allocator, SSH_MSG_KEX_ECDH_REPLY); 925 try writeStringField(&reply, allocator, host_key_blob.items); 926 try writeStringField(&reply, allocator, server_blob); 927 try writeStringField(&reply, allocator, signature_blob.items); 928 try writePlainPacket(io, writer, reply.items); 929 930 // NEWKEYS — both sides switch to encrypted mode after this is sent and 931 // the peer's NEWKEYS is received. 932 try writePlainPacket(io, writer, &[_]u8{SSH_MSG_NEWKEYS}); 933 934 const peer_newkeys = try readPlainPacket(allocator, reader); 935 defer allocator.free(peer_newkeys); 936 if (peer_newkeys.len < 1 or peer_newkeys[0] != SSH_MSG_NEWKEYS) return error.UnexpectedMessage; 937 938 // derive session keys per RFC 4253 §7.2. session_id == H for the first 939 // KEX. only the encrypt keys are needed for chacha20-poly1305 (no 940 // separate MAC/IV). 941 var keys: SessionKeys = undefined; 942 try deriveSessionKeys(allocator, k, &exchange_hash, &exchange_hash, &keys, hybrid); 943 944 return .{ 945 .cs_key = keys.cs_enc, 946 .sc_key = keys.sc_enc, 947 .session_id = exchange_hash, 948 }; 949 } 950 951 // --------------------------------------------------------------------------- 952 // exchange hash (RFC 4253 §8, RFC 5656 §4) 953 // --------------------------------------------------------------------------- 954 955 pub fn computeExchangeHash( 956 allocator: std.mem.Allocator, 957 client_version: []const u8, 958 server_version_str: []const u8, 959 client_kex_init: []const u8, 960 server_kex_init: []const u8, 961 host_key_blob: []const u8, 962 client_ephemeral: []const u8, 963 server_ephemeral: []const u8, 964 shared_secret: []const u8, 965 /// curve25519-sha256 encodes K as mpint; mlkem768x25519-sha256 encodes it 966 /// as a plain SSH string (length-prefixed bytes). 967 k_is_string: bool, 968 ) ![Sha256.digest_length]u8 { 969 var buf: std.ArrayList(u8) = .empty; 970 defer buf.deinit(allocator); 971 972 try writeStringField(&buf, allocator, client_version); 973 try writeStringField(&buf, allocator, server_version_str); 974 try writeStringField(&buf, allocator, client_kex_init); 975 try writeStringField(&buf, allocator, server_kex_init); 976 try writeStringField(&buf, allocator, host_key_blob); 977 try writeStringField(&buf, allocator, client_ephemeral); 978 try writeStringField(&buf, allocator, server_ephemeral); 979 if (k_is_string) { 980 try writeStringField(&buf, allocator, shared_secret); 981 } else { 982 try writeMpint(&buf, allocator, shared_secret); 983 } 984 985 var hasher = Sha256.init(.{}); 986 hasher.update(buf.items); 987 return hasher.finalResult(); 988 } 989 990 // --------------------------------------------------------------------------- 991 // key derivation (RFC 4253 §7.2) 992 // --------------------------------------------------------------------------- 993 994 // chacha20-poly1305@openssh.com wants 64 bytes per direction (32-byte main key 995 // + 32-byte header key); SHA256 produces 32, so each encrypt key is two hash 996 // blocks chained per RFC 4253. 997 pub const SessionKeys = struct { 998 cs_enc: [64]u8, 999 sc_enc: [64]u8, 1000 }; 1001 1002 pub fn deriveSessionKeys( 1003 allocator: std.mem.Allocator, 1004 shared_secret: []const u8, 1005 exchange_hash: []const u8, 1006 session_id: []const u8, 1007 out: *SessionKeys, 1008 /// see computeExchangeHash — must match the KEX algorithm's K encoding. 1009 k_is_string: bool, 1010 ) !void { 1011 // pre-build the K || H prefix once; reused for every derivation 1012 var prefix: std.ArrayList(u8) = .empty; 1013 defer prefix.deinit(allocator); 1014 if (k_is_string) { 1015 try writeStringField(&prefix, allocator, shared_secret); 1016 } else { 1017 try writeMpint(&prefix, allocator, shared_secret); 1018 } 1019 try prefix.appendSlice(allocator, exchange_hash); 1020 1021 try deriveKey(allocator, prefix.items, 'C', session_id, &out.cs_enc); 1022 try deriveKey(allocator, prefix.items, 'D', session_id, &out.sc_enc); 1023 } 1024 1025 fn deriveKey( 1026 allocator: std.mem.Allocator, 1027 prefix: []const u8, // K || H, already encoded 1028 letter: u8, 1029 session_id: []const u8, 1030 out: []u8, 1031 ) !void { 1032 // first block: HASH(K || H || letter || session_id) 1033 var first_block: [Sha256.digest_length]u8 = undefined; 1034 { 1035 var hasher = Sha256.init(.{}); 1036 hasher.update(prefix); 1037 hasher.update(&[_]u8{letter}); 1038 hasher.update(session_id); 1039 first_block = hasher.finalResult(); 1040 } 1041 const first_copy = @min(out.len, first_block.len); 1042 @memcpy(out[0..first_copy], first_block[0..first_copy]); 1043 1044 // chain additional blocks if requested length exceeds one hash: 1045 // K_{n+1} = HASH(K || H || K_1 || K_2 || … || K_n) 1046 var chained: std.ArrayList(u8) = .empty; 1047 defer chained.deinit(allocator); 1048 try chained.appendSlice(allocator, first_block[0..]); 1049 1050 var produced: usize = first_copy; 1051 while (produced < out.len) { 1052 var hasher = Sha256.init(.{}); 1053 hasher.update(prefix); 1054 hasher.update(chained.items); 1055 const block = hasher.finalResult(); 1056 const copy_len = @min(out.len - produced, block.len); 1057 @memcpy(out[produced .. produced + copy_len], block[0..copy_len]); 1058 produced += copy_len; 1059 try chained.appendSlice(allocator, block[0..]); 1060 } 1061 } 1062 1063 // --------------------------------------------------------------------------- 1064 // chacha20-poly1305@openssh.com packet codec 1065 // --------------------------------------------------------------------------- 1066 // 1067 // per openssh's PROTOCOL.chacha20poly1305: 1068 // K_2 = first 32 bytes of key material — encrypts the packet body 1069 // K_1 = next 32 bytes — encrypts the 4-byte length field 1070 // nonce = 64-bit big-endian sequence number 1071 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1072 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1073 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1074 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1075 // 1076 // padding is computed on the body alone (padding_length byte + payload + 1077 // padding) — the 4-byte length field is excluded from alignment. body must 1078 // be a multiple of 8 bytes; minimum padding 4 bytes. 1079 1080 pub const Cipher = struct { 1081 main_key: [32]u8, // K_2 1082 header_key: [32]u8, // K_1 1083 seq: u64, 1084 1085 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1086 return .{ 1087 .main_key = key_material[0..32].*, 1088 .header_key = key_material[32..64].*, 1089 .seq = initial_seq, 1090 }; 1091 } 1092 1093 fn makeNonce(seq: u64) [8]u8 { 1094 var nonce: [8]u8 = undefined; 1095 std.mem.writeInt(u64, &nonce, seq, .big); 1096 return nonce; 1097 } 1098 1099 pub fn writePacket( 1100 self: *Cipher, 1101 io: std.Io, 1102 allocator: std.mem.Allocator, 1103 writer: *std.Io.Writer, 1104 payload: []const u8, 1105 ) !void { 1106 const block: usize = 8; 1107 const initial_pad = block - ((1 + payload.len) % block); 1108 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1109 const body_len: u32 = @intCast(1 + payload.len + padding_len); 1110 1111 const nonce = makeNonce(self.seq); 1112 1113 // plaintext body = padding_length || payload || random padding 1114 const body = try allocator.alloc(u8, body_len); 1115 defer allocator.free(body); 1116 body[0] = padding_len; 1117 @memcpy(body[1 .. 1 + payload.len], payload); 1118 io.random(body[1 + payload.len ..]); 1119 1120 // encrypt body in place with counter=1 1121 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1122 1123 // encrypt length field with header key, counter=0 1124 var enc_length: [4]u8 = undefined; 1125 var length_plain: [4]u8 = undefined; 1126 std.mem.writeInt(u32, &length_plain, body_len, .big); 1127 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1128 1129 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1130 var poly_key: [Poly1305.key_length]u8 = undefined; 1131 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1132 1133 // mac over encrypted_length || encrypted_body 1134 const mac_input = try allocator.alloc(u8, 4 + body_len); 1135 defer allocator.free(mac_input); 1136 @memcpy(mac_input[0..4], &enc_length); 1137 @memcpy(mac_input[4..], body); 1138 var tag: [Poly1305.mac_length]u8 = undefined; 1139 Poly1305.create(&tag, mac_input, &poly_key); 1140 1141 try writer.writeAll(&enc_length); 1142 try writer.writeAll(body); 1143 try writer.writeAll(&tag); 1144 try writer.flush(); 1145 1146 self.seq += 1; 1147 } 1148 1149 pub fn readPacket( 1150 self: *Cipher, 1151 allocator: std.mem.Allocator, 1152 reader: *std.Io.Reader, 1153 ) ![]u8 { 1154 const nonce = makeNonce(self.seq); 1155 1156 var enc_length: [4]u8 = undefined; 1157 try reader.readSliceAll(&enc_length); 1158 1159 var length_plain: [4]u8 = undefined; 1160 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1161 const body_len = std.mem.readInt(u32, &length_plain, .big); 1162 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1163 1164 const enc_body = try allocator.alloc(u8, body_len); 1165 defer allocator.free(enc_body); 1166 try reader.readSliceAll(enc_body); 1167 1168 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1169 try reader.readSliceAll(&tag_recv); 1170 1171 var poly_key: [Poly1305.key_length]u8 = undefined; 1172 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1173 1174 const mac_input = try allocator.alloc(u8, 4 + body_len); 1175 defer allocator.free(mac_input); 1176 @memcpy(mac_input[0..4], &enc_length); 1177 @memcpy(mac_input[4..], enc_body); 1178 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1179 Poly1305.create(&tag_computed, mac_input, &poly_key); 1180 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1181 return error.MacVerificationFailed; 1182 } 1183 1184 // decrypt body in place into a separate buffer (caller owns) 1185 const body = try allocator.alloc(u8, body_len); 1186 errdefer allocator.free(body); 1187 ChaCha20.xor(body, enc_body, 1, self.main_key, nonce); 1188 1189 const padding_len = body[0]; 1190 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1191 const payload_len = body_len - 1 - @as(u32, padding_len); 1192 1193 const payload = try allocator.dupe(u8, body[1 .. 1 + payload_len]); 1194 allocator.free(body); 1195 1196 self.seq += 1; 1197 return payload; 1198 } 1199 }; 1200 1201 // --------------------------------------------------------------------------- 1202 // post-KEX: service request + user authentication (RFC 4252) 1203 // --------------------------------------------------------------------------- 1204 1205 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1206 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1207 /// `Offering public key: … SHA256:…`. 1208 pub const fingerprint_len = 50; 1209 1210 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1211 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1212 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1213 var digest: [Sha256.digest_length]u8 = undefined; 1214 Sha256.hash(pubkey_blob, &digest, .{}); 1215 1216 var out: [fingerprint_len]u8 = undefined; 1217 @memcpy(out[0..7], "SHA256:"); 1218 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1219 std.debug.assert(encoded.len == fingerprint_len - 7); 1220 return out; 1221 } 1222 1223 fn runAuth( 1224 io: std.Io, 1225 allocator: std.mem.Allocator, 1226 reader: *std.Io.Reader, 1227 writer: *std.Io.Writer, 1228 cs_cipher: *Cipher, 1229 sc_cipher: *Cipher, 1230 session_id: *const [Sha256.digest_length]u8, 1231 ) ![fingerprint_len]u8 { 1232 // step 1: service request for ssh-userauth → service accept 1233 { 1234 const req = try cs_cipher.readPacket(allocator, reader); 1235 defer allocator.free(req); 1236 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1237 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1238 return error.RekeyUnsupported; 1239 } 1240 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1241 1242 var req_reader = std.Io.Reader.fixed(req[1..]); 1243 const service = try takeStringField(allocator, &req_reader, 64); 1244 defer allocator.free(service); 1245 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1246 1247 var accept: std.ArrayList(u8) = .empty; 1248 defer accept.deinit(allocator); 1249 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1250 try writeStringField(&accept, allocator, "ssh-userauth"); 1251 try sc_cipher.writePacket(io, allocator, writer, accept.items); 1252 } 1253 1254 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1255 // signature verifies against the offered pubkey. 1256 var auth_attempts: u32 = 0; 1257 while (true) { 1258 const req = try cs_cipher.readPacket(allocator, reader); 1259 defer allocator.free(req); 1260 if (req.len >= 1 and req[0] == SSH_MSG_KEXINIT) { 1261 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1262 return error.RekeyUnsupported; 1263 } 1264 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1265 1266 var req_reader = std.Io.Reader.fixed(req[1..]); 1267 const user_name = try takeStringField(allocator, &req_reader, 256); 1268 defer allocator.free(user_name); 1269 const service_name = try takeStringField(allocator, &req_reader, 64); 1270 defer allocator.free(service_name); 1271 const method = try takeStringField(allocator, &req_reader, 64); 1272 defer allocator.free(method); 1273 1274 if (!std.mem.eql(u8, method, "publickey")) { 1275 auth_attempts += 1; 1276 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1277 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1278 continue; 1279 } 1280 1281 const has_signature = (try req_reader.takeByte()) != 0; 1282 const algo = try takeStringField(allocator, &req_reader, 64); 1283 defer allocator.free(algo); 1284 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1285 defer allocator.free(pubkey_blob); 1286 1287 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1288 auth_attempts += 1; 1289 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1290 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1291 continue; 1292 } 1293 1294 if (!has_signature) { 1295 // probe — tell the client this key is acceptable so it'll send 1296 // the signed version next. 1297 var pk_ok: std.ArrayList(u8) = .empty; 1298 defer pk_ok.deinit(allocator); 1299 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1300 try writeStringField(&pk_ok, allocator, algo); 1301 try writeStringField(&pk_ok, allocator, pubkey_blob); 1302 try sc_cipher.writePacket(io, allocator, writer, pk_ok.items); 1303 continue; 1304 } 1305 1306 // has signature — verify it 1307 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1308 defer allocator.free(signature_blob); 1309 1310 const ok = verifyUserauthSignature( 1311 allocator, 1312 session_id, 1313 user_name, 1314 service_name, 1315 algo, 1316 pubkey_blob, 1317 signature_blob, 1318 ) catch false; 1319 1320 if (!ok) { 1321 auth_attempts += 1; 1322 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1323 try sendUserauthFailure(io, allocator, sc_cipher, writer); 1324 continue; 1325 } 1326 1327 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1328 return formatFingerprint(pubkey_blob); 1329 } 1330 } 1331 1332 fn sendUserauthFailure( 1333 io: std.Io, 1334 allocator: std.mem.Allocator, 1335 sc_cipher: *Cipher, 1336 writer: *std.Io.Writer, 1337 ) !void { 1338 var buf: std.ArrayList(u8) = .empty; 1339 defer buf.deinit(allocator); 1340 try buf.append(allocator, SSH_MSG_USERAUTH_FAILURE); 1341 try writeNameList(&buf, allocator, &.{"publickey"}); // allowed methods 1342 try buf.append(allocator, 0); // partial_success = false 1343 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1344 } 1345 1346 fn sendDisconnect( 1347 io: std.Io, 1348 allocator: std.mem.Allocator, 1349 sc_cipher: *Cipher, 1350 writer: *std.Io.Writer, 1351 description: []const u8, 1352 ) !void { 1353 var buf: std.ArrayList(u8) = .empty; 1354 defer buf.deinit(allocator); 1355 try buf.append(allocator, SSH_MSG_DISCONNECT); 1356 try writeU32(&buf, allocator, SSH_DISCONNECT_PROTOCOL_ERROR); 1357 try writeStringField(&buf, allocator, description); 1358 try writeStringField(&buf, allocator, ""); 1359 try sc_cipher.writePacket(io, allocator, writer, buf.items); 1360 } 1361 1362 /// Append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1363 /// Used by the server to recompute the signed input for verification 1364 pub fn appendPublickeySignedData( 1365 buf: *std.ArrayList(u8), 1366 allocator: std.mem.Allocator, 1367 session_id: []const u8, 1368 user_name: []const u8, 1369 service_name: []const u8, 1370 algo: []const u8, 1371 pubkey_blob: []const u8, 1372 ) !void { 1373 try writeStringField(buf, allocator, session_id); 1374 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1375 try writeStringField(buf, allocator, user_name); 1376 try writeStringField(buf, allocator, service_name); 1377 try writeStringField(buf, allocator, "publickey"); 1378 try buf.append(allocator, 1); 1379 try writeStringField(buf, allocator, algo); 1380 try writeStringField(buf, allocator, pubkey_blob); 1381 } 1382 1383 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1384 // verify the supplied signature against them. 1385 fn verifyUserauthSignature( 1386 allocator: std.mem.Allocator, 1387 session_id: *const [Sha256.digest_length]u8, 1388 user_name: []const u8, 1389 service_name: []const u8, 1390 algo: []const u8, 1391 pubkey_blob: []const u8, 1392 signature_blob: []const u8, 1393 ) !bool { 1394 var signed: std.ArrayList(u8) = .empty; 1395 defer signed.deinit(allocator); 1396 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1397 1398 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1399 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1400 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1401 defer allocator.free(pk_algo); 1402 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1403 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1404 defer allocator.free(raw_pubkey); 1405 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1406 1407 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1408 var sig_reader = std.Io.Reader.fixed(signature_blob); 1409 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1410 defer allocator.free(sig_algo); 1411 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1412 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1413 defer allocator.free(raw_sig); 1414 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1415 1416 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1417 @memcpy(&pubkey_bytes, raw_pubkey); 1418 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1419 @memcpy(&sig_bytes, raw_sig); 1420 1421 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1422 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1423 sig.verify(signed.items, pk) catch return false; 1424 return true; 1425 } 1426 1427 // --------------------------------------------------------------------------- 1428 // connection layer (RFC 4254): channels, requests, data, flow control 1429 // --------------------------------------------------------------------------- 1430 1431 const Channel = struct { 1432 local_id: u32, 1433 remote_id: u32, 1434 local_window: u32, // bytes peer may still send us before we adjust 1435 remote_window: u32, // bytes we may still send to peer before they adjust 1436 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1437 pty: ?PtySize = null, 1438 }; 1439 1440 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1441 1442 fn runChannelLayer( 1443 io: std.Io, 1444 allocator: std.mem.Allocator, 1445 reader: *std.Io.Reader, 1446 writer: *std.Io.Writer, 1447 cs_cipher: *Cipher, 1448 sc_cipher: *Cipher, 1449 fingerprint: *const [fingerprint_len]u8, 1450 handler: anytype, 1451 ) !void { 1452 var channel: ?Channel = null; 1453 var pending_exec: ?[]u8 = null; 1454 defer if (pending_exec) |s| allocator.free(s); 1455 1456 while (true) { 1457 const packet = try cs_cipher.readPacket(allocator, reader); 1458 defer allocator.free(packet); 1459 if (packet.len < 1) return error.EmptyPacket; 1460 const msg_type = packet[0]; 1461 1462 switch (msg_type) { 1463 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(io, allocator, sc_cipher, writer, packet), 1464 1465 SSH_MSG_KEXINIT => { 1466 try sendDisconnect(io, allocator, sc_cipher, writer, "rekey is not supported"); 1467 return error.RekeyUnsupported; 1468 }, 1469 1470 SSH_MSG_CHANNEL_OPEN => { 1471 if (channel != null) { 1472 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1473 continue; 1474 } 1475 channel = try handleChannelOpen(io, allocator, sc_cipher, writer, packet) orelse continue; 1476 }, 1477 1478 SSH_MSG_CHANNEL_REQUEST => { 1479 const ch = if (channel) |*c| c else continue; 1480 const start_request = try handleChannelRequest(io, allocator, sc_cipher, writer, ch, packet, &pending_exec); 1481 if (start_request) |req_kind| { 1482 const request: Request = switch (req_kind) { 1483 .shell => .{ .shell = ch.pty }, 1484 .exec => .{ .exec = pending_exec.? }, 1485 }; 1486 var sess = SessionCtx{ 1487 .io = io, 1488 .allocator = allocator, 1489 .reader = reader, 1490 .writer = writer, 1491 .cs_cipher = cs_cipher, 1492 .sc_cipher = sc_cipher, 1493 .channel = ch, 1494 .fingerprint = fingerprint.*, 1495 }; 1496 defer sess.deinit(); 1497 handler.handleSession(&sess, request) catch |session_err| { 1498 // try to send a non-zero exit status before closing 1499 sess.exit(1) catch {}; 1500 return session_err; 1501 }; 1502 if (!sess.closed) try sess.exit(0); 1503 return; 1504 } 1505 }, 1506 1507 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1508 const ch = if (channel) |*c| c else continue; 1509 try handleWindowAdjust(ch, packet); 1510 }, 1511 1512 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1513 const ch = if (channel) |*c| c else continue; 1514 // before shell/exec the client shouldn't be sending data, but 1515 // some clients are chatty; discard and refill window. 1516 try discardChannelData(io, allocator, sc_cipher, writer, ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1517 }, 1518 1519 SSH_MSG_CHANNEL_EOF => { 1520 if (channel) |*c| try parseChannelId(packet, c.local_id); 1521 }, 1522 1523 SSH_MSG_CHANNEL_CLOSE => { 1524 if (channel) |*c| try parseChannelId(packet, c.local_id); 1525 return; 1526 }, 1527 1528 else => {}, // ignore unknown messages 1529 } 1530 } 1531 } 1532 1533 fn handleGlobalRequest( 1534 io: std.Io, 1535 allocator: std.mem.Allocator, 1536 sc_cipher: *Cipher, 1537 writer: *std.Io.Writer, 1538 packet: []const u8, 1539 ) !void { 1540 // byte SSH_MSG_GLOBAL_REQUEST 1541 // string request_name 1542 // boolean want_reply 1543 // …request-specific data we ignore 1544 var r = std.Io.Reader.fixed(packet[1..]); 1545 const name = try takeStringField(allocator, &r, 256); 1546 defer allocator.free(name); 1547 const want_reply = (try r.takeByte()) != 0; 1548 if (want_reply) { 1549 try sc_cipher.writePacket(io, allocator, writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1550 } 1551 } 1552 1553 /// Parse a CHANNEL_OPEN. On a session channel, send CHANNEL_OPEN_CONFIRMATION 1554 /// and return the new Channel. On other types, send CHANNEL_OPEN_FAILURE and 1555 /// return null. 1556 fn handleChannelOpen( 1557 io: std.Io, 1558 allocator: std.mem.Allocator, 1559 sc_cipher: *Cipher, 1560 writer: *std.Io.Writer, 1561 packet: []const u8, 1562 ) !?Channel { 1563 // byte SSH_MSG_CHANNEL_OPEN 1564 // string channel_type 1565 // uint32 sender_channel (peer's id) 1566 // uint32 initial_window 1567 // uint32 max_packet 1568 var r = std.Io.Reader.fixed(packet[1..]); 1569 const ch_type = try takeStringField(allocator, &r, 64); 1570 defer allocator.free(ch_type); 1571 const remote_id = try r.takeInt(u32, .big); 1572 const initial_window = try r.takeInt(u32, .big); 1573 const max_packet = try r.takeInt(u32, .big); 1574 1575 if (!std.mem.eql(u8, ch_type, "session")) { 1576 try sendChannelOpenFailure(io, allocator, sc_cipher, writer, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1577 return null; 1578 } 1579 1580 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1581 var reply: std.ArrayList(u8) = .empty; 1582 defer reply.deinit(allocator); 1583 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1584 try writeU32(&reply, allocator, remote_id); 1585 try writeU32(&reply, allocator, local_id); 1586 try writeU32(&reply, allocator, initial_recv_window); 1587 try writeU32(&reply, allocator, max_packet_size); 1588 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1589 1590 return .{ 1591 .local_id = local_id, 1592 .remote_id = remote_id, 1593 .local_window = initial_recv_window, 1594 .remote_window = initial_window, 1595 .max_packet = max_packet, 1596 }; 1597 } 1598 1599 fn sendChannelOpenFailure( 1600 io: std.Io, 1601 allocator: std.mem.Allocator, 1602 sc_cipher: *Cipher, 1603 writer: *std.Io.Writer, 1604 open_packet: []const u8, 1605 reason: u32, 1606 description: []const u8, 1607 ) !void { 1608 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1609 // address the failure to the correct id 1610 var r = std.Io.Reader.fixed(open_packet[1..]); 1611 const ch_type_len = try r.takeInt(u32, .big); 1612 try r.discardAll(ch_type_len); 1613 const remote_id = try r.takeInt(u32, .big); 1614 1615 var reply: std.ArrayList(u8) = .empty; 1616 defer reply.deinit(allocator); 1617 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1618 try writeU32(&reply, allocator, remote_id); 1619 try writeU32(&reply, allocator, reason); 1620 try writeStringField(&reply, allocator, description); 1621 try writeStringField(&reply, allocator, ""); // language tag 1622 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1623 } 1624 1625 const RequestKind = enum { shell, exec }; 1626 1627 /// Returns the kind of session request if this triggered one, else null. 1628 fn handleChannelRequest( 1629 io: std.Io, 1630 allocator: std.mem.Allocator, 1631 sc_cipher: *Cipher, 1632 writer: *std.Io.Writer, 1633 ch: *Channel, 1634 packet: []const u8, 1635 pending_exec: *?[]u8, 1636 ) !?RequestKind { 1637 // byte SSH_MSG_CHANNEL_REQUEST 1638 // uint32 recipient_channel (== our local_id) 1639 // string request_type 1640 // boolean want_reply 1641 // …request-specific data 1642 var r = std.Io.Reader.fixed(packet[1..]); 1643 const recipient_channel = try r.takeInt(u32, .big); 1644 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1645 const req_type = try takeStringField(allocator, &r, 64); 1646 defer allocator.free(req_type); 1647 const want_reply = (try r.takeByte()) != 0; 1648 1649 if (std.mem.eql(u8, req_type, "pty-req")) { 1650 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1651 // uint32 height px, string modes 1652 const term = try takeStringField(allocator, &r, 64); 1653 defer allocator.free(term); 1654 const width = try r.takeInt(u32, .big); 1655 const height = try r.takeInt(u32, .big); 1656 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1657 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1658 return null; 1659 } 1660 1661 if (std.mem.eql(u8, req_type, "env")) { 1662 // ignore environment variables silently (we don't pass them anywhere) 1663 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1664 return null; 1665 } 1666 1667 if (std.mem.eql(u8, req_type, "window-change")) { 1668 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1669 const width = try r.takeInt(u32, .big); 1670 const height = try r.takeInt(u32, .big); 1671 if (ch.pty != null) { 1672 ch.pty = .{ .width_cells = @intCast(@min(width, 0xFFFF)), .height_cells = @intCast(@min(height, 0xFFFF)) }; 1673 } 1674 // spec: window-change MUST NOT request a reply, but accept either 1675 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1676 return null; 1677 } 1678 1679 if (std.mem.eql(u8, req_type, "shell")) { 1680 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1681 return .shell; 1682 } 1683 1684 if (std.mem.eql(u8, req_type, "exec")) { 1685 // capture the command string for the handler to inspect 1686 const cmd = try takeStringField(allocator, &r, 4096); 1687 if (pending_exec.*) |old| allocator.free(old); 1688 pending_exec.* = cmd; 1689 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, true); 1690 return .exec; 1691 } 1692 1693 // unknown request kind — fail it 1694 try replyChannelRequest(io, allocator, sc_cipher, writer, ch, want_reply, false); 1695 return null; 1696 } 1697 1698 fn replyChannelRequest( 1699 io: std.Io, 1700 allocator: std.mem.Allocator, 1701 sc_cipher: *Cipher, 1702 writer: *std.Io.Writer, 1703 ch: *Channel, 1704 want_reply: bool, 1705 success: bool, 1706 ) !void { 1707 if (!want_reply) return; 1708 var reply: std.ArrayList(u8) = .empty; 1709 defer reply.deinit(allocator); 1710 try reply.append(allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1711 try writeU32(&reply, allocator, ch.remote_id); 1712 try sc_cipher.writePacket(io, allocator, writer, reply.items); 1713 } 1714 1715 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1716 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1717 // uint32 recipient_channel 1718 // uint32 bytes_to_add 1719 var r = std.Io.Reader.fixed(packet[1..]); 1720 const recipient_channel = try r.takeInt(u32, .big); 1721 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1722 const add = try r.takeInt(u32, .big); 1723 ch.remote_window +|= add; 1724 } 1725 1726 fn discardChannelData( 1727 io: std.Io, 1728 allocator: std.mem.Allocator, 1729 sc_cipher: *Cipher, 1730 writer: *std.Io.Writer, 1731 ch: *Channel, 1732 packet: []const u8, 1733 extended: bool, 1734 ) !void { 1735 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1736 // uint32 recipient_channel 1737 // [if extended: uint32 type_code] 1738 // string data 1739 const payload = try parseChannelData(packet, extended, ch.local_id); 1740 const data_len: u32 = @intCast(payload.len); 1741 1742 if (data_len > ch.local_window) return error.WindowExceeded; 1743 ch.local_window -= data_len; 1744 try maybeRefillRecvWindow(io, allocator, sc_cipher, writer, ch); 1745 } 1746 1747 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1748 if (packet.len < 1) return error.EmptyPacket; 1749 var r = std.Io.Reader.fixed(packet[1..]); 1750 const recipient_channel = try r.takeInt(u32, .big); 1751 if (recipient_channel != expected_channel) return error.UnknownChannel; 1752 if (extended) { 1753 const data_type = try r.takeInt(u32, .big); 1754 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1755 } 1756 const data_len = try r.takeInt(u32, .big); 1757 // catches both data_len > remaining (would otherwise be a bounds-check 1758 // panic on the slice) and trailing junk after the declared payload. 1759 if (data_len != r.buffered().len) return error.InvalidChannelData; 1760 return r.buffered(); 1761 } 1762 1763 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1764 if (packet.len < 1) return error.EmptyPacket; 1765 var r = std.Io.Reader.fixed(packet[1..]); 1766 const recipient_channel = try r.takeInt(u32, .big); 1767 if (recipient_channel != expected_channel) return error.UnknownChannel; 1768 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1769 } 1770 1771 /// Send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1772 /// of the initial value. Used both for the pre-session discard path and by 1773 /// SessionCtx after it consumes a CHANNEL_DATA payload. 1774 fn maybeRefillRecvWindow( 1775 io: std.Io, 1776 allocator: std.mem.Allocator, 1777 sc_cipher: *Cipher, 1778 writer: *std.Io.Writer, 1779 ch: *Channel, 1780 ) !void { 1781 if (ch.local_window >= initial_recv_window / 2) return; 1782 const add = initial_recv_window - ch.local_window; 1783 ch.local_window += add; 1784 var adj: std.ArrayList(u8) = .empty; 1785 defer adj.deinit(allocator); 1786 try adj.append(allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 1787 try writeU32(&adj, allocator, ch.remote_id); 1788 try writeU32(&adj, allocator, add); 1789 try sc_cipher.writePacket(io, allocator, writer, adj.items); 1790 } 1791 1792 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 1793 var bytes: [4]u8 = undefined; 1794 std.mem.writeInt(u32, &bytes, value, .big); 1795 try buf.appendSlice(allocator, &bytes); 1796 } 1797