96 lines
3.8 KiB
Python
96 lines
3.8 KiB
Python
"""Bounded migration of the observed NODE.DC B2 nftables policy; no flush."""
|
|
|
|
import hashlib
|
|
import json
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
CONFIG = Path("/etc/nftables.conf")
|
|
FRAGMENT = Path("/etc/nftables.d/ndc-mission-vps.nft")
|
|
BACKUP = Path("/opt/nodedc-mission-vps/firewall-before.json")
|
|
INCLUDE = 'include "/etc/nftables.d/ndc-mission-vps.nft"'
|
|
MARKER = "ndc-mission-vps-v1"
|
|
|
|
|
|
def run(*args, **kwargs):
|
|
return subprocess.run(args, check=True, capture_output=True, **kwargs)
|
|
|
|
|
|
def plan():
|
|
if not CONFIG.exists() or "table inet nodedc_b2_vps" not in CONFIG.read_text():
|
|
# A clean host can use its own provider firewall. Unknown local policies
|
|
# are not rewritten; public endpoint acceptance remains mandatory.
|
|
return {"mode": "external", "config_sha256": None}
|
|
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
|
chain = next(x["chain"] for x in live["nftables"] if "chain" in x)
|
|
if chain.get("policy") != "drop" or chain.get("hook") != "input":
|
|
raise ValueError("unsupported legacy firewall policy")
|
|
if FRAGMENT.exists() and MARKER not in FRAGMENT.read_text():
|
|
raise ValueError("foreign firewall fragment conflict")
|
|
return {
|
|
"mode": "nodedc-b2-v1",
|
|
"config_sha256": hashlib.sha256(CONFIG.read_bytes()).hexdigest(),
|
|
}
|
|
|
|
|
|
def rules(api, tracker):
|
|
return (
|
|
f"add rule inet nodedc_b2_vps input tcp dport {api} ct state new "
|
|
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-api"\n'
|
|
f"add rule inet nodedc_b2_vps input tcp dport {tracker} ct state new "
|
|
f'limit rate 600/minute burst 128 packets accept comment "{MARKER}-tracker"\n'
|
|
)
|
|
|
|
|
|
def removal():
|
|
live = json.loads(run("nft", "-j", "list", "chain", "inet", "nodedc_b2_vps", "input").stdout)
|
|
commands = []
|
|
for item in live["nftables"]:
|
|
rule = item.get("rule", {})
|
|
if rule.get("comment") in (MARKER + "-api", MARKER + "-tracker"):
|
|
commands.append(f"delete rule inet nodedc_b2_vps input handle {int(rule['handle'])}\n")
|
|
return "".join(commands)
|
|
|
|
|
|
def apply(proposal, api, tracker, atomic):
|
|
if proposal["mode"] != "nodedc-b2-v1":
|
|
return False
|
|
if plan() != proposal:
|
|
raise ValueError("firewall changed after plan")
|
|
content = rules(api, tracker)
|
|
if INCLUDE in CONFIG.read_text():
|
|
if not FRAGMENT.exists() or FRAGMENT.read_text() != content:
|
|
raise ValueError("managed firewall drift")
|
|
# Reconcile only our named live rules if nftables was reloaded.
|
|
run("nft", "-f", "-", input=(removal() + content).encode())
|
|
return False
|
|
original = CONFIG.read_text()
|
|
desired = original.rstrip() + "\n\n" + INCLUDE + "\n"
|
|
backup = {
|
|
"before": original,
|
|
"after_sha256": hashlib.sha256(desired.encode()).hexdigest(),
|
|
"fragment_sha256": hashlib.sha256(content.encode()).hexdigest(),
|
|
}
|
|
atomic(BACKUP, json.dumps(backup).encode())
|
|
FRAGMENT.parent.mkdir(mode=0o755, exist_ok=True)
|
|
# Validate the live transaction before modifying persistent files.
|
|
run("nft", "-c", "-f", "-", input=(removal() + content).encode())
|
|
atomic(FRAGMENT, content.encode(), 0o644)
|
|
atomic(CONFIG, desired.encode(), 0o644)
|
|
run("nft", "-f", "-", input=(removal() + content).encode())
|
|
return True
|
|
|
|
|
|
def rollback(atomic):
|
|
record = json.loads(BACKUP.read_text())
|
|
if (
|
|
hashlib.sha256(CONFIG.read_bytes()).hexdigest() != record["after_sha256"]
|
|
or hashlib.sha256(FRAGMENT.read_bytes()).hexdigest() != record["fragment_sha256"]
|
|
):
|
|
raise ValueError("firewall changed; rollback will not overwrite foreign edits")
|
|
commands = removal()
|
|
if commands:
|
|
run("nft", "-f", "-", input=commands.encode())
|
|
atomic(CONFIG, record["before"].encode(), 0o644)
|
|
FRAGMENT.unlink()
|