Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,15 @@ 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.

## Use the window

Expand Down
2 changes: 1 addition & 1 deletion npm/piewall-mcp/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
5 changes: 3 additions & 2 deletions packaging/piewall-macos.spec
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@ 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
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
Expand Down
10 changes: 6 additions & 4 deletions packaging/piewall.spec
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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
]
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
5 changes: 5 additions & 0 deletions site/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
32 changes: 30 additions & 2 deletions src/piewall/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()


Expand Down
8 changes: 2 additions & 6 deletions src/piewall/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"}
Expand Down Expand Up @@ -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]:
Expand Down
107 changes: 88 additions & 19 deletions src/piewall/pf.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
"""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
piewall manages live in STATE_FILE (readable by everyone, so listing needs no password);
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

import contextlib
import json
import os
import re
import shlex
import subprocess
import tempfile
Expand All @@ -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))}"
Expand Down Expand Up @@ -97,6 +103,33 @@
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)

Check warning on line 110 in src/piewall/pf.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Simplify this regular expression to reduce its runtime, as it has super-linear performance due to backtracking.

See more on https://sonarcloud.io/project/issues?id=TheeraphatStudent_piewall&issues=AaDcspfg2339CDgUXzPV&open=AaDcspfg2339CDgUXzPV&pullRequest=3
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]
Expand All @@ -110,16 +143,18 @@
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:
Expand All @@ -129,13 +164,14 @@
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):
Expand All @@ -144,28 +180,39 @@
self._depth += 1
try:
yield
if self._depth == 1 and self._dirty:
if self._depth == 1:
self._commit()
except BaseException:
self._rules = saved
raise
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:
Expand All @@ -181,19 +228,33 @@
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()
Expand All @@ -203,7 +264,15 @@
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)
Loading
Loading