In this tutorial we will cover the steps needed to setup a firewall on your Linux platform

Requirements

  • SSH access (Command line access to the server)
  • root privileges
  • Basic skills for working on a Linux environment

Introduction

The iptables comes as standard firewall software in most of the Linux distributions. A set of rules can be set inside which can filter the network traffic. The data packets can be filtered by source/destination address or port (or range of addresses/ports), protocol type network interface etc. The packets can be accepted, rejected (dropped), forwarded. This way you can protect the server from unwanted traffic.

The iptables rules are organized in groups (chains). If it matches some of the rules the corresponding actions is taken and no further check is made for that rule in the chain. By default there are three chains set inside iptables:

INPUT – handles the incoming traffic addressed to the server
OUPUT – handles the outgoing traffic originated from the server
FORWARD – routing the traffic

Each chain has default policy which will take effect if the traffic does not match any of the rules inside the chain.

iptables commands

Let's start by listing all rules that are set on the server:

We can allow incoming traffic on specific port with the following syntax:

The command appends the rule to the INPUT chain. Once the firewall is restarted all incoming tcp traffic on port 1234 will be allowed.

You can also block the whole incoming traffic with the following command:

Here is a list of the iptables options which can be used with the rules:

Any new rules added inside iptables should be saved otherwise they will disappear on system reboot

The default file where the rules are being saved might differ depending on the Linux platform:

CentOS:

Ubuntu:

The firewall rules can be saved into specific file with the following syntax:

Rules that were saved into a file can be restored with the following comamnd: