# 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 (User Override) - **Target IPs Parsing:** The script MUST NOT rely on `#Access` comments for client target isolation rules. - Instead, target allowed IPs should be parsed directly from the client's `AllowedIPs` list in the peer configuration (e.g., `AllowedIPs = 172.20.8.0/24,172.20.10.91/32,...`). - Note: Usually `AllowedIPs` defines the client's source IP (often a `/32`), but in this specific setup logic, multiple IPs listed in a peer's `AllowedIPs` act as the allowed destinations/access targets for that peer. ## 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`