diff --git a/deploy/systemd/coulobre-fail2ban.service b/deploy/systemd/coulobre-fail2ban.service new file mode 100644 index 0000000..45dd752 --- /dev/null +++ b/deploy/systemd/coulobre-fail2ban.service @@ -0,0 +1,23 @@ +[Unit] +Description=Coulobre Fail2ban instance +After=coulobre-firewall.service network.target + +[Service] +Type=exec +UMask=0077 +RuntimeDirectory=coulobre-fail2ban +RuntimeDirectoryMode=0700 +StateDirectory=coulobre/firewall +StateDirectoryMode=0700 +ExecStartPre=/opt/coulobre/bin/coulobre-firewall prepare-bans +ExecStart=/usr/bin/fail2ban-server -xf -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock -p /run/coulobre-fail2ban/fail2ban.pid +ExecReload=/opt/coulobre/bin/coulobre-firewall prepare-bans +ExecReload=/usr/bin/fail2ban-client -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock reload +ExecStop=/usr/bin/fail2ban-client -c /run/coulobre-fail2ban/config -s /run/coulobre-fail2ban/fail2ban.sock stop +Restart=on-failure +NoNewPrivileges=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/deploy/systemd/coulobre-firewall.service b/deploy/systemd/coulobre-firewall.service new file mode 100644 index 0000000..728e325 --- /dev/null +++ b/deploy/systemd/coulobre-firewall.service @@ -0,0 +1,20 @@ +[Unit] +Description=Coulobre host firewall +Wants=network-pre.target +After=local-fs.target nftables.service +Before=network-pre.target + +[Service] +Type=oneshot +RemainAfterExit=yes +UMask=0077 +StateDirectory=coulobre/firewall +StateDirectoryMode=0700 +ExecStart=/opt/coulobre/bin/coulobre-firewall restore +ExecReload=/opt/coulobre/bin/coulobre-firewall restore +NoNewPrivileges=true +ProtectHome=true +ProtectSystem=strict + +[Install] +WantedBy=multi-user.target diff --git a/pyproject.toml b/pyproject.toml index ddc60e6..3fa31f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,7 @@ coulobre-account-backup = "coulobre.account_backup:main" coulobre-database-node = "coulobre.database_node:main" coulobre-directadmin = "coulobre.directadmin:main" coulobre-dns-node = "coulobre.dns_node:main" +coulobre-firewall = "coulobre.firewall:main" coulobre-mail-node = "coulobre.mail_node:main" coulobre-node-setup = "coulobre.node_setup:main" coulobre-service-credentials = "coulobre.service_credentials:main" diff --git a/src/coulobre/firewall.py b/src/coulobre/firewall.py new file mode 100644 index 0000000..2107b3d --- /dev/null +++ b/src/coulobre/firewall.py @@ -0,0 +1,273 @@ +import argparse +import json +import os +import subprocess +from pathlib import Path +from uuid import uuid4 + +from . import firewall_bans +from .firewall_policy import ( + OWNER, + TABLE, + FirewallPolicy, + policy_comment, + render_rules, +) +from .node_files import ( + locked_root_directory, + read_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) + +STATE = Path("/var/lib/coulobre/firewall") +ENTRY_POINT = "/opt/coulobre/bin/coulobre-firewall" +NFT = "/usr/sbin/nft" +MAX_POLICY_BYTES = 65536 + + +def run(*command, content=None): + try: + result = subprocess.run( + command, + input=content, + capture_output=True, + text=True, + env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}, + timeout=15, + ) + except subprocess.TimeoutExpired: + raise ValueError(f"{command[0]} did not respond.") from None + if result.returncode: + detail = result.stderr.strip() or result.stdout.strip() + raise ValueError(f"{command[0]} failed. {detail}".strip()) + return result.stdout + + +def nftables(*command): + reply = json.loads(run(NFT, "--json", *command)) + return reply["nftables"] + + +def active_table(): + definitions = nftables("list", "tables") + if not any( + table.get("family") == "inet" and table.get("name") == TABLE + for item in definitions + if (table := item.get("table")) + ): + return None + snapshot = nftables("list", "table", "inet", TABLE) + if not table_comment(snapshot).startswith(f"{OWNER} "): + raise ValueError( + f"The existing inet {TABLE} table is not owned by Coulobre." + ) + return snapshot + + +def table_comment(snapshot): + return next( + ( + table.get("comment", "") + for item in snapshot + if (table := item.get("table")) and table.get("name") == TABLE + ), + "", + ) + + +def policy_batch(policy): + existing = active_table() + prefix = f"delete table inet {TABLE}\n" if existing is not None else "" + return prefix + (render_rules(policy) if policy is not None else "") + + +def activate(content): + if content: + run(NFT, "--file", "-", content=content) + + +def read_policy(path): + with path.open("rb") as source: + body = source.read(MAX_POLICY_BYTES + 1) + if len(body) > MAX_POLICY_BYTES: + raise ValueError("Firewall profile exceeds 64 KiB.") + return FirewallPolicy.from_manifest(json.loads(body)) + + +def load_state(): + path = STATE / "state.json" + if not os.path.lexists(path): + return {"confirmed": None, "pending": None} + return json.loads(read_root_file(path, mode=0o600)) + + +def save_state(state): + path = STATE / "state.json" + content = json.dumps(state, indent=2) + "\n" + if os.path.lexists(path): + replace_configuration(path, content, mode=0o600) + else: + write_new_file(path, content, mode=0o600) + + +def confirmed_policy(state): + data = state["confirmed"] + return FirewallPolicy.from_manifest(data) if data is not None else None + + +def arm_rollback(operation, seconds): + run( + "/usr/bin/systemd-run", + "--quiet", + "--collect", + f"--unit=coulobre-firewall-rollback-{operation}", + f"--on-active={seconds}s", + "--timer-property=AccuracySec=1s", + ENTRY_POINT, + "rollback", + operation, + ) + + +def stage_policy(state, policy, seconds): + if state["pending"] is not None: + raise ValueError( + "Confirm or roll back the pending firewall change first." + ) + content = policy_batch(policy) + run(NFT, "--check", "--file", "-", content=content) + operation = uuid4().hex + pending = {"id": operation, "policy": policy.manifest(), "applied": False} + save_state(state | {"pending": pending}) + try: + arm_rollback(operation, seconds) + except (OSError, ValueError): + save_state(state) + raise + activate(content) + save_state(state | {"pending": pending | {"applied": True}}) + return operation + + +def confirm(state, operation): + pending = state["pending"] + if pending is None or pending["id"] != operation or not pending["applied"]: + raise ValueError( + "No applied firewall change matches this confirmation ID." + ) + snapshot = active_table() + policy = FirewallPolicy.from_manifest(pending["policy"]) + if snapshot is None or table_comment(snapshot) != policy_comment(policy): + raise ValueError("The staged firewall table is no longer active.") + save_state({"confirmed": pending["policy"], "pending": None}) + + +def restore(state, operation=None): + pending = state["pending"] + if operation is not None and ( + pending is None or operation != pending["id"] + ): + return + activate(policy_batch(confirmed_policy(state))) + if pending is not None: + save_state(state | {"pending": None}) + + +def state_status(state): + try: + bans = firewall_bans.ban_status(run) + except (OSError, ValueError) as error: + bans = {"problem": str(error)} + return state | {"table": active_table(), "bans": bans} + + +def timeout_seconds(value): + seconds = int(value) + if not 15 <= seconds <= 600: + raise argparse.ArgumentTypeError("Enter 15 to 600 seconds.") + return seconds + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="coulobre-firewall") + commands = parser.add_subparsers(dest="command", required=True) + for name, help_text in ( + ("preview", "Render a policy as nftables rules."), + ("apply", "Stage a policy with a scheduled rollback."), + ): + action = commands.add_parser(name, help=help_text) + action.add_argument("policy", type=Path) + if name == "apply": + action.add_argument("--timeout", type=timeout_seconds, default=120) + commands.add_parser( + "confirm", help="Keep the staged policy." + ).add_argument("id") + rollback = commands.add_parser( + "rollback", help="Restore the confirmed policy." + ) + rollback.add_argument("id", nargs="?") + commands.add_parser( + "restore", help="Load the confirmed policy at startup." + ) + commands.add_parser("clear", help="Remove the Coulobre host firewall.") + commands.add_parser("status", help="Report live rules and managed bans.") + commands.add_parser( + "prepare-bans", help="Write the managed Fail2ban configuration." + ) + commands.add_parser("audit", help="Show manual unblock events.") + unblock = commands.add_parser( + "unblock", help="Remove one managed ban and log it." + ) + unblock.add_argument("jail", choices=firewall_bans.JAILS) + unblock.add_argument("address") + unblock.add_argument("--reason", required=True) + args = parser.parse_args(argv) + try: + if args.command == "preview": + print(render_rules(read_policy(args.policy)), end="") + return 0 + if os.geteuid() != 0: + raise ValueError("Run this command as root.") + require_root_directory(STATE.parent, create_mode=0o750) + require_root_directory(STATE, create_mode=0o700) + with locked_root_directory(STATE): + dispatch(args, load_state()) + except (OSError, ValueError, KeyError, RecursionError) as error: + parser.exit(1, f"coulobre-firewall: {error}\n") + return 0 + + +def dispatch(args, state): + action = args.command + audit = STATE / "unblock.jsonl" + if action == "apply": + operation = stage_policy(state, read_policy(args.policy), args.timeout) + print( + f"Confirmation ID {operation}. Rollback in {args.timeout} seconds." + ) + elif action == "confirm": + confirm(state, args.id) + print("Confirmed the firewall policy.") + elif action == "rollback": + restore(state, args.id) + elif action == "restore": + restore(state) + elif action == "clear": + activate(policy_batch(None)) + save_state({"confirmed": None, "pending": None}) + elif action == "status": + print(json.dumps(state_status(state), indent=2)) + elif action == "prepare-bans": + policy = confirmed_policy(state) + if policy is None: + raise ValueError( + "Confirm the host firewall before enabling managed bans." + ) + firewall_bans.prepare_bans(policy, STATE) + elif action == "unblock": + firewall_bans.unblock(run, audit, args.jail, args.address, args.reason) + print("Recorded the unblock request and result.") + elif os.path.lexists(audit): + print(read_root_file(audit, mode=0o600), end="") diff --git a/src/coulobre/firewall_bans.py b/src/coulobre/firewall_bans.py new file mode 100644 index 0000000..741ab4a --- /dev/null +++ b/src/coulobre/firewall_bans.py @@ -0,0 +1,163 @@ +import ipaddress +import json +import os +import pwd +from datetime import UTC, datetime +from pathlib import Path +from uuid import uuid4 + +from .node_files import ( + check_root_file, + replace_configuration, + require_root_directory, + write_new_file, +) + +RUNTIME = Path("/run/coulobre-fail2ban") +CONFIG = RUNTIME / "config" +SOCKET = RUNTIME / "fail2ban.sock" +JAILS = ("coulobre-sshd", "coulobre-postfix", "coulobre-dovecot") +BAN_TABLE = "coulobre_bans" + + +def render_jails(policy): + sources = " ".join(map(str, policy.admin_sources)) + defaults = ( + "[DEFAULT]\n" + "backend = systemd\n" + "bantime = 600\n" + "findtime = 600\n" + "maxretry = 5\n" + "usedns = no\n" + f"ignoreip = 127.0.0.0/8 ::1 {sources}\n" + ) + jails = [(JAILS[0], "sshd", str(policy.ssh_port))] + if "mail" in policy.services: + jails.extend( + ( + (JAILS[1], "postfix[mode=auth]", "465,587"), + (JAILS[2], "dovecot", "143,993"), + ) + ) + return defaults + "".join( + f"\n[{name}]\nenabled = true\nfilter = {filter_name}\n" + f"action = nftables[type=multiport, table={BAN_TABLE}, " + f'name={name}, port="{destinations}", protocol=tcp, blocktype=drop]\n' + for name, filter_name, destinations in jails + ) + + +def prepare_bans(policy, state_directory): + config = CONFIG + require_root_directory(config, create_mode=0o700) + for name in ("filter.d", "action.d"): + link = config / name + target = Path("/etc/fail2ban") / name + require_root_directory(target) + if not os.path.lexists(link): + link.symlink_to(target, target_is_directory=True) + elif not link.is_symlink() or link.readlink() != target: + raise ValueError(f"Unexpected Fail2ban configuration at {link}.") + server_config = ( + "[Definition]\n" + "logtarget = STDOUT\n" + "loglevel = INFO\n" + f"socket = {SOCKET}\n" + f"pidfile = {RUNTIME / 'fail2ban.pid'}\n" + f"dbfile = {state_directory / 'fail2ban.sqlite3'}\n" + ) + for name, content in ( + ("fail2ban.conf", server_config), + ("jail.conf", render_jails(policy)), + ): + path = config / name + if os.path.lexists(path): + check_root_file(path, mode=0o600) + replace_configuration(path, content, mode=0o600) + else: + write_new_file(path, content, mode=0o600) + + +def client(run, *arguments): + return run( + "/usr/bin/fail2ban-client", + "-c", + str(CONFIG), + "-s", + str(SOCKET), + *arguments, + ) + + +def ban_status(run): + if not SOCKET.is_socket(): + return {"running": False, "jails": {}} + summary = client(run, "status") + names = next( + ( + line.split("Jail list:", 1)[1] + for line in summary.splitlines() + if "Jail list:" in line + ), + "", + ) + enabled = {name.strip() for name in names.split(",")} + return { + "running": True, + "jails": { + name: client(run, "get", name, "banip").split() + for name in JAILS + if name in enabled + }, + } + + +def operator_name(): + try: + uid = int(Path("/proc/self/loginuid").read_text()) + except (OSError, ValueError): + uid = 4294967295 + if uid == 4294967295: + uid = int(os.environ.get("SUDO_UID", "0")) + try: + return pwd.getpwuid(uid).pw_name + except KeyError: + return str(uid) + + +def record_unblock(path, event, result): + if os.path.lexists(path): + check_root_file(path, mode=0o600) + fd = os.open( + path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600 + ) + with os.fdopen(fd, "a", encoding="utf-8") as log: + event = event | { + "time": datetime.now(UTC).isoformat(), + "result": result, + } + log.write(json.dumps(event) + "\n") + log.flush() + os.fsync(log.fileno()) + + +def unblock(run, path, jail, address, reason): + if "%" in address or not reason.strip() or len(reason) > 250: + raise ValueError( + "Enter an IP address and a reason of up to 250 characters." + ) + address = str(ipaddress.ip_address(address)) + event = { + "id": str(uuid4()), + "operator": operator_name(), + "jail": jail, + "address": address, + "reason": reason, + } + record_unblock(path, event, "requested") + try: + count = client(run, "set", jail, "unbanip", address).strip() + except (OSError, ValueError): + record_unblock(path, event, "failed") + raise + record_unblock(path, event | {"removed": count == "1"}, "completed") diff --git a/src/coulobre/firewall_policy.py b/src/coulobre/firewall_policy.py new file mode 100644 index 0000000..6b53eac --- /dev/null +++ b/src/coulobre/firewall_policy.py @@ -0,0 +1,283 @@ +import hashlib +import ipaddress +import json +from dataclasses import dataclass + +TABLE = "coulobre_host" +OWNER = "Coulobre managed host firewall v1" +PROFILES = ("public", "lan", "proxy", "node") +SERVICE_PORTS = { + "web": (80, 443), + "mail": (25, 143, 465, 587, 993), + "dns": (53,), + "sftp": (), +} +DEFAULT_RATES = {"panel": 40, "web": 120, "mail": 30, "dns": 100, "ssh": 8} +POLICY_FIELDS = { + "version", + "profile", + "services", + "admin_sources", + "extra_tcp_ports", + "extra_udp_ports", + "panel_sources", + "ssh_port", + "panel_ports", + "rates", +} + + +def integer(value, minimum, maximum): + return type(value) is int and minimum <= value <= maximum + + +def ports(value): + if ( + not isinstance(value, list) + or len(value) > 8 + or any(not integer(port, 1, 65535) for port in value) + ): + raise ValueError("Expected up to eight TCP ports from 1 to 65535.") + return tuple(sorted(set(value))) + + +def networks(value): + if ( + not isinstance(value, list) + or len(value) > 64 + or any(not isinstance(item, str) or "%" in item for item in value) + ): + raise ValueError("Expected up to 64 IPv4 or IPv6 source networks.") + try: + subnets = [ipaddress.ip_network(item) for item in value] + except ValueError: + raise ValueError( + "Enter source IP addresses or CIDR networks." + ) from None + collapsed = tuple( + subnet + for version in (4, 6) + for subnet in ipaddress.collapse_addresses( + item for item in subnets if item.version == version + ) + ) + if any(not subnet.prefixlen for subnet in collapsed): + raise ValueError("Use specific source networks for restricted access.") + return collapsed + + +@dataclass(frozen=True) +class FirewallPolicy: + profile: str + services: tuple + admin_sources: tuple + panel_sources: tuple + ssh_port: int + panel_ports: tuple + extra_tcp_ports: tuple + extra_udp_ports: tuple + rates: dict + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or data.keys() - POLICY_FIELDS + or type(data.get("version")) is not int + or data["version"] != 1 + or data.get("profile") not in PROFILES + ): + raise ValueError("Expected a version 1 firewall profile.") + profile = data["profile"] + services = data.get("services", []) + if not isinstance(services, list) or any( + not isinstance(service, str) or service not in SERVICE_PORTS + for service in services + ): + raise ValueError("Choose web, mail, dns, or sftp services.") + services = tuple(sorted(set(services))) + admins = networks(data.get("admin_sources", [])) + sources = networks(data.get("panel_sources", [])) + if not admins: + raise ValueError( + "Enter at least one administrator source network." + ) + if bool(sources) != (profile in ("lan", "proxy")): + raise ValueError("Set panel_sources for LAN and proxy profiles.") + default_ports = {"node": [], "proxy": [8080]} + panel = ports( + data.get("panel_ports", default_ports.get(profile, [80, 443])) + ) + if bool(panel) == (profile == "node"): + raise ValueError( + "Panel ports are required for public, LAN and proxy profiles." + ) + ssh = data.get("ssh_port", 22) + service_ports = { + port for service in services for port in SERVICE_PORTS[service] + } + if not integer(ssh, 1, 65535) or ssh in service_ports or ssh in panel: + raise ValueError( + "Set an SSH port distinct from panel and service ports." + ) + shared_ports = service_ports.intersection(panel) + if shared_ports and not ( + profile == "public" and shared_ports <= {80, 443} + ): + raise ValueError( + "Use separate TCP listeners for panel and public services." + ) + extra_tcp = ports(data.get("extra_tcp_ports", [])) + extra_udp = ports(data.get("extra_udp_ports", [])) + if set(extra_tcp) & (service_ports | set(panel) | {ssh}) or ( + "dns" in services and 53 in extra_udp + ): + raise ValueError( + "Extra ports must be distinct from managed ports." + ) + overrides = data.get("rates", {}) + if not isinstance(overrides, dict) or any( + service not in DEFAULT_RATES or not integer(rate, 0, 100000) + for service, rate in overrides.items() + ): + raise ValueError( + "Set per-second rates from 0 to 100000 for known services." + ) + return cls( + profile, + services, + admins, + sources, + ssh, + panel, + extra_tcp, + extra_udp, + DEFAULT_RATES | overrides, + ) + + def manifest(self): + return { + "version": 1, + "profile": self.profile, + "services": list(self.services), + "admin_sources": [str(item) for item in self.admin_sources], + "panel_sources": [str(item) for item in self.panel_sources], + "ssh_port": self.ssh_port, + "panel_ports": list(self.panel_ports), + "extra_tcp_ports": list(self.extra_tcp_ports), + "extra_udp_ports": list(self.extra_udp_ports), + "rates": self.rates, + } + + +def policy_comment(policy): + canonical = json.dumps(policy.manifest(), sort_keys=True).encode() + return f"{OWNER} {hashlib.sha256(canonical).hexdigest()}" + + +def nft_set(values): + return "{ " + ", ".join(map(str, values)) + " }" + + +def source_sets(name, sources): + return [ + f" set {name}{version} {{ type {address_type}; flags interval; " + f"elements = {nft_set(subnets)}; }}" + for version, _, address_type in ADDRESS_FAMILIES + if (subnets := [item for item in sources if item.version == version]) + ] + + +ADDRESS_FAMILIES = ((4, "ip", "ipv4_addr"), (6, "ip6", "ipv6_addr")) + + +def render_rules(policy): + sets = source_sets("admins", policy.admin_sources) + sets.extend(source_sets("panel", policy.panel_sources)) + chains = [] + udp = [] + incoming = [ + " ct state established,related counter accept", + *( + f" {family} saddr @admins{version} tcp dport {policy.ssh_port}" + " counter accept" + for version, family, _ in ADDRESS_FAMILIES + if any(item.version == version for item in policy.admin_sources) + ), + ] + + def add_service(name, protocol, allowed, *, sources=()): + if not allowed: + return + chain = f"{name}_{protocol}" + destination = f"{protocol} dport {nft_set(allowed)}" + rate = policy.rates[name] + verdict = f"jump {chain}" if rate else "counter accept" + rules = udp if protocol == "udp" else incoming + if sources: + rules.extend( + f" {family} saddr @panel{version} {destination} {verdict}" + for version, family, _ in ADDRESS_FAMILIES + if any(item.version == version for item in sources) + ) + else: + rules.append(f" {destination} {verdict}") + if rate: + render_rate(chain, rate, sets, chains) + + for name in policy.services: + if name == "sftp": + add_service("ssh", "tcp", (policy.ssh_port,)) + else: + add_service(name, "tcp", SERVICE_PORTS[name]) + if "dns" in policy.services: + add_service("dns", "udp", SERVICE_PORTS["dns"]) + panel_ports = tuple( + port + for port in policy.panel_ports + if "web" not in policy.services or port not in SERVICE_PORTS["web"] + ) + add_service("panel", "tcp", panel_ports, sources=policy.panel_sources) + for protocol, additional in ( + ("tcp", policy.extra_tcp_ports), + ("udp", policy.extra_udp_ports), + ): + if additional: + incoming.append( + f" {protocol} dport {nft_set(additional)} counter accept" + ) + + lines = [ + f"table inet {TABLE} {{", + f' comment "{policy_comment(policy)}"', + *sets, + *chains, + " chain input {", + " type filter hook input priority 10; policy drop;", + ' iifname "lo" counter accept', + " meta l4proto { icmp, ipv6-icmp } counter accept", + " udp sport 67 udp dport 68 counter accept", + " ip6 saddr fe80::/10 udp sport 547 udp dport 546 counter accept", + " ct state invalid counter drop", + *udp, + *incoming, + " counter drop", + " }", + "}", + ] + return "\n".join(lines) + "\n" + + +def render_rate(chain, rate, sets, chains): + chains.append(f" chain {chain} {{") + for version, family, address_type in ADDRESS_FAMILIES: + name = f"{chain}{version}" + sets.append( + f" set {name} {{ type {address_type}; flags dynamic,timeout; " + "timeout 1m; size 16384; }" + ) + chains.append( + f" update @{name} {{ {family} saddr limit rate {rate}/second " + f"burst {rate} packets }} counter accept" + ) + chains.extend((" counter drop", " }")) diff --git a/src/coulobre/hosting/test_firewall.py b/src/coulobre/hosting/test_firewall.py new file mode 100644 index 0000000..57d0359 --- /dev/null +++ b/src/coulobre/hosting/test_firewall.py @@ -0,0 +1,177 @@ +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import call, patch + +from django.test import SimpleTestCase + +from coulobre import firewall, firewall_bans +from coulobre.firewall_policy import ( + TABLE, + FirewallPolicy, + policy_comment, + render_rules, +) + +SOURCES = ["192.0.2.10", "2001:db8::10"] +PUBLIC = {"version": 1, "profile": "public", "admin_sources": SOURCES} + + +class FirewallPolicyTests(SimpleTestCase): + def test_node_policy_limits_dns_before_the_established_flow_accept(self): + policy = FirewallPolicy.from_manifest( + PUBLIC | {"profile": "node", "services": ["dns"]} + ) + output = render_rules(policy) + dns = output.index("udp dport { 53 } jump dns_udp") + established = output.index("ct state established,related") + self.assertLess(dns, established) + self.assertIn("update @dns_udp4 { ip saddr limit", output) + self.assertIn("update @dns_udp6 { ip6 saddr limit", output) + self.assertIn("size 16384", output) + self.assertNotIn("flush ruleset", output) + + def test_proxy_profile_does_not_open_its_listener_to_web_clients(self): + policy = FirewallPolicy.from_manifest( + PUBLIC + | { + "profile": "proxy", + "panel_ports": [8443], + "panel_sources": ["192.0.2.20"], + "services": ["web"], + } + ) + output = render_rules(policy) + self.assertIn( + "ip saddr @panel4 tcp dport { 8443 } jump panel_tcp", output + ) + self.assertIn("tcp dport { 80, 443 } jump web_tcp", output) + self.assertNotIn("@panel6 tcp dport", output) + self.assertEqual( + FirewallPolicy.from_manifest(policy.manifest()), policy + ) + + def test_rejects_ambiguous_or_unrestricted_profiles(self): + for changes in ( + {"admin_sources": []}, + {"admin_sources": ["0.0.0.0/1", "128.0.0.0/1"]}, + {"ssh_port": True}, + {"profile": "lan", "services": ["web"], "panel_sources": SOURCES}, + { + "profile": "proxy", + "panel_sources": SOURCES, + "extra_tcp_ports": [8080], + }, + {"services": ["dns"], "extra_udp_ports": [53]}, + {"rates": {"dns": -1}}, + ): + with self.subTest(changes=changes), self.assertRaises(ValueError): + FirewallPolicy.from_manifest(PUBLIC | changes) + + +class FirewallChangeTests(SimpleTestCase): + def setUp(self): + self.policy = FirewallPolicy.from_manifest(PUBLIC) + self.state = {"confirmed": None, "pending": None} + + def test_timer_is_armed_before_the_candidate_changes_the_kernel(self): + events = self.enterContext(patch.object(firewall, "run")) + self.enterContext( + patch.object(firewall, "active_table", return_value=None) + ) + self.enterContext(patch.object(firewall, "save_state")) + operation = firewall.stage_policy(self.state, self.policy, 90) + first, second, third = events.call_args_list + self.assertEqual(first.args, (firewall.NFT, "--check", "--file", "-")) + self.assertEqual(second.args[0], "/usr/bin/systemd-run") + self.assertIn(operation, second.args) + self.assertEqual(third.args, (firewall.NFT, "--file", "-")) + + def test_timer_failure_keeps_the_current_rules(self): + with ( + patch.object(firewall, "policy_batch", return_value="candidate"), + patch.object(firewall, "run"), + patch.object(firewall, "save_state") as saved, + patch.object(firewall, "arm_rollback", side_effect=ValueError), + patch.object(firewall, "activate") as active, + self.assertRaises(ValueError), + ): + firewall.stage_policy(self.state, self.policy, 90) + active.assert_not_called() + self.assertEqual(saved.call_args, call(self.state)) + + def test_confirmation_checks_the_live_policy_and_invalidates_its_timer( + self, + ): + stage = { + "id": "pending", + "policy": self.policy.manifest(), + "applied": True, + } + state = self.state | {"pending": stage} + snapshot = [ + {"table": {"name": TABLE, "comment": policy_comment(self.policy)}} + ] + with ( + patch.object(firewall, "active_table", return_value=snapshot), + patch.object(firewall, "save_state") as save, + patch.object(firewall, "activate") as activate, + ): + firewall.confirm(state, "pending") + saved = save.call_args.args[0] + self.assertEqual(saved["confirmed"], stage["policy"]) + self.assertIsNone(saved["pending"]) + firewall.restore(saved, "pending") + activate.assert_not_called() + + def test_rule_replacement_refuses_an_unmanaged_table_with_the_same_name( + self, + ): + contents = [{"table": {"family": "inet", "name": TABLE}}] + with ( + patch.object(firewall, "nftables", return_value=contents), + self.assertRaisesMessage(ValueError, "is not owned by Coulobre"), + ): + firewall.policy_batch(self.policy) + + +class FirewallBanTests(SimpleTestCase): + def test_mail_jails_share_the_allowlist_and_use_their_own_nftables_table( + self, + ): + policy = FirewallPolicy.from_manifest(PUBLIC | {"services": ["mail"]}) + rendered = firewall_bans.render_jails(policy) + self.assertIn("192.0.2.10/32 2001:db8::10/128", rendered) + self.assertIn("[coulobre-postfix]", rendered) + self.assertIn('port="465,587"', rendered) + self.assertIn("table=coulobre_bans", rendered) + + def test_unblock_records_the_operator_and_failure_before_returning(self): + directory = Path(self.enterContext(TemporaryDirectory())) + path = directory / "audit" + + def fail(*arguments): + self.assertIn('"result": "requested"', path.read_text()) + raise ValueError("Fail2ban is unavailable.") + + with ( + patch.object( + firewall_bans, "operator_name", return_value="operator" + ), + patch.object(firewall_bans, "check_root_file"), + self.assertRaisesMessage(ValueError, "Fail2ban is unavailable."), + ): + firewall_bans.unblock( + fail, path, "coulobre-sshd", "192.0.2.20", "verified" + ) + self.assertIn('"operator": "operator"', path.read_text()) + self.assertIn('"result": "failed"', path.read_text()) + + def test_public_audit_interface_accepts_only_fixed_jails(self): + with ( + patch.object(firewall, "dispatch") as dispatch, + self.assertRaises(SystemExit), + ): + firewall.main( + ["unblock", "other-jail", "192.0.2.20", "--reason", "test"] + ) + dispatch.assert_not_called() diff --git a/src/coulobre/node_files.py b/src/coulobre/node_files.py index 407aac9..1d65a63 100644 --- a/src/coulobre/node_files.py +++ b/src/coulobre/node_files.py @@ -53,7 +53,7 @@ def write_new_file(path, content, *, mode, group=None): os.link(staged.name, path) -def replace_configuration(path, content): +def replace_configuration(path, content, *, mode=0o644): with NamedTemporaryFile( mode="w", encoding="utf-8", dir=path.parent, delete=False ) as temporary: @@ -61,7 +61,7 @@ def replace_configuration(path, content): try: temporary.write(content) temporary.flush() - os.fchmod(temporary.fileno(), 0o644) + os.fchmod(temporary.fileno(), mode) os.fsync(temporary.fileno()) staged.replace(path) finally: diff --git a/src/coulobre/service_health.py b/src/coulobre/service_health.py index 96fb46f..49ab304 100644 --- a/src/coulobre/service_health.py +++ b/src/coulobre/service_health.py @@ -23,8 +23,18 @@ SERVICES = { "dovecot": ("Dovecot", "dovecot.service"), "spamd": ("SpamAssassin", "spamd.service"), "spamass-milter": ("SpamAssassin milter", "spamass-milter.service"), + "firewall": ("Coulobre firewall", "coulobre-firewall.service"), + "fail2ban": ("Coulobre Fail2ban", "coulobre-fail2ban.service"), } -REMOTE_SERVICES = ("bind9", "postfix", "dovecot", "spamd", "spamass-milter") +REMOTE_SERVICES = ( + "bind9", + "postfix", + "dovecot", + "spamd", + "spamass-milter", + "firewall", + "fail2ban", +) REMOTE_VERSION = 1 SSH_CONFIG = "/etc/coulobre-health/ssh_config" NODE_NAME = re.compile(r"[a-z][a-z0-9-]{0,62}")