Friday, September 16, 2016

Using the Linux iptables firewall

The most common firewall for Linux-systems is the iptables firewall. Iptables is generally preinstalled on any Linux distribution. If it is not installed on your system, just get it via


sudo apt-get install iptables



Iptables uses  policy chains,i.e sets of rules, to allow or block inbound/outbound traffic.
These policy chains consist of three different types:



INPUT  -            Manages incoming connections.

FORWARD -     Manages packets that are not to be delivered locally,
                           but  instead forwarded to their target(s).

OUTPUT -         Handles outgoing traffic. If you try to ping www.google.com,
                           iptables will check its output chain regarding icmp packets and
                           the destined host before deciding whether or not to allow/deny
                           the connection



When securing a system with iptables, keep in mind that a lot of communication protocols,
such as ssh, require two-way communication. Hence, both the INPUT chain as well as the
OUTPUT chain must be configured accordingly.

The command

sudo iptables -L | grep policy

will display all policies currently set on your system. On a newly installed system no
rules is yet configured so output will be:


Chain INPUT (policy ACCEPT)
Chain FORWARD (policy ACCEPT)
Chain FORWARD (policy ACCEPT)


SIMPLE TEST : DISABLE AND RE-ENABLE WAN CONNECTIVITY


ping -c 3 www.google.com

If this works, stop all packets to your system by  issuing the command:


sudo iptables --table filter --append INPUT --jump DROP


Repeating the ping-command will now not work.
Running

sudo iptables -L

will display the newly added iptables policy. The "flush"-command

sudo iptables -F

will remove the rule and it will work to ping Google again.

Note that the "--append" flag to OUTPUT/FORWARD/INPUT policies also can be written as "-A".

MANAGING CONNECTIONS FROM RANGES OF IP-ADDRESSES

Ex: Block all connections from IP address 10.10.10.4


sudo iptables -A INPUT -s 10.10.10.4 -j DROP


Ex: Block all connections from IP-range 10.10.10.0/24


sudo iptables -A INPUT 10.10.10.0/24 -j DROP


Ex: Block ssh-traffic from IP ADDRESS 10.10.10.4


sudo iptables -A INPUT -p tcp --dport ssh -s 10.10.10.4 -j DROP

The -p option above tells what kind of connection the protocol uses.

Ex: Block ssh-traffic from any connection

sudo iptables -A INPUT -p tcp --dport ssh -j DROP