I recently came across a situation in which I wanted to block a linux machine from all traffic to the outside world. The requirements were to allow incoming and outgoing traffic to anything on the local network (192.168.1.*) for the ability to SSH to/from different machines on the network, use an NFS share I have setup, and anything else involving the local network.

iptables makes this incredibly simple.

Before anything, apt-get install iptables-persistent before cutting your machine off from the outside world.

First, we can set the machines iptables policy for the INPUT and OUTPUT chains to be DROP:

iptables --policy OUTPUT DROP
iptables --policy INPUT DROP

Add a rule to the OUTPUT chain that if the destination of the packet matches 192.168.1.0/24, jump to ACCEPT it. Add a rule to the INPUT chain that if the source of the packet matches 192.168.1.0/24, jump to ACCEPT it.

iptables --insert OUTPUT --destination 192.168.1.0/24 --jump ACCEPT
iptables --insert INPUT  --source      192.168.1.0/24 --jump ACCEPT

We can confirm our rules are in place by running iptables --list which should show something like this:

Chain INPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     all  --  192.168.1.0/24       anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             192.168.1.0/24

In addition, trying to ping outside addresses should yield:

$ ping -c1 google.com
PING google.com (173.194.123.78) 56(84) bytes of data.
ping: sendmsg: Operation not permitted

And trying to ping a device I know is on the network..

$ ping -c1 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_req=1 ttl=64 time=0.653 ms

Persisting iptables rules

We need to persist these rules so in the event of the machine restarting, they'll still be in effect.

The iptables-persistent package makes this dead simple, once the rules are in effect, run the following:

iptables-save > /etc/iptables/rules.v4

# or, for ipv6 rules
ip6tables-save > /etc/iptables/rules.v6