Our computer encounters a lot of traffic when connected to the Internet. Firewalls are used to control the flow of packets to and from our machines. Iptable is a firewall that is installed in all distributions of Linux machines by default. One can make their system secure by configuring the iptables properly. Uncomplicated Firewall (UFW) is a tool for default firewall configuration set up. This improves the ease of using iptables. But UFW is disabled by default and can be enabled as follows.
$ sudo ufw enable
Linux machine can be configured as a router. When a new packet arrives at the router, it consults the routing table where it is compared with the stored IP address and destination IP address of the packet. The packet is accepted by the operating system, only if the packet matches with any of the configuration set in the OS. Based on the configuration rules in the firewall as the INPUT, OUTPUT, and FORWARD, the system will accept or block the packet. If you want to set up you Linux system as a router, give the following command.
echo -n 1 | /proc/sys/net/ipv4/ip_forward
Now let us get into iptables. In iptables, rules are set as chains. Each chain has a list of rules. Also, each rule has matching criteria and action. Each chain has a default policy like ACCEPT/DROP and a list of rules. If none of the rules matches, the default policy is enforced. There are three primary chains :
- INPUT (takes packet)
- OUTPUT (gives out packet)
- FORWARD (takes input through one interface and forward through another)
Try entering the following in your Linux machine.
$ sudo iptables -L
You will find an output as follows :
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 if you want to add a specific rule you can add as follows.
$sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT
A : Append to a chain (INPUT here)
p : Protocol can be specified
dport : The specific port number or a range of port numbers as start:end can be specified.
j : jump target
The above command adds a rule to allow all incoming traffic on the default ssh port. Similarly you can also drop the packets that you want to block from entering your system.
$ sudo iptables -A INPUT -j DROP
This will block all the packets other that tcp packets from entering your machine.
Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT tcp -- anywhere anywhere tcp dpt:ssh DROP all -- anywhere anywhere
In a similar way you can add more rules to control the traffic. But one important thing to keep in mind is that this should not forbid you from desired packets to get dropped. The sequence in which the rules are mentioned plays an important role.