2.2 KiB
2.2 KiB
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.shmonitorswg0.confviainotifywaitand debounces changes to re-run the sync and engine.
Critical Parsing Rules & Design Constraints
- Target IPs Parsing (
#Access): The firewall script uses the custom#Accesscomment inwg0.confto define egress/firewall whitelists for clients. - Why
#Accessis mandatory: WireGuard's nativeAllowedIPson a Server dictates routing towards the client. If we put target destinations in the Server'sAllowedIPs, the Server would wrongly route traffic destined for those IPs into the client tunnel. Therefore, a custom#Accesscomment 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 fromAllowedIPs. 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: Validatespolicy.jsonwithout applying.wg-policy-ctl rules: View the applied iptables rules in the active chain (WG_POLICY).wg-policy-ctl reload: Forces a re-sync fromwg0.confand re-applies iptables.
Script Constraints & Gotchas
- Atomic Operations: Always use atomic writes (
mv -f tmp target) forpolicy.jsonto prevent the policy engine from reading partial files. - Locking:
wg-sync-policy.shuses file-based locking (flock) to prevent race conditions during updates. - Rollback:
wg-policy-engine.shcreates a backup chain (WG_POLICY_BAK) and uses a trap onERRto rollback if applying rules fails halfway. - Dependencies: Requires
jqandinotify-tools.
Development Commands
- Restart the watcher service:
systemctl restart wg-policy.service - Check service logs:
journalctl -u wg-policy.service -f