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