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