WarningEditing the firewall via SSH can easily lock you out of the system, use these commands with caution and make sure you have console access.
Linux includes a built-in firewall known as iptables. But it’s rather open by default. Applying some basic rules are recommended to all new installations.
Ensure you have root access first. Let’s take a look at the current state of the firewall:
root@linux:/home/user# iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination
The firewall by default is very open, with no rules. There are three ‘chains’ available. The three chains relate to the following:
|FORWARD||Packets not specifically addressed to an interface IP. Used for routing\IP forwarding|
Most commonly, you’ll want both INPUT and FORWARD dropping all traffic, while creating exceptions for packets you require. Outbound traffic is typically allowed on all ports.
By default all chains are set to ACCEPT, meaning all traffic is allowed.
Before we change this, lets add our exceptions in so we don’t lose SSH access. Let’s allow inbound SSH:
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT -m comment –-comment "Allow SSH Access"
This adds a new rule to the INPUT chain, accepting traffic destined for TCP port 22, in a NEW or ESTABLISHED state. We also add a handy comment to the rule.
We’ll also want to allow any ESTABLISHED, or RELATED connections, regardless of port:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
RELATED simply means the incoming packet is expected, because it’s related to another socket already ESTABLISHED on the client which the kernel is tracking.
Changing the defaults
Once we’ve established which connections are allowed, let’s change the default behaviour of the chains to DROP (except OUTPUT):
root@linux:/home/user# iptables -P FORWARD DROP root@linux:/home/user# iptables -P INPUT DROP root@linux:/home/user# iptables -P OUTPUT ACCEPT
Now if we check the firewall rules using
iptables -L, we’ll see the changes have taken effect immediately.
If you made a mistake and want to delete a rule, display them with line numbers:
iptables -L --line-numbers
You can then delete the line by referencing it along with the CHAIN:
iptables -D INPUT 2
Making rules persistent
One last thing to note – the changes are not persistent and will be deleted on reboot. To keep them, let’s save the rules somewhere:
iptables-save > /path/to/fwrules.fw
You’ll now have a file with the rules defined. We’ll now need to ensure these rules apply on start up. How we do this depends on your Linux distribution, but
iptables includes a handy tool to execute this:
On Debian based systems, you can place this within
/etc/network/interfaces under an
up directive for your interface.
|Posted August 10, 2019||Tweet|
|Updated Dec 27, 2020|
|Written by John Payne|