Enabling VPN-only access in Linux to the Net with NetBlocker
With the option persist-tun enabled in the OpenVPN client configuration file, when a VPN connection is lost (when the server is unavailable) the primary network gateway for accessing the Internet is still the network interface of the VPN, and the traffic is still routed through it.
But just as it was mentioned in the article Allowing network connections in Linux with active VPN only (kill switch), sometimes it is necessary to block access to the Net when no active VPN connection is available. So, we have prepared a script that makes the job easier.
Download netblocker.sh and install it into your system:
sudo mkdir /etc/netblocker sudo wget https://zorrovpn.com/static/download/netblocker.sh -O /etc/netblocker/netblocker.sh sudo chmod +x /etc/netblocker/netblocker.sh
sudo /etc/netblocker/netblocker.sh start
The script will create necessary rules for iptables, obtain all incoming IP addresses of VPN servers of the service and add them to the list of allowed for connections (the list will be stored in the file /etc/netblocker/vpn.list), and then block not allowed outoing connections
After the start, you can see for yourself that the disallowed addresses are no longer available; for example, try accessing 184.108.40.206 using ping 220.127.116.11
PING 18.104.22.168 (22.214.171.124) 56(84) bytes of data. ping: sendmsg: Operation not permitted ping: sendmsg: Operation not permitted ping: sendmsg: Operation not permitted ^C --- 126.96.36.199 ping statistics --- 3 packets transmitted, 0 received, 100% packet loss, time 1999ms
Connections will be available only to the allowed IP addresses of VPN servers.
You can add your own allowed IP addresses to the file /etc/netblocker/custom.list (one IP address per line): 192.168.1.1 (for accessing the router; this will also allow accessing the router’s DNS), 188.8.131.52 (for Google’s public DNS), etc.
Once added, run the command:
sudo /etc/netblocker/netblocker.sh reload
Update the list of IP addresses of VPN servers:
sudo /etc/netblocker/netblocker.sh update
sudo /etc/netblocker/netblocker.sh stop
Adding local nameservers to custom address list:
sudo /etc/netblocker/netblocker.sh add_dns_to_custom
To start on system boot, add the following line to your /etc/rc.local (before the line with the "exit 0" statement)