╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1519 deriveKey(prefix.items, 'C', session_id, &out.cs_enc); 1520 deriveKey(prefix.items, 'D', session_id, &out.sc_enc); 1521 } 1522 1523 fn deriveKey( 1524 prefix: []const u8, // K || H, already encoded 1525 letter: u8, 1526 session_id: []const u8, 1527 out: *[2 * Sha256.digest_length]u8, 1528 ) void { 1529 // a finished context still holds its digest and last input block 1530 // K_1 = HASH(K || H || letter || session_id) 1531 var first = Sha256.init(.{}); 1532 defer std.crypto.secureZero(u8, std.mem.asBytes(&first)); 1533 first.update(prefix); 1534 first.update(&.{letter}); 1535 first.update(session_id); 1536 first.final(out[0..Sha256.digest_length]); 1537 1538 // K_2 = HASH(K || H || K_1) 1539 var second = Sha256.init(.{}); 1540 defer std.crypto.secureZero(u8, std.mem.asBytes(&second)); 1541 second.update(prefix); 1542 second.update(out[0..Sha256.digest_length]); 1543 second.final(out[Sha256.digest_length..]); 1544 } 1545 1546 // --------------------------------------------------------------------------- 1547 // chacha20-poly1305@openssh.com packet codec 1548 // --------------------------------------------------------------------------- 1549 // 1550 // per openssh's PROTOCOL.chacha20poly1305: 1551 // K_2 = first 32 bytes of key material — encrypts the packet body 1552 // K_1 = next 32 bytes — encrypts the 4-byte length field 1553 // nonce = 64-bit big-endian sequence number 1554 // body = chacha20(K_2, nonce, counter=1) XOR plaintext_body 1555 // length = chacha20(K_1, nonce, counter=0) XOR length_uint32_be 1556 // mac = poly1305(poly_key, encrypted_length || encrypted_body) 1557 // where poly_key = chacha20(K_2, nonce, counter=0)[0..32] 1558 // 1559 // padding is computed on the body alone (padding_length byte + payload + 1560 // padding) — the 4-byte length field is excluded from alignment. body must 1561 // be a multiple of 8 bytes; minimum padding 4 bytes. 1562 1563 pub const Cipher = struct { 1564 main_key: [32]u8, // K_2 1565 header_key: [32]u8, // K_1 1566 // wider than the 32-bit wire seqno, so a peer that never rekeys fails the 1567 // mac at 2^32 packets instead of wrapping into nonce reuse 1568 seq: u64, 1569 1570 pub fn init(key_material: *const [64]u8, initial_seq: u64) Cipher { 1571 return .{ 1572 .main_key = key_material[0..32].*, 1573 .header_key = key_material[32..64].*, 1574 .seq = initial_seq, 1575 }; 1576 } 1577 1578 /// swap in new key material after a rekey, leaving the rest of the 1579 /// cipher state alone 1580 fn setKeys(self: *Cipher, key_material: *const [64]u8, seq: u64) void { 1581 self.main_key = key_material[0..32].*; 1582 self.header_key = key_material[32..64].*; 1583 self.seq = seq; 1584 } 1585 1586 fn makeNonce(seq: u64) [8]u8 { 1587 var nonce: [8]u8 = undefined; 1588 std.mem.writeInt(u64, &nonce, seq, .big); 1589 return nonce; 1590 } 1591 1592 fn bodyLength(self: *const Cipher, enc_length: *const [4]u8) !u32 { 1593 var plain: [4]u8 = undefined; 1594 ChaCha20.xor(&plain, enc_length, 0, self.header_key, makeNonce(self.seq)); 1595 const len = std.mem.readInt(u32, &plain, .big); 1596 if (len < 8 or len > max_packet_len or len % 8 != 0) return error.InvalidPacketLength; 1597 return len; 1598 } 1599 1600 fn peekPacket(self: *const Cipher, reader: *std.Io.Reader) !void { 1601 const len = 4 + (try self.bodyLength(try reader.peekArray(4))) + Poly1305.mac_length; 1602 if (len > reader.buffer.len) return error.ReadBufferTooSmall; 1603 _ = try reader.peek(len); 1604 } 1605 1606 fn hasBufferedPacket(self: *const Cipher, reader: *std.Io.Reader) !bool { 1607 const bytes = reader.buffered(); 1608 if (bytes.len < 4) return false; 1609 return bytes.len >= 4 + (try self.bodyLength(bytes[0..4])) + Poly1305.mac_length; 1610 } 1611 1612 /// the payload is the concatenation of `parts` 1613 pub fn writePacket( 1614 self: *Cipher, 1615 io: std.Io, 1616 writer: *std.Io.Writer, 1617 parts: []const []const u8, 1618 ) !void { 1619 var payload_len: usize = 0; 1620 for (parts) |part| payload_len += part.len; 1621 1622 const block: usize = 8; 1623 const initial_pad = block - ((1 + payload_len) % block); 1624 const padding_len: u8 = @intCast(if (initial_pad < 4) initial_pad + block else initial_pad); 1625 const body_len = 1 + payload_len + padding_len; 1626 if (body_len > max_packet_len) return error.PacketTooLarge; 1627 1628 const nonce = makeNonce(self.seq); 1629 1630 // encrypted length || body || mac, contiguous so the packet goes out 1631 // in one write. stack-allocated to avoid a heap alloc on every packet. 1632 var packet_buf: [packet_buffer_size]u8 = undefined; 1633 const packet = packet_buf[0 .. 4 + body_len + Poly1305.mac_length]; 1634 const enc_length = packet[0..4]; 1635 const body = packet[4..][0..body_len]; 1636 1637 // plaintext body = padding_length || payload || random padding 1638 body[0] = padding_len; 1639 var end: usize = 1; 1640 for (parts) |part| { 1641 @memcpy(body[end..][0..part.len], part); 1642 end += part.len; 1643 } 1644 io.random(body[end..]); 1645 1646 // encrypt body in place with counter=1 1647 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1648 1649 // encrypt length field with header key, counter=0 1650 std.mem.writeInt(u32, enc_length, @intCast(body_len), .big); 1651 ChaCha20.xor(enc_length, enc_length, 0, self.header_key, nonce); 1652 1653 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1654 var poly_key: [Poly1305.key_length]u8 = undefined; 1655 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1656 1657 // mac over encrypted_length || encrypted_body 1658 var poly = Poly1305.init(&poly_key); 1659 poly.update(packet[0 .. 4 + body_len]); 1660 poly.final(packet[4 + body_len ..][0..Poly1305.mac_length]); 1661 1662 try writer.writeAll(packet); 1663 try writer.flush(); 1664 1665 self.seq += 1; 1666 } 1667 1668 pub fn readPacket( 1669 self: *Cipher, 1670 allocator: std.mem.Allocator, 1671 reader: *std.Io.Reader, 1672 ) ![]u8 { 1673 const nonce = makeNonce(self.seq); 1674 1675 var enc_length: [4]u8 = undefined; 1676 try reader.readSliceAll(&enc_length); 1677 1678 const body_len = try self.bodyLength(&enc_length); 1679 1680 // the body allocation becomes the returned payload, so a packet only 1681 // ever costs one allocation 1682 const body = try allocator.alloc(u8, body_len); 1683 errdefer allocator.free(body); 1684 try reader.readSliceAll(body); 1685 1686 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1687 try reader.readSliceAll(&tag_recv); 1688 1689 var poly_key: [Poly1305.key_length]u8 = undefined; 1690 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1691 1692 var poly = Poly1305.init(&poly_key); 1693 poly.update(&enc_length); 1694 poly.update(body); 1695 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1696 poly.final(&tag_computed); 1697 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1698 return error.MacVerificationFailed; 1699 } 1700 1701 // decrypt the body in place 1702 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1703 1704 const padding_len = body[0]; 1705 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1706 const payload_len = body_len - 1 - @as(u32, padding_len); 1707 1708 // shift the payload over the padding_length byte, then release the 1709 // trailing padding (caller owns the result) 1710 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1711 const payload = try allocator.realloc(body, payload_len); 1712 1713 self.seq += 1; 1714 return payload; 1715 } 1716 }; 1717 1718 // --------------------------------------------------------------------------- 1719 // post-KEX: service request + user authentication (RFC 4252) 1720 // --------------------------------------------------------------------------- 1721 1722 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1723 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1724 /// `Offering public key: … SHA256:…`. 1725 pub const fingerprint_len = 50; 1726 1727 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1728 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1729 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1730 var digest: [Sha256.digest_length]u8 = undefined; 1731 Sha256.hash(pubkey_blob, &digest, .{}); 1732 1733 var out: [fingerprint_len]u8 = undefined; 1734 @memcpy(out[0..7], "SHA256:"); 1735 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1736 std.debug.assert(encoded.len == fingerprint_len - 7); 1737 return out; 1738 } 1739 1740 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1741 const allocator = conn.allocator; 1742 1743 // step 1: service request for ssh-userauth → service accept 1744 { 1745 const req = try readSessionPacket(conn); 1746 defer allocator.free(req); 1747 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1748 1749 var req_reader = std.Io.Reader.fixed(req[1..]); 1750 const service = try takeString(&req_reader, 64); 1751 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1752 1753 var accept: std.ArrayList(u8) = .empty; 1754 defer accept.deinit(allocator); 1755 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1756 try writeStringField(&accept, allocator, "ssh-userauth"); 1757 try conn.writePacket(&.{accept.items}); 1758 } 1759 1760 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1761 // signature verifies against the offered pubkey. 1762 var auth_attempts: u32 = 0; 1763 while (true) { 1764 const req = try readSessionPacket(conn); 1765 defer allocator.free(req); 1766 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1767 1768 // every request counts, probes included, so a client can't loop here 1769 // forever 1770 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1771 auth_attempts += 1; 1772 1773 var req_reader = std.Io.Reader.fixed(req[1..]); 1774 const user_name = try takeString(&req_reader, 256); 1775 const service_name = try takeString(&req_reader, 64); 1776 const method = try takeString(&req_reader, 64); 1777 1778 // RFC 4252 §5: the server must verify the requested service 1779 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1780 try sendUserauthFailure(conn); 1781 continue; 1782 } 1783 1784 if (!std.mem.eql(u8, method, "publickey")) { 1785 try sendUserauthFailure(conn); 1786 continue; 1787 } 1788 1789 const has_signature = (try req_reader.takeByte()) != 0; 1790 const algo = try takeString(&req_reader, 64); 1791 const pubkey_blob = try takeString(&req_reader, 4096); 1792 1793 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1794 try sendUserauthFailure(conn); 1795 continue; 1796 } 1797 1798 if (!has_signature) { 1799 // probe — tell the client this key is acceptable so it'll send 1800 // the signed version next. 1801 var pk_ok: std.ArrayList(u8) = .empty; 1802 defer pk_ok.deinit(allocator); 1803 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1804 try writeStringField(&pk_ok, allocator, algo); 1805 try writeStringField(&pk_ok, allocator, pubkey_blob); 1806 try conn.writePacket(&.{pk_ok.items}); 1807 continue; 1808 } 1809 1810 // has signature — verify it 1811 const signature_blob = try takeString(&req_reader, 1024); 1812 1813 const ok = verifyUserauthSignature( 1814 allocator, 1815 &conn.rekey.session_id, 1816 user_name, 1817 service_name, 1818 algo, 1819 pubkey_blob, 1820 signature_blob, 1821 ) catch |err| switch (err) { 1822 error.OutOfMemory => return err, 1823 // a malformed key or signature blob 1824 else => false, 1825 }; 1826 1827 if (!ok) { 1828 try sendUserauthFailure(conn); 1829 continue; 1830 } 1831 1832 try conn.writePacket(&.{&[_]u8{SSH_MSG_USERAUTH_SUCCESS}}); 1833 return formatFingerprint(pubkey_blob); 1834 } 1835 } 1836 1837 fn sendUserauthFailure(conn: *Conn) !void { 1838 var buf: std.ArrayList(u8) = .empty; 1839 defer buf.deinit(conn.allocator); 1840 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1841 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1842 try buf.append(conn.allocator, 0); // partial_success = false 1843 try conn.writePacket(&.{buf.items}); 1844 } 1845 1846 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1847 /// used by the server to recompute the signed input for verification 1848 pub fn appendPublickeySignedData( 1849 buf: *std.ArrayList(u8), 1850 allocator: std.mem.Allocator, 1851 session_id: []const u8, 1852 user_name: []const u8, 1853 service_name: []const u8, 1854 algo: []const u8, 1855 pubkey_blob: []const u8, 1856 ) !void { 1857 try writeStringField(buf, allocator, session_id); 1858 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1859 try writeStringField(buf, allocator, user_name); 1860 try writeStringField(buf, allocator, service_name); 1861 try writeStringField(buf, allocator, "publickey"); 1862 try buf.append(allocator, 1); 1863 try writeStringField(buf, allocator, algo); 1864 try writeStringField(buf, allocator, pubkey_blob); 1865 } 1866 1867 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1868 // verify the supplied signature against them. 1869 fn verifyUserauthSignature( 1870 allocator: std.mem.Allocator, 1871 session_id: *const [Sha256.digest_length]u8, 1872 user_name: []const u8, 1873 service_name: []const u8, 1874 algo: []const u8, 1875 pubkey_blob: []const u8, 1876 signature_blob: []const u8, 1877 ) !bool { 1878 var signed: std.ArrayList(u8) = .empty; 1879 defer signed.deinit(allocator); 1880 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1881 1882 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1883 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1884 const pk_algo = try takeString(&pubkey_reader, 64); 1885 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1886 const raw_pubkey = try takeString(&pubkey_reader, 64); 1887 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1888 1889 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1890 var sig_reader = std.Io.Reader.fixed(signature_blob); 1891 const sig_algo = try takeString(&sig_reader, 64); 1892 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1893 const raw_sig = try takeString(&sig_reader, Ed25519.Signature.encoded_length); 1894 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1895 1896 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1897 @memcpy(&pubkey_bytes, raw_pubkey); 1898 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1899 @memcpy(&sig_bytes, raw_sig); 1900 1901 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1902 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1903 sig.verify(signed.items, pk) catch return false; 1904 return true; 1905 } 1906 1907 // --------------------------------------------------------------------------- 1908 // connection layer (RFC 4254): channels, requests, data, flow control 1909 // --------------------------------------------------------------------------- 1910 1911 const Channel = struct { 1912 local_id: u32, 1913 remote_id: u32, 1914 local_window: u32, // bytes peer may still send us before we adjust 1915 remote_window: u32, // bytes we may still send to peer before they adjust 1916 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1917 pty: ?PtySize = null, 1918 // value of GIT_PROTOCOL, the one env variable we keep 1919 git_protocol_buf: [64]u8 = undefined, 1920 git_protocol_len: ?usize = null, 1921 }; 1922 1923 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1924 1925 // take the uint32 width/height cell counts of a pty-req or window-change, 1926 // bounded before either initial rendering or a resize can allocate grids. 1927 // keep zero dimensions intact (unspecified at startup, minimized on resize). 1928 fn takePtySize(r: *std.Io.Reader) !PtySize { 1929 const width = @min(try r.takeInt(u32, .big), max_pty_width); 1930 const height = @min(try r.takeInt(u32, .big), max_pty_height); 1931 return .{ 1932 .width_cells = @intCast(width), 1933 .height_cells = @intCast(height), 1934 }; 1935 } 1936 1937 fn runChannelLayer( 1938 conn: *Conn, 1939 fingerprint: *const [fingerprint_len]u8, 1940 handler: anytype, 1941 ) !void { 1942 const allocator = conn.allocator; 1943 var channel: ?Channel = null; 1944 1945 while (true) { 1946 const packet = try readSessionPacket(conn); 1947 defer allocator.free(packet); 1948 if (packet.len < 1) return error.EmptyPacket; 1949 const msg_type = packet[0]; 1950 1951 switch (msg_type) { 1952 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1953 1954 SSH_MSG_CHANNEL_OPEN => { 1955 if (channel != null) { 1956 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1957 continue; 1958 } 1959 channel = try handleChannelOpen(conn, packet) orelse continue; 1960 }, 1961 1962 SSH_MSG_CHANNEL_REQUEST => { 1963 const ch = if (channel) |*c| c else continue; 1964 const start_request = try handleChannelRequest(conn, ch, packet); 1965 // the request borrows from the packet, which outlives the session 1966 if (start_request) |request| { 1967 // any key authenticates, so the deadline holds until here 1968 if (conn.idle) |idle| idle.session_started.store(true, .release); 1969 var sess = SessionCtx{ 1970 .conn = conn, 1971 .channel = ch, 1972 .fingerprint = fingerprint.*, 1973 }; 1974 defer sess.deinit(); 1975 handler.handleSession(&sess, request) catch |session_err| { 1976 // try to send a non-zero exit status before closing 1977 sess.exit(1) catch {}; 1978 return sess.underlyingError(session_err); 1979 }; 1980 if (!sess.closed) try sess.exit(0); 1981 return; 1982 } 1983 }, 1984 1985 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1986 const ch = if (channel) |*c| c else continue; 1987 try handleWindowAdjust(ch, packet); 1988 }, 1989 1990 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1991 const ch = if (channel) |*c| c else continue; 1992 // before shell/exec the client shouldn't be sending data, but 1993 // some clients are chatty; discard and refill window. nothing 1994 // is buffered yet, so the whole window is available to credit. 1995 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1996 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1997 }, 1998 1999 SSH_MSG_CHANNEL_EOF => { 2000 if (channel) |*c| try parseChannelId(packet, c.local_id); 2001 }, 2002 2003 SSH_MSG_CHANNEL_CLOSE => { 2004 if (channel) |*c| { 2005 try parseChannelId(packet, c.local_id); 2006 try sendChannelMessage(conn, c, SSH_MSG_CHANNEL_CLOSE); 2007 drainConnection(conn); 2008 } 2009 return; 2010 }, 2011 2012 // RFC 4252 §5.1: silently ignored once authenticated 2013 SSH_MSG_USERAUTH_REQUEST => {}, 2014 else => try sendUnimplemented(conn), 2015 } 2016 } 2017 } 2018 2019 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 2020 // byte SSH_MSG_GLOBAL_REQUEST 2021 // string request_name 2022 // boolean want_reply 2023 // …request-specific data we ignore 2024 var r = std.Io.Reader.fixed(packet[1..]); 2025 _ = try takeString(&r, 256); 2026 const want_reply = (try r.takeByte()) != 0; 2027 if (want_reply) { 2028 try conn.writePacket(&.{&[_]u8{SSH_MSG_REQUEST_FAILURE}}); 2029 } 2030 } 2031 2032 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 2033 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 2034 /// return null. 2035 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 2036 const allocator = conn.allocator; 2037 2038 // byte SSH_MSG_CHANNEL_OPEN 2039 // string channel_type 2040 // uint32 sender_channel (peer's id) 2041 // uint32 initial_window 2042 // uint32 max_packet 2043 var r = std.Io.Reader.fixed(packet[1..]); 2044 const ch_type = try takeString(&r, 64); 2045 const remote_id = try r.takeInt(u32, .big); 2046 const initial_window = try r.takeInt(u32, .big); 2047 const max_packet = try r.takeInt(u32, .big); 2048 2049 if (!std.mem.eql(u8, ch_type, "session")) { 2050 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 2051 return null; 2052 } 2053 2054 // a zero max_packet would leave writeChannel looping without progress 2055 if (max_packet == 0) { 2056 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 2057 return null; 2058 } 2059 2060 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 2061 var reply: std.ArrayList(u8) = .empty; 2062 defer reply.deinit(allocator); 2063 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 2064 try writeU32(&reply, allocator, remote_id); 2065 try writeU32(&reply, allocator, local_id); 2066 try writeU32(&reply, allocator, initial_recv_window); 2067 try writeU32(&reply, allocator, max_packet_size); 2068 try conn.writePacket(&.{reply.items}); 2069 2070 return .{ 2071 .local_id = local_id, 2072 .remote_id = remote_id, 2073 .local_window = initial_recv_window, 2074 .remote_window = initial_window, 2075 .max_packet = max_packet, 2076 }; 2077 } 2078 2079 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 2080 const allocator = conn.allocator; 2081 2082 // recover the sender_channel field from the CHANNEL_OPEN packet so we 2083 // address the failure to the correct id 2084 var r = std.Io.Reader.fixed(open_packet[1..]); 2085 const ch_type_len = try r.takeInt(u32, .big); 2086 try r.discardAll(ch_type_len); 2087 const remote_id = try r.takeInt(u32, .big); 2088 2089 var reply: std.ArrayList(u8) = .empty; 2090 defer reply.deinit(allocator); 2091 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 2092 try writeU32(&reply, allocator, remote_id); 2093 try writeU32(&reply, allocator, reason); 2094 try writeStringField(&reply, allocator, description); 2095 try writeStringField(&reply, allocator, ""); // language tag 2096 try conn.writePacket(&.{reply.items}); 2097 } 2098 2099 /// returns the session request if this one triggered it, else null. an exec 2100 /// command borrows from `packet`. 2101 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8) !?Request { 2102 // byte SSH_MSG_CHANNEL_REQUEST 2103 // uint32 recipient_channel (== our local_id) 2104 // string request_type 2105 // boolean want_reply 2106 // …request-specific data 2107 var r = std.Io.Reader.fixed(packet[1..]); 2108 const recipient_channel = try r.takeInt(u32, .big); 2109 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2110 const req_type = try takeString(&r, 64); 2111 const want_reply = (try r.takeByte()) != 0; 2112 2113 if (std.mem.eql(u8, req_type, "pty-req")) { 2114 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 2115 // uint32 height px, string modes 2116 _ = try takeString(&r, 64); 2117 ch.pty = try takePtySize(&r); 2118 try replyChannelRequest(conn, ch, want_reply, true); 2119 return null; 2120 } 2121 2122 if (std.mem.eql(u8, req_type, "env")) { 2123 // string name, string value. the rest are ignored silently. 2124 const name = try takeString(&r, max_packet_len); 2125 const value = try takeString(&r, max_packet_len); 2126 if (std.mem.eql(u8, name, "GIT_PROTOCOL") and value.len <= ch.git_protocol_buf.len) { 2127 @memcpy(ch.git_protocol_buf[0..value.len], value); 2128 ch.git_protocol_len = value.len; 2129 } 2130 try replyChannelRequest(conn, ch, want_reply, true); 2131 return null; 2132 } 2133 2134 if (std.mem.eql(u8, req_type, "window-change")) { 2135 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 2136 const sz = try takePtySize(&r); 2137 if (ch.pty != null) ch.pty = sz; 2138 // spec: window-change MUST NOT request a reply, but accept either 2139 try replyChannelRequest(conn, ch, want_reply, true); 2140 return null; 2141 } 2142 2143 if (std.mem.eql(u8, req_type, "shell")) { 2144 try replyChannelRequest(conn, ch, want_reply, true); 2145 return .{ .shell = ch.pty }; 2146 } 2147 2148 if (std.mem.eql(u8, req_type, "exec")) { 2149 // capture the command string for the handler to inspect 2150 const cmd = try takeString(&r, 4096); 2151 try replyChannelRequest(conn, ch, want_reply, true); 2152 return .{ .exec = .{ 2153 .command = cmd, 2154 .git_protocol = if (ch.git_protocol_len) |len| ch.git_protocol_buf[0..len] else null, 2155 } }; 2156 } 2157 2158 // unknown request kind — fail it 2159 try replyChannelRequest(conn, ch, want_reply, false); 2160 return null; 2161 } 2162 2163 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 2164 if (!want_reply) return; 2165 try sendChannelMessage(conn, ch, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 2166 } 2167 2168 fn sendChannelMessage(conn: *Conn, ch: *Channel, msg_type: u8) !void { 2169 var packet: [5]u8 = undefined; 2170 packet[0] = msg_type; 2171 std.mem.writeInt(u32, packet[1..5], ch.remote_id, .big); 2172 try conn.writePacket(&.{&packet}); 2173 } 2174 2175 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 2176 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 2177 // uint32 recipient_channel 2178 // uint32 bytes_to_add 2179 var r = std.Io.Reader.fixed(packet[1..]); 2180 const recipient_channel = try r.takeInt(u32, .big); 2181 if (recipient_channel != ch.local_id) return error.UnknownChannel; 2182 const add = try r.takeInt(u32, .big); 2183 ch.remote_window +|= add; 2184 } 2185 2186 // charge a payload's bytes against the receive window without keeping them. 2187 // the caller credits the window back, choosing the budget that suits it. 2188 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 2189 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 2190 // uint32 recipient_channel 2191 // [if extended: uint32 type_code] 2192 // string data 2193 const payload = try parseChannelData(packet, extended, ch.local_id); 2194 const data_len: u32 = @intCast(payload.len); 2195 2196 if (data_len > ch.local_window) return error.WindowExceeded; 2197 ch.local_window -= data_len; 2198 } 2199 2200 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 2201 if (packet.len < 1) return error.EmptyPacket; 2202 var r = std.Io.Reader.fixed(packet[1..]); 2203 const recipient_channel = try r.takeInt(u32, .big); 2204 if (recipient_channel != expected_channel) return error.UnknownChannel; 2205 if (extended) { 2206 const data_type = try r.takeInt(u32, .big); 2207 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 2208 } 2209 const data_len = try r.takeInt(u32, .big); 2210 // catches both data_len > remaining (would otherwise be a bounds-check 2211 // panic on the slice) and trailing junk after the declared payload. 2212 if (data_len != r.buffered().len) return error.InvalidChannelData; 2213 return r.buffered(); 2214 } 2215 2216 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 2217 if (packet.len < 1) return error.EmptyPacket; 2218 var r = std.Io.Reader.fixed(packet[1..]); 2219 const recipient_channel = try r.takeInt(u32, .big); 2220 if (recipient_channel != expected_channel) return error.UnknownChannel; 2221 if (r.buffered().len != 0) return error.InvalidChannelMessage; 2222 } 2223 2224 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 2225 /// of `budget`, the credit we're willing to have outstanding. used both for 2226 /// the pre-session discard path and by SessionCtx after it consumes a 2227 /// CHANNEL_DATA payload. 2228 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2229 if (ch.local_window >= budget / 2) return; 2230 const add = budget - ch.local_window; 2231 ch.local_window += add; 2232 var adj: std.ArrayList(u8) = .empty; 2233 defer adj.deinit(conn.allocator); 2234 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2235 try writeU32(&adj, conn.allocator, ch.remote_id); 2236 try writeU32(&adj, conn.allocator, add); 2237 try conn.writePacket(&.{adj.items}); 2238 } 2239 2240 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2241 var bytes: [4]u8 = undefined; 2242 std.mem.writeInt(u32, &bytes, value, .big); 2243 try buf.appendSlice(allocator, &bytes); 2244 } 2245 2246 test "pty dimensions have bounded axes, preserving normal and zero sizes" { 2247 for ([_]struct { width: u32, height: u32, expected: PtySize }{ 2248 .{ .width = 80, .height = 24, .expected = .{ .width_cells = 80, .height_cells = 24 } }, 2249 .{ .width = 0, .height = 0, .expected = .{ .width_cells = 0, .height_cells = 0 } }, 2250 .{ .width = 0xffffffff, .height = 0xffffffff, .expected = .{ .width_cells = 512, .height_cells = 128 } }, 2251 }) |case| { 2252 var bytes: [8]u8 = undefined; 2253 std.mem.writeInt(u32, bytes[0..4], case.width, .big); 2254 std.mem.writeInt(u32, bytes[4..8], case.height, .big); 2255 var reader = std.Io.Reader.fixed(&bytes); 2256 try std.testing.expectEqual(case.expected, try takePtySize(&reader)); 2257 } 2258 } 2259 2260 test "channel close before shell or exec is acknowledged" { 2261 const io = std.testing.io; 2262 const allocator = std.testing.allocator; 2263 const key = [_]u8{0x5a} ** 64; 2264 var encoded: [256]u8 = undefined; 2265 var encoded_writer = std.Io.Writer.fixed(&encoded); 2266 var sender = Cipher.init(&key, 0); 2267 var open: std.ArrayList(u8) = .empty; 2268 defer open.deinit(allocator); 2269 try open.append(allocator, SSH_MSG_CHANNEL_OPEN); 2270 try writeStringField(&open, allocator, "session"); 2271 try writeU32(&open, allocator, 7); 2272 try writeU32(&open, allocator, 32768); 2273 try writeU32(&open, allocator, 32768); 2274 try sender.writePacket(io, &encoded_writer, &.{open.items}); 2275 try sender.writePacket(io, &encoded_writer, &.{&.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 0 }}); 2276 var reader = std.Io.Reader.fixed(encoded_writer.buffered()); 2277 var output: [256]u8 = undefined; 2278 var writer = std.Io.Writer.fixed(&output); 2279 var conn = Conn{ 2280 .io = io, 2281 .allocator = allocator, 2282 .reader = &reader, 2283 .writer = &writer, 2284 .cs_cipher = Cipher.init(&key, 0), 2285 .sc_cipher = Cipher.init(&key, 0), 2286 .rekey = undefined, 2287 }; 2288 const Handler = struct { 2289 pub fn handleSession(_: *@This(), _: *SessionCtx, _: Request) !void { 2290 return error.UnexpectedSession; 2291 } 2292 }; 2293 var handler = Handler{}; 2294 try runChannelLayer(&conn, &([_]u8{0} ** fingerprint_len), &handler); 2295 var output_reader = std.Io.Reader.fixed(writer.buffered()); 2296 var receiver = Cipher.init(&key, 0); 2297 const confirmation = try receiver.readPacket(allocator, &output_reader); 2298 defer allocator.free(confirmation); 2299 try std.testing.expectEqual(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, confirmation[0]); 2300 const close = try receiver.readPacket(allocator, &output_reader); 2301 defer allocator.free(close); 2302 try std.testing.expectEqualSlices(u8, &.{ SSH_MSG_CHANNEL_CLOSE, 0, 0, 0, 7 }, close); 2303 try std.testing.expectEqual(0, output_reader.buffered().len); 2304 } 2305