In the following tutorial I will show you how you can secure your Ubuntu or Debian based server using a firewall application called iptables.
What is iptables?
It's a user space application program that allows a system administrator to configure the tables provided by the Linux kernel firewall (implemented as different netfilter modules) and the chains and rules it stores.
In order to keep down the number of attempted break-ins and to filter the ports opened on your virtual server, it is necessary to properly configure your firewall.
FLUSH OLD RULES
The firewall rules can be flushed using the following commands:
iptables --table nat --flush
iptables --table nat --delete-chain
SET-UP FIREWALL RULES
The first thing to do, is to enable free use of the loop back interface, to ensure that all TCP sessions should begin with SYN and to allow established and related packets:
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Next thing, let's open up our service ports by using firewall rules like these examples below:
iptables -A INPUT -p tcp --dport 5622 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 25 -j ACCEPT
Once all the services are white listed, it's a good idea to allow ICMP packets and to LOG and DROP everything else in the INPUT chain.
iptables -A INPUT -p ICMP --icmp-type 8 -j ACCEPT
iptables -A INPUT -j LOG
iptables -A INPUT -j DROP
SETUP DEFAULT POLICIES
We can setup our firewall policies to DROP everything in the INPUT and FORWARD chains, and allow traffic in the OUTPUT chain. The default table filter contains three built in chains:
- Inbound traffic addressed to the machine itself hits the INPUT chain.
- Outbound, locally-generated traffic hits the OUTPUT chain.
- Routed traffic which should not be delivered locally hits the FORWARD chain.
Default policies can be applied using the following commands:
iptables -P INPUT DROP # <- do not run this over ssh as it will lock you out
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
And that's it folks, let me know if you have any suggestions on additional configurations that might help.