WireGuard doesn’t have a built-in kill switch by default, but you can create one using firewall rules to block all traffic if the VPN disconnects.
There are two ways to do this:
Option 1: Use PostUp and PreDown in the WireGuard config (Recommended)
This method automates the process and makes it easier to switch the VPN on and off without manually adjusting firewall rules.
Add these lines in the [Interface] section of your WireGuard config:
PostUp = iptables -I OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT
PreDown = iptables -D OUTPUT ! -o %i -m mark ! --mark $(wg show %i fwmark) -m addrtype ! --dst-type LOCAL -j REJECT
Here’s a breakdown of what those PostUp and PreDown commands do:
-
PostUp: This command is executed when the WireGuard interface is brought up (i.e., when the VPN is connected, sudo wg-quick up wg0).iptables -I OUTPUT: This inserts a new rule into theOUTPUTchain, which controls outgoing traffic.! -o %i:%iis a placeholder for the interface name (e.g.,wg0). This rule matches any traffic not going through the WireGuard interface.-m mark ! --mark $(wg show %i fwmark): This ensures the rule doesn’t apply to traffic that is already marked by WireGuard, preventing conflicts with marked packets.-m addrtype ! --dst-type LOCAL: This excludes local traffic (such as to your own machine), ensuring that local connections aren’t blocked.-j REJECT: This rejects any other outgoing traffic not going through the VPN.
-
PreDown: This command is executed when the WireGuard interface is brought down (i.e., when the VPN is disconnected, sudo wg-quick down wg0).iptables -D OUTPUT: This deletes the rule that was added when the interface was brought up, removing the restriction on outgoing traffic.- The rest of the command is the same as
PostUp, but instead of inserting the rule, it removes it.
Option 2: Set up firewall rules manually with iptables
- First, find your WireGuard interface name (e.g.,
wg0,wg1) and your default network interface name (e.g.,eth0,wlan0). - Then, add the following firewall rules using
iptablesto block traffic unless WireGuard is active:
# Allow traffic through the WireGuard interface
sudo iptables -A OUTPUT -o wg0 -j ACCEPT
sudo iptables -A INPUT -i wg0 -j ACCEPT
# Allow established connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Block all other outgoing traffic (replace eth0 with your default interface)
sudo iptables -A OUTPUT -o eth0 -j DROP
Make sure to save these rules so they persist after a reboot using iptables-save and iptables-restore. One downside of this method is that you’d need to manually adjust the firewall rules every time you want to stop using the VPN.