Introduction

Today, when it comes to virtual machine netsec, a lot of people talks of solution like Fail2Ban. Fail2ban is great, but, you can do filtering with native firewall : iptables.

I know that it easier to install and configure Fail2Ban, but you can do simple firewall rules. Today, I am going to show how to allow HTTP, DNS, ICMP and SSH on not default port through iptables.

First things first

In order to allow any HTTP, DNS or any protocol, we need to allow connections that have ESTABLISHED states.

iptables -I INPUT -m state --state ESTABLISHED -j ACCEPT
iptables -I OUTPUT -m state --state ESTABLISHED -j ACCEPT

We allow incoming and outgoing connections.

This two rules means that the packet is associated with a connection which has seen packets in both directions.

HTTP and HTTPS

To allow outgoing HTTP and HTTPS connections, like allowing the machine to go on the Internet we add the two following rules :

iptables -A OUTPUT -o ens37 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT 
iptables -A OUTPUT -o ens37 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT 

We allow NEW and ESTABLISHED connections on 80 (HTTP) and 443 (HTTPS).

DNS

Without allowing DNS outgoig rule, we have no name resolution.

So, if you try to go on the Internet without the following rule, you may believe that your previous rules are not working, but they are.

Add the two rules :

iptables -A INPUT -i ens37 -p udp --sport 53 -j ACCEPT 
iptables -A OUTPUT -o ens37 -p udp --dport 53 -j ACCEPT

As you can see, I only allow UDP protocol, because DNS do not use TCP but UDP.

SSH on non default port

Like the previous rules, we are going to allow traffic on other port than default port. It is not more complex, we just change the 22 port by our ssh server port, 65022 :

iptables -A INPUT -i ens37 -p tcp --dport 65022 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o ens37 -p tcp --sport 65022 -m state --state ESTABLISHED -j ACCEPT

This is all!

Conclusion

Iptables allow to do a lot of firewalling on virtual machines.

Once you master Iptables, you can do everything you want, and use other tools in complement like Fail2ban, to block unwanted connections for 3 times for examples.