Restrict traffic to local network and VPN using ufw or iptables

I want to restrict all traffic from my ubuntu-machine to come or go from the local network (eth0) or from or to my VPN (tun0).
It should be possible to connect the router in the local network but not possible to leave the local network not using the VPN.

Since i have no experience with iptables and i couldn’t find some how-to i tried ufw but i did not succeed.

Thank you for some hints or code snippets how to come closer!

Answer

You will want to operate on the filter table’s INPUT chain with a default action of DROP, and then set ACCEPT rules for packets incoming (-i) on each interface. To improve security, you could also enforce the subnet of the source host, but the rules below will suffice.

iptables -t filter -p INPUT DROP
iptables -t filter -A INPUT -i eth0 -j ACCEPT
iptables -t filter -A INPUT -i tun0 -j ACCEPT
iptables -t filter -A INPUT -i lo -j ACCEPT

If you also want to enforce the same thing for traffic leaving the host, also do these:

iptables -t filter -p OUTPUT DROP
iptables -t filter -A OUTPUT -o eth0 -j ACCEPT
iptables -t filter -A OUTPUT -o tun0 -j ACCEPT
iptables -t filter -A OUTPUT -o lo -j ACCEPT

Though, if you do this, you really may as well not have the other interfaces. Also, lo is in there because it is the loopback interface; without those rules loopback would no longer work.

Note that if your host is a router, these rules will not apply to traffic it is routing (only to traffic it generates itself or that is destined to it rather than through it).

Attribution
Source : Link , Question Author : Piezo Pea , Answer Author : Falcon Momot

Leave a Comment