4

I have written my first IPtables rule file to try and protect my server on all ports apart from SSH and the ports needed for the web.

This is what I have come up with:

i=/sbin/iptables

# Flush all rules
$i -F
$i -X

# Setup default filter policy
$i -P INPUT DROP
$i -P OUTPUT DROP
$i -P FORWARD DROP

# Allow unlimited traffic on loopback
$i -A INPUT -i lo -j ACCEPT
$i -A OUTPUT -o lo -j ACCEPT

# Open up ports for nginx
$i -A INPUT -p tcp --dport 443 -j ACCEPT
$i -A INPUT -p tcp --dport 80 -j ACCEPT
$i -A INPUT -p tcp --dport 22 -j ACCEPT

# Make sure nothing comes or goes out of this box
$i -A INPUT -j DROP
$i -A OUTPUT -j DROP

I know there is somewhat of a black art when it comes to IP tables so I was wondering if anyone could pitch in and see if this is the right approach to securing a web server.

Jimmy
  • 279

3 Answers3

6

You probably don't want to drop all outgoing connections.

You might want to add a rule early on to allow ESTABLISHED connections and if using protocols like ftp you might add RELATED to the rule too e.g.

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

remember rule order matters - first match wins.

You should probably take a look at this Q&A that we have on securing a web server Tips for Securing a LAMP Server it has lots of great information.

user9517
  • 117,122
1

You are missing -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT somewhere. Additionally, I would not drop all outgoing packets.

kasperd
  • 31,086
0

INPUT chain

Allow new sessions to be created. @Lain's answer have a small problem, it do not perform stateful inspection. This can be achieved by doing the following:

-A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT

Allow established sessions

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

OUTPUT chain

Option #1

Allow all outbound traffic

-P OUTPUT ACCEPT

Option #2

Allow only outbound traffic that is replies to acceped input. This can be useful if you want to enforce outbound traffic.

-P OUTPUT DROP
-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

And an example rule for accepted outbound traffic

-A OUTPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT

. . .

And a final note, keep the rules containing "-m state --state ESTABLISHED,RELATED" near the top of the ruleset, as they often will be matched against. Rules that initiate sessions will only be used once pr session.