diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 6c2b2863..66194c08 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,5 +1,36 @@ # 本版验证记录 +## 2026-10-09:越过 nft 安装后发现的目录与回读兼容问题 + +- `6a99181` 已通过后台在线更新部署,SSH 确认 Engine 为新进程;新一轮真实 + operation 中 Alma 的 nft journal 已到 `refreshed`,两份 root-only snapshot + 已发布,证明原 nft 归属误拒绝已越过。Alma 随后的 profile 发布遇到现有 + NetworkManager 目录 `root:755`,原代码只允许 `700`;现只接受 root 自有、 + 无符号链接的 `700/750/755`,不 chmod 管理员已有目录,新目录仍建为 700, + 含私钥的 keyfile 和事务快照仍为 600,其他用户/不安全权限继续拒绝。 +- Debian 本轮推进至 `final_readback`。实际渲染路由校验可复现合法裸 IPv4 + host prefix 被 `/32` 字符串误拒绝;apply、boot 与 observe 统一只归一化 + canonical IPv4 host 地址,不改 `/24` 等更宽前缀、table/device、VPC proto + 186/完整 tuple 或重复路由门禁。boot 也精确排除自身 kernel local route。 +- boot nft 校验不再要求 8 个 ASCII 空格缩进,完整有序语义与 8 条精确 digest + 仍保留;observe 的错误嵌套 AWK `BEGIN` 改为顶层。NetworkManager profile + 以 metric 50 创建 peer route,apply/boot 的 replace 现在使用同一 metric, + 避免创建另一个 metric 0 的路由;ifupdown 行为不变,不清除未知旧路由。 +- 依据:[NetworkManager keyfile 安全规则](https://networkmanager.dev/docs/api/latest/nm-settings-keyfile.html)、 + [IPv4 route metric](https://networkmanager.dev/docs/api/latest/settings-ipv4.html)、 + [iproute2 host-prefix 输出](https://github.com/iproute2/iproute2/blob/main/ip/iproute.c) + 与 [Linux FIB replace 的 priority 匹配](https://github.com/torvalds/linux/blob/master/net/ipv4/fib_trie.c)。 +- 新增 NM 目录 26 项与 route/boot nft/observe/metric 67 项独立回归通过;只读 + 交叉审查执行全部渲染 apply/BOOT/observe 的 shell 检查及 166/67/59 个 AWK + 程序语法检查,无错误。最终稳定源码分组回归:Fabric/proc/helper/nft/NM + 八套联合 **641 passed、9 skipped**;route/Engine boundary/VPC/dataplane + 四套联合 **345 passed、23 warnings**。py_compile 与 diff 检查通过。 +- 最新修复完成后电脑锁屏,浏览器与 SSH 控制明确阻断,故未执行这一版在线更新 + 或新 operation。需解锁后继续;上方真实推进结果属于此前 `6a99181`,不得 + 把当前回归通过误写成宿主已部署或组网成功。 +- 本轮未手动清空规则、删除事务、停用 firewalld/SELinux 或改公网接口策略。 + 两台真实宿主尚未最终 active,双向 overlay、租户 VPC 与重启验收仍未通过。 + ## 2026-10-09:真实 nft 安装后归属校验修复 - 接管两台 electerm SSH 会话后,Debian 13 与 AlmaLinux 10 均确认 journal 为 diff --git a/engine/tests/test_fabric_nm_profile_directory.py b/engine/tests/test_fabric_nm_profile_directory.py new file mode 100644 index 00000000..fca322da --- /dev/null +++ b/engine/tests/test_fabric_nm_profile_directory.py @@ -0,0 +1,170 @@ +"""Run the actual rendered NetworkManager keyfile publication fragment.""" +from __future__ import annotations + +import base64 +import os +from pathlib import Path +import shlex +import subprocess +import sys + +import pytest + +from virsh_panel.fabric import _apply_script, parse_fabric_plan + + +@pytest.fixture(params=["native_nftables", "firewalld_nft"]) +def rendered_nm_publication(request): + plan = parse_fabric_plan({ + "fabric_id": "nm-dir-test", "region": "test", + "overlay_cidr": "100.64.1.0/24", "revision": 1, + "nodes": [ + {"host_id": "a", "overlay_ip": "100.64.1.1", + "endpoint": "203.0.113.1:51820"}, + {"host_id": "b", "overlay_ip": "100.64.1.2", + "endpoint": "203.0.113.2:51820"}, + ], + }) + keys = { + "a": base64.b64encode(bytes([1]) * 32).decode(), + "b": base64.b64encode(bytes([2]) * 32).decode(), + } + rendered = _apply_script( + plan, plan.nodes[0], keys, + deployment_mode="networkmanager_nmcli", firewall_mode=request.param, + ) + transaction_start = rendered.index( + "COMMITTED=no\nROLLBACK_FAILED=no\nJOURNAL_READY=no\n", + ) + functions_start = rendered.index("snapshot_file() {", transaction_start) + functions_end = rendered.index("restore_file() {", functions_start) + helper_publish = rendered.index( + 'publish_desired_file "$_tmp_helper" "$HELPER" helper', + ) + nm_start = rendered.index( + 'if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then\n' + " if [ -e /etc/NetworkManager/system-connections ] || " + "[ -L /etc/NetworkManager/system-connections ]; then", + helper_publish, + ) + nm_end = rendered.index( + '\nif [ "$DEPLOYMENT_MODE" = ifupdown ]; then', nm_start, + ) + return rendered[functions_start:functions_end], rendered[nm_start:nm_end] + + +_STAT_TOOL = r'''import os +from pathlib import Path +import stat +import sys + +assert sys.argv[1] == "-c" +path = Path(sys.argv[3]) +value = path.stat() +uid = os.environ["VC_DIR_UID"] if str(path) == os.environ["VC_DIR"] else "0" +mode = format(stat.S_IMODE(value.st_mode), "o") +fields = {"%u": uid, "%a": mode, "%u:%a": uid + ":" + mode} +print(fields[sys.argv[2]]) +''' + + +def _run_publication(rendered_nm_publication, tmp_path: Path, *, + mode: int | None = 0o700, uid: int = 0, + kind: str = "directory"): + functions, publication = rendered_nm_publication + manager = tmp_path / "NetworkManager" + manager.mkdir() + directory = manager / "system-connections" + if kind == "symlink": + other = tmp_path / "other" + other.mkdir(mode=0o700) + directory.symlink_to(other, target_is_directory=True) + elif kind == "dangling-symlink": + directory.symlink_to(tmp_path / "absent", target_is_directory=True) + elif kind == "file": + directory.write_text("external", encoding="utf-8") + elif mode is not None: + directory.mkdir() + directory.chmod(mode) + txn = tmp_path / "txn" + txn.mkdir(mode=0o700) + marker = txn / "nm_profile.absent" + marker.touch(mode=0o600) + key = tmp_path / "test.key" + test_key = base64.b64encode(bytes([3]) * 32).decode() + "\n" + key.write_text(test_key, encoding="utf-8") + key.chmod(0o600) + stat_tool = tmp_path / "stat-tool" + stat_tool.write_text( + "#!/bin/sh\nexec " + shlex.quote(sys.executable) + " -c " + + shlex.quote(_STAT_TOOL) + ' "$@"\n', encoding="utf-8", + ) + stat_tool.chmod(0o700) + publication = publication.replace( + "/etc/NetworkManager/system-connections", str(directory), + ) + profile = directory / "virt-cloud-wg-fabric0.nmconnection" + result = subprocess.run( + ["/bin/sh", "-c", "\n".join(( + "set -eu", "umask 077", functions, + 'STAT="$VC_STAT"', "CMP=cmp", 'TXN="$VC_TXN"', + 'KEY="$VC_KEY"', 'NM_PROFILE="$VC_PROFILE"', + "DEPLOYMENT_MODE=networkmanager_nmcli", publication, + ))], + env={**os.environ, "VC_STAT": str(stat_tool), "VC_TXN": str(txn), + "VC_KEY": str(key), "VC_PROFILE": str(profile), + "VC_DIR": str(directory), "VC_DIR_UID": str(uid)}, + check=False, capture_output=True, text=True, + ) + return result, directory, profile, txn, test_key + + +@pytest.mark.parametrize("mode", [0o700, 0o750, 0o755]) +def test_preserves_secure_existing_nm_directory_and_publishes_0600_profile( + rendered_nm_publication, tmp_path: Path, mode): + result, directory, profile, txn, key = _run_publication( + rendered_nm_publication, tmp_path, mode=mode, + ) + assert result.returncode == 0, result.stderr + assert directory.stat().st_mode & 0o7777 == mode + assert profile.stat().st_mode & 0o7777 == 0o600 + content = profile.read_text(encoding="utf-8") + assert "private-key=" + key in content + assert "interface-name=wg-fabric0\n" in content + assert "autoconnect=false\n" in content + snapshot = txn / "nm_profile.desired" + assert snapshot.read_bytes() == profile.read_bytes() + assert snapshot.stat().st_mode & 0o7777 == 0o600 + + +def test_creates_new_nm_directory_as_root_private( + rendered_nm_publication, tmp_path: Path): + result, directory, profile, _, _ = _run_publication( + rendered_nm_publication, tmp_path, mode=None, + ) + assert result.returncode == 0, result.stderr + assert directory.stat().st_mode & 0o7777 == 0o700 + assert profile.stat().st_mode & 0o7777 == 0o600 + + +@pytest.mark.parametrize(("mode", "uid", "kind"), [ + (0o775, 0, "directory"), (0o777, 0, "directory"), + (0o757, 0, "directory"), (0o770, 0, "directory"), + (0o1755, 0, "directory"), (0o700, 1000, "directory"), + (0o700, 0, "symlink"), (0o700, 0, "dangling-symlink"), + (0o700, 0, "file"), +]) +def test_rejects_unsafe_nm_directory_without_publishing_or_chmod( + rendered_nm_publication, tmp_path: Path, mode, uid, kind): + result, directory, profile, txn, _ = _run_publication( + rendered_nm_publication, tmp_path, mode=mode, uid=uid, kind=kind, + ) + assert result.returncode == 71 + assert not profile.exists() + assert not (txn / "nm_profile.desired").exists() + if kind == "directory": + assert directory.stat().st_mode & 0o7777 == mode + elif kind in {"symlink", "dangling-symlink"}: + assert directory.is_symlink() + else: + assert directory.read_text(encoding="utf-8") == "external" diff --git a/engine/tests/test_fabric_route_readback.py b/engine/tests/test_fabric_route_readback.py new file mode 100644 index 00000000..7ac03125 --- /dev/null +++ b/engine/tests/test_fabric_route_readback.py @@ -0,0 +1,246 @@ +"""Run real rendered Fabric route and boot-nft readback programs.""" +from __future__ import annotations + +import base64 +import re +import subprocess + +import pytest + +from virsh_panel.fabric import ( + FIREWALL_MODE_FIREWALLD, + _BOOT_HELPER, + _FABRIC_NFT_VALIDATION_SH, + _apply_script, + _nft_rules_text, + _observe_script, + parse_fabric_plan, +) + + +def _plan(): + return parse_fabric_plan({ + "fabric_id": "route-test", "region": "hk", + "overlay_cidr": "100.64.1.0/24", "revision": 1, + "nodes": [ + {"host_id": "a", "overlay_ip": "100.64.1.1", + "endpoint": "203.0.113.1:51820"}, + {"host_id": "b", "overlay_ip": "100.64.1.2", + "endpoint": "203.0.113.2:51820"}, + ], + }) + + +def _render_apply(mode="ifupdown"): + plan = _plan() + keys = {node.host_id: base64.b64encode(bytes([index]) * 32).decode() + for index, node in enumerate(plan.nodes, 1)} + return _apply_script(plan, plan.nodes[0], keys, deployment_mode=mode, + firewall_mode=FIREWALL_MODE_FIREWALLD) + + +def _assignment(script, name, start=0): + begin = script.index(name + "=$(printf", start) + end = script.index("')", begin) + 2 + return script[begin:end] + + +def _route_program(variant): + if variant.startswith("apply_"): + script = _render_apply() + # Embedded helper is intentionally not the program under test. + start = script.index("MANAGED_ROUTES=") + name = {"apply_preflight": "route_conflict", + "apply_final": "final_route_extra", + "apply_seen": "final_route_seen"}[variant] + if variant == "apply_seen": + start = script.index("for final_expected_route in", start) + else: + script = _BOOT_HELPER + start = 0 + name = {"boot_preflight": "route_conflict", + "boot_final": "route_extra", + "boot_seen": "route_seen"}[variant] + if variant == "boot_preflight": + start = script.index("if ! fabric_routes=") + if variant == "boot_seen": + start = script.index("for expected_route in") + return _assignment(script, name, start) + f'\nprintf "%s" "${name}"\n' + + +def _run_route(variant, routes, vpc_file="/dev/null"): + result = subprocess.run( + ["/bin/sh", "-eu", "-c", _route_program(variant)], + capture_output=True, text=True, check=False, + env={"IFACE": "wg-fabric0", "overlay": "100.64.1.1", + "allowed_routes": "100.64.1.2/32", + "MANAGED_ROUTES": "100.64.1.2/32", "OLD_MANAGED_ROUTES": "", + "fabric_routes": routes, "actual_fabric_routes": routes, + "final_fabric_routes": routes, "VPC_ROUTE_FILE": str(vpc_file), + "expected_route": "100.64.1.2/32", + "final_expected_route": "100.64.1.2/32"}, + ) + assert result.returncode == 0, result.stderr + return result.stdout + + +EXTRA_VARIANTS = ("apply_preflight", "apply_final", + "boot_preflight", "boot_final") +OWN_ROUTE = ("local 100.64.1.1 dev wg-fabric0 table local proto kernel " + "scope host src 100.64.1.1\n") + + +@pytest.mark.parametrize("variant", EXTRA_VARIANTS) +@pytest.mark.parametrize("prefix", ["100.64.1.2", "100.64.1.2/32"]) +def test_real_host_route_and_owned_local_route_are_equivalent(variant, prefix): + routes = f"{prefix} dev wg-fabric0 scope link\n" + OWN_ROUTE + assert _run_route(variant, routes) == "" + + +@pytest.mark.parametrize("variant", ["apply_seen", "boot_seen"]) +@pytest.mark.parametrize("prefix", ["100.64.1.2", "100.64.1.2/32"]) +def test_real_host_route_positive_readback(variant, prefix): + assert _run_route(variant, f"{prefix} dev wg-fabric0 scope link\n") == "1" + assert _run_route(variant, OWN_ROUTE) == "" + + +@pytest.mark.parametrize("variant", EXTRA_VARIANTS) +@pytest.mark.parametrize("foreign", [ + "100.64.1.2/24 dev wg-fabric0 scope link", + "100.64.1.3 dev wg-fabric0 scope link", + "100.64.1.02 dev wg-fabric0 scope link", + "100.64.1.256 dev wg-fabric0 scope link", + "100.64.1.2 dev br0 scope link", + "100.64.1.2 dev wg-fabric0 table 100 scope link", + "local 100.64.1.1 dev br0 table local proto kernel scope host", + "local 100.64.1.1 dev wg-fabric0 table 100 proto kernel scope host", + "default dev wg-fabric0", + "100.64.1.2 dev wg-fabric0\n100.64.1.2/32 dev wg-fabric0", +]) +def test_host_canonicalization_keeps_foreign_and_duplicate_routes_blocked( + variant, foreign): + assert _run_route(variant, foreign + "\n") in ("foreign", "extra") + + +@pytest.mark.parametrize("variant", EXTRA_VARIANTS) +def test_vpc_host_route_requires_exact_owned_tuple_and_protocol(tmp_path, variant): + vpc_file = tmp_path / "routes" + vpc_file.write_text( + "10.1.0.3/32|wg-fabric0|100|100.64.1.2|100\n", encoding="utf-8") + normal = "100.64.1.2 dev wg-fabric0 scope link\n" + OWN_ROUTE + vpc = ("10.1.0.3 via 100.64.1.2 dev wg-fabric0 table 100 " + "proto 186 metric 100 scope link\n") + assert _run_route(variant, normal + vpc, vpc_file) == "" + for changed in (vpc.replace("proto 186", "proto static"), + vpc.replace("metric 100", "metric 101"), + vpc.replace("table 100", "table 101"), + vpc.replace("via 100.64.1.2", "via 100.64.1.3")): + assert _run_route(variant, normal + changed, vpc_file) in ("foreign", "extra") + + +def _boot_nft_program(): + start = _BOOT_HELPER.index("validate_nft_table() {") + end = _BOOT_HELPER.index("\nfabric_acl_ready()", start) + return (_FABRIC_NFT_VALIDATION_SH + "\n" + _BOOT_HELPER[start:end] + + '\ntable=$(cat)\nvalidate_nft_table "$table"\n') + + +@pytest.mark.parametrize("indent", ["spaces", "tabs"]) +@pytest.mark.parametrize("named_output", [False, True]) +def test_boot_nft_owner_readback_ignores_only_serialization_indentation( + indent, named_output): + plan = _plan() + rules = _nft_rules_text(plan.digest) + if indent == "tabs": + rules = re.sub(r"^( )+", lambda match: "\t" * (len(match[0]) // 4), + rules, flags=re.MULTILINE) + if named_output: + rules = rules.replace("hook output priority -100", "hook output priority dstnat") + result = subprocess.run(["/bin/sh", "-eu", "-c", _boot_nft_program()], + input=rules, capture_output=True, text=True, + env={"EXPECTED_DIGEST": plan.digest}, check=False) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("drift", ["digest", "verdict", "extra_rule", "extra_chain"]) +def test_boot_nft_whitespace_fix_keeps_complete_ownership_validation(drift): + plan = _plan() + rules = _nft_rules_text(plan.digest) + if drift == "digest": + rules = rules.replace(plan.digest, "a" * 64) + elif drift == "verdict": + rules = rules.replace("counter drop", "counter accept", 1) + elif drift == "extra_rule": + rules = rules.replace(" chain output {", ( + ' chain output {\n oifname "wg-fabric0" accept')) + else: + rules = rules.replace(" chain output {", " chain foreign {\n }\n chain output {") + result = subprocess.run(["/bin/sh", "-eu", "-c", _boot_nft_program()], + input=rules, capture_output=True, text=True, + env={"EXPECTED_DIGEST": plan.digest}, check=False) + assert result.returncode != 0 + + +def test_observe_route_awk_runs_begin_outside_record_action(tmp_path): + script = _observe_script(("100.64.1.2",), "100.64.1.1", + endpoint_ips=("203.0.113.2",), + deployment_mode="ifupdown", + firewall_mode=FIREWALL_MODE_FIREWALLD) + start = script.index('awk -v vpc_file="${VPC_ROUTE_FILE:-}"') + program = script[start:script.index("\n }'", start) + len("\n }'")] + program = program.replace('"${VPC_ROUTE_FILE:-}"', '"$VPC_ROUTE_FILE"') + vpc_file = tmp_path / "routes" + vpc_file.write_text("10.1.0.3/32|wg-fabric0|100|100.64.1.2|100\n", + encoding="utf-8") + routes = ("100.64.1.2 dev wg-fabric0 scope link\n" + OWN_ROUTE + + "10.1.0.3 via 100.64.1.2 dev wg-fabric0 table 100 proto 186 metric 100\n") + result = subprocess.run(["/bin/sh", "-eu", "-c", program], input=routes, + capture_output=True, text=True, check=False, + env={"VPC_ROUTE_FILE": str(vpc_file), "VPC_STATE_STATUS": "valid"}) + assert result.returncode == 0, result.stderr + assert result.stdout.splitlines() == [ + "__VC_FABRIC_ROUTE__=100.64.1.2/32|main|wg-fabric0", + "__VC_FABRIC_ROUTE__=100.64.1.1/32|local|wg-fabric0", + ] + + +@pytest.mark.parametrize("mode", ["ifupdown", "networkmanager_nmcli"]) +def test_apply_and_boot_replace_the_same_route_priority_as_selected_manager(mode): + script = _render_apply(mode) + generated = re.findall(r"^\$IP route replace [^\n]+$", script, re.MULTILINE) + assert len(generated) == 1 + # Inspect the rendered keyfile rather than invent a second expected metric. + keyfile_metric = re.search(r"^route-metric=([0-9]+)$", script, re.MULTILINE)[1] + metric = keyfile_metric if mode == "networkmanager_nmcli" else "0" + assert (" metric " + keyfile_metric in generated[0]) == ( + mode == "networkmanager_nmcli") + + boot_start = _BOOT_HELPER.index( + "while IFS='|' read -r kind a b c d; do\n" + " [ \"$kind\" = route ] || continue\n", + _BOOT_HELPER.index('"$WG" set "$IFACE" listen-port "$listen"'), + ) + boot_end = _BOOT_HELPER.index("done < \"$CONF\"", boot_start) + len('done < "$CONF"') + # Run actual shell commands with an argv-only IP double. This test has no + # route mutation privileges; it verifies both sources address the same + # kernel route key, independently of optional host integration tests. + capture = 'mock_ip() { printf "%s\\n" "$*"; }; IP=mock_ip\n' + apply = subprocess.run(["/bin/sh", "-eu", "-c", capture + generated[0]], + capture_output=True, text=True, + env={"IFACE": "wg-fabric0"}, check=False) + boot = subprocess.run( + ["/bin/sh", "-eu", "-c", capture + _BOOT_HELPER[boot_start:boot_end]], + input="route|100.64.1.2/32\n", capture_output=True, text=True, + env={"IFACE": "wg-fabric0", "DEPLOYMENT_MODE": mode, "CONF": "/dev/stdin"}, + check=False, + ) + assert apply.returncode == boot.returncode == 0 + assert apply.stdout == boot.stdout + args = apply.stdout.split() + replacement_metric = args[args.index("metric") + 1] if "metric" in args else "0" + assert replacement_metric == metric + # The documented kernel key includes priority. Existing NM priority50 or + # ifupdown priority0 gets replaced, not duplicated by a different key. + route_keys = {("100.64.1.2/32", "main", metric)} + route_keys.add((args[2], args[4], replacement_metric)) + assert len(route_keys) == 1 diff --git a/engine/virsh_panel/fabric.py b/engine/virsh_panel/fabric.py index 0bcf1171..64811ed2 100644 --- a/engine/virsh_panel/fabric.py +++ b/engine/virsh_panel/fabric.py @@ -1962,6 +1962,21 @@ table inet {FABRIC_NFT_TABLE} {{ ''' +_FABRIC_ROUTE_VALIDATION_AWK = r''' +function canonical_host_prefix(value, octet, count, pos) { + # iproute2 omits /32 for host routes. Canonicalize only an exact IPv4 + # address; never turn a broader or malformed prefix into an owned /32. + if (index(value, "/")) return value + count=split(value, octet, ".") + if (count != 4) return value + for (pos=1; pos<=4; pos++) { + if (octet[pos] !~ /^(0|[1-9][0-9]*)$/ || octet[pos] > 255) return value + } + return value "/32" +} +'''.strip() + + _FABRIC_NFT_VALIDATION_SH = r''' vc_fabric_nft_strict_shape() { vc_fabric_nft_text=$1 @@ -5679,11 +5694,13 @@ done < "$CONF" if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then if ! fabric_routes=$($IP -o route show table all dev "$IFACE" 2>/dev/null); then exit 75; fi route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own="$overlay" -v allowed="$allowed_routes" -v vpc_file="$VPC_ROUTE_FILE" ' + __VC_FABRIC_ROUTE_VALIDATION_AWK__ BEGIN {while ((getline line < vpc_file) > 0) {n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1} close(vpc_file)} NF {prefix=$1; if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + prefix=canonical_host_prefix(prefix) table="main"; device=""; via="-"; metric="100"; proto=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)} if (table=="254") table="main"; if (table=="255") table="local" - if (prefix==own && (table=="local" || table=="main") && device==iface) next + if (prefix==canonical_host_prefix(own) && (table=="local" || table=="main") && device==iface) next if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 if (table!="main" || device!=iface || !ok || ++seen[prefix]>1) {print "foreign"; exit}}') @@ -5732,14 +5749,10 @@ else fi validate_nft_table() { vc_fabric_nft_strict_shape "$1" || return 1 - nft_owner_count=$(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip protocol icmp accept comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip protocol icmp accept comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip saddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip daddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " iifname \"wg-fabric0\" ip saddr @vpc_tenant_ips ip daddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) - nft_owner_count=$((nft_owner_count + $(printf '%s\n' "$1" | grep -Fxc " oifname \"wg-fabric0\" ip daddr @vpc_tenant_ips ip saddr != @vpc_tenant_ips counter drop comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true))) + # The strict grammar above already proves all eight complete expressions. + # nft lists them with tabs or spaces depending on its serializer; bind + # their exact digest without depending on presentation indentation. + nft_owner_count=$(printf '%s\n' "$1" | grep -Foc "comment \"virt-cloud-wg-fabric-v1:$EXPECTED_DIGEST\"" || true) nft_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain [A-Za-z0-9_.-]+ \{' || true) nft_named_chain_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]*chain (input|output|forward) \{' || true) nft_rule_count=$(printf '%s\n' "$1" | grep -Ec '^[[:space:]]+(iifname|oifname) "wg-fabric0".* (accept|drop)( |$)' || true) @@ -6461,7 +6474,14 @@ while IFS='|' read -r kind a b c d; do done < "$CONF" while IFS='|' read -r kind a b c d; do [ "$kind" = route ] || continue - "$IP" route replace "$a" table main dev "$IFACE" + if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then + # Priority is part of the kernel route replacement key. Match the + # NetworkManager keyfile's route-metric rather than create a second + # priority-zero alias for the same owned host route. + "$IP" route replace "$a" table main dev "$IFACE" metric 50 + else + "$IP" route replace "$a" table main dev "$IFACE" + fi done < "$CONF" recover_vpc_dataplanes actual_peers=$("$WG" show "$IFACE" peers 2>/dev/null) || exit 78 @@ -6472,22 +6492,26 @@ for expected_peer in $seen_peers; do case " $actual_peers " in *" $expected_peer "*) : ;; *) exit 78 ;; esac done actual_fabric_routes=$("$IP" -o route show table all dev "$IFACE" 2>/dev/null) || exit 78 - route_extra=$(printf '%s\n' "$actual_fabric_routes" | awk -v allowed="$allowed_routes" -v vpc_file="$VPC_ROUTE_FILE" ' + route_extra=$(printf '%s\n' "$actual_fabric_routes" | awk -v allowed="$allowed_routes" -v own="$overlay" -v vpc_file="$VPC_ROUTE_FILE" ' + __VC_FABRIC_ROUTE_VALIDATION_AWK__ BEGIN {while ((getline line < vpc_file) > 0) {n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1} close(vpc_file)} NF { prefix=$1 if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + prefix=canonical_host_prefix(prefix) table="main"; device=""; via="-"; metric="100"; proto="" for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)} if (table=="254") table="main"; if (table=="255") table="local" + if (prefix==canonical_host_prefix(own) && (table=="local" || table=="main") && device=="wg-fabric0") next if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 - if (!ok || table!="main" || device!="wg-fabric0") {print "extra"; exit} + if (!ok || table!="main" || device!="wg-fabric0" || ++seen[prefix]>1) {print "extra"; exit} }') [ -z "$route_extra" ] || exit 78 for expected_route in $allowed_routes; do route_seen=$(printf '%s\n' "$actual_fabric_routes" | awk -v wanted="$expected_route" ' - NF {prefix=$1; table="main"; device=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)} if (prefix==wanted && table=="main" && device=="wg-fabric0") {print 1; exit}}') + __VC_FABRIC_ROUTE_VALIDATION_AWK__ + NF {prefix=canonical_host_prefix($1); table="main"; device=""; for (i=1;i<=NF;i++) {if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1)} if (prefix==wanted && table=="main" && device=="wg-fabric0") {print 1; exit}}') [ "$route_seen" = 1 ] || exit 78 done for route in $allowed_routes; do @@ -6520,6 +6544,9 @@ _BOOT_HELPER = _BOOT_HELPER.replace( ).replace( "__VC_VPC_SYSCTL_VALIDATION__", VPC_SYSCTL_VALIDATION_SH, + ).replace( + "__VC_FABRIC_ROUTE_VALIDATION_AWK__", + _FABRIC_ROUTE_VALIDATION_AWK, ) _LIBVIRT_GATE_GENERATOR = r'''#!/bin/sh @@ -8209,7 +8236,8 @@ def _apply_script(plan: FabricPlan, host: FabricNode, route_keys = " ".join( _q(p.allowed_ip) for p in plan.nodes if p.host_id != host.host_id) route_commands = "\n".join( - f"$IP route replace {_q(p.allowed_ip)} table main dev $IFACE" + (f"$IP route replace {_q(p.allowed_ip)} table main dev $IFACE" + + (" metric 50" if deployment_mode == "networkmanager_nmcli" else "")) for p in plan.nodes if p.host_id != host.host_id) path_checks = "\n".join( "fabric_path=$($IP route get %s from %s 2>/dev/null) || exit 78\n" @@ -8364,11 +8392,13 @@ done if "$IP" link show dev "$IFACE" >/dev/null 2>&1; then if ! fabric_routes=$($IP -o route show table all dev "$IFACE" 2>/dev/null); then exit 75; fi route_conflict=$(printf '%s\n' "$fabric_routes" | awk -v iface="$IFACE" -v own={_q(host.overlay_ip)} -v allowed="$MANAGED_ROUTES $OLD_MANAGED_ROUTES" -v vpc_file="$VPC_ROUTE_FILE" ' + {_FABRIC_ROUTE_VALIDATION_AWK} BEGIN {{while ((getline line < vpc_file) > 0) {{n=split(line, parts, "|"); if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1}} close(vpc_file)}} NF {{prefix=$1; if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + prefix=canonical_host_prefix(prefix) table="main"; device=""; via="-"; metric="100"; proto=""; for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)}} if (table=="254") table="main"; if (table=="255") table="local" - if (prefix==own && (table=="local" || table=="main") && device==iface) next + if (prefix==canonical_host_prefix(own) && (table=="local" || table=="main") && device==iface) next if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0; n=split(allowed, values, " "); for (i=1;i<=n;i++) if (values[i]==prefix) ok=1 if (table!="main" || device!=iface || !ok || ++seen[prefix]>1) {{print "foreign"; exit}}}}') @@ -8443,9 +8473,17 @@ done < "$CONF" fi''' nm_write = f'''if [ "$DEPLOYMENT_MODE" = networkmanager_nmcli ]; then - if [ -e /etc/NetworkManager/system-connections ]; then + if [ -e /etc/NetworkManager/system-connections ] || [ -L /etc/NetworkManager/system-connections ]; then [ -d /etc/NetworkManager/system-connections ] && [ ! -L /etc/NetworkManager/system-connections ] || exit 71 - [ "$($STAT -c '%u:%a' /etc/NetworkManager/system-connections 2>/dev/null)" = 0:700 ] || exit 71 + # RHEL/AlmaLinux may ship this root-owned directory as 0755. + # Traversal/listing is not key disclosure: the individual keyfile is + # still root-only 0600. Never accept non-root or writable-by-others + # directories, and never chmod a pre-existing administrator directory. + nm_profile_directory_owner_mode=$($STAT -c '%u:%a' /etc/NetworkManager/system-connections 2>/dev/null) || exit 71 + case "$nm_profile_directory_owner_mode" in + 0:700|0:750|0:755) : ;; + *) exit 71 ;; + esac else mkdir -p /etc/NetworkManager/system-connections chmod 700 /etc/NetworkManager/system-connections @@ -9136,6 +9174,7 @@ if [ "$FIREWALL_MODE" = firewalld_nft ] || final_route_extra=$(printf '%s\n' "$final_fabric_routes" | awk \ -v allowed="$MANAGED_ROUTES" -v own={_q(host.overlay_ip)} \ -v vpc_file="$VPC_ROUTE_FILE" ' + {_FABRIC_ROUTE_VALIDATION_AWK} BEGIN {{while ((getline line < vpc_file) > 0) {{ n=split(line, parts, "|") if (n>=5) vpc[parts[1] "|" parts[2] "|" parts[3] "|" parts[4] "|" parts[5]]=1 @@ -9144,6 +9183,7 @@ if [ "$FIREWALL_MODE" = firewalld_nft ] || prefix=$1 if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + prefix=canonical_host_prefix(prefix) table="main"; device=""; via="-"; metric="100"; proto="" for (i=1;i<=NF;i++) {{ if ($i=="table") table=$(i+1) @@ -9154,7 +9194,7 @@ if [ "$FIREWALL_MODE" = firewalld_nft ] || }} if (table=="254") table="main" if (table=="255") table="local" - if (prefix==own && (table=="local" || table=="main") && device=="wg-fabric0") next + if (prefix==canonical_host_prefix(own) && (table=="local" || table=="main") && device=="wg-fabric0") next if (table!="main" && proto=="186" && vpc[prefix "|" device "|" table "|" via "|" metric]) next ok=0 @@ -9167,8 +9207,9 @@ if [ "$FIREWALL_MODE" = firewalld_nft ] || [ -z "$final_route_extra" ] || exit 71 for final_expected_route in $MANAGED_ROUTES; do final_route_seen=$(printf '%s\n' "$final_fabric_routes" | awk -v wanted="$final_expected_route" ' + {_FABRIC_ROUTE_VALIDATION_AWK} NF {{ - prefix=$1; table="main"; device="" + prefix=canonical_host_prefix($1); table="main"; device="" for (i=1;i<=NF;i++) {{ if ($i=="table") table=$(i+1) if ($i=="dev") device=$(i+1) @@ -9773,7 +9814,8 @@ if "$IP" link show dev "$IFACE" >/dev/null 2>&1 && "$WG" show "$IFACE" >/dev/nul printf '%s\\n' "__VC_FABRIC_PEER__=$peer|$endpoint|$allowed" printf '%s\\n' "__VC_FABRIC_HANDSHAKE__=$peer|$handshake" done - $IP -o route show table all dev "$IFACE" 2>/dev/null | awk -v vpc_file="${{VPC_ROUTE_FILE:-}}" -v vpc_state="${{VPC_STATE_STATUS:-invalid}}" '{{ + $IP -o route show table all dev "$IFACE" 2>/dev/null | awk -v vpc_file="${{VPC_ROUTE_FILE:-}}" -v vpc_state="${{VPC_STATE_STATUS:-invalid}}" ' + {_FABRIC_ROUTE_VALIDATION_AWK} BEGIN {{ if (vpc_state != "invalid" && vpc_file != "") {{ while ((getline line < vpc_file) > 0) {{ @@ -9783,8 +9825,10 @@ if "$IP" link show dev "$IFACE" >/dev/null 2>&1 && "$WG" show "$IFACE" >/dev/nul close(vpc_file) }} }} + NF {{ table="main"; device=""; via="-"; metric="100"; proto=""; prefix=$1 if ($1=="local" || $1=="broadcast" || $1=="unreachable" || $1=="blackhole" || $1=="prohibit" || $1=="throw") prefix=$2 + prefix=canonical_host_prefix(prefix) for (i=1;i<=NF;i++) {{if ($i=="table") table=$(i+1); if ($i=="dev") device=$(i+1); if ($i=="via") via=$(i+1); if ($i=="metric") metric=$(i+1); if ($i=="proto") proto=$(i+1)}} if (table=="254") table="main" if (table=="255") table="local"