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