iptables – add, remove and backup your rules!

iptables – add, remove and backup your rules!

Hi,

today, in this post, we are going to talk about iptables. It’s user-space application that allows to configure the tables provided by the Linux kernel firewall (implemented as different Netfilter modules) and the chains and rules it stores.

The first basic command to learn is the one allowing to list all rules in all chains, “iptables -L” or “iptables –list”. In iptables by default three different chain exist: INPUT, FORWARD and OUTPUT. Each one of these chains is related to an “action”, INPUT handles the rules for input connections and so on.

Empty iptbales rules listing:

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

Now let’s try to add a simple rule allowing ssh access only form a certain IP range:

iptables -A INPUT -s 10.0.0.0/8 -p tcp -m multiport --dports 22 -m comment --comment "010 ssh" -m state --state NEW -j ACCEPT

The meaning of each option is described here below:

  • -A : append the rule to a chain, in this case to the INPUT chain
  • -s : address/mask source specification (the source of the connection), in this case only 10.x.x.x addresses are allowed to use ssh
  • -p : the connection protocol used, in this case TCP
  • -m multiport: matches multiple ports
  • –dports : the destination port or port range
  • -m comment –comment : adds a comment to the rule
  • -m state : allow filter rules to match based on connection state, in this case NEW connections
  • -j : jump to the specified target, in this case ACCEPT (accept connection)

Instead if we want to remove the rule the -D option can be used:

iptables -D INPUT -s 10.0.0.0/8 -p tcp -m multiport --dports 22 -m comment --comment "010 ssh" -m state --state NEW -j ACCEPT

Another useful command is the one allowing the dump of all the rules:

sudo iptables-save > iptables-export.bak

All rules of all chains are written to the file, so that you can restore them later.

To make any change persistent after a reboot of the iptables service the “iptables-save” command has to be executed.

This concludes this small overview of iptables!

CYA,

Vincenzo


Comments are closed.