# WireGuard Policy Firewall (`03.wireguard-policy`) ## Architecture & Configuration Flow - **Goal:** Dynamic iptables/ipset rules based on WireGuard configuration (`wg0.conf`). - **Data Flow:** `wg0.conf` -> `wg-sync-policy.sh` -> `policy.json` -> `wg-policy-engine.sh` -> `iptables`/`ipset` - **File Watcher:** `wg-sync-watch.sh` monitors `wg0.conf` via `inotifywait` and debounces changes to re-run the sync and engine. ## Critical Parsing Rules & Design Constraints - **Target IPs Parsing (`#Access`):** The firewall script uses the custom `#Access` comment in `wg0.conf` to define egress/firewall whitelists for clients. - **Why `#Access` is mandatory:** WireGuard's native `AllowedIPs` on a Server dictates *routing* towards the client. If we put target destinations in the Server's `AllowedIPs`, the Server would wrongly route traffic destined for those IPs *into* the client tunnel. Therefore, a custom `#Access` comment is the only correct way to define firewall whitelist destinations without breaking WireGuard's Cryptokey Routing. - **Do not remove `#Access`:** Future agents MUST NOT attempt to refactor the script to parse targets from `AllowedIPs`. It is architecturally incorrect for this use case. ## Testing & Verifying - `wg-policy-ctl status`: Check the overall health, including interface status, JSON validity, lock files, and iptables rules counts. - `wg-policy-ctl validate`: Validates `policy.json` without applying. - `wg-policy-ctl rules`: View the applied iptables rules in the active chain (`WG_POLICY`). - `wg-policy-ctl reload`: Forces a re-sync from `wg0.conf` and re-applies iptables. ## Script Constraints & Gotchas - **Atomic Operations:** Always use atomic writes (`mv -f tmp target`) for `policy.json` to prevent the policy engine from reading partial files. - **Locking:** `wg-sync-policy.sh` uses file-based locking (`flock`) to prevent race conditions during updates. - **Rollback:** `wg-policy-engine.sh` creates a backup chain (`WG_POLICY_BAK`) and uses a trap on `ERR` to rollback if applying rules fails halfway. - **Dependencies:** Requires `jq` and `inotify-tools`. ## Development Commands - Restart the watcher service: `systemctl restart wg-policy.service` - Check service logs: `journalctl -u wg-policy.service -f`