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/network_roles.py

200 lines
7.9 KiB
Python

"""Stable guest network-role helpers shared by cloud-init and libvirt.
The public interface is the only interface that may carry the panel's
provider-facing anti-spoofing/nwfilter policy. A VPC interface is a separate
L3 dataplane and must never be inferred from the public bridge. Product and
cloud-init role names deliberately remain separate from libvirt device
aliases: libvirt requires every user-supplied alias to start with ``ua-``.
"""
from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from typing import Any
PUBLIC_INTERFACE_ROLE = "public0"
PRIVATE_INTERFACE_ROLE = "private0"
SUPPORTED_INTERFACE_ROLES = frozenset({
PUBLIC_INTERFACE_ROLE,
PRIVATE_INTERFACE_ROLE,
})
PUBLIC_LIBVIRT_ALIAS = f"ua-{PUBLIC_INTERFACE_ROLE}"
PRIVATE_LIBVIRT_ALIAS = f"ua-{PRIVATE_INTERFACE_ROLE}"
SUPPORTED_LIBVIRT_ALIASES = frozenset({
PUBLIC_LIBVIRT_ALIAS,
PRIVATE_LIBVIRT_ALIAS,
})
# Libvirt permits these characters in a device alias. Role recognition below
# remains an exact allowlist; accepting the complete syntax here only ensures
# that an operator alias is classified as unknown instead of being mistaken
# for malformed XML.
_ALIAS_RE = re.compile(r"[A-Za-z0-9_-]+\Z")
# Read-only compatibility for definitions produced before the libvirt alias
# contract was separated from the cloud-init role keys. New XML must never
# write either of these values as a device alias.
_LEGACY_PUBLIC_ROLE_ALIASES = frozenset({PUBLIC_INTERFACE_ROLE})
_LEGACY_PRIVATE_ROLE_ALIASES = frozenset({PRIVATE_INTERFACE_ROLE})
# libvirt adds a generated interface alias when an older domain definition did
# not provide one. Those aliases can identify the legacy public NIC, but they
# do not constitute an explicit private role. Keep the compatibility scope
# narrow so an arbitrary operator alias is never silently treated as public.
_LEGACY_PUBLIC_ALIAS_RE = re.compile(r"(?:net|ua-net-)[0-9]+\Z")
def _is_legacy_public_alias(alias: str | None) -> bool:
return alias is not None and _LEGACY_PUBLIC_ALIAS_RE.fullmatch(alias) is not None
def interface_alias(interface: ET.Element) -> str | None:
"""Return a validated libvirt interface alias, if one is present."""
alias = interface.find("alias")
value = alias.get("name") if alias is not None else None
if value is None:
return None
if not isinstance(value, str) or not _ALIAS_RE.fullmatch(value):
raise ValueError("虚拟机网卡别名无效")
return value
def set_libvirt_interface_alias(
root: ET.Element,
interface: ET.Element,
alias: str,
) -> None:
"""Set one panel alias after proving domain-wide device uniqueness."""
if alias not in SUPPORTED_LIBVIRT_ALIASES:
raise ValueError("libvirt 网卡别名不受支持")
devices = root.find("./devices")
if devices is None:
raise ValueError("虚拟机 XML 缺少 devices")
current = interface.find("alias")
for candidate in devices.iter("alias"):
if candidate is current:
continue
if candidate.get("name") == alias:
raise ValueError("libvirt 设备别名在虚拟机内重复")
if current is None:
current = ET.SubElement(interface, "alias")
current.set("name", alias)
def interface_role(interface: ET.Element, *, legacy_public: bool = False) -> str:
"""Classify one interface without guessing a role for a multi-NIC VM.
A legacy single-NIC domain with no alias, or with libvirt's generated
``net0``/``ua-net-0`` alias, is treated as public for backwards
compatibility when ``legacy_public`` is requested. An unaliased or
generated interface in a multi-NIC domain is intentionally ``unknown``
and must be rejected by callers that apply a security policy.
"""
alias = interface_alias(interface)
if alias == PUBLIC_LIBVIRT_ALIAS or alias in _LEGACY_PUBLIC_ROLE_ALIASES:
return "public"
if alias == PRIVATE_LIBVIRT_ALIAS or alias in _LEGACY_PRIVATE_ROLE_ALIASES:
return "private"
if alias is not None:
if legacy_public and _is_legacy_public_alias(alias):
return "public"
return "unknown"
if legacy_public and alias is None:
return "public"
return "unknown"
def role_for_cloud_key(key: Any) -> str:
"""Map a cloud-init ethernet key to a product network role."""
if key == PUBLIC_INTERFACE_ROLE:
return "public"
if key == PRIVATE_INTERFACE_ROLE:
return "private"
raise ValueError("cloud-init 网卡角色不受支持")
def select_public_interface(
interfaces: list[ET.Element] | tuple[ET.Element, ...],
*,
allow_legacy: bool = True,
) -> ET.Element:
"""Select the provider-facing NIC and validate every other NIC's role.
New definitions must label every interface. An old one-NIC domain without
an alias is still safely identifiable as public. A generated
``netN``/``ua-net-N`` alias also remains identifiable after one explicit
private NIC is live-attached: this is the transient live XML shape until
the guest restarts with its migrated persistent ``ua-public0`` alias.
Every other multi-NIC ambiguity is rejected.
"""
values = list(interfaces)
if not values:
raise ValueError("虚拟机缺少网卡")
candidates = [
item for item in values
if interface_role(item, legacy_public=False) == "public"
]
if not candidates and allow_legacy and len(values) == 1:
if interface_role(values[0], legacy_public=True) == "public":
candidates = [values[0]]
if not candidates and allow_legacy and len(values) > 1:
generated = [
item for item in values
if _is_legacy_public_alias(interface_alias(item))
]
if len(generated) == 1 and all(
item is generated[0] or interface_role(item) == "private"
for item in values
):
candidates = generated
if len(candidates) != 1:
raise ValueError("虚拟机公网网卡角色不明确")
selected = candidates[0]
private_count = 0
for item in values:
if item is selected:
continue
role = interface_role(item)
if role == "private":
private_count += 1
elif role == "unknown":
raise ValueError("多网卡虚拟机必须声明每张网卡的角色")
if private_count > 1:
raise ValueError("虚拟机不能包含多张 private0 网卡")
return selected
def select_private_interface(
interfaces: list[ET.Element] | tuple[ET.Element, ...],
) -> ET.Element | None:
"""Return the single explicit private NIC, if a domain has one."""
candidates = [
item for item in interfaces
if interface_role(item, legacy_public=False) == "private"
]
if len(candidates) > 1:
raise ValueError("虚拟机不能包含多张 private0 网卡")
return candidates[0] if candidates else None
def assert_public_interface(interface: ET.Element, *, legacy_public: bool = False) -> None:
"""Reject attaching public policy to a private or ambiguous interface."""
role = interface_role(interface, legacy_public=legacy_public)
if role != "public":
raise ValueError("公网过滤器只能绑定 public0 网卡")
def private_interface_has_public_filter(interface: ET.Element) -> bool:
"""Return whether a non-public role carries a public filter reference.
An explicitly private NIC is the normal case. Treating an unknown alias
as unsafe here also matters during migration: a future or externally
edited NIC must never become an unreviewed place to attach a provider
anti-spoofing policy.
"""
role = interface_role(interface)
# The private dataplane is governed by its own nftables context. Any
# libvirt nwfilter on a non-public NIC is therefore outside this contract;
# accepting an arbitrary filter would make it impossible to prove that a
# provider anti-spoofing policy was not copied to the private interface.
return role != "public" and bool(interface.findall("filterref"))