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