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.
363 lines
15 KiB
Python
363 lines
15 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
|
|
|
|
|
|
_VM_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z")
|
|
_MAC = re.compile(r"(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}\Z")
|
|
_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"
|
|
)
|
|
|
|
|
|
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 12 <= len(password) <= 128
|
|
or any(not char.isprintable() for char in password)):
|
|
raise ValueError("初始 root 密码须为 12 至 128 个可打印字符")
|
|
if (not any(char in string.ascii_uppercase for char in password)
|
|
or not any(char in string.ascii_lowercase for char in password)
|
|
or not any(not char.isalnum() and not char.isspace()
|
|
for char in password)):
|
|
raise ValueError("初始 root 密码须包含大写字母、小写字母和符号")
|
|
from passlib.hash import sha512_crypt
|
|
|
|
return sha512_crypt.using(rounds=100_000).hash(password)
|
|
|
|
|
|
def generate_root_password() -> str:
|
|
"""Generate a high-entropy password satisfying the same guest policy."""
|
|
symbols = "!@#$%*-_=+?"
|
|
alphabet = string.ascii_letters + string.digits + symbols
|
|
password = [
|
|
secrets.choice(string.ascii_uppercase),
|
|
secrets.choice(string.ascii_lowercase),
|
|
secrets.choice(symbols),
|
|
]
|
|
password.extend(secrets.choice(alphabet) for _ in range(29))
|
|
secrets.SystemRandom().shuffle(password)
|
|
return "".join(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,
|
|
) -> 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 地址不能重复")
|
|
public_key, password_hash = _validate_guest_auth(
|
|
guest_ssh_public_key, root_password_hash)
|
|
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],
|
|
) -> 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("网络配置无效")
|
|
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 = re.sub(r"[^a-z0-9-]", "-", name.lower()).strip("-")[:63]
|
|
if not hostname:
|
|
hostname = f"vm-{instance_id[:8]}"
|
|
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"
|
|
)
|
|
user_data = {
|
|
"users": [root_user],
|
|
"ssh_pwauth": use_password,
|
|
"disable_root": False,
|
|
"write_files": [{
|
|
"path": "/etc/ssh/sshd_config.d/00-virsh-panel-root.conf",
|
|
"content": sshd_config,
|
|
"permissions": "0644",
|
|
}],
|
|
}
|
|
metadata = {"instance-id": instance_id, "local-hostname": hostname}
|
|
network_config = {
|
|
"version": 2,
|
|
"ethernets": {
|
|
"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"]},
|
|
},
|
|
},
|
|
}
|
|
|
|
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"),
|
|
)
|
|
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:
|
|
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)
|
|
return output.getvalue()
|
|
finally:
|
|
iso.close()
|
|
|
|
|
|
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
|