Last Updated on 16 July 2023 by Daniel

Setting up iptables is a powerful way to harden your server’s security by configuring firewall rules. Here’s a general overview of the steps involved in setting up iptables:
- Check existing rules: Before making any changes, check the existing iptables rules on your server by running the command
iptables -L -n
. This will display the current ruleset. - Define your security policy: Determine the security policy you want to enforce. This includes identifying which services should be accessible and which should be restricted or blocked.
- Allow essential services: Start by allowing essential services such as SSH (port 22) to ensure remote access to your server. Run the command
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
to allow SSH connections. - Allow established connections: Allow traffic related to established connections to pass through the firewall. Use the command
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
. - Block unwanted traffic: Create rules to block unwanted traffic. For example, to block all incoming traffic on a specific port, use
iptables -A INPUT -p tcp --dport <port_number> -j DROP
. - Enable outgoing connections: Allow outgoing connections by default. Use the command
iptables -A OUTPUT -j ACCEPT
. - Enable loopback interface: Allow communication on the loopback interface. Run
iptables -A INPUT -i lo -j ACCEPT
. - Test the rules: After setting up your rules, test them to ensure they work as expected. Verify that essential services are accessible while unwanted traffic is blocked.
- Save the rules: Once you’re satisfied with the rules, save them so they persist across reboots. Use the appropriate command for your Linux distribution, such as
iptables-save
ornetfilter-persistent
.
Remember to be cautious when configuring iptables rules, as incorrect rules can lock you out of your server or disrupt its functionality. It’s recommended to have a backup plan, such as access to the server console or a backup firewall rule, in case of any issues.
It’s also worth mentioning that iptables alone is just one aspect of server hardening. It’s important to implement other security measures, such as regularly updating your software, configuring secure authentication methods, and monitoring system logs for suspicious activity.