So you’ve got your Linux server going, it’s configured the way you want it , and everything is coming up roses. You try to ping it, but the server doesn’t seem to exist. You’ve been blocked by some of the best/most insane firewall in the galaxy: iptables. A firewall’s job is to block unwanted traffic, and iptables takes its job seriously. By default, it. drops. everything. Got a http request incoming? Psh, drop that packet. I don’t care if you’ve got apache running. FTP request? Same story. Mysql? Nope.
Ssh is usually fine though, so we can log in and edit the rules. Iptables rules are added to rule chains. The only chain we’re interested in is the INPUT chain for now; We want to be able to receive http requests to our server, ssh connections, and nothing else. We’ll also want to allow existing connections to persist. These are the switches we’ll be using (you can find all these in the manpages, of course, but some are in the iptables-extensions manpage).
-Fflushes the rulechains. This means exactly what you’d think.
-A [chain]adds a rule to the specified chain.
-I [chain] [number]same as
-Abut inserts rule at a given point in the chain.
-i [interface]specifies the interface the rule will act on. If you don’t specify this, the rule will act on all interfaces, including loopback (more on this later).
-p [protocol]specifies whether the rule is for tcp, udp, or whathaveyou.
--dport [port]further narrows down the packets to look at by checking which port they’re headed for.
-m [match]this is an extension that looks at the type of traffic the packet belongs to. We use it with:
--state [state], which asks a different module called conntrack whether the connection is
INVALID, NEW, ESTABLISHED, RELATED,or
UNTRACKED. This is magic, I have only a vague understanding of how it works.
-j [policy]says whether to accept or drop the packet.
Alright, let’s get to it. You can think of iptables as a sieve, where every rule along the way checks out a packet and decides whether to keep it or discard it. If the rule doesn’t match the packet, it moves further down the sieve to be checked by other rules. Therefore, at the end of it, if the packet doesn’t match any of our rules, we will just discard it. A good policy for internet traffic is that if you don’t know what it is, don’t touch it. Every rule we add gets added last in the chain/sieve.
And that’s it. We’ve configured our firewall. It will reset every time you reboot your server, but that isn’t often. I just keep a script like the one above to reconfigure it. You can get NetworkManager to configure it for you on boot, but I don’t really see the point unless you reboot your server all the time, which, I mean, why would you do such a thing?
I am still a wizard