feat(firewall): read the PVE firewall at every level, and the node's loaded ruleset (NetOrk/netork#2654)
This commit is contained in:
1 parent
dc0d6345a8
commit
c0453655b7
6 files changed
+412
No files matched your search
@@ -0,0 +1,190 @@
|
||||
"""The PVE firewall of the cluster, read-only (NetOrk/netork#2654).
|
||||
|
||||
``get_pve_firewall()`` reads what the operator wrote, at every level PVE has one:
|
||||
the datacenter's options, rules, security groups, IP sets and aliases, the node's
|
||||
options and rules, and each guest's on this node -- options, rules, and which NICs
|
||||
carry ``firewall=1``. The datacenter level is the cluster's (pmxcfs keeps it once
|
||||
for every node), so every node reads the same; a node reads its own guests, the
|
||||
ones it runs. Nothing is written: pve-firewall rules are the operator's (see
|
||||
``host_mixin``), and netOrk only reads them.
|
||||
|
||||
Each rule keeps PVE's own fields -- ``pos``, ``type`` (``in``, ``out``, ``group``,
|
||||
``forward``), ``action`` (``ACCEPT``, ``DROP``, ``REJECT``, or a group's name),
|
||||
``macro``, ``source``, ``dest``, ``proto``, ``dport``, ``sport``, ``iface``,
|
||||
``enable``, ``comment`` -- and says where it came from (``origin``: ``cluster``,
|
||||
``node``, ``guest`` or ``group``). A level whose call is refused (no
|
||||
``Sys.Audit``/``VM.Audit``) is None, not empty: an unread level is no claim.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_JsonDict = dict[str, Any]
|
||||
|
||||
#: The rule fields kept as PVE returns them.
|
||||
_RULE_FIELDS = (
|
||||
"pos",
|
||||
"type",
|
||||
"action",
|
||||
"macro",
|
||||
"source",
|
||||
"dest",
|
||||
"proto",
|
||||
"dport",
|
||||
"sport",
|
||||
"iface",
|
||||
"comment",
|
||||
"log",
|
||||
"icmp-type",
|
||||
)
|
||||
#: A guest's NIC keys: ``net0`` … for both QEMU and LXC.
|
||||
_NIC = re.compile(r"^net\d+$")
|
||||
|
||||
|
||||
def _rule(raw: _JsonDict, origin: str) -> _JsonDict:
|
||||
found = {k.replace("-", "_"): raw[k] for k in _RULE_FIELDS if raw.get(k) not in (None, "")}
|
||||
found["enable"] = str(raw.get("enable", 1)) not in ("0", "")
|
||||
found["origin"] = origin
|
||||
return found
|
||||
|
||||
|
||||
def _rules(rows: Any, origin: str) -> list[_JsonDict]:
|
||||
return [_rule(r, origin) for r in rows or [] if isinstance(r, dict)]
|
||||
|
||||
|
||||
def nic_firewalls(config: _JsonDict) -> list[_JsonDict]:
|
||||
"""Each NIC of a guest config with whether ``firewall=1`` is set on it."""
|
||||
found = []
|
||||
for key in sorted(k for k in config if _NIC.match(k)):
|
||||
options = dict(part.split("=", 1) for part in str(config[key]).split(",") if "=" in part)
|
||||
found.append({"name": key, "firewall": options.get("firewall") == "1"})
|
||||
return found
|
||||
|
||||
|
||||
def _read(call: Any, what: str) -> Any:
|
||||
"""One GET; None when PVE refuses or fails it -- an unread level, not an empty one."""
|
||||
try:
|
||||
return call.get()
|
||||
except Exception as exc: # noqa: BLE001 - proxmoxer raises its own and requests' errors
|
||||
logger.warning("get_pve_firewall: %s not read: %s", what, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _rules_or_none(rows: Any, origin: str) -> list[_JsonDict] | None:
|
||||
return None if rows is None else _rules(rows, origin)
|
||||
|
||||
|
||||
def _named(rows: Any, key: str) -> list[str]:
|
||||
return [str(r[key]) for r in rows or [] if isinstance(r, dict) and r.get(key)]
|
||||
|
||||
|
||||
def _groups(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||
"""Each security group's rules; a group whose rules are refused has none listed."""
|
||||
listed = _read(fw.groups, "security groups")
|
||||
if listed is None:
|
||||
return None
|
||||
return {
|
||||
name: _rules(_read(fw.groups(name), f"group {name}"), "group")
|
||||
for name in _named(listed, "group")
|
||||
}
|
||||
|
||||
|
||||
def _entry(raw: _JsonDict) -> _JsonDict:
|
||||
return {
|
||||
"cidr": raw.get("cidr"),
|
||||
"nomatch": bool(raw.get("nomatch")),
|
||||
"comment": raw.get("comment"),
|
||||
}
|
||||
|
||||
|
||||
def _ipsets(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||
listed = _read(fw.ipset, "IP sets")
|
||||
if listed is None:
|
||||
return None
|
||||
return {
|
||||
name: [
|
||||
_entry(e) for e in _read(fw.ipset(name), f"IP set {name}") or [] if isinstance(e, dict)
|
||||
]
|
||||
for name in _named(listed, "name")
|
||||
}
|
||||
|
||||
|
||||
def _aliases(rows: Any) -> dict[str, Any] | None:
|
||||
if rows is None:
|
||||
return None
|
||||
return {str(a["name"]): a.get("cidr") for a in rows if isinstance(a, dict) and a.get("name")}
|
||||
|
||||
|
||||
class ProxmoxFirewallMixin:
|
||||
"""``get_pve_firewall`` for the PVE driver: the cluster's firewall as written, read only."""
|
||||
|
||||
_node_name: str
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||
_api: Any
|
||||
|
||||
def _node_api(self) -> Any: ...
|
||||
|
||||
def _cluster_firewall(self) -> _JsonDict:
|
||||
fw = self._api.cluster.firewall
|
||||
return {
|
||||
"options": _read(fw.options, "datacenter options"),
|
||||
"rules": _rules_or_none(_read(fw.rules, "datacenter rules"), "cluster"),
|
||||
"groups": _groups(fw),
|
||||
"ipsets": _ipsets(fw),
|
||||
"aliases": _aliases(_read(fw.aliases, "aliases")),
|
||||
}
|
||||
|
||||
def _guest_firewall(self, kind: str, guest: _JsonDict) -> _JsonDict:
|
||||
vmid = int(guest.get("vmid", 0))
|
||||
api = getattr(self._node_api(), kind)(vmid)
|
||||
rules = _read(api.firewall.rules, f"{kind} {vmid} rules")
|
||||
config = _read(api.config, f"{kind} {vmid} config")
|
||||
return {
|
||||
"vmid": str(vmid),
|
||||
"type": "vm" if kind == "qemu" else "container",
|
||||
"name": guest.get("name") or "",
|
||||
"node": self._node_name,
|
||||
"options": _read(api.firewall.options, f"{kind} {vmid} options"),
|
||||
"rules": _rules_or_none(rules, "guest"),
|
||||
"nics": None if config is None else nic_firewalls(config),
|
||||
}
|
||||
|
||||
def _guests(self) -> list[_JsonDict]:
|
||||
found: list[_JsonDict] = []
|
||||
for kind in ("qemu", "lxc"):
|
||||
for guest in _read(getattr(self._node_api(), kind), f"{kind} guests") or []:
|
||||
if isinstance(guest, dict) and guest.get("vmid") is not None:
|
||||
found.append(self._guest_firewall(kind, guest))
|
||||
return found
|
||||
|
||||
def get_pve_firewall(self) -> _JsonDict:
|
||||
"""
|
||||
Return the PVE firewall as the operator wrote it: the datacenter level, this
|
||||
node's, and every guest's on this node. Read only.
|
||||
|
||||
* cluster (dict) - ``options``, ``rules``, ``groups`` (name -> rules),
|
||||
``ipsets`` (name -> ``[{cidr, nomatch, comment}]``), ``aliases`` (name -> cidr)
|
||||
* node (dict) - ``name``, ``options``, ``rules``
|
||||
* guests (list) - ``vmid``, ``type`` (``vm``/``container``), ``name``, ``node``,
|
||||
``options``, ``rules``, ``nics`` (``[{name, firewall}]``)
|
||||
|
||||
Any part PVE refuses is None, never empty. Each rule carries PVE's fields and
|
||||
its ``origin`` (``cluster``, ``group``, ``node``, ``guest``).
|
||||
"""
|
||||
node = self._node_api().firewall
|
||||
rules = _read(node.rules, "node rules")
|
||||
return {
|
||||
"cluster": self._cluster_firewall(),
|
||||
"node": {
|
||||
"name": self._node_name,
|
||||
"options": _read(node.options, "node options"),
|
||||
"rules": _rules_or_none(rules, "node"),
|
||||
},
|
||||
"guests": self._guests(),
|
||||
}
|
||||
Reference in new issue
Block a user