From c0a84acaea3a4b4f1f0c4d4f5539eb24c6eb5b0f Mon Sep 17 00:00:00 2001 From: th33raphat Date: Sat, 26 Sep 2026 14:44:49 +0700 Subject: [PATCH 1/3] Update check on startup; coffee button needs a Stripe link to build - update.py asks GitHub releases/latest (stdlib urllib); the window offers the installer for this OS/arch when a newer version exists, silently skips on any network error. Windows builds keep ssl; both builds carry piewall's metadata so the frozen app knows its version. - site: a production build fails without PUBLIC_COFFEE_URL instead of shipping a coffee button that links to #coffee. --- README.md | 3 +++ packaging/piewall-macos.spec | 5 ++-- packaging/piewall.spec | 10 ++++--- site/src/config.ts | 5 ++++ src/piewall/gui.py | 32 ++++++++++++++++++++-- src/piewall/mcp_server.py | 8 ++---- src/piewall/update.py | 51 ++++++++++++++++++++++++++++++++++++ tests/test_gui.py | 17 ++++++++++++ tests/test_update.py | 32 ++++++++++++++++++++++ 9 files changed, 149 insertions(+), 14 deletions(-) create mode 100644 src/piewall/update.py create mode 100644 tests/test_update.py diff --git a/README.md b/README.md index aececa8..cd58b49 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,9 @@ On macOS piewall manages its own rules in the pf anchor `com.apple/piewall` (the ports and addresses, not programs, and piewall lists only the rules it manages. Every change asks for your administrator password; Block rules are ordered last so Block wins, as on Windows. +**Updates**: when the window opens, piewall asks GitHub once for the latest release (nothing +else is sent). If a newer version is out, it offers to download the installer for your system. + ## Use the window Search, filter by port / action / direction / state, click a column to sort. diff --git a/packaging/piewall-macos.spec b/packaging/piewall-macos.spec index a109455..58c6d42 100644 --- a/packaging/piewall-macos.spec +++ b/packaging/piewall-macos.spec @@ -10,7 +10,7 @@ import os import tomllib from pathlib import Path -from PyInstaller.utils.hooks import collect_data_files +from PyInstaller.utils.hooks import collect_data_files, copy_metadata HERE = Path(SPECPATH) # noqa: F821 (injected by PyInstaller) ROOT = HERE.parent @@ -18,7 +18,8 @@ SRC = ROOT / "src" VERSION = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"] ICON = os.environ.get("PIEWALL_ICNS") # made by build-macos.sh with iconutil -DATAS = [(str(SRC / "piewall" / "assets"), "piewall/assets"), *collect_data_files("sv_ttk")] +DATAS = [(str(SRC / "piewall" / "assets"), "piewall/assets"), *collect_data_files("sv_ttk"), + *copy_metadata("piewall")] # update.current_version() reads it EXCLUDES = ["pytest", "_pytest", "pip", "setuptools", "pkg_resources", "lib2to3", "idlelib", "pydoc_data", "turtle", "turtledemo", "test", "tkinter.test", "numpy", "PIL", "mcp", "uvicorn", "starlette", "pydantic"] # MCP server is not bundled on macOS diff --git a/packaging/piewall.spec b/packaging/piewall.spec index 1514bbc..15a6bcd 100644 --- a/packaging/piewall.spec +++ b/packaging/piewall.spec @@ -67,6 +67,7 @@ VSVersionInfo( DATAS = [ (str(SRC / "piewall" / "assets"), "piewall/assets"), # icons read via importlib.resources *collect_data_files("sv_ttk"), # Sun Valley theme .tcl + images + *copy_metadata("piewall"), # update.current_version() reads it ] # Imported lazily (inside functions or by gui.py as it evolves); list them so they are always bundled. HIDDEN = ["sv_ttk", "darkdetect", "win32com.client.dynamic", "win32com.shell.shell"] @@ -76,16 +77,17 @@ EXCLUDES = [ "sqlite3", "xmlrpc", "curses", "doctest", "pdb", "unittest", "win32ui", "pythonwin", "win32com.demos", "win32com.test", "win32comext.axscript", "numpy", "PIL", - # Optional C accelerators with pure-Python / builtin fallbacks (libcrypto alone is ~8 MB). - "_hashlib", "_ssl", "ssl", "_decimal", "_bz2", "_lzma", + # Optional C accelerators with pure-Python / builtin fallbacks. ssl stays: the update check + # talks HTTPS to GitHub. + "_decimal", "_bz2", "_lzma", ] # Tcl/Tk data piewall never uses: time zones (clock) and message catalogs (Windows dialogs are native). DROP_DATA = ("_tcl_data/tzdata/", "_tcl_data/msgs/", "_tk_data/msgs/") -# The MCP server needs what the GUI/CLI leave out: ssl (uvicorn, httpx2 import it at start-up) and +# The MCP server needs what the GUI/CLI leave out: # the mcp SDK's lazily imported modules (transports, pydantic models) plus their dist metadata. -MCP_KEEP = {"_hashlib", "_ssl", "ssl", "_decimal", "unittest"} +MCP_KEEP = {"_decimal", "unittest"} MCP_EXCLUDES = [m for m in EXCLUDES if m not in MCP_KEEP] + [ "sv_ttk", "darkdetect", "tkinter", "_tkinter", "piewall.gui", "piewall.theme", # console only ] diff --git a/site/src/config.ts b/site/src/config.ts index 04aa785..3eda9a2 100644 --- a/site/src/config.ts +++ b/site/src/config.ts @@ -3,7 +3,12 @@ export const INSTALLER_URL = GITHUB_URL + "/releases/latest/download/piewall-set export const PORTABLE_URL = GITHUB_URL + "/releases/latest/download/piewall.exe"; export const MAC_ARM_URL = GITHUB_URL + "/releases/latest/download/piewall-macos-arm64.pkg"; export const MAC_INTEL_URL = GITHUB_URL + "/releases/latest/download/piewall-macos-x86_64.pkg"; +// Stripe Payment Link, from site/.env (see .env.example). A production build without it fails +// instead of shipping a coffee button that goes nowhere. export const COFFEE_URL: string = import.meta.env.PUBLIC_COFFEE_URL || "#coffee"; +if (import.meta.env.PROD && !COFFEE_URL.startsWith("https://buy.stripe.com/")) { + throw new Error("PUBLIC_COFFEE_URL must be a https://buy.stripe.com/ Payment Link (set it in site/.env)"); +} export const SITE_URL = "https://piewall.th33raphat.dev"; export const LICENSE_URL = GITHUB_URL + "/blob/main/LICENSE"; diff --git a/src/piewall/gui.py b/src/piewall/gui.py index 9dd9742..a12147b 100644 --- a/src/piewall/gui.py +++ b/src/piewall/gui.py @@ -3,7 +3,9 @@ from __future__ import annotations import sys +import threading import tkinter as tk +import webbrowser from pathlib import Path from tkinter import filedialog, messagebox, ttk from tkinter import font as tkfont @@ -14,7 +16,7 @@ from .listeners import current_listeners from .model import PIEWALL_GROUP, Rule, filter_rules, parse_profiles from .transfer import export_rules, import_rules -from . import theme +from . import theme, update COLUMNS = [ # (id, heading, width, stretch) ("enabled", "On", 44, False), @@ -392,6 +394,32 @@ def _can_change(self) -> bool: self.restart_as_admin() return False + def check_for_update(self) -> None: + """Ask GitHub in the background; offer the download when a newer piewall is out.""" + found: list[tuple[str, str] | None] = [] + + def work() -> None: + try: + found.append(update.check()) + except (OSError, ValueError, KeyError): # offline, rate-limited, …: next launch + found.append(None) + + def poll() -> None: + if not found: + self.root.after(500, poll) + elif found[0]: + self._offer_update(*found[0]) + + threading.Thread(target=work, daemon=True, name="piewall-update").start() + self.root.after(500, poll) + + def _offer_update(self, version: str, url: str) -> None: + if messagebox.askyesno( + "Update available", + f"piewall {version} is available. You have {update.current_version()}.\n\n" + f"Download it now?", parent=self.root): + webbrowser.open(url) + def restart_as_admin(self) -> None: try: run_elevated(["piewall.gui"], wait=False, windowed=True) @@ -534,7 +562,7 @@ def main(backend_factory=None) -> None: from .backend import default_backend as backend_factory root = tk.Tk() theme.set_icon(root) - App(root, backend_factory(), is_admin()) + App(root, backend_factory(), is_admin()).check_for_update() root.mainloop() diff --git a/src/piewall/mcp_server.py b/src/piewall/mcp_server.py index b5fb70d..2c167f7 100644 --- a/src/piewall/mcp_server.py +++ b/src/piewall/mcp_server.py @@ -13,7 +13,6 @@ import argparse import os import sys -from importlib import metadata from pathlib import Path from typing import Annotated, Any, Callable, Literal @@ -28,6 +27,7 @@ from .conflicts import Listener, find_conflicts from .elevate import is_admin, run_elevated from .model import Rule, filter_rules +from .update import current_version CLI_COMMANDS = {"list", "open", "close", "enable", "disable", "delete", "allow", "block", "conflicts", "export", "import"} @@ -56,11 +56,7 @@ "this name are affected)")] -def version() -> str: - try: - return metadata.version("piewall") - except metadata.PackageNotFoundError: - return "0.0.0" +version = current_version def rule_json(r: Rule, *, full: bool = False) -> dict[str, Any]: diff --git a/src/piewall/update.py b/src/piewall/update.py new file mode 100644 index 0000000..8e6e09c --- /dev/null +++ b/src/piewall/update.py @@ -0,0 +1,51 @@ +"""Ask GitHub whether a newer piewall release is out.""" + +from __future__ import annotations + +import json +import platform +import sys +import urllib.request +from importlib import metadata + +LATEST_URL = "https://api.github.com/repos/TheeraphatStudent/piewall/releases/latest" + + +def current_version() -> str: + try: + return metadata.version("piewall") + except metadata.PackageNotFoundError: + return "0.0.0" + + +def _parse(version: str) -> tuple[int, ...] | None: + """'v0.2.1' -> (0, 2, 1); None for anything else (pre-releases, dev builds).""" + try: + return tuple(int(part) for part in version.removeprefix("v").split(".")) + except ValueError: + return None + + +def asset_name() -> str: + """The release file this machine should download.""" + if sys.platform == "darwin": + return f"piewall-macos-{'arm64' if platform.machine() == 'arm64' else 'x86_64'}.pkg" + return "piewall-setup.exe" + + +def newer_release(release: dict, current: str) -> tuple[str, str] | None: + """(version, download URL) when `release` (GitHub API JSON) is newer than `current`.""" + latest, mine = _parse(release.get("tag_name", "")), _parse(current) + if latest is None or mine is None or latest <= mine: + return None + urls = {a["name"]: a["browser_download_url"] for a in release.get("assets", [])} + return release["tag_name"].removeprefix("v"), urls.get(asset_name(), release["html_url"]) + + +def check(timeout: float = 5) -> tuple[str, str] | None: + """Network call. Raises OSError (offline, HTTP error) or ValueError (bad JSON).""" + current = current_version() + request = urllib.request.Request(LATEST_URL, headers={ + "Accept": "application/vnd.github+json", "User-Agent": f"piewall/{current}"}) + with urllib.request.urlopen(request, timeout=timeout) as response: + return newer_release(json.load(response), current) diff --git a/tests/test_gui.py b/tests/test_gui.py index a23f268..35d6a50 100644 --- a/tests/test_gui.py +++ b/tests/test_gui.py @@ -64,3 +64,20 @@ def test_make_allow_clears_conflict(app): app.set_action("allow") assert app.conflicts == [] assert app.banner.winfo_manager() == "" + + +@pytest.mark.parametrize("found, opened", [(("9.9.9", "https://dl/x.pkg"), ["https://dl/x.pkg"]), + (None, [])]) +def test_update_check_offers_download(app, root, monkeypatch, found, opened): + import time + + asked, urls = [], [] + monkeypatch.setattr(gui.update, "check", lambda: found) + monkeypatch.setattr(gui.messagebox, "askyesno", lambda *a, **k: asked.append(a) or True) + monkeypatch.setattr(gui.webbrowser, "open", urls.append) + app.check_for_update() + deadline = time.monotonic() + 3 + while time.monotonic() < deadline and not urls: + root.update() + assert urls == opened + assert len(asked) == len(opened) diff --git a/tests/test_update.py b/tests/test_update.py new file mode 100644 index 0000000..e709956 --- /dev/null +++ b/tests/test_update.py @@ -0,0 +1,32 @@ +"""Update check: version comparison and asset choice. No network.""" + +import pytest + +from piewall import update + + +def release(tag, *names): + return {"tag_name": tag, "html_url": f"https://example/{tag}", + "assets": [{"name": n, "browser_download_url": f"https://dl/{n}"} for n in names]} + + +@pytest.mark.parametrize("platform, machine, asset", [ + ("win32", "AMD64", "piewall-setup.exe"), + ("darwin", "arm64", "piewall-macos-arm64.pkg"), + ("darwin", "x86_64", "piewall-macos-x86_64.pkg"), +]) +def test_newer_release_offers_this_machines_download(monkeypatch, platform, machine, asset): + monkeypatch.setattr(update.sys, "platform", platform) + monkeypatch.setattr(update.platform, "machine", lambda: machine) + names = ["piewall-setup.exe", "piewall-macos-arm64.pkg", "piewall-macos-x86_64.pkg"] + assert update.newer_release(release("v0.10.0", *names), "0.9.3") == ("0.10.0", f"https://dl/{asset}") + + +@pytest.mark.parametrize("tag, current", [("v0.2.1", "0.2.1"), ("v0.2.0", "0.2.1"), + ("v0.3.0rc1", "0.2.1"), ("v0.3.0", "0.3.0.dev1")]) +def test_no_offer_when_not_newer_or_unparseable(tag, current): + assert update.newer_release(release(tag), current) is None + + +def test_falls_back_to_release_page_without_matching_asset(): + assert update.newer_release(release("v9.0.0"), "0.2.1") == ("9.0.0", "https://example/v9.0.0") From 906853060b2e380d9b155afb2ee6e74c4bc60280 Mon Sep 17 00:00:00 2001 From: th33raphat Date: Sat, 26 Sep 2026 14:45:51 +0700 Subject: [PATCH 2/3] Release 0.2.2 --- npm/piewall-mcp/package.json | 2 +- pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/npm/piewall-mcp/package.json b/npm/piewall-mcp/package.json index 094c0d3..bad52ea 100644 --- a/npm/piewall-mcp/package.json +++ b/npm/piewall-mcp/package.json @@ -1,6 +1,6 @@ { "name": "piewall-mcp", - "version": "0.2.1", + "version": "0.2.2", "description": "MCP server for piewall: list, analyse and manage Windows Firewall rules from AI assistants", "type": "module", "license": "MIT", diff --git a/pyproject.toml b/pyproject.toml index 01c04cb..a088499 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "piewall" -version = "0.2.1" +version = "0.2.2" description = "Manage Windows Firewall rules from a simple window or the command line" readme = "README.md" license = "MIT" diff --git a/uv.lock b/uv.lock index a2a0bb2..b2e042d 100644 --- a/uv.lock +++ b/uv.lock @@ -383,7 +383,7 @@ wheels = [ [[package]] name = "piewall" -version = "0.2.1" +version = "0.2.2" source = { editable = "." } dependencies = [ { name = "darkdetect" }, From d59d543363d36ded2ad7417d5e6bdf335b757390 Mon Sep 17 00:00:00 2001 From: th33raphat Date: Sat, 26 Sep 2026 14:50:37 +0700 Subject: [PATCH 3/3] macOS: show and manage Application Firewall app rules piewall listed only the pf rules it had created, so a fresh install showed an empty window. It now also lists the macOS Application Firewall's app list (readable without a password) and routes Allow/Block/Delete and per-program rules to socketfilterfw, batched into the same single password prompt as pf. --- README.md | 10 +++-- src/piewall/pf.py | 107 ++++++++++++++++++++++++++++++++++++++-------- tests/test_pf.py | 67 +++++++++++++++++++++++++++-- 3 files changed, 158 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index cd58b49..45a0be6 100644 --- a/README.md +++ b/README.md @@ -57,10 +57,12 @@ not notarized yet, so the first time macOS says it can't verify it: click **Done **Open Anyway** in System Settings › Privacy & Security. Uninstall: `sudo rm -rf /Applications/piewall.app /usr/local/bin/piewall`. -On macOS piewall manages its own rules in the pf anchor `com.apple/piewall` (the stock -`/etc/pf.conf` already loads it) and keeps them across reboots with a LaunchDaemon. pf filters -ports and addresses, not programs, and piewall lists only the rules it manages. Every change -asks for your administrator password; Block rules are ordered last so Block wins, as on Windows. +On macOS piewall shows two kinds of rules. **App rules** come from the macOS Application +Firewall (System Settings › Network › Firewall): allow or block incoming connections per app. +They are enforced only while that firewall is on, and piewall shows them as disabled when it is +off. **Port rules** (`open`, `close`) live in piewall's own pf anchor `com.apple/piewall` (the +stock `/etc/pf.conf` already loads it) and survive reboots through a LaunchDaemon; Block rules +are ordered last so Block wins, as on Windows. Every change asks for your administrator password. **Updates**: when the window opens, piewall asks GitHub once for the latest release (nothing else is sent). If a newer version is out, it offers to download the installer for your system. diff --git a/src/piewall/pf.py b/src/piewall/pf.py index 3721cb9..bbe3e25 100644 --- a/src/piewall/pf.py +++ b/src/piewall/pf.py @@ -1,4 +1,4 @@ -"""macOS firewall access through pf (the packet filter behind `pfctl`). +"""macOS firewall access: pf (the packet filter behind `pfctl`) and the Application Firewall. piewall owns one pf anchor, `com.apple/piewall`. The stock /etc/pf.conf already evaluates every `com.apple/*` anchor, so nothing outside piewall's own files is edited. The rules @@ -6,7 +6,10 @@ each change rewrites it, reloads the anchor and installs a LaunchDaemon that reloads it at boot. Changes run as root through the standard macOS administrator password prompt. -pf filters packets, not programs: rules with a program or service are refused. +pf filters packets, not programs. Per-program rules are the macOS Application Firewall's +(System Settings > Network > Firewall): its app list is shown as rules in the +ALF_GROUP group, and program rules piewall adds go there. It only filters incoming traffic +and has no per-app on/off, so its rules show as enabled exactly when that firewall is on. """ from __future__ import annotations @@ -14,6 +17,7 @@ import contextlib import json import os +import re import shlex import subprocess import tempfile @@ -30,6 +34,8 @@ PF_FILE = STATE_DIR / "pf.rules" DAEMON_LABEL = "io.github.theeraphatstudent.piewall" DAEMON_FILE = Path("/Library/LaunchDaemons") / f"{DAEMON_LABEL}.plist" +ALF = "/usr/libexec/ApplicationFirewall/socketfilterfw" +ALF_GROUP = "macOS Application Firewall" # pfctl -E takes a reference on pf so it stays on alongside other pf users (VPNs, Docker…). _LOAD = f"/sbin/pfctl -q -E; /sbin/pfctl -q -a {ANCHOR} -f {shlex.quote(str(PF_FILE))}" @@ -97,6 +103,33 @@ def render(rules: list[Rule]) -> str: line + "\n" for line in lines) +def parse_alf(listapps: str, firewall_on: bool) -> list[Rule]: + """`socketfilterfw --listapps` output -> one incoming rule per app.""" + rules, path = [], None + for line in listapps.splitlines(): + entry = re.match(r"\s*\d+\s*:\s*(.+?)\s*$", line) + if entry: + path = entry.group(1) + elif path and line.strip().startswith("("): + rules.append(Rule( + name=path, enabled=firewall_on, direction="in", + action="block" if "block" in line.lower() else "allow", program=path, + group=ALF_GROUP, description="Incoming connections (macOS Application Firewall)", + display_name=Path(path).name.removesuffix(".app"))) + path = None + return rules + + +def _read_alf() -> list[Rule]: + """The Application Firewall's app list; reading needs no password.""" + try: + state = subprocess.run([ALF, "--getglobalstate"], capture_output=True, text=True).stdout + apps = subprocess.run([ALF, "--listapps"], capture_output=True, text=True).stdout + except OSError: # not macOS + return [] + return parse_alf(apps, "State = 0" not in state) + + def _run_as_root(script: str) -> None: if os.geteuid() == 0: cmd = ["/bin/sh", "-c", script] @@ -110,16 +143,18 @@ def _run_as_root(script: str) -> None: return if "(-128)" in done.stderr: # user pressed Cancel raise ElevationCancelled - raise FirewallError(done.stderr.strip() or f"pfctl failed ({done.returncode})") + raise FirewallError(done.stderr.strip() or f"firewall change failed ({done.returncode})") class PfBackend: - def __init__(self, state_file: Path = STATE_FILE, run=_run_as_root) -> None: + def __init__(self, state_file: Path = STATE_FILE, run=_run_as_root, read_alf=_read_alf) -> None: self.state_file = state_file self._run = run + self._read_alf = read_alf self._rules: list[Rule] = [] self._depth = 0 - self._dirty = False + self._dirty = False # pf rules changed + self._alf: list[str] = [] # pending socketfilterfw commands def _load(self) -> list[Rule]: try: @@ -129,13 +164,14 @@ def _load(self) -> list[Rule]: return [Rule.from_dict(d) for d in data["rules"]] def _current(self) -> list[Rule]: - """Fresh from disk (another piewall may have changed it), except mid-batch.""" + """piewall's pf rules, fresh from disk (another piewall may have changed them), + except mid-batch.""" if not self._depth: self._rules = self._load() return self._rules def list_rules(self) -> list[Rule]: - return list(self._current()) + return [*self._current(), *self._read_alf()] @contextlib.contextmanager def batch(self): @@ -144,7 +180,7 @@ def batch(self): self._depth += 1 try: yield - if self._depth == 1 and self._dirty: + if self._depth == 1: self._commit() except BaseException: self._rules = saved @@ -152,20 +188,31 @@ def batch(self): finally: self._depth -= 1 if not self._depth: - self._dirty = False + self._dirty, self._alf = False, [] - def _changed(self, rules: list[Rule]) -> None: - before, self._rules = self._rules, rules + def _pending(self) -> None: + """Commit now, unless a batch will.""" if self._depth: - self._dirty = True return try: self._commit() - except BaseException: - self._rules = before - raise + finally: + self._dirty, self._alf = False, [] + + def _changed(self, rules: list[Rule]) -> None: + self._rules, self._dirty = rules, True + self._pending() + + def _alf_do(self, *commands: str) -> None: + self._alf += [f"{ALF} {c}" for c in commands] + self._pending() def _commit(self) -> None: + if not (self._dirty or self._alf): + return + if not self._dirty: + self._run(" && ".join(self._alf)) + return pf = render(self._rules) # raises before anything is touched state = json.dumps({"version": 1, "rules": [r.to_dict() for r in self._rules]}, indent=2) with tempfile.TemporaryDirectory(prefix="piewall-") as tmp: @@ -181,19 +228,33 @@ def _commit(self) -> None: f"/usr/bin/install -m 644 {t('pf.rules')} {q(PF_FILE)}", f"/usr/bin/install -m 644 {t('daemon.plist')} {q(DAEMON_FILE)}", f"({_LOAD})", + *self._alf, ])) + def _alf_apps(self, name: str) -> list[str]: + return [r.program for r in self._read_alf() if r.name == name] + def add_rule(self, rule: Rule) -> None: + if rule.program and not rule.service: + if rule.direction != "in": + raise FirewallError(f"'{rule.name}': the macOS Application Firewall only " + f"filters incoming connections") + app = shlex.quote(rule.program) + verb = "--unblockapp" if rule.action == "allow" else "--blockapp" + self._alf_do(f"--add {app}", f"{verb} {app}") + return render_rule(rule) # refuse before prompting for a password self._changed([*self._current(), rule]) def delete_rules(self, name: str) -> int: rules = self._current() kept = [r for r in rules if r.name != name] - count = len(rules) - len(kept) - if count: + apps = self._alf_apps(name) + if len(kept) < len(rules): self._changed(kept) - return count + if apps: + self._alf_do(*(f"--remove {shlex.quote(a)}" for a in apps)) + return len(rules) - len(kept) + len(apps) def _set(self, name: str, **changes) -> int: rules = self._current() @@ -203,7 +264,15 @@ def _set(self, name: str, **changes) -> int: return count def set_enabled(self, name: str, enabled: bool) -> int: + if self._alf_apps(name): + raise FirewallError("macOS Application Firewall rules can't be switched off one by " + "one: make the rule Allow or Block, delete it, or turn the " + "firewall on or off in System Settings > Network > Firewall.") return self._set(name, enabled=enabled) def set_action(self, name: str, action: str) -> int: - return self._set(name, action=action) + apps = self._alf_apps(name) + if apps: + verb = "--unblockapp" if action == "allow" else "--blockapp" + self._alf_do(*(f"{verb} {shlex.quote(a)}" for a in apps)) + return self._set(name, action=action) + len(apps) diff --git a/tests/test_pf.py b/tests/test_pf.py index 020f004..b91466b 100644 --- a/tests/test_pf.py +++ b/tests/test_pf.py @@ -8,7 +8,7 @@ from piewall.backend import FirewallError, batch from piewall.elevate import ElevationCancelled from piewall.model import Rule -from piewall.pf import PfBackend, render, render_rule +from piewall.pf import ALF_GROUP, PfBackend, parse_alf, render, render_rule def rule(name="r", **kw): @@ -57,7 +57,7 @@ def __call__(self, script): def test_changes_commit_and_batch_prompts_once(tmp_path): state = tmp_path / "rules.json" root = Root(state) - fw = PfBackend(state, run=root) + fw = PfBackend(state, run=root, read_alf=list) fw.add_rule(rule("a")) assert len(root.scripts) == 1 assert "pfctl -q -n -a" in root.scripts[0] @@ -75,8 +75,69 @@ def test_changes_commit_and_batch_prompts_once(tmp_path): def test_cancel_changes_nothing(tmp_path): state = tmp_path / "rules.json" - fw = PfBackend(state, run=Root(state, cancel=True)) + fw = PfBackend(state, run=Root(state, cancel=True), read_alf=list) with pytest.raises(ElevationCancelled), batch(fw): fw.add_rule(rule()) assert fw.list_rules() == [] assert not state.exists() + + +LISTAPPS = """Total number of apps = 2 + +1 : /usr/sbin/cupsd + (Allow incoming connections) +2 : /Applications/Some Game.app + (Block incoming connections) +""" + + +def test_parse_alf(): + cups, game = parse_alf(LISTAPPS, firewall_on=True) + assert (cups.name, cups.action, cups.program, cups.enabled) == \ + ("/usr/sbin/cupsd", "allow", "/usr/sbin/cupsd", True) + assert (game.action, game.title, game.group) == ("block", "Some Game", ALF_GROUP) + assert not any(r.enabled for r in parse_alf(LISTAPPS, firewall_on=False)) + + +class Recorder: + def __init__(self): + self.scripts = [] + + def __call__(self, script): + self.scripts.append(script) + + +def alf_backend(tmp_path): + run = Recorder() + fw = PfBackend(tmp_path / "rules.json", run=run, + read_alf=lambda: parse_alf(LISTAPPS, firewall_on=True)) + return fw, run + + +def test_app_rules_are_listed_and_changed_through_socketfilterfw(tmp_path): + fw, run = alf_backend(tmp_path) + assert [r.title for r in fw.list_rules()] == ["cupsd", "Some Game"] + with batch(fw): # one password prompt for both + assert fw.set_action("/Applications/Some Game.app", "allow") == 1 + assert fw.delete_rules("/usr/sbin/cupsd") == 1 + assert len(run.scripts) == 1 + assert "--unblockapp '/Applications/Some Game.app'" in run.scripts[0] + assert "--remove /usr/sbin/cupsd" in run.scripts[0] + assert "pfctl" not in run.scripts[0] # pf untouched + + +def test_program_rule_goes_to_the_application_firewall(tmp_path): + fw, run = alf_backend(tmp_path) + fw.add_rule(rule("nc", program="/usr/bin/nc", local_ports="", protocol="any", + action="block")) + assert run.scripts == ["/usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/bin/nc && " + "/usr/libexec/ApplicationFirewall/socketfilterfw --blockapp /usr/bin/nc"] + with pytest.raises(FirewallError): + fw.add_rule(rule("out", program="/usr/bin/nc", direction="out")) + + +def test_app_rules_cannot_be_disabled_one_by_one(tmp_path): + fw, run = alf_backend(tmp_path) + with pytest.raises(FirewallError): + fw.set_enabled("/usr/sbin/cupsd", False) + assert run.scripts == []