╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ serve_ssh_protocol.zig ───────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1401 // plaintext body = padding_length || payload || random padding. 1402 // stack-allocated to avoid a heap alloc on every packet. 1403 var body_buf: [max_packet_len]u8 = undefined; 1404 if (body_len > body_buf.len) return error.PacketTooLarge; 1405 const body = body_buf[0..body_len]; 1406 body[0] = padding_len; 1407 @memcpy(body[1 .. 1 + payload.len], payload); 1408 io.random(body[1 + payload.len ..]); 1409 1410 // encrypt body in place with counter=1 1411 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1412 1413 // encrypt length field with header key, counter=0 1414 var enc_length: [4]u8 = undefined; 1415 var length_plain: [4]u8 = undefined; 1416 std.mem.writeInt(u32, &length_plain, body_len, .big); 1417 ChaCha20.xor(&enc_length, &length_plain, 0, self.header_key, nonce); 1418 1419 // poly1305 key = first 32 bytes of chacha20(K_2, nonce, counter=0) 1420 var poly_key: [Poly1305.key_length]u8 = undefined; 1421 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1422 1423 // mac over encrypted_length || encrypted_body 1424 var poly = Poly1305.init(&poly_key); 1425 poly.update(&enc_length); 1426 poly.update(body); 1427 var tag: [Poly1305.mac_length]u8 = undefined; 1428 poly.final(&tag); 1429 1430 try writer.writeAll(&enc_length); 1431 try writer.writeAll(body); 1432 try writer.writeAll(&tag); 1433 try writer.flush(); 1434 1435 self.seq += 1; 1436 } 1437 1438 pub fn readPacket( 1439 self: *Cipher, 1440 allocator: std.mem.Allocator, 1441 reader: *std.Io.Reader, 1442 ) ![]u8 { 1443 const nonce = makeNonce(self.seq); 1444 1445 var enc_length: [4]u8 = undefined; 1446 try reader.readSliceAll(&enc_length); 1447 1448 var length_plain: [4]u8 = undefined; 1449 ChaCha20.xor(&length_plain, &enc_length, 0, self.header_key, nonce); 1450 const body_len = std.mem.readInt(u32, &length_plain, .big); 1451 if (body_len < 8 or body_len > max_packet_len or body_len % 8 != 0) return error.InvalidPacketLength; 1452 1453 // the body allocation becomes the returned payload, so a packet only 1454 // ever costs one allocation 1455 const body = try allocator.alloc(u8, body_len); 1456 errdefer allocator.free(body); 1457 try reader.readSliceAll(body); 1458 1459 var tag_recv: [Poly1305.mac_length]u8 = undefined; 1460 try reader.readSliceAll(&tag_recv); 1461 1462 var poly_key: [Poly1305.key_length]u8 = undefined; 1463 ChaCha20.stream(&poly_key, 0, self.main_key, nonce); 1464 1465 var poly = Poly1305.init(&poly_key); 1466 poly.update(&enc_length); 1467 poly.update(body); 1468 var tag_computed: [Poly1305.mac_length]u8 = undefined; 1469 poly.final(&tag_computed); 1470 if (!std.crypto.timing_safe.eql([Poly1305.mac_length]u8, tag_recv, tag_computed)) { 1471 return error.MacVerificationFailed; 1472 } 1473 1474 // decrypt the body in place 1475 ChaCha20.xor(body, body, 1, self.main_key, nonce); 1476 1477 const padding_len = body[0]; 1478 if (padding_len < 4 or 1 + @as(u32, padding_len) > body_len) return error.InvalidPadding; 1479 const payload_len = body_len - 1 - @as(u32, padding_len); 1480 1481 // shift the payload over the padding_length byte, then release the 1482 // trailing padding (caller owns the result) 1483 std.mem.copyForwards(u8, body[0..payload_len], body[1 .. 1 + payload_len]); 1484 const payload = try allocator.realloc(body, payload_len); 1485 1486 self.seq += 1; 1487 return payload; 1488 } 1489 }; 1490 1491 // --------------------------------------------------------------------------- 1492 // post-KEX: service request + user authentication (RFC 4252) 1493 // --------------------------------------------------------------------------- 1494 1495 /// "SHA256:" (7 bytes) + base64-no-padding of a 32-byte SHA256 digest 1496 /// (43 bytes) = 50 bytes. matches what openssh's client logs as 1497 /// `Offering public key: … SHA256:…`. 1498 pub const fingerprint_len = 50; 1499 1500 /// hash the SSH wire-format pubkey blob (`string algo` + `string raw_key`) 1501 /// the same way openssh does for `ssh-keygen -lf` / authorized-key logs. 1502 pub fn formatFingerprint(pubkey_blob: []const u8) [fingerprint_len]u8 { 1503 var digest: [Sha256.digest_length]u8 = undefined; 1504 Sha256.hash(pubkey_blob, &digest, .{}); 1505 1506 var out: [fingerprint_len]u8 = undefined; 1507 @memcpy(out[0..7], "SHA256:"); 1508 const encoded = std.base64.standard_no_pad.Encoder.encode(out[7..], &digest); 1509 std.debug.assert(encoded.len == fingerprint_len - 7); 1510 return out; 1511 } 1512 1513 fn runAuth(conn: *Conn) ![fingerprint_len]u8 { 1514 const allocator = conn.allocator; 1515 1516 // step 1: service request for ssh-userauth → service accept 1517 { 1518 const req = try readSessionPacket(conn); 1519 defer allocator.free(req); 1520 if (req.len < 1 or req[0] != SSH_MSG_SERVICE_REQUEST) return error.UnexpectedMessage; 1521 1522 var req_reader = std.Io.Reader.fixed(req[1..]); 1523 const service = try takeStringField(allocator, &req_reader, 64); 1524 defer allocator.free(service); 1525 if (!std.mem.eql(u8, service, "ssh-userauth")) return error.UnsupportedService; 1526 1527 var accept: std.ArrayList(u8) = .empty; 1528 defer accept.deinit(allocator); 1529 try accept.append(allocator, SSH_MSG_SERVICE_ACCEPT); 1530 try writeStringField(&accept, allocator, "ssh-userauth"); 1531 try conn.sc_cipher.writePacket(conn.io, conn.writer, accept.items); 1532 } 1533 1534 // step 2: USERAUTH loop until SUCCESS. accept any ed25519 key whose 1535 // signature verifies against the offered pubkey. 1536 var auth_attempts: u32 = 0; 1537 while (true) { 1538 const req = try readSessionPacket(conn); 1539 defer allocator.free(req); 1540 if (req.len < 1 or req[0] != SSH_MSG_USERAUTH_REQUEST) return error.UnexpectedMessage; 1541 1542 var req_reader = std.Io.Reader.fixed(req[1..]); 1543 const user_name = try takeStringField(allocator, &req_reader, 256); 1544 defer allocator.free(user_name); 1545 const service_name = try takeStringField(allocator, &req_reader, 64); 1546 defer allocator.free(service_name); 1547 const method = try takeStringField(allocator, &req_reader, 64); 1548 defer allocator.free(method); 1549 1550 // RFC 4252 §5: the server must verify the requested service 1551 if (!std.mem.eql(u8, service_name, "ssh-connection")) { 1552 auth_attempts += 1; 1553 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1554 try sendUserauthFailure(conn); 1555 continue; 1556 } 1557 1558 if (!std.mem.eql(u8, method, "publickey")) { 1559 auth_attempts += 1; 1560 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1561 try sendUserauthFailure(conn); 1562 continue; 1563 } 1564 1565 const has_signature = (try req_reader.takeByte()) != 0; 1566 const algo = try takeStringField(allocator, &req_reader, 64); 1567 defer allocator.free(algo); 1568 const pubkey_blob = try takeStringField(allocator, &req_reader, 4096); 1569 defer allocator.free(pubkey_blob); 1570 1571 if (!std.mem.eql(u8, algo, "ssh-ed25519")) { 1572 auth_attempts += 1; 1573 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1574 try sendUserauthFailure(conn); 1575 continue; 1576 } 1577 1578 if (!has_signature) { 1579 // probes count as attempts so a client can't loop here forever 1580 auth_attempts += 1; 1581 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1582 // probe — tell the client this key is acceptable so it'll send 1583 // the signed version next. 1584 var pk_ok: std.ArrayList(u8) = .empty; 1585 defer pk_ok.deinit(allocator); 1586 try pk_ok.append(allocator, SSH_MSG_USERAUTH_PK_OK); 1587 try writeStringField(&pk_ok, allocator, algo); 1588 try writeStringField(&pk_ok, allocator, pubkey_blob); 1589 try conn.sc_cipher.writePacket(conn.io, conn.writer, pk_ok.items); 1590 continue; 1591 } 1592 1593 // has signature — verify it 1594 const signature_blob = try takeStringField(allocator, &req_reader, 1024); 1595 defer allocator.free(signature_blob); 1596 1597 const ok = verifyUserauthSignature( 1598 allocator, 1599 &conn.rekey.session_id, 1600 user_name, 1601 service_name, 1602 algo, 1603 pubkey_blob, 1604 signature_blob, 1605 ) catch false; 1606 1607 if (!ok) { 1608 auth_attempts += 1; 1609 if (auth_attempts >= max_auth_attempts) return error.TooManyAuthAttempts; 1610 try sendUserauthFailure(conn); 1611 continue; 1612 } 1613 1614 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_USERAUTH_SUCCESS}); 1615 return formatFingerprint(pubkey_blob); 1616 } 1617 } 1618 1619 fn sendUserauthFailure(conn: *Conn) !void { 1620 var buf: std.ArrayList(u8) = .empty; 1621 defer buf.deinit(conn.allocator); 1622 try buf.append(conn.allocator, SSH_MSG_USERAUTH_FAILURE); 1623 try writeNameList(&buf, conn.allocator, &.{"publickey"}); // allowed methods 1624 try buf.append(conn.allocator, 0); // partial_success = false 1625 try conn.sc_cipher.writePacket(conn.io, conn.writer, buf.items); 1626 } 1627 1628 /// append the canonical publickey-signed-data bytes (RFC 4252 §7) to `buf`. 1629 /// used by the server to recompute the signed input for verification 1630 pub fn appendPublickeySignedData( 1631 buf: *std.ArrayList(u8), 1632 allocator: std.mem.Allocator, 1633 session_id: []const u8, 1634 user_name: []const u8, 1635 service_name: []const u8, 1636 algo: []const u8, 1637 pubkey_blob: []const u8, 1638 ) !void { 1639 try writeStringField(buf, allocator, session_id); 1640 try buf.append(allocator, SSH_MSG_USERAUTH_REQUEST); 1641 try writeStringField(buf, allocator, user_name); 1642 try writeStringField(buf, allocator, service_name); 1643 try writeStringField(buf, allocator, "publickey"); 1644 try buf.append(allocator, 1); 1645 try writeStringField(buf, allocator, algo); 1646 try writeStringField(buf, allocator, pubkey_blob); 1647 } 1648 1649 // build the bytes a publickey signature is computed over (RFC 4252 §7) and 1650 // verify the supplied signature against them. 1651 fn verifyUserauthSignature( 1652 allocator: std.mem.Allocator, 1653 session_id: *const [Sha256.digest_length]u8, 1654 user_name: []const u8, 1655 service_name: []const u8, 1656 algo: []const u8, 1657 pubkey_blob: []const u8, 1658 signature_blob: []const u8, 1659 ) !bool { 1660 var signed: std.ArrayList(u8) = .empty; 1661 defer signed.deinit(allocator); 1662 try appendPublickeySignedData(&signed, allocator, session_id, user_name, service_name, algo, pubkey_blob); 1663 1664 // parse pubkey_blob: string "ssh-ed25519" || string raw_pubkey 1665 var pubkey_reader = std.Io.Reader.fixed(pubkey_blob); 1666 const pk_algo = try takeStringField(allocator, &pubkey_reader, 64); 1667 defer allocator.free(pk_algo); 1668 if (!std.mem.eql(u8, pk_algo, "ssh-ed25519")) return false; 1669 const raw_pubkey = try takeStringField(allocator, &pubkey_reader, 64); 1670 defer allocator.free(raw_pubkey); 1671 if (raw_pubkey.len != Ed25519.PublicKey.encoded_length) return false; 1672 1673 // parse signature_blob: string "ssh-ed25519" || string raw_signature 1674 var sig_reader = std.Io.Reader.fixed(signature_blob); 1675 const sig_algo = try takeStringField(allocator, &sig_reader, 64); 1676 defer allocator.free(sig_algo); 1677 if (!std.mem.eql(u8, sig_algo, "ssh-ed25519")) return false; 1678 const raw_sig = try takeStringField(allocator, &sig_reader, Ed25519.Signature.encoded_length); 1679 defer allocator.free(raw_sig); 1680 if (raw_sig.len != Ed25519.Signature.encoded_length) return false; 1681 1682 var pubkey_bytes: [Ed25519.PublicKey.encoded_length]u8 = undefined; 1683 @memcpy(&pubkey_bytes, raw_pubkey); 1684 var sig_bytes: [Ed25519.Signature.encoded_length]u8 = undefined; 1685 @memcpy(&sig_bytes, raw_sig); 1686 1687 const pk = Ed25519.PublicKey.fromBytes(pubkey_bytes) catch return false; 1688 const sig = Ed25519.Signature.fromBytes(sig_bytes); 1689 sig.verify(signed.items, pk) catch return false; 1690 return true; 1691 } 1692 1693 // --------------------------------------------------------------------------- 1694 // connection layer (RFC 4254): channels, requests, data, flow control 1695 // --------------------------------------------------------------------------- 1696 1697 const Channel = struct { 1698 local_id: u32, 1699 remote_id: u32, 1700 local_window: u32, // bytes peer may still send us before we adjust 1701 remote_window: u32, // bytes we may still send to peer before they adjust 1702 max_packet: u32, // max CHANNEL_DATA payload the peer accepts in one packet 1703 pty: ?PtySize = null, 1704 }; 1705 1706 pub const PtySize = struct { width_cells: u16, height_cells: u16 }; 1707 1708 // take the uint32 width/height cell counts of a pty-req or window-change, 1709 // clamped to u16 1710 fn takePtySize(r: *std.Io.Reader) !PtySize { 1711 const width = try r.takeInt(u32, .big); 1712 const height = try r.takeInt(u32, .big); 1713 return .{ 1714 .width_cells = @intCast(@min(width, 0xFFFF)), 1715 .height_cells = @intCast(@min(height, 0xFFFF)), 1716 }; 1717 } 1718 1719 fn runChannelLayer( 1720 conn: *Conn, 1721 fingerprint: *const [fingerprint_len]u8, 1722 handler: anytype, 1723 ) !void { 1724 const allocator = conn.allocator; 1725 var channel: ?Channel = null; 1726 var pending_exec: ?[]u8 = null; 1727 defer if (pending_exec) |s| allocator.free(s); 1728 1729 while (true) { 1730 const packet = try readSessionPacket(conn); 1731 defer allocator.free(packet); 1732 if (packet.len < 1) return error.EmptyPacket; 1733 const msg_type = packet[0]; 1734 1735 switch (msg_type) { 1736 SSH_MSG_GLOBAL_REQUEST => try handleGlobalRequest(conn, packet), 1737 1738 SSH_MSG_CHANNEL_OPEN => { 1739 if (channel != null) { 1740 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "only one channel per connection"); 1741 continue; 1742 } 1743 channel = try handleChannelOpen(conn, packet) orelse continue; 1744 }, 1745 1746 SSH_MSG_CHANNEL_REQUEST => { 1747 const ch = if (channel) |*c| c else continue; 1748 const start_request = try handleChannelRequest(conn, ch, packet, &pending_exec); 1749 if (start_request) |request| { 1750 var sess = SessionCtx{ 1751 .conn = conn, 1752 .channel = ch, 1753 .fingerprint = fingerprint.*, 1754 }; 1755 defer sess.deinit(); 1756 handler.handleSession(&sess, request) catch |session_err| { 1757 // try to send a non-zero exit status before closing 1758 sess.exit(1) catch {}; 1759 return session_err; 1760 }; 1761 if (!sess.closed) try sess.exit(0); 1762 return; 1763 } 1764 }, 1765 1766 SSH_MSG_CHANNEL_WINDOW_ADJUST => { 1767 const ch = if (channel) |*c| c else continue; 1768 try handleWindowAdjust(ch, packet); 1769 }, 1770 1771 SSH_MSG_CHANNEL_DATA, SSH_MSG_CHANNEL_EXTENDED_DATA => { 1772 const ch = if (channel) |*c| c else continue; 1773 // before shell/exec the client shouldn't be sending data, but 1774 // some clients are chatty; discard and refill window. nothing 1775 // is buffered yet, so the whole window is available to credit. 1776 try discardChannelData(ch, packet, msg_type == SSH_MSG_CHANNEL_EXTENDED_DATA); 1777 try maybeRefillRecvWindow(conn, ch, initial_recv_window); 1778 }, 1779 1780 SSH_MSG_CHANNEL_EOF => { 1781 if (channel) |*c| try parseChannelId(packet, c.local_id); 1782 }, 1783 1784 SSH_MSG_CHANNEL_CLOSE => { 1785 if (channel) |*c| try parseChannelId(packet, c.local_id); 1786 return; 1787 }, 1788 1789 else => try sendUnimplemented(conn), 1790 } 1791 } 1792 } 1793 1794 fn handleGlobalRequest(conn: *Conn, packet: []const u8) !void { 1795 // byte SSH_MSG_GLOBAL_REQUEST 1796 // string request_name 1797 // boolean want_reply 1798 // …request-specific data we ignore 1799 var r = std.Io.Reader.fixed(packet[1..]); 1800 const name = try takeStringField(conn.allocator, &r, 256); 1801 defer conn.allocator.free(name); 1802 const want_reply = (try r.takeByte()) != 0; 1803 if (want_reply) { 1804 try conn.sc_cipher.writePacket(conn.io, conn.writer, &[_]u8{SSH_MSG_REQUEST_FAILURE}); 1805 } 1806 } 1807 1808 /// parse a CHANNEL_OPEN. on a session channel, send CHANNEL_OPEN_CONFIRMATION 1809 /// and return the new Channel. on other types, send CHANNEL_OPEN_FAILURE and 1810 /// return null. 1811 fn handleChannelOpen(conn: *Conn, packet: []const u8) !?Channel { 1812 const allocator = conn.allocator; 1813 1814 // byte SSH_MSG_CHANNEL_OPEN 1815 // string channel_type 1816 // uint32 sender_channel (peer's id) 1817 // uint32 initial_window 1818 // uint32 max_packet 1819 var r = std.Io.Reader.fixed(packet[1..]); 1820 const ch_type = try takeStringField(allocator, &r, 64); 1821 defer allocator.free(ch_type); 1822 const remote_id = try r.takeInt(u32, .big); 1823 const initial_window = try r.takeInt(u32, .big); 1824 const max_packet = try r.takeInt(u32, .big); 1825 1826 if (!std.mem.eql(u8, ch_type, "session")) { 1827 try sendChannelOpenFailure(conn, packet, SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "only session channels are supported"); 1828 return null; 1829 } 1830 1831 // a zero max_packet would leave writeChannel looping without progress 1832 if (max_packet == 0) { 1833 try sendChannelOpenFailure(conn, packet, SSH_OPEN_RESOURCE_SHORTAGE, "max packet size must be non-zero"); 1834 return null; 1835 } 1836 1837 const local_id: u32 = 0; // single-channel connection — id is always 0 from our side 1838 var reply: std.ArrayList(u8) = .empty; 1839 defer reply.deinit(allocator); 1840 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_CONFIRMATION); 1841 try writeU32(&reply, allocator, remote_id); 1842 try writeU32(&reply, allocator, local_id); 1843 try writeU32(&reply, allocator, initial_recv_window); 1844 try writeU32(&reply, allocator, max_packet_size); 1845 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1846 1847 return .{ 1848 .local_id = local_id, 1849 .remote_id = remote_id, 1850 .local_window = initial_recv_window, 1851 .remote_window = initial_window, 1852 .max_packet = max_packet, 1853 }; 1854 } 1855 1856 fn sendChannelOpenFailure(conn: *Conn, open_packet: []const u8, reason: u32, description: []const u8) !void { 1857 const allocator = conn.allocator; 1858 1859 // recover the sender_channel field from the CHANNEL_OPEN packet so we 1860 // address the failure to the correct id 1861 var r = std.Io.Reader.fixed(open_packet[1..]); 1862 const ch_type_len = try r.takeInt(u32, .big); 1863 try r.discardAll(ch_type_len); 1864 const remote_id = try r.takeInt(u32, .big); 1865 1866 var reply: std.ArrayList(u8) = .empty; 1867 defer reply.deinit(allocator); 1868 try reply.append(allocator, SSH_MSG_CHANNEL_OPEN_FAILURE); 1869 try writeU32(&reply, allocator, remote_id); 1870 try writeU32(&reply, allocator, reason); 1871 try writeStringField(&reply, allocator, description); 1872 try writeStringField(&reply, allocator, ""); // language tag 1873 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1874 } 1875 1876 /// returns the session request if this one triggered it, else null. an exec 1877 /// command is owned by `pending_exec`, which outlives the packet it arrived in. 1878 fn handleChannelRequest(conn: *Conn, ch: *Channel, packet: []const u8, pending_exec: *?[]u8) !?Request { 1879 const allocator = conn.allocator; 1880 1881 // byte SSH_MSG_CHANNEL_REQUEST 1882 // uint32 recipient_channel (== our local_id) 1883 // string request_type 1884 // boolean want_reply 1885 // …request-specific data 1886 var r = std.Io.Reader.fixed(packet[1..]); 1887 const recipient_channel = try r.takeInt(u32, .big); 1888 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1889 const req_type = try takeStringField(allocator, &r, 64); 1890 defer allocator.free(req_type); 1891 const want_reply = (try r.takeByte()) != 0; 1892 1893 if (std.mem.eql(u8, req_type, "pty-req")) { 1894 // string TERM, uint32 width chars, uint32 height rows, uint32 width px, 1895 // uint32 height px, string modes 1896 const term = try takeStringField(allocator, &r, 64); 1897 defer allocator.free(term); 1898 ch.pty = try takePtySize(&r); 1899 try replyChannelRequest(conn, ch, want_reply, true); 1900 return null; 1901 } 1902 1903 if (std.mem.eql(u8, req_type, "env")) { 1904 // ignore environment variables silently (we don't pass them anywhere) 1905 try replyChannelRequest(conn, ch, want_reply, true); 1906 return null; 1907 } 1908 1909 if (std.mem.eql(u8, req_type, "window-change")) { 1910 // uint32 width cells, uint32 height rows, uint32 width px, uint32 height px 1911 const sz = try takePtySize(&r); 1912 if (ch.pty != null) ch.pty = sz; 1913 // spec: window-change MUST NOT request a reply, but accept either 1914 try replyChannelRequest(conn, ch, want_reply, true); 1915 return null; 1916 } 1917 1918 if (std.mem.eql(u8, req_type, "shell")) { 1919 try replyChannelRequest(conn, ch, want_reply, true); 1920 return .{ .shell = ch.pty }; 1921 } 1922 1923 if (std.mem.eql(u8, req_type, "exec")) { 1924 // capture the command string for the handler to inspect 1925 const cmd = try takeStringField(allocator, &r, 4096); 1926 if (pending_exec.*) |old| allocator.free(old); 1927 pending_exec.* = cmd; 1928 try replyChannelRequest(conn, ch, want_reply, true); 1929 return .{ .exec = cmd }; 1930 } 1931 1932 // unknown request kind — fail it 1933 try replyChannelRequest(conn, ch, want_reply, false); 1934 return null; 1935 } 1936 1937 fn replyChannelRequest(conn: *Conn, ch: *Channel, want_reply: bool, success: bool) !void { 1938 if (!want_reply) return; 1939 var reply: std.ArrayList(u8) = .empty; 1940 defer reply.deinit(conn.allocator); 1941 try reply.append(conn.allocator, if (success) SSH_MSG_CHANNEL_SUCCESS else SSH_MSG_CHANNEL_FAILURE); 1942 try writeU32(&reply, conn.allocator, ch.remote_id); 1943 try conn.sc_cipher.writePacket(conn.io, conn.writer, reply.items); 1944 } 1945 1946 fn handleWindowAdjust(ch: *Channel, packet: []const u8) !void { 1947 // byte SSH_MSG_CHANNEL_WINDOW_ADJUST 1948 // uint32 recipient_channel 1949 // uint32 bytes_to_add 1950 var r = std.Io.Reader.fixed(packet[1..]); 1951 const recipient_channel = try r.takeInt(u32, .big); 1952 if (recipient_channel != ch.local_id) return error.UnknownChannel; 1953 const add = try r.takeInt(u32, .big); 1954 ch.remote_window +|= add; 1955 } 1956 1957 // charge a payload's bytes against the receive window without keeping them. 1958 // the caller credits the window back, choosing the budget that suits it. 1959 fn discardChannelData(ch: *Channel, packet: []const u8, extended: bool) !void { 1960 // byte SSH_MSG_CHANNEL_DATA/EXTENDED_DATA 1961 // uint32 recipient_channel 1962 // [if extended: uint32 type_code] 1963 // string data 1964 const payload = try parseChannelData(packet, extended, ch.local_id); 1965 const data_len: u32 = @intCast(payload.len); 1966 1967 if (data_len > ch.local_window) return error.WindowExceeded; 1968 ch.local_window -= data_len; 1969 } 1970 1971 pub fn parseChannelData(packet: []const u8, extended: bool, expected_channel: u32) ![]const u8 { 1972 if (packet.len < 1) return error.EmptyPacket; 1973 var r = std.Io.Reader.fixed(packet[1..]); 1974 const recipient_channel = try r.takeInt(u32, .big); 1975 if (recipient_channel != expected_channel) return error.UnknownChannel; 1976 if (extended) { 1977 const data_type = try r.takeInt(u32, .big); 1978 if (data_type != SSH_EXTENDED_DATA_STDERR) return error.UnsupportedExtendedData; 1979 } 1980 const data_len = try r.takeInt(u32, .big); 1981 // catches both data_len > remaining (would otherwise be a bounds-check 1982 // panic on the slice) and trailing junk after the declared payload. 1983 if (data_len != r.buffered().len) return error.InvalidChannelData; 1984 return r.buffered(); 1985 } 1986 1987 fn parseChannelId(packet: []const u8, expected_channel: u32) !void { 1988 if (packet.len < 1) return error.EmptyPacket; 1989 var r = std.Io.Reader.fixed(packet[1..]); 1990 const recipient_channel = try r.takeInt(u32, .big); 1991 if (recipient_channel != expected_channel) return error.UnknownChannel; 1992 if (r.buffered().len != 0) return error.InvalidChannelMessage; 1993 } 1994 1995 /// send a CHANNEL_WINDOW_ADJUST if our receive window has dipped below half 1996 /// of `budget`, the credit we're willing to have outstanding. used both for 1997 /// the pre-session discard path and by SessionCtx after it consumes a 1998 /// CHANNEL_DATA payload. 1999 fn maybeRefillRecvWindow(conn: *Conn, ch: *Channel, budget: u32) !void { 2000 if (ch.local_window >= budget / 2) return; 2001 const add = budget - ch.local_window; 2002 ch.local_window += add; 2003 var adj: std.ArrayList(u8) = .empty; 2004 defer adj.deinit(conn.allocator); 2005 try adj.append(conn.allocator, SSH_MSG_CHANNEL_WINDOW_ADJUST); 2006 try writeU32(&adj, conn.allocator, ch.remote_id); 2007 try writeU32(&adj, conn.allocator, add); 2008 try conn.sc_cipher.writePacket(conn.io, conn.writer, adj.items); 2009 } 2010 2011 pub fn writeU32(buf: *std.ArrayList(u8), allocator: std.mem.Allocator, value: u32) !void { 2012 var bytes: [4]u8 = undefined; 2013 std.mem.writeInt(u32, &bytes, value, .big); 2014 try buf.appendSlice(allocator, &bytes); 2015 } 2016