Networking – Block WAN Access, Allow LAN Access on Linux Hosts

iptablesnetworking

What I am looking to do is block access to WAN and only allow these hosts to talk to each other on the 192.168.1.0/24 LAN. This configuration should be done on the hosts in question.

There are some similar posts to this, but tend to be too specific use case, or overly complicated. I now pay for internet per/GB. I have certain VM's that don't really need WAN Access after being setup, but seem to be using large amounts of data. (LDAP Server for some reason?)

I'm looking into DD-WRT Filtering, but I wondered how to do this host side.

I will also be looking into enabling WAN Access for 1 hour daily. This could be done via "iptables script" with CRON, or just via DD-WRT.

I'm guessing IPTables is the way to go. I think all of my servers use IPTables, some have UFW and some have FirewallD.

I figure this can be a "generic question" with mostly answers that should work across many/all distros. But just to add, I'm mostly using Ubuntu 14/16 and CentOS 6/7.

Best Answer

Filtering with IPTABLES

This can be accomplished by creating a set of rules for allowed traffic and dropping the rest.

For the OUTPUT chain, create rules to accept loopback traffic and traffic to 192.168.1.0/24 network. Default action is applied when no rules are matched, set it to REJECT.

iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -d 192.168.1.0/24 -j ACCEPT
iptables -P OUTPUT REJECT

For INPUT chain, you can create similar rules. Allow traffic from loopback and local network, drop the rest.

You can match established traffic (reply traffic to connections initiated by your host) with a single rule using -m conntrack --ctstate ESTABLISHED. This way you do not need to alter the chain when you want to enable Internet access. This works when you do not run any programs/daemons expecting connections from outside of your local network.

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT
iptables -P INPUT DROP

If you need to allow connections initiated outside of your local network, you need to configure the INPUT chain in the same way as the OUTPUT chain and use similar mechanism to apply

To allow unrestricted (WAN access) network access, change the default action to ACCEPT. To put the limits back, change the default action back to REJECT. Same effect is achieved by adding/removing -j ACCEPT as last rule.

iptables -P OUTPUT ACCEPT

You can also use iptables time module to accept the traffic at specific time of a day, in which case you do not need to use cron. For example, to allow any outgoing traffic between 12:00 and 13:00 with following rule:

iptables -A OUTPUT -m time --timestart 12:00 --timestop 13:00 -j ACCEPT
Related Question