"""Validate public IPv4 guest settings and build a NoCloud seed ISO. The seed may contain a guest SSH public key and a salted root password hash, but never a plaintext password, private key, or panel credential. JSON is used as a YAML subset so untrusted fields cannot inject directives. """ from __future__ import annotations import base64 import binascii import ipaddress import json import re import secrets import string import uuid from io import BytesIO from typing import Any _VM_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") # Linux host names are case-insensitive DNS labels. Keep the panel contract # deliberately narrower than the kernel's permissive hostname(5) parser so a # pasted value can never become a cloud-init directive or an ambiguous FQDN. _HOSTNAME_LABEL = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\Z") _MAC = re.compile(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\Z") _NETWORK_POLICY_KEY = "virt-cloud-network-policy" _NETWORK_POLICY_VALUE = "boot-v1" _SSH_TYPES = { "ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", } _SHA512_CRYPT = re.compile( r"\$6\$rounds=([1-9][0-9]{3,8})\$[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}\Z" ) ROOT_PASSWORD_LENGTH = 32 ROOT_PASSWORD_MIN_LENGTH = 12 ROOT_PASSWORD_MAX_LENGTH = 128 ROOT_PASSWORD_UPPERCASE = string.ascii_uppercase ROOT_PASSWORD_LOWERCASE = string.ascii_lowercase ROOT_PASSWORD_DIGITS = string.digits ROOT_PASSWORD_SYMBOLS = "!@#$%*-_=+?" ROOT_PASSWORD_ALPHABET = ( ROOT_PASSWORD_UPPERCASE + ROOT_PASSWORD_LOWERCASE + ROOT_PASSWORD_DIGITS + ROOT_PASSWORD_SYMBOLS ) def validate_guest_hostname(value: Any) -> str: """Return a canonical guest hostname suitable for cloud-init metadata. A single-label hostname and a DNS-style FQDN are both accepted. Leading or trailing dots, empty labels, underscores, whitespace, Unicode and control characters are rejected; the returned value is lower-case so a retry of the same settings request is deterministic. """ if not isinstance(value, str): raise ValueError("主机名格式无效") hostname = value.strip().lower() if not 1 <= len(hostname) <= 253 or hostname.endswith("."): raise ValueError("主机名长度必须为 1 到 253 个字符") labels = hostname.split(".") if any(not _HOSTNAME_LABEL.fullmatch(label) for label in labels): raise ValueError("主机名只能包含字母、数字、连字符和点,且每段不能以连字符开头或结尾") return hostname def default_guest_hostname(name: str, vm_uuid: str | None = None) -> str: """Derive the initial guest hostname using the same rule as seed creation.""" if not isinstance(name, str) or not _VM_NAME.fullmatch(name): raise ValueError("虚拟机名称无效") hostname = re.sub(r"[^a-z0-9-]", "-", name.lower()).strip("-")[:63] if hostname: return hostname try: suffix = str(uuid.UUID(vm_uuid)).replace("-", "")[:8] if vm_uuid else "guest" except (ValueError, TypeError, AttributeError): suffix = "guest" return f"vm-{suffix}" def _root_password_has_required_classes(password: str) -> bool: return ( any(char in ROOT_PASSWORD_UPPERCASE for char in password) and any(char in ROOT_PASSWORD_LOWERCASE for char in password) and any(char in ROOT_PASSWORD_DIGITS for char in password) and any(not char.isalnum() for char in password) ) def hash_root_password(password: str) -> str: """Hash a guest root password for /etc/shadow before writing the seed.""" if (not isinstance(password, str) or not ROOT_PASSWORD_MIN_LENGTH <= len(password) <= ROOT_PASSWORD_MAX_LENGTH or any(not 0x21 <= ord(char) <= 0x7e for char in password)): raise ValueError("初始 root 密码须为 12 至 128 位可打印 ASCII 字符且不能包含空格") if not _root_password_has_required_classes(password): raise ValueError("初始 root 密码须包含大写字母、小写字母、数字和符号") from passlib.hash import sha512_crypt return sha512_crypt.using(rounds=100_000).hash(password) def generate_root_password() -> str: """Return a uniform random password from all compliant 32-char strings. Generating every position from the complete alphabet and rejecting the rare candidate missing a required class avoids fixed category positions and the distribution bias introduced by "one of each, then shuffle". ``secrets.randbelow`` performs an unbiased CSPRNG selection. """ while True: password = "".join( ROOT_PASSWORD_ALPHABET[ secrets.randbelow(len(ROOT_PASSWORD_ALPHABET)) ] for _ in range(ROOT_PASSWORD_LENGTH) ) if _root_password_has_required_classes(password): return password def _validate_guest_auth(guest_ssh_public_key: Any, root_password_hash: Any) -> tuple[str, str | None]: if not isinstance(guest_ssh_public_key, str): raise ValueError("虚拟机 SSH 公钥格式无效") public_key = guest_ssh_public_key.strip() if not public_key and not root_password_hash: raise ValueError("请填写虚拟机 SSH 公钥或初始 root 密码") if public_key: public_key = _validate_ssh_public_key(public_key) if root_password_hash is not None: if not isinstance(root_password_hash, str): raise ValueError("初始 root 密码哈希格式无效") match = _SHA512_CRYPT.fullmatch(root_password_hash) if match is None or not 100_000 <= int(match.group(1)) <= 1_000_000: raise ValueError("初始 root 密码哈希格式无效") return public_key, root_password_hash def _ssh_string(blob: bytes, offset: int) -> tuple[bytes, int]: if offset + 4 > len(blob): raise ValueError("SSH 公钥内容无效") size = int.from_bytes(blob[offset:offset + 4], "big") start = offset + 4 end = start + size if size > 8192 or end > len(blob): raise ValueError("SSH 公钥内容无效") return blob[start:end], end def _validate_ssh_public_key(value: Any) -> str: if not isinstance(value, str) or not value or len(value) > 16384: raise ValueError("请填写虚拟机登录用的 SSH 公钥") if any(char in value for char in ("\n", "\r", "\x00")): raise ValueError("SSH 公钥必须是单行 OpenSSH 公钥") fields = value.strip().split(maxsplit=2) if len(fields) < 2 or fields[0] not in _SSH_TYPES: raise ValueError("SSH 公钥格式无效,仅支持 Ed25519、RSA 或 ECDSA") key_type, encoded = fields[:2] try: blob = base64.b64decode(encoded, validate=True) embedded_type, offset = _ssh_string(blob, 0) except (ValueError, binascii.Error) as exc: raise ValueError("SSH 公钥内容无效") from exc if embedded_type != key_type.encode("ascii"): raise ValueError("SSH 公钥类型与内容不匹配") # An OpenSSH key is a series of length-prefixed binary strings. Verify # its structure rather than accepting arbitrary base64 after the prefix. if key_type == "ssh-ed25519": key, offset = _ssh_string(blob, offset) if len(key) != 32: raise ValueError("Ed25519 公钥长度无效") elif key_type == "ssh-rsa": exponent, offset = _ssh_string(blob, offset) modulus, offset = _ssh_string(blob, offset) if (not exponent or int.from_bytes(exponent, "big") < 3 or int.from_bytes(exponent, "big") % 2 == 0 or int.from_bytes(modulus, "big").bit_length() < 2048): raise ValueError("RSA 公钥无效或不足 2048 位") else: curve, offset = _ssh_string(blob, offset) point, offset = _ssh_string(blob, offset) suffix = key_type.removeprefix("ecdsa-sha2-") point_lengths = {"nistp256": 65, "nistp384": 97, "nistp521": 133} if (curve != suffix.encode("ascii") or len(point) != point_lengths[suffix] or point[0] != 4): raise ValueError("ECDSA 公钥内容无效") if offset != len(blob): raise ValueError("SSH 公钥存在多余数据") # Keep a harmless OpenSSH comment for operator identification. The # generated user-data is JSON-escaped, not assembled as raw YAML. return value.strip() def _ipv4(value: Any, label: str) -> ipaddress.IPv4Address: if not isinstance(value, str) or not value or value != value.strip(): raise ValueError(f"{label}必须是 IPv4 地址") try: address = ipaddress.ip_address(value) except ValueError as exc: raise ValueError(f"{label}必须是 IPv4 地址") from exc if not isinstance(address, ipaddress.IPv4Address): raise ValueError(f"{label}必须是 IPv4 地址") return address def validate_cloud_network( public_ip_cidr: str, gateway: str, dns_servers: list[str] | tuple[str, ...], guest_ssh_public_key: str = "", root_password_hash: str | None = None, *, require_auth: bool = True, ) -> dict[str, Any]: """Return canonical guest network fields or raise ``ValueError``. This first version supports an on-link gateway on a public IPv4 subnet, including /24 and /28. Routed /32/off-link gateways need a separate explicit model; silently treating them as on-link would strand the guest. """ if (not isinstance(public_ip_cidr, str) or not public_ip_cidr or public_ip_cidr != public_ip_cidr.strip()): raise ValueError("公网 IP 必须采用 IPv4 地址/前缀长度格式,例如实际分配的地址加 /28") try: interface = ipaddress.ip_interface(public_ip_cidr) except ValueError as exc: raise ValueError("公网 IP/CIDR 格式无效") from exc if not isinstance(interface, ipaddress.IPv4Interface): raise ValueError("暂时只支持公网 IPv4") network = interface.network if not 1 <= network.prefixlen <= 30: raise ValueError("当前网桥方案仅支持 /1 到 /30 的 IPv4 前缀") if (not interface.ip.is_global or interface.ip.is_multicast or interface.ip.is_reserved): raise ValueError("IP 不是可用的公网 IPv4 地址") if interface.ip in (network.network_address, network.broadcast_address): raise ValueError("不能使用子网地址或广播地址作为虚拟机 IP") gateway_ip = _ipv4(gateway, "网关") if (not gateway_ip.is_global or gateway_ip.is_multicast or gateway_ip.is_reserved or gateway_ip not in network or gateway_ip == interface.ip or gateway_ip in (network.network_address, network.broadcast_address)): raise ValueError("网关必须是同一网段内另一可用 IPv4 地址") if (not isinstance(dns_servers, (list, tuple)) or not 1 <= len(dns_servers) <= 4): raise ValueError("请填写 1 到 4 个 DNS IPv4 地址") dns_ips = [_ipv4(item, "DNS") for item in dns_servers] if any(not address.is_global or address.is_multicast or address.is_reserved for address in dns_ips): raise ValueError("当前公网模板只支持可公开路由的 DNS IPv4 地址") dns = [str(address) for address in dns_ips] if len(set(dns)) != len(dns): raise ValueError("DNS 地址不能重复") if not isinstance(require_auth, bool): raise ValueError("网络认证校验选项无效") if require_auth: public_key, password_hash = _validate_guest_auth( guest_ssh_public_key, root_password_hash) else: # A network-only update must not require, receive, or regenerate the # guest credential. Credentials are not accepted or regenerated by # ``replace_seed_network``. public_key, password_hash = "", None result = { "public_ip_cidr": str(interface), "gateway": str(gateway_ip), "dns_servers": dns, "guest_ssh_public_key": public_key, } if password_hash is not None: result["root_password_hash"] = password_hash return result def build_seed_iso( vm_uuid: str, name: str, mac: str, validated_network: dict[str, Any], *, debian12_network_fix: bool = False, ) -> bytes: """Build a CIDATA ISO with user-data, meta-data, and network-config.""" try: instance_id = str(uuid.UUID(vm_uuid)) except (ValueError, TypeError, AttributeError) as exc: raise ValueError("虚拟机 UUID 无效") from exc if not isinstance(name, str) or not _VM_NAME.fullmatch(name): raise ValueError("虚拟机名称无效") if not isinstance(mac, str) or not _MAC.fullmatch(mac): raise ValueError("虚拟机 MAC 地址无效") normalized_mac = mac.lower() mac_octets = [int(part, 16) for part in normalized_mac.split(":")] if mac_octets[0] & 1 or not any(mac_octets): raise ValueError("虚拟机 MAC 地址不能是组播或全零地址") if not isinstance(validated_network, dict): raise ValueError("网络配置无效") if not isinstance(debian12_network_fix, bool): raise ValueError("Debian 12 网络修复选项无效") network = validate_cloud_network( validated_network.get("public_ip_cidr"), validated_network.get("gateway"), validated_network.get("dns_servers"), validated_network.get("guest_ssh_public_key"), validated_network.get("root_password_hash"), ) # Keep Linux hostname valid even when the libvirt VM name contains dots or # underscores. The libvirt name itself remains unchanged. hostname = default_guest_hostname(name, instance_id) use_public_key = bool(network["guest_ssh_public_key"]) use_password = bool(network.get("root_password_hash")) root_user: dict[str, Any] = {"name": "root", "lock_passwd": not use_password} if use_public_key: root_user["ssh_authorized_keys"] = [network["guest_ssh_public_key"]] if use_password: root_user["hashed_passwd"] = network["root_password_hash"] # RHEL/AlmaLinux 10 defaults to prohibit-password for root. An early # drop-in makes the two requested authentication modes explicit; cloud-init # itself writes a later 50-cloud-init.conf for PasswordAuthentication. sshd_config = ( ("PermitRootLogin yes\nPasswordAuthentication yes\n" if use_password else "PermitRootLogin prohibit-password\nPasswordAuthentication no\n") + "KbdInteractiveAuthentication no\n" ) write_files = [{ "path": "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf", "content": sshd_config, "permissions": "0644", }] user_data: dict[str, Any] = { "users": [root_user], "ssh_pwauth": use_password, "disable_root": False, "write_files": write_files, # Cloud-init renders a datasource network configuration only on the # first boot by default. Public-IP replacement updates the NoCloud # seed and reboots the guest, so explicitly opt in to applying the # current network-config on every boot. "updates": {"network": {"when": ["boot"]}}, } if use_password: _set_root_chpasswd(user_data, network["root_password_hash"]) if debian12_network_fix: # NoCloud normally consumes user-data in its network stage. Debian 12 # can wait for a still-disabled systemd-networkd before reaching that # stage, so consume this local seed during init-local instead. The # network itself remains entirely in the standard network-config file; # bootcmd only prepares the renderer and starts its backend. queue_networkd = "\n".join([ # cloud-init clean --machine-id can leave a custom Debian image # without this file. The systemd helper initializes a valid ID # from the guest's system sources and is a no-op when one already # exists. "systemd-machine-id-setup", # cloud-init 22.4 on Debian 12 can write the Netplan YAML during # init-local without generating networkd's runtime configuration. "netplan generate", "systemctl unmask systemd-networkd.service", "systemctl enable systemd-networkd.service", "systemctl start --no-block systemd-networkd.service", ]) user_data["bootcmd"] = [ ["/bin/sh", "-ec", queue_networkd], ] metadata = { "instance-id": instance_id, "local-hostname": hostname, # This marker lets a later IP change distinguish a new panel seed # (already carrying the network refresh policy) from a legacy seed # that needs one cache-invalidating instance generation. _NETWORK_POLICY_KEY: _NETWORK_POLICY_VALUE, } if debian12_network_fix: # Consume bootcmd in cloud-init-local, before systemd waits for # network-online. This stays scoped to the Debian 12 compatibility # path because remote user-data cannot be fetched in local mode. metadata["dsmode"] = "local" network_config = { "version": 2, "ethernets": { # ``public0`` is only a stable Netplan/cloud-init configuration # identifier. Do not rename the guest interface: Debian 12 can # apply a first-boot rename after network activation has already # run, leaving the renamed device up but without its static IP. # Matching the libvirt MAC applies this configuration directly to # the kernel-provided interface name (for example ``enp1s0``). "public0": { "match": {"macaddress": normalized_mac}, "dhcp4": False, "dhcp6": False, "addresses": [network["public_ip_cidr"]], "routes": [{"to": "0.0.0.0/0", "via": network["gateway"]}], "nameservers": {"addresses": network["dns_servers"]}, }, }, } if debian12_network_fix: # dhcp6=false does not disable DHCPv6 started in response to a router # advertisement. This product currently provisions IPv4 only, so # express that intent through Netplan instead of writing a second, # provider-specific .network file. network_config["ethernets"]["public0"]["accept-ra"] = False network_config["renderer"] = "networkd" files = ( ("/USERDATA.;1", "user-data", "/user-data", b"#cloud-config\n" + json.dumps(user_data, ensure_ascii=True).encode("ascii") + b"\n"), ("/METADATA.;1", "meta-data", "/meta-data", json.dumps(metadata, ensure_ascii=True).encode("ascii") + b"\n"), ("/NETWORK.;1", "network-config", "/network-config", json.dumps(network_config, ensure_ascii=True).encode("ascii") + b"\n"), ) return _build_seed_iso(files) def _build_seed_iso(files: tuple[tuple[str, str, str, bytes], ...]) -> bytes: """Build a bounded CIDATA image from trusted, already-encoded files.""" import pycdlib iso = pycdlib.PyCdlib() payloads: list[BytesIO] = [] try: iso.new(vol_ident="CIDATA", rock_ridge="1.09", joliet=3) for iso_path, rock_ridge_name, joliet_path, contents in files: if not isinstance(contents, bytes) or len(contents) > 256 * 1024: raise ValueError("cloud-init 配置文件过大") payload = BytesIO(contents) payloads.append(payload) # pycdlib reads these during write_fp. iso.add_fp(payload, len(contents), iso_path=iso_path, rr_name=rock_ridge_name, joliet_path=joliet_path) output = BytesIO() iso.write_fp(output) result = output.getvalue() if not result or len(result) > 1024 * 1024: raise ValueError("cloud-init 配置盘大小无效") return result finally: iso.close() def _enable_network_updates(user_data: bytes) -> bytes: """Ensure a panel cloud-config reapplies datasource networking on boot. Panel-created user-data is a bounded JSON document prefixed with ``#cloud-config``. Keeping this transformation limited to that format avoids guessing how an arbitrary user-data document should be merged while still allowing old panel instances (created before IP replacement was introduced) to opt in when their seed is updated. """ if (not isinstance(user_data, bytes) or not user_data or len(user_data) > 256 * 1024): raise ValueError("原 cloud-init 用户数据大小无效") prefix = b"#cloud-config\n" if not user_data.startswith(prefix): raise ValueError("原 cloud-init 用户数据格式无效") try: config = json.loads(user_data[len(prefix):]) except (TypeError, ValueError, json.JSONDecodeError) as exc: raise ValueError("原 cloud-init 用户数据格式无效") from exc if not isinstance(config, dict) or not config: raise ValueError("原 cloud-init 用户数据格式无效") updates = config.get("updates") if updates is None: updates = {} elif not isinstance(updates, dict): raise ValueError("原 cloud-init 更新策略格式无效") network = updates.get("network") if network is None: network = {} elif not isinstance(network, dict): raise ValueError("原 cloud-init 网络更新策略格式无效") when = network.get("when") if when is None: when = [] elif (not isinstance(when, list) or any(not isinstance(event, str) for event in when)): raise ValueError("原 cloud-init 网络更新事件格式无效") if "boot" not in when: when.append("boot") network["when"] = when updates["network"] = network config["updates"] = updates # Avoid changing the seed (and its digest) when the policy is already # present. This also preserves the original opaque user-data bytes for # current instances while upgrading older panel-generated seeds. if user_data[len(prefix):].rstrip(b"\n") == ( json.dumps(config, ensure_ascii=True).encode("ascii")): return user_data return (prefix + json.dumps(config, ensure_ascii=True).encode("ascii") + b"\n") def _decode_seed_metadata(meta_data: bytes) -> dict[str, Any]: """Decode and validate the JSON metadata emitted by this panel.""" if (not isinstance(meta_data, bytes) or not meta_data or len(meta_data) > 256 * 1024): raise ValueError("原 cloud-init 元数据大小无效") try: metadata = json.loads(meta_data) except (TypeError, ValueError, json.JSONDecodeError) as exc: raise ValueError("原 cloud-init 元数据格式无效") from exc if (not isinstance(metadata, dict) or not metadata or not isinstance(metadata.get("instance-id"), str) or not metadata["instance-id"].strip()): raise ValueError("原 cloud-init 元数据缺少有效实例标识") return metadata def _encode_seed_metadata(metadata: dict[str, Any]) -> bytes: """Encode bounded panel metadata without exposing credentials.""" encoded = json.dumps(metadata, ensure_ascii=True).encode("ascii") + b"\n" if len(encoded) > 256 * 1024: raise ValueError("原 cloud-init 元数据过大") return encoded def _prepare_seed_metadata(meta_data: bytes, *, rotate: bool) -> bytes: """Mark a seed as network-refresh capable, rotating its ID when needed.""" metadata = _decode_seed_metadata(meta_data) if rotate: metadata["instance-id"] = f"virt-cloud-network-{uuid.uuid4().hex}" metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE return _encode_seed_metadata(metadata) def replace_seed_network( seed: bytes, public_ip_cidr: str, gateway: str, dns_servers: list[str] | tuple[str, ...], ) -> bytes: """Replace network settings in a panel-created NoCloud seed. The guest credentials and hostname fields are retained. The generated user-data is upgraded with the network-on-boot policy. A legacy seed gets one fresh NoCloud instance generation so its cached datasource is invalidated; already-migrated seeds keep their generation to avoid re-running unrelated per-instance user-data modules on every IP change. Reject non-panel seeds instead of trying to infer their format. """ if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: raise ValueError("原 cloud-init 配置盘大小无效") import pycdlib iso = pycdlib.PyCdlib() opened = False files: dict[str, bytes] = {} try: iso.open_fp(BytesIO(seed)) opened = True for rr_path, key in (("/user-data", "user-data"), ("/meta-data", "meta-data"), ("/network-config", "network-config")): output = BytesIO() iso.get_file_from_iso_fp(output, rr_path=rr_path) value = output.getvalue() if not value or len(value) > 256 * 1024: raise ValueError("原 cloud-init 配置文件大小无效") files[key] = value except (OSError, KeyError, TypeError, ValueError, pycdlib.pycdlibexception.PyCdlibException) as exc: raise ValueError("无法读取原 cloud-init 配置盘") from exc finally: if opened: iso.close() try: user_data = _enable_network_updates(files["user-data"]) original_metadata = _decode_seed_metadata(files["meta-data"]) # A legacy seed has neither the explicit marker nor the boot policy in # its cached user-data. Rotate its NoCloud generation once so the # guest consumes this migration. New seeds and already-migrated # seeds can refresh network-config through the supported boot event # without re-running all per-instance user-data modules. needs_generation = ( user_data != files["user-data"] or original_metadata.get(_NETWORK_POLICY_KEY) != _NETWORK_POLICY_VALUE ) meta_data = _prepare_seed_metadata( files["meta-data"], rotate=needs_generation) config = json.loads(files["network-config"]) if (config.get("version") != 2 or not isinstance(config.get("ethernets"), dict) or set(config["ethernets"]) != {"public0"}): raise ValueError public = config["ethernets"]["public0"] match = public.get("match") mac = match.get("macaddress") if isinstance(match, dict) else None if (public.get("dhcp4") is not False or public.get("dhcp6") is not False or not isinstance(mac, str) or not _MAC.fullmatch(mac) or not isinstance(public.get("addresses"), list) or len(public["addresses"]) != 1 or not isinstance(public.get("routes"), list) or len(public["routes"]) != 1): raise ValueError route = public["routes"][0] if route.get("to") != "0.0.0.0/0": raise ValueError # Validate only fields that are changing. No credential is accepted # by this operation; only the network-on-boot policy is merged into # the panel-generated user-data above. network = validate_cloud_network( public_ip_cidr, gateway, dns_servers, require_auth=False) public["addresses"] = [network["public_ip_cidr"]] route["via"] = network["gateway"] nameservers = public.get("nameservers") if not isinstance(nameservers, dict): raise ValueError nameservers["addresses"] = list(network["dns_servers"]) network_data = (json.dumps(config, ensure_ascii=True).encode("ascii") + b"\n") rebuilt = ( ("/USERDATA.;1", "user-data", "/user-data", user_data), ("/METADATA.;1", "meta-data", "/meta-data", meta_data), ("/NETWORK.;1", "network-config", "/network-config", network_data), ) return _build_seed_iso(rebuilt) except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: raise ValueError("原 cloud-init 网络配置格式无效") from exc def _read_seed_files(seed: bytes) -> dict[str, bytes]: """Read the three bounded files from a panel-generated NoCloud seed.""" if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: raise ValueError("原 cloud-init 配置盘大小无效") import pycdlib iso = pycdlib.PyCdlib() opened = False files: dict[str, bytes] = {} try: iso.open_fp(BytesIO(seed)) opened = True for rr_path, key in (("/user-data", "user-data"), ("/meta-data", "meta-data"), ("/network-config", "network-config")): output = BytesIO() iso.get_file_from_iso_fp(output, rr_path=rr_path) value = output.getvalue() if not value or len(value) > 256 * 1024: raise ValueError("原 cloud-init 配置文件大小无效") files[key] = value except (OSError, KeyError, TypeError, ValueError, pycdlib.pycdlibexception.PyCdlibException) as exc: raise ValueError("无法读取原 cloud-init 配置盘") from exc finally: if opened: iso.close() return files def _decode_seed_user_data(user_data: bytes) -> dict[str, Any]: """Decode the bounded JSON cloud-config emitted by this panel.""" prefix = b"#cloud-config\n" if (not isinstance(user_data, bytes) or not user_data or len(user_data) > 256 * 1024 or not user_data.startswith(prefix)): raise ValueError("原 cloud-init 用户数据格式无效") try: value = json.loads(user_data[len(prefix):]) except (TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError("原 cloud-init 用户数据格式无效") from exc if not isinstance(value, dict) or not value: raise ValueError("原 cloud-init 用户数据格式无效") return value def _root_user(config: dict[str, Any]) -> dict[str, Any]: users = config.get("users") if not isinstance(users, list) or len(users) > 32: raise ValueError("原 cloud-init 用户配置格式无效") matches = [item for item in users if isinstance(item, dict) and item.get("name") == "root"] if len(matches) != 1: raise ValueError("原 cloud-init root 用户配置格式无效") root = matches[0] lock_passwd = root.get("lock_passwd") if lock_passwd is not None and not isinstance(lock_passwd, bool): raise ValueError("原 cloud-init root 用户配置格式无效") existing_hash = root.get("hashed_passwd") if existing_hash is not None: try: _validate_guest_auth("", existing_hash) except ValueError as exc: raise ValueError("原 cloud-init root 密码配置格式无效") from exc if lock_passwd is True: raise ValueError("原 cloud-init root 密码配置无效") keys = root.get("ssh_authorized_keys") if keys is not None: if (not isinstance(keys, list) or len(keys) > 64 or any(not isinstance(item, str) for item in keys)): raise ValueError("原 cloud-init SSH 公钥配置格式无效") for key in keys: try: _validate_ssh_public_key(key) except ValueError as exc: raise ValueError("原 cloud-init SSH 公钥配置格式无效") from exc return root def _update_root_sshd_config(config: dict[str, Any], *, use_password: bool) -> None: """Keep the panel-managed root sshd drop-in aligned with credentials.""" if not isinstance(use_password, bool): raise ValueError("root 密码配置无效") write_files = config.get("write_files") if write_files is None: write_files = [] config["write_files"] = write_files if not isinstance(write_files, list) or len(write_files) > 128: raise ValueError("原 cloud-init 写入文件配置格式无效") path = "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf" matches = [item for item in write_files if isinstance(item, dict) and item.get("path") == path] if len(matches) > 1: raise ValueError("原 cloud-init SSH 配置重复") content = ( ("PermitRootLogin yes\nPasswordAuthentication yes\n" if use_password else "PermitRootLogin prohibit-password\nPasswordAuthentication no\n") + "KbdInteractiveAuthentication no\n" ) if matches: item = matches[0] if (item.get("permissions", "0644") != "0644" or any(key not in {"path", "content", "permissions"} for key in item)): raise ValueError("原 cloud-init SSH 配置格式无效") item["content"] = content item["permissions"] = "0644" else: write_files.append({"path": path, "content": content, "permissions": "0644"}) config["ssh_pwauth"] = use_password config["disable_root"] = False def _replace_root_authorized_keys(config: dict[str, Any], public_key: str) -> None: """Make the requested SSH key replacement explicit and deterministic. ``users[].ssh_authorized_keys`` is retained for distro compatibility, but a panel-managed write_files entry guarantees that an old authorized_keys line is replaced rather than merely appended by a distro cloud-init implementation. The key has already passed strict OpenSSH validation and is JSON-encoded, so no shell interpolation is involved. """ public_key = _validate_ssh_public_key(public_key) write_files = config.get("write_files") if write_files is None: write_files = [] config["write_files"] = write_files if (not isinstance(write_files, list) or len(write_files) > 128 or any(not isinstance(item, dict) for item in write_files)): raise ValueError("原 cloud-init 写入文件配置格式无效") path = "/root/.ssh/authorized_keys" matches = [item for item in write_files if item.get("path") == path] if len(matches) > 1: raise ValueError("原 cloud-init SSH 公钥文件配置重复") replacement = { "path": path, "content": public_key + "\n", "owner": "root:root", "permissions": "0600", } if matches: item = matches[0] if any(key not in {"path", "content", "owner", "permissions"} for key in item): raise ValueError("原 cloud-init SSH 公钥文件配置格式无效") item.clear() item.update(replacement) else: write_files.append(replacement) def _set_root_chpasswd(config: dict[str, Any], root_password_hash: str) -> None: """Set a hashed root password through cloud-init's password module. ``users[].hashed_passwd`` is retained for older cloud-init releases, but recent releases have reported existing users as locked even when that field is paired with ``lock_passwd: false``. The ``chpasswd`` module runs after user creation and applies the hash to an already-existing root account, which makes password replacement consistent across supported AlmaLinux, Debian and Ubuntu images. The hash is never converted back to plaintext. """ try: _validate_guest_auth("", root_password_hash) except ValueError as exc: raise ValueError("root 密码哈希格式无效") from exc config["chpasswd"] = { "expire": False, "users": [{ "name": "root", "password": root_password_hash, "type": "hash", }], } def _remove_root_chpasswd(config: dict[str, Any]) -> None: """Remove a panel-managed root chpasswd entry when password auth is off.""" chpasswd = config.get("chpasswd") if chpasswd is None: return if not isinstance(chpasswd, dict): raise ValueError("原 cloud-init 密码配置格式无效") users = chpasswd.get("users") if users is None: config.pop("chpasswd", None) return if not isinstance(users, list) or len(users) > 32: raise ValueError("原 cloud-init 密码配置格式无效") root_count = sum( 1 for item in users if isinstance(item, dict) and item.get("name") == "root" ) if root_count > 1: raise ValueError("原 cloud-init root 密码配置重复") remaining = [item for item in users if not (isinstance(item, dict) and item.get("name") == "root")] if remaining: chpasswd["users"] = remaining else: config.pop("chpasswd", None) def replace_seed_settings( seed: bytes, *, hostname: str | None = None, root_password_hash: str | None = None, ssh_public_key: str | None = None, ) -> bytes: """Replace panel-managed guest hostname/password/key in a NoCloud seed. ``None`` means "leave this setting unchanged"; an empty value is never a request to clear credentials. The metadata instance ID is rotated so cloud-init treats the next boot as a new panel configuration and applies the changed users/hostname modules. Network data is copied unchanged and is validated through :func:`read_seed_network` before any output is built. """ if hostname is None and root_password_hash is None and ssh_public_key is None: raise ValueError("至少需要修改一项虚拟机设置") if hostname is not None: hostname = validate_guest_hostname(hostname) if root_password_hash is not None: try: _validate_guest_auth("", root_password_hash) except ValueError as exc: raise ValueError("root 密码哈希格式无效") from exc if ssh_public_key is not None: ssh_public_key = _validate_ssh_public_key(ssh_public_key) files = _read_seed_files(seed) try: metadata = _decode_seed_metadata(files["meta-data"]) # Also verify that this is a panel network seed before retaining it. read_seed_network(seed) # Upgrade legacy panel seeds to the network-on-boot policy while the # settings generation is already being rotated. This keeps a later # IP replacement from silently losing its cloud-init refresh hook. user_data = _decode_seed_user_data( _enable_network_updates(files["user-data"]) ) root = _root_user(user_data) except (KeyError, TypeError, ValueError) as exc: raise ValueError("原 cloud-init 配置格式无效") from exc if hostname is not None: metadata["local-hostname"] = hostname if not isinstance(metadata.get("local-hostname"), str): raise ValueError("原 cloud-init 主机名配置格式无效") if root_password_hash is not None: root["hashed_passwd"] = root_password_hash root["lock_passwd"] = False if ssh_public_key is not None: root["ssh_authorized_keys"] = [ssh_public_key] _replace_root_authorized_keys(user_data, ssh_public_key) # A panel-generated seed either has a validated hash or explicitly locks # root. Preserve the existing state for key-only changes; changing a # password always enables password authentication above. use_password = bool(root.get("hashed_passwd")) if "hashed_passwd" not in root and root.get("lock_passwd") is False: # Do not silently preserve a malformed unlocked root record. raise ValueError("原 cloud-init root 密码配置格式无效") root["lock_passwd"] = not use_password if use_password: _set_root_chpasswd(user_data, root["hashed_passwd"]) else: _remove_root_chpasswd(user_data) _update_root_sshd_config(user_data, use_password=use_password) user_data = json.loads(json.dumps(user_data, ensure_ascii=True)) metadata["instance-id"] = f"virt-cloud-settings-{uuid.uuid4().hex}" metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE rebuilt = ( ("/USERDATA.;1", "user-data", "/user-data", b"#cloud-config\n" + json.dumps(user_data, ensure_ascii=True).encode("ascii") + b"\n"), ("/METADATA.;1", "meta-data", "/meta-data", json.dumps(metadata, ensure_ascii=True).encode("ascii") + b"\n"), ("/NETWORK.;1", "network-config", "/network-config", files["network-config"]), ) return _build_seed_iso(rebuilt) def read_seed_network(seed: bytes) -> dict[str, Any]: """Read the network settings from a panel-created NoCloud ISO. Only the network-config file is parsed: user-data can contain a password hash or an SSH key and must never be returned to the web API. """ if not isinstance(seed, bytes) or not seed or len(seed) > 1024 * 1024: raise ValueError("原 cloud-init 配置盘大小无效") import pycdlib iso = pycdlib.PyCdlib() opened = False try: iso.open_fp(BytesIO(seed)) opened = True output = BytesIO() iso.get_file_from_iso_fp(output, rr_path="/network-config") raw = output.getvalue() if len(raw) > 65536: raise ValueError("原网络配置过大") config = json.loads(raw) except (OSError, KeyError, TypeError, ValueError, pycdlib.pycdlibexception.PyCdlibException) as exc: raise ValueError("无法读取原 cloud-init 网络配置") from exc finally: if opened: iso.close() try: if config["version"] != 2: raise ValueError ethernets = config["ethernets"] if not isinstance(ethernets, dict) or set(ethernets) != {"public0"}: raise ValueError public = ethernets["public0"] if public["dhcp4"] is not False or public["dhcp6"] is not False: raise ValueError addresses = public["addresses"] routes = public["routes"] dns = public["nameservers"]["addresses"] mac = public["match"]["macaddress"] if (not isinstance(addresses, list) or len(addresses) != 1 or not isinstance(routes, list) or len(routes) != 1 or routes[0]["to"] != "0.0.0.0/0" or not isinstance(mac, str) or not _MAC.fullmatch(mac)): raise ValueError return { "public_ip_cidr": addresses[0], "gateway": routes[0]["via"], "dns_servers": dns, "mac": mac.lower(), } except (KeyError, TypeError, ValueError) as exc: raise ValueError("原 cloud-init 网络配置格式无效") from exc