Skip to content

Instantly share code, notes, and snippets.

@thangnc
Last active December 16, 2015 09:39
Show Gist options
  • Save thangnc/e968fc690c14dfb95f45 to your computer and use it in GitHub Desktop.
Save thangnc/e968fc690c14dfb95f45 to your computer and use it in GitHub Desktop.
Set Up a Basic Iptables Firewall on Centos 6

Block the most common attacks

iptables -F

First, we start with blocking null packets.

iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

The next pattern to reject is a syn-flood attack.

iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

Now we move on to one more common pattern: XMAS packets, also a recon packet.

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

Open up ports for selected services

Now we can start adding selected services to our firewall filter. The first such thing is a localhost interface:

iptables -A INPUT -i lo -j ACCEPT

Now we can allow web server traffic:

iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

Limiting SSH access

We should also allow SSH traffic, so we can connect to the VPS remotely. The simple way to do it would be with this command:

iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

Now, you can create the firewall rule to only allow traffic to SSH port if it comes from one source: your IP address:

iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 22 -j ACCEPT

Right now, we need to add one more rule that will allow us to use outgoing connections (ie. ping from VPS or run software updates);

iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

It will allow any established outgoing connections to receive replies from the VPS on the other side of that connection. When we have it all set up, we will block everything else, and allow all outgoing connections.

iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP

Save the configuration

Now that we have all the configuration in, we can list the rules to see if anything is missing.

iptables -L -n

The -n switch here is because we need only ip addresses, not domain names. Ie. if there is an IP in the rules like this: 69.55.48.33: the firewall would go look it up and see that it was a digitalocean.com IP. We don't need that, just the address itself. Now we can finally save our firewall configuration:

iptables-save | sudo tee /etc/sysconfig/iptables

The iptables configuration file on CentOS is located at /etc/sysconfig/iptables. The above command saved the rules we created into that file. Just to make sure everything works, we can restart the firewall:

service iptables restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment