VPS Notes

Security Tutorial - A Simple Firewall

Firewall is a popular way of protecting servers. It is used to control which network traffic to pass to and from the server. Typically, all incoming ports to the server are blocked except for a few that servers the public. Like port 80 if our server is a web server.

Prepare The Rules

We will use iptables to manage our firewall rules. From the man pages: iptables — administration tool for IPv4 packet filtering and NAT.

The first step is to prepare a text file that will contain the rules:

$ nano /etc/iptables.up.rules

And use the following content:


# Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0 -A INPUT -i lo -j ACCEPT -A INPUT ! -i lo -d -j REJECT

# Accepts all established inbound connections -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allows all outbound traffic -A OUTPUT -j ACCEPT

# Allows SSH connections to our ssh port -A INPUT -p tcp --dport 22 -j ACCEPT

# Open Other TCP Ports (like 80 if you will install a webserver). add more lines like this if you like -A INPUT -p tcp --dport 80 -j ACCEPT

# Allow ping -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# log iptables denied calls -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

# Reject all other inbound - default deny unless explicitly allowed policy -A INPUT -j REJECT -A FORWARD -j REJECT


What the above rules say is that all ports are blocked except port 22 (for ssh and scp) and port 80 (web server). If you want to open more ports, just add a line below the line where port 80 was opened. For example, if you wish to open port 21 (ftp) and port 25 (smtp for mailservers), below is the config:
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 21 -j ACCEPT
-A INPUT -p tcp --dport 25 -j ACCEPT

Apply the Rules

This is how to apply the rules now:

iptables -F
/sbin/iptables-restore < /etc/iptables.up.rules

Make It Sticky

If you want the firewall rules to be automatically applied after reboot, create a script:

$ nano /etc/network/if-pre-up.d/iptables

And put these contents:

/sbin/iptables-restore < /etc/iptables.up.rules

Make it executable:

chmod +x /etc/network/if-pre-up.d/iptables


Tags: iptables, security