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