You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/virsh_panel/cloud_init.py

1304 lines
57 KiB
Python

"""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
from virsh_panel.network_roles import (
PRIVATE_INTERFACE_ROLE,
PUBLIC_INTERFACE_ROLE,
)
_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
)
_RFC1918_NETWORKS = (
ipaddress.IPv4Network("10.0.0.0/8"),
ipaddress.IPv4Network("172.16.0.0/12"),
ipaddress.IPv4Network("192.168.0.0/16"),
)
class SeedNetworkPolicyMigrationRequired(ValueError):
"""A legacy seed cannot be made reboot-safe without replaying user-data."""
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 validate_private_network(private_ip_cidr: Any) -> dict[str, str]:
"""Validate one L3 VPC guest address.
Each guest address and the host route to that address use ``/32``. Guests
do not get a default route or provider gateway here; the separate seed
renderer adds exactly one on-link VPC CIDR route.
"""
if (not isinstance(private_ip_cidr, str)
or not private_ip_cidr
or private_ip_cidr != private_ip_cidr.strip()):
raise ValueError("私网 IP 必须采用 IPv4 地址/32 格式")
try:
interface = ipaddress.ip_interface(private_ip_cidr)
except ValueError as exc:
raise ValueError("私网 IP/CIDR 格式无效") from exc
if not isinstance(interface, ipaddress.IPv4Interface):
raise ValueError("私网一期仅支持 IPv4")
if interface.network.prefixlen != 32:
raise ValueError("私网实例地址必须使用 /32")
address = interface.ip
# ``is_private`` also includes loopback/link-local ranges, which are not
# valid tenant addresses. Explicitly keep the product contract to RFC1918
# space so a host-local or metadata address cannot be routed as a member.
if (not any(address in network for network in _RFC1918_NETWORKS)
or address.is_loopback or address.is_link_local
or address.is_reserved or address.is_multicast):
raise ValueError("私网 IP 必须是 RFC1918 IPv4 地址")
return {"private_ip_cidr": str(interface)}
def _validate_private_routes(
value: Any,
*,
allow_legacy: bool = True,
private_ip_cidr: str | None = None,
public_ip_cidr: str | None = None,
) -> list[str]:
"""Validate one stable VPC prefix or one legacy exact-/32 route set.
New seeds use exactly one RFC1918 /16../24 link-scope prefix. This keeps
the guest contract stable when members or service /32s change; exact host
routes, proxy neighbours and nftables destination sets remain the routing
authority. The parser still accepts an all-/32 legacy set so a stopped VM
can migrate, but mixed or ambiguous representations are rejected.
"""
if value is None:
value = []
if not isinstance(value, (list, tuple)) or len(value) > 4096:
raise ValueError("私网路由列表无效")
result: list[ipaddress.IPv4Network] = []
for item in value:
if isinstance(item, str):
destination = item
elif isinstance(item, dict):
if item.get("to") in {"default", "0.0.0.0/0", "::/0"}:
# Keep the legacy diagnostic used by seed validation callers:
# private0 is never allowed to acquire a default route.
raise ValueError("私网地址必须是静态 /32 且无默认路由")
if set(item) != {"to", "scope"} or item.get("scope") != "link":
raise ValueError("私网路由必须使用 link scope")
destination = item.get("to")
else:
raise ValueError("私网路由格式无效")
if destination in {"default", "0.0.0.0/0", "::/0"}:
raise ValueError("私网地址必须是静态 /32 且无默认路由")
try:
network = ipaddress.ip_network(destination, strict=True)
except (TypeError, ValueError) as exc:
raise ValueError("私网路由必须是 IPv4 网络") from exc
if (not isinstance(network, ipaddress.IPv4Network)
or not any(network.subnet_of(block)
for block in _RFC1918_NETWORKS)):
raise ValueError("私网路由必须位于 RFC1918 IPv4 空间")
result.append(network)
if len(set(result)) != len(result):
raise ValueError("私网路由不能重复")
legacy = all(network.prefixlen == 32 for network in result)
stable = bool(
len(result) == 1 and 16 <= result[0].prefixlen <= 24
)
if not stable and not (allow_legacy and legacy):
raise ValueError(
"私网路由必须是唯一 VPC /16 到 /24 前缀,"
"或完全由历史 /32 路由组成"
)
if private_ip_cidr is not None:
private_ip = ipaddress.ip_interface(
validate_private_network(private_ip_cidr)["private_ip_cidr"]
).ip
if stable and private_ip not in result[0]:
raise ValueError("私网实例地址必须位于 VPC 路由前缀内")
if public_ip_cidr is not None:
try:
public_network = ipaddress.ip_interface(public_ip_cidr).network
except (TypeError, ValueError) as exc:
raise ValueError("公网直连前缀无效") from exc
if any(network.overlaps(public_network) for network in result):
raise ValueError("VPC 前缀不能与公网网卡直连前缀重叠")
return sorted(str(network) for network in result)
def _validate_network_mac(value: Any, label: str) -> str:
if not isinstance(value, str) or not _MAC.fullmatch(value):
raise ValueError(f"{label} MAC 地址无效")
normalized = value.lower()
octets = [int(part, 16) for part in normalized.split(":")]
if octets[0] & 1 or not any(octets):
raise ValueError(f"{label} MAC 地址不能是组播或全零地址")
return normalized
def _parse_network_config(config: Any) -> dict[str, Any]:
"""Parse role-aware Netplan v2 data without accepting implicit bridges."""
if not isinstance(config, dict) or config.get("version") != 2:
raise ValueError("原 cloud-init 网络配置格式无效")
if (set(config) - {"version", "ethernets", "renderer"}
or ("renderer" in config and config["renderer"] != "networkd")):
raise ValueError("原 cloud-init 网络配置字段不受支持")
ethernets = config.get("ethernets")
if (not isinstance(ethernets, dict)
or not ethernets
or any(key not in {PUBLIC_INTERFACE_ROLE, PRIVATE_INTERFACE_ROLE}
for key in ethernets)):
raise ValueError("原 cloud-init 网卡角色格式无效")
if PUBLIC_INTERFACE_ROLE not in ethernets:
raise ValueError("原 cloud-init 网络配置缺少 public0")
public = ethernets[PUBLIC_INTERFACE_ROLE]
if not isinstance(public, dict):
raise ValueError("原 cloud-init 公网网卡配置无效")
if set(public) - {
"match", "dhcp4", "dhcp6", "addresses", "routes",
"nameservers", "accept-ra",
}:
raise ValueError("原 cloud-init 公网网卡字段不受支持")
match = public.get("match")
public_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 ("accept-ra" in public and public.get("accept-ra") is not False)
or not isinstance(public.get("addresses"), list)
or len(public["addresses"]) != 1
or not isinstance(public.get("routes"), list)
or len(public["routes"]) != 1
or not isinstance(public.get("nameservers"), dict)
or not isinstance(match, dict)
or set(match) != {"macaddress"}):
raise ValueError("原 cloud-init 公网网卡配置无效")
route = public["routes"][0]
if (not isinstance(route, dict) or route.get("to") != "0.0.0.0/0"
or set(route) != {"to", "via"}
or not isinstance(route.get("via"), str)):
raise ValueError("原 cloud-init 公网默认路由无效")
dns = public["nameservers"].get("addresses")
if (set(public["nameservers"]) != {"addresses"}
or not isinstance(dns, list)):
raise ValueError("原 cloud-init 公网 DNS 配置无效")
public_network = validate_cloud_network(
public["addresses"][0], route["via"], dns, require_auth=False,
)
public_mac = _validate_network_mac(public_mac, "公网")
result: dict[str, Any] = {
**public_network,
"mac": public_mac,
"roles": [PUBLIC_INTERFACE_ROLE],
}
private = ethernets.get(PRIVATE_INTERFACE_ROLE)
if private is not None:
if not isinstance(private, dict):
raise ValueError("原 cloud-init 私网网卡配置无效")
if set(private) - {
"match", "dhcp4", "dhcp6", "accept-ra", "addresses", "routes",
}:
raise ValueError("原 cloud-init 私网网卡字段不受支持")
private_match = private.get("match")
private_mac = (private_match.get("macaddress")
if isinstance(private_match, dict) else None)
if (private.get("dhcp4") is not False
or private.get("dhcp6") is not False
or private.get("accept-ra") is not False
or not isinstance(private.get("addresses"), list)
or len(private["addresses"]) != 1
or not isinstance(private_match, dict)
or set(private_match) != {"macaddress"}):
raise ValueError("原 cloud-init 私网地址必须是静态 /32 且无默认路由")
private_mac = _validate_network_mac(private_mac, "私网")
private_network = validate_private_network(private["addresses"][0])
if private_mac == public_mac:
raise ValueError("公网和私网网卡不能使用同一个 MAC")
result.update({
**private_network,
"private_mac": private_mac,
"private_routes": _validate_private_routes(
private.get("routes"),
private_ip_cidr=private_network["private_ip_cidr"],
public_ip_cidr=public_network["public_ip_cidr"],
),
"roles": [PUBLIC_INTERFACE_ROLE, PRIVATE_INTERFACE_ROLE],
})
return result
def build_seed_iso(
vm_uuid: str,
name: str,
mac: str,
validated_network: dict[str, Any],
*,
debian12_network_fix: bool = False,
private_mac: str | None = None,
private_network: dict[str, Any] | None = None,
) -> 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``).
PUBLIC_INTERFACE_ROLE: {
"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 (private_mac is None) != (private_network is None):
raise ValueError("私网网卡必须同时提供 MAC 和地址")
if private_mac is not None and private_network is not None:
normalized_private_mac = _validate_network_mac(private_mac, "私网")
private = validate_private_network(
private_network.get("private_ip_cidr")
if isinstance(private_network, dict) else None
)
private_routes = _validate_private_routes(
private_network.get("routes", [])
if isinstance(private_network, dict) else [],
allow_legacy=False,
private_ip_cidr=private["private_ip_cidr"],
public_ip_cidr=network["public_ip_cidr"],
)
if normalized_private_mac == normalized_mac:
raise ValueError("公网和私网网卡不能使用同一个 MAC")
network_config["ethernets"][PRIVATE_INTERFACE_ROLE] = {
"match": {"macaddress": normalized_private_mac},
"dhcp4": False,
"dhcp6": False,
"accept-ra": False,
"addresses": [private["private_ip_cidr"]],
**({"routes": [
{"to": destination, "scope": "link"}
for destination in private_routes
]} if private_routes else {}),
}
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"][PUBLIC_INTERFACE_ROLE]["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"])
_parse_network_config(config)
public = config["ethernets"][PUBLIC_INTERFACE_ROLE]
route = public["routes"][0]
# 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 replace_seed_private_network(
seed: bytes,
*,
private_mac: str | None,
private_ip_cidr: str | None,
private_routes: list[str] | tuple[str, ...] | None = None,
) -> bytes:
"""Add, replace, or remove the panel-managed ``private0`` network.
The public NIC, credentials, hostname and DNS settings are copied from
the existing panel seed. A private NIC never receives DHCP, IPv6 RA, or a
default route; its only address is the validated RFC1918 /32. Passing
``None`` for both values removes the private role and is used when a VPC
member is detached.
"""
if (private_mac is None) != (private_ip_cidr is None):
raise ValueError("私网网卡必须同时提供 MAC 和地址")
if private_mac is None and private_routes:
raise ValueError("移除私网网卡时不能保留路由")
files = _read_seed_files(seed)
try:
config = json.loads(files["network-config"])
parsed = _parse_network_config(config)
# Validate the complete existing role before editing it. This keeps a
# hand-edited or foreign seed from becoming a partially managed
# multi-NIC configuration.
_parse_network_config(config)
user_data = _enable_network_updates(files["user-data"])
metadata = _decode_seed_metadata(files["meta-data"])
if user_data != files["user-data"]:
# Changing instance-id would make NoCloud replay credential and
# sshd per-instance modules. Keeping the id may leave legacy
# cloud-init versions on their cached network policy. Refuse this
# ambiguous migration; a reinstall or explicit offline migration
# must establish boot-v1 first.
raise SeedNetworkPolicyMigrationRequired(
"原 cloud-init 配置盘缺少安全的启动网络更新策略")
ethernets = config.get("ethernets")
if not isinstance(ethernets, dict):
raise ValueError("原 cloud-init 网卡配置无效")
if private_mac is None:
network_unchanged = PRIVATE_INTERFACE_ROLE not in parsed["roles"]
if not network_unchanged:
ethernets.pop(PRIVATE_INTERFACE_ROLE, None)
else:
normalized_mac = _validate_network_mac(private_mac, "私网")
private = validate_private_network(private_ip_cidr)
routes = _validate_private_routes(
private_routes,
allow_legacy=False,
private_ip_cidr=private["private_ip_cidr"],
public_ip_cidr=parsed["public_ip_cidr"],
)
if normalized_mac == parsed["mac"]:
raise ValueError("公网和私网网卡不能使用同一个 MAC")
network_unchanged = bool(
PRIVATE_INTERFACE_ROLE in parsed["roles"]
and parsed.get("private_mac") == normalized_mac
and parsed.get("private_ip_cidr")
== private["private_ip_cidr"]
and parsed.get("private_routes", []) == routes
)
if not network_unchanged:
ethernets[PRIVATE_INTERFACE_ROLE] = {
"match": {"macaddress": normalized_mac},
"dhcp4": False,
"dhcp6": False,
"accept-ra": False,
"addresses": [private["private_ip_cidr"]],
**({"routes": [
{"to": destination, "scope": "link"}
for destination in routes
]} if routes else {}),
}
policy_unchanged = bool(
user_data == files["user-data"]
and metadata.get(_NETWORK_POLICY_KEY) == _NETWORK_POLICY_VALUE
)
# A waiting-observed VPC is retried periodically. Returning the exact
# original ISO for an identical target prevents every retry from
# inventing a new NoCloud instance and re-running per-instance modules
# at the next boot.
if network_unchanged and policy_unchanged:
return seed
# Never rotate the NoCloud instance identity for a network-only
# change. A new instance-id would make cloud-init run every
# per-instance module again, including the credentials and sshd
# policy stored in this seed. The explicit boot event above is the
# only mechanism used to consume the refreshed network-config.
metadata[_NETWORK_POLICY_KEY] = _NETWORK_POLICY_VALUE
network_data = json.dumps(config, ensure_ascii=True).encode("ascii") + b"\n"
return _build_seed_iso((
("/USERDATA.;1", "user-data", "/user-data", user_data),
("/METADATA.;1", "meta-data", "/meta-data",
_encode_seed_metadata(metadata)),
("/NETWORK.;1", "network-config", "/network-config", network_data),
))
except SeedNetworkPolicyMigrationRequired:
raise
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:
parsed = _parse_network_config(config)
result = {
"public_ip_cidr": parsed["public_ip_cidr"],
"gateway": parsed["gateway"],
"dns_servers": parsed["dns_servers"],
"mac": parsed["mac"],
}
if PRIVATE_INTERFACE_ROLE in parsed["roles"]:
result.update({
"private_ip_cidr": parsed["private_ip_cidr"],
"private_mac": parsed["private_mac"],
"private_routes": list(parsed.get("private_routes", [])),
"roles": list(parsed["roles"]),
})
return result
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("原 cloud-init 网络配置格式无效") from exc