Good old iptables...

So this method of hardening your server has been around for a while, but it's still REALLY powerful! Basically a way of dictating what traffic can move in and out of your server and on which ports, it can severely reduce the attack surface for your server. And the best part (when working with Linode) is that their web based LISH terminal still works even when you've locked down everything, so it's almost impossible to lock yourself out of your server!

So I'm going to use iptables to secure my Mongodb database server. First thing to do is to install the persistent version of iptables in Debian - you don't want your firewall to evaporate as soon as you reboot your server!

sudo apt install iptables-persistent

Now we need to define some rules - the great news is that the good folks at Linode / MongoDB give us these... I only want to allow DB access from my application server so these two rules are enough - note there is one input and one output rule needed.

If you want to dig deeper into this, there is a full write-up here

iptables -A INPUT -s <ip-address> -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT

iptables -A OUTPUT -d <ip-address> -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT

Now make sure that your default policy is to DROP traffic in both directions - then only that traffic explicitly enabled with these two rules will be permitted.

iptables -P INPUT DROP

iptables -P OUTPUT DROP

Finally - let's save our rules so that they are reloaded each time the server reboots...

sudo iptables-save > /etc/iptables/rules.v4

One final check (because not everything you read on the internet is true!!) reboot your system and when you reconnect, you should be able to see your iptables rules with the following:

sudo iptables -L

Here's the gotcha that hit me... Now your server cannot hit the APT servers to get updates!!! No problem - you can either add in additional rules to allow the APT communications, or just turn off iptables while you update - just don't forget to turn it back on again afterwards!!