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