Get Rewarded! We will reward you with up to €50 credit on your account for every tutorial that you write and we publish!

Setting up a packet filter on Linux

profile picture
Author
Markus
Published
2020-06-17
Time to read
9 minutes reading time

Introduction

This article is about understanding and using the functions of iptables.

Attention: Caution is advised, due to ill-considered changes to the firewall, you can quickly be locked out of the system.

Prerequisites

root access to a Linux shell with iptables installed

Section 1 - What is iptables?

iptables is a userspace program that is used to configure the netfilter firewall in the Linux kernel. iptables is only a tool to configure the firewall integrated in the Linux kernel.

iptables is divided into two areas, with separate tools for IPv4 and IPv6. For IPv4 you use iptables and for IPv6 ip6tables. All the following commands can be used with both tools in the same way.

Through the netfilter it is possible to:

  • filter incoming packets before they are routed to the target application.
  • filter outgoing packets before they leave the computer.
  • check packets routed through the computer (router).
  • perform packet manipulation.

Section 1.1 - Structure

Package checking with iptables has a three-step structure (top to bottom):

  • tables
  • chains
  • filter rules

If one of the defined filter rules in the tables / chains applies, it will be executed. If no rule is defined or none of the defined rules apply, the defined policy will be applied (more on this later).

Tables

In the tables, different chains are grouped together according to the basic task.

Table Description
filter The standard table here all filter rules are stored
nat This table is used for NAT (Network Address Translation) and port forwarding.
mangle This table is used for packet manipulation.
raw This table is used to define connection tracking exceptions.

Chains

The chains determine when a package is checked, e.g. before it is sent. A chain can occur in several tables.

Chain Table Description
INPUT filter, mangle Applied to all packets directed to the local address.
OUTPUT filter, nat, mangle, raw Applies to all packets coming from the local address.
FORWARD filter, mangle Applies to all packets that are routed.
PREROUTING nat, mangle, raw applied to all packets before they are routed.
POSTROUTING nat, mangle Apply to all packets after they are routed.

Section 2 - Definition of filter rules

The most common CLI parameters for creating filter rules are listed here, along with their meaning.

Option Description
-t Table This filter rule applies to the named table.
-I Chain (Position) Rule is added to selected position of the chain. By default, the rule is added at the beginning of the chain.
-A Chain Rule is added to the chain.
-D Chain Rule is deleted from the chain.
-F Chain Delete all rules in the chain.
-L Chain List all rules in the chain.
-p Protocol The packet is only checked if it complies with the protocol (e.g. TCP, UDP, ICMP).
-s IP Address The packet is only checked if it originates from the defined IP address / IP network.
-d IP address The packet is only checked if it is sent to the defined IP address.
-i Network Interface The packet is only checked if it has arrived via the corresponding network interface.
-o Network Interface The packet is only checked if it is sent via the corresponding network interface.
--sport (port) or --source-port (port) The packet is only checked if it comes from the defined port. Must be used in conjunction with -p
--dport (port) or --destination-port (port) The packet is only checked if it is sent to the defined port. Must be used in conjunction with -p
-j Action Defines which action should be applied to the packet.

Section 2.1 - Definition of actions

Action Description
ACCEPT The package is accepted and accepted.
DROP The packet is not accepted, the sender does not receive a message.
REJECT The packet is not accepted, the sender is notified.
LOG The packet data is recorded in the system log, then the next rule in the chain is checked and applied if necessary.

Section 2.2 - Defining Policies

A policy is to be seen as a principle rule - it always applies if no other filter rule applies.

A policy consists of a chain and an action:

iptables -P INPUT DROP

Attention: This policy blocks the incoming traffic if no rules are defined.

In this example, all incoming packets in the Filter table are discarded by the policy.

Section 3 - Loopback Interface (127.0.0.1)

On every Linux system there is a local network adapter called lo. Internal host applications run over this, these sometimes communicate via IPC (Inter Process Communication) using this adapter. It is therefore advisable not to apply any filter rules to this adapter, as this can lead to communication problems.

This adapter should be allowed to communicate without restrictions:

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

Section 4 - Practical Examples

Create a packet filter rule

This rule allows incoming HTTPS traffic:

iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Create a host filter rule

This rule allows incoming traffic from the specified host:

iptables -A INPUT -s 10.0.0.1 -j ACCEPT

This rule prohibits incoming traffic from the specified host:

iptables -A INPUT -s 10.0.0.1 -j DROP

Rules can also be added at a specific location:

iptables -I INPUT 2 -s 10.0.0.1 -j DROP

This rule is, for example, in second place.

Delete all rules

Deletes all rules in all chains:

iptables -F

Deletes all rules in the INPUT chain:

iptables -F INPUT

Delete a rule

This specifies the rules with the corresponding numbers:

iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
2    ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh

Chain FORWARD (policy ACCEPT)
num  target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination

This number can now be used to delete the desired rule:

iptables -D INPUT 1

Connection State

Connection state filters can be used so that not every packet has to go through the filter for connections already established.

Allow incoming packets for existing connections:

iptables -A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

Allow outgoing packets for existing connections:

iptables -A OUTPUT -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

Hint: The connection state rules should be high up in the firewall list, otherwise they lose their use.

Discarding invalid packages

This command discards all incoming packets that do not comply with the TCP / IP format:

iptables -A INPUT --ctstate INVALID -j DROP

Syn-Flood Protection

These entries prevent the server from being overloaded by too many requests:

iptables -N syn_floodiptables -A INPUT -p tcp --syn -j syn_floodiptables -A syn_flood -m limit --limit 1/s --limit-burst 3 -j RETURN
iptables -A syn_flood -j DROP
iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j ACCEPT
iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j LOG --log-prefix PING-DROP:
iptables -A INPUT -p icmp -j DROP
iptables -A OUTPUT -p icmp -j ACCEPT

Section 5 - Persistence

The configured firewall rules are not automatically persistent. To change this, the package iptables-persistent must be installed.

After that, you can use the command:

iptables-save > /etc/iptables/rules.v4 # For IPv4
ip6tables-save > /etc/iptables/rules.v6 # For IPv6

The current configuration can be saved.

Section 6 - Countries Block

With the included script you can create IP drop rules for whole countries.

Note: This blocking is limited to IPv4 addresses.

#!/bin/bash
###PUT HERE SEPARATED LIST OF COUNTRY CODE###
COUNTRIES=(de at)
WORKDIR=$(mktemp -d)
#######################################
for i in "${COUNTRIES[@]}";
do
curl http://www.ipdeny.com/ipblocks/data/countries/$i.zone >> $WORKDIR/iptables-blocklist.txt;
done

if [ -f $WORKDIR/iptables-blocklist.txt ]; then
  iptables -F
  BLOCKDB="$WORKDIR/iptables-blocklist.txt"
  IPS=$(grep -Ev "^#" $BLOCKDB)
  for i in $IPS
  do
    echo iptables -A INPUT -s $i -j DROP >> input.sh
    echo iptables -A OUTPUT -d $i -j DROP >> output.sh
  done
fi
rm -r $WORKDIR

In the script above, the variables 'COUNTRIES' can be updated to include any countries you want to block. When the script is executed it creates two files input.sh and output.sh which contain the iptables commands needed to block the IP addresses of the countries.

Summary

In this article, the functionality of iptables was explained. In addition, practical examples were used to illustrate the different ways of using iptables in an optimal way.

License: MIT
Want to contribute?

Get Rewarded: Get up to €50 in credit! Be a part of the community and contribute. Do it for the money. Do it for the bragging rights. And do it to teach others!

Report Issue
Try Hetzner Cloud

Get 20€ free credit!

Valid until: 31 December 2024 Valid for: 3 months and only for new customers
Get started
Want to contribute?

Get Rewarded: Get up to €50 credit on your account for every tutorial you write and we publish!

Find out more