Using Linux iptables for a firewall

In this article, we are going to set up a firewall using iptables. iptables is the standard firewall software present in most Linux distributions. We are going to use these set of rules to filter the network traffic. You can protect the server from unwanted traffic by filtering the data packets by specifying the source or destination IP address, port addresses, protocol types, network interfaces, and so on. We can configure this for accepting, rejecting, or forwarding network packets.

Rules are arranged in chains. By default, there are three chains (input, output, and forward). The input chain handles incoming traffic, while the output chain handles outgoing traffic. The forward chain handles routing traffic. Each chain has a default policy to adhere to if network packets do not match any policy inside the chain.

Prerequisites

Please check that the following requirements are satisfied before proceeding to the next activity:

  • Root privileges
  • SSH access (command line access to the server)
  • Make sure you have gt and looptools installed in your Linux environment
  • Basic skills for working on a Linux environment

How to do it

Now, we are going to see some of the iptables commands:

  • Run the following command to list all the rules that are set on the server:
$ sudo iptables -L
  • To allow incoming traffic from a specific port, use the following command:
$ sudo iptables -A INPUT -p tcp --dport 4321 -j ACCEPT

This rule will allow incoming traffic from port 4321. The firewall needs to be restarted to make this rule effective.

 Using iptables, you can block the incoming traffic. For that, run the following command:$ sudo iptables -A INPUT -j DROP

  • If any new rules are added in the iptables, we should save them first. Otherwise, after a system reboot, they will disappear. Run the following command to saving the iptables after adding new rules:
$ sudo iptables-save
  • The default file where rules are saved might differ depending on which Linux distribution you are working on.
  • We can save rules in a specific file by using the following command:
$ sudo iptables-save > /path/to/the/file
  • You can restore these rules that are saved in the file. Run the following command:
$ sudo iptables-restore > /path/to/the/file

How it works

Using iptables, we can control the incoming traffic, drop the traffic on a specific port, and add new rules and save them.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Related Articles