Дисклеймер

Внимание: в этом блоге могут описываться события, явления и факты при помощи ненормативной лексики. Убедитесь, что Вы готовы к этому.

четверг, 9 февраля 2017 г.

How to block any non-VPN connections

Some people care about their internet privacy and some of them also use GNU/Linux distros. Most VPN apps for Windows have killswitch option, so if VPN suddenly disconnects, some applications or whole internet connection will be stopped.
However, there's no such option for Linux systems. But there's a beatiful thing called iptables, a very powerful firewall.

My setup is mostly automated (check the link to understand), so I have put this script in /etc/openvpn/ and named it iptables-update.sh

Here's the content:
#!/bin/bash

# CLEAR all previous iptables rules
iptables -F;

### List of the rules ###

# ALLOW loopback access
iptables -A INPUT -i lo -j ACCEPT; iptables -A OUTPUT -o lo -j ACCEPT;

# ALLOW connections within own network (e.g. to router)
iptables -A INPUT -s 192.168.1.1/16 -d 192.168.1.1/16 -j ACCEPT;  iptables -A OUTPUT -s 192.168.1.1/16 -d 192.168.1.1/16 -j ACCEPT;

# ALLOW eth+ and tun+ to communicate
iptables -A FORWARD -i eth+ -o tun+ -j ACCEPT; sudo iptables -A FORWARD -i tun+ -o eth+ -j ACCEPT; # ALLOW eth+ and tun+ to communicate

# Complicated stuff
iptables -t nat -A POSTROUTING -o tun+ -j MASQUERADE;

# DROP any eth+ outgoing packets with different destination than server IP
iptables -A OUTPUT -o eth+ ! -d $(grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" /etc/openvpn/openvpn.conf) -j DROP;

# SAVE iptables rules
/etc/init.d/iptables save;
This script works perfectly for me with NordVPN setup. Last rule is the most crucial one - it takes server IP from /etc/openvpn/openvpn.conf and drops any packets with different destination to prevent leaks.

NOTE: make sure you have iptables starting at system boot.

It is reworked version of the information I found here.
And to make it automated, I put the following aliases examples in my ~/.bashrc:

alias de100="sudo /etc/init.d/openvpn stop; sudo /etc/init.d/iptables stop; sudo cp /etc/openvpn/de100.nordvpn.com.udp1194.ovpn /etc/openvpn/openvpn.conf; sudo /etc/openvpn/iptables-update.sh; sudo /etc/init.d/iptables start; sudo /etc/init.d/openvpn start"

alias de101="sudo /etc/init.d/openvpn stop; sudo /etc/init.d/iptables stop; sudo cp /etc/openvpn/de101.nordvpn.com.udp1194.ovpn /etc/openvpn/openvpn.conf; sudo /etc/openvpn/iptables-update.sh; sudo /etc/init.d/iptables start; sudo /etc/init.d/openvpn start"
Every time I change server with this alias, bash script automatically updates the rules.
As always, maybe not the most elegant way, but it's working fine :-)