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