0% found this document useful (0 votes)
61 views

11 Iptables

Iptables is a stateful firewall that comes preinstalled on Linux systems. It tracks the state of network connections as they progress and can be configured to allow or block packets based on their state. Iptables uses tables, chains, and rules to filter packets. A packet traversing the firewall will be processed by rules in different tables like filter, nat, and mangle based on its source, destination, and whether it is incoming, outgoing, or forwarding traffic. Iptables is being replaced by nftables, which offers improved syntax and capabilities.

Uploaded by

tdyrdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

11 Iptables

Iptables is a stateful firewall that comes preinstalled on Linux systems. It tracks the state of network connections as they progress and can be configured to allow or block packets based on their state. Iptables uses tables, chains, and rules to filter packets. A packet traversing the firewall will be processed by rules in different tables like filter, nat, and mangle based on its source, destination, and whether it is incoming, outgoing, or forwarding traffic. Iptables is being replaced by nftables, which offers improved syntax and capabilities.

Uploaded by

tdyrdy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

iptables

Iptables comes builtin on a linux system.

IPChains, which preceded iptables, is used to create a stateless firewall.

iptables is a stateful firewall. It tracks the state of a connection during its life.

An iptables firewall consists of several tables, each with a default policy and built-in
chains of rules. Further rule chains can optionally be created in each table. Different
tables and chains are traversed according to the source and destination of the packet.
A packet that is received via a network interface on the system goes through a
sequence of steps before it is handled locally or forwarded to another host.

Note that nftables, which is replacing iptables, is now available on most linux
distros.

It will replace the existing iptables, ip6tables, arptables and ebtables framework.

It has many syntax improvements over iptables.

iptables 1 Vincent Ryan


Stateful Inspection
A stateful firewall, detects that a packet (is/is not) part of an ongoing session and can
be configured to prevent entry to the packet. A stateful firewall is therefore more
secure than a stateless firewall.

For example, if you have clients behind a firewall that make Domain Name Server
(DNS) queries to an external DNS server, the client initiates a query by connecting
from one of its high-numbered ports to UDP port 53 on the server. The DNS server
answers the query from UDP port 53 back to the high-numbered port on the client.

To cater for this on a stateless firewall, all high-numbered ports above 1023 must be
opened to accommodate inbound connections.

A stateful firewall can be configured to only accept incoming UDP packets with a
source address that matches the destination address of the DNS Query, noting the port
numbers also. Therefore, the firewall will only accept query responses from DNS
servers that match outgoing queries that the firewall has already seen.

iptables 2 Vincent Ryan


Table Descriptions
IPTables has 4 tables:

▪ filter,

▪ nat,

▪ mangle and

▪ raw.

There is also a Security Table which is used to set internal SELinux security context
marks on packets, which will affect how SELinux or other systems that can interpret
SELinux security contexts handle the packets. These marks can be applied on a per-
packet or per-connection basis.

Each table has a number of chains.

Some chains are built-in.

Users can also define their own chains.

A typical rule looks like

iptables -t <table-name> -A <chain-name> rule -j ACCEPT

iptables 3 Vincent Ryan


filter Table : default chains

The filter table is the default table for any rule. It is where the bulk of the work in an
iptables firewall occurs. Avoid filtering in any other table as it may not work. It has
three commonly used builtin chains. Those chains are
· INPUT,
· OUTPUT, and
· FORWARD.
Packets destined for the host traverse the INPUT chain.
Packets created by the host to send to another system traverse the OUTPUT chain.
Packets received by the host that are destined for another host traverse the
FORWARD chain.

FORWARD

INPUT INPUT

OUTPUT OUTPUT
Intranet
Internet
Firewall
running
iptables

iptables 4 Vincent Ryan


nat Table
The Network Address Translation or nat table is used to map the source or destination
field in packets. A system with a static IP should use Source Network Address
Translation (snat) since it uses fewer system resources and it serves to hide the IP
Address. However, iptables also supports hosts with a dynamic connection to the
Internet with a masquerade feature. Masquerade uses the current address on the
interface for address translation.
The nat table has two built-in chains:
● PREROUTING chain: NATs packets when the destination address of the
packet needs to be changed.
● POSTROUTING chain: NATs packets when the source address of the packet
needs to be changed.

mangle table
The mangle table is used to alter certain fields in the headers of IP packets. It can be
used to change the Time to Live or TTL, change the Type of Service or TOS field, or
mark packets for later filtering.
The mangle table has 5 builtin chains: INPUT, OUTPUT, FORWARD,
PREROUTING and POSTROUTING.

raw table
The raw table is a relatively newer addition to iptables and the kernel. For this table to
work, the iptable_raw module must be loaded. The raw table is mainly only used for
one thing, and that is to set a mark on packets that should not be handled by the
connection tracking system. This is done by using the NOTRACK target on the
packet. If a connection is hit with the NOTRACK target, then conntrack will simply
not track the connection.

A fifth table, security, is used only by SELINUX.

iptables 5 Vincent Ryan


filter table
The filter table might look like this:

INPUT OUTPUT FORWARD


Rule 1 Rule 1 Rule 1
Rule 2 Rule 2 Rule 2
Rule 3 Rule 3 Rule 3
: : :
: : :
: : :
: : :
Rule N Rule M Rule O

Default Policy Default Policy Default Policy

Suppose that a packet comes into the firewall.


It is presented to the INPUT chain on the filter table.
It first tries to match Rule 1. If it matches, it will execute the jump on the rule, which
might be ACCEPT, DROP, REJECT, LOG etc. If it is ACCEPT, DROP or REJECT,
it is not processed further on the INPUT chain.
If the packet does not match rule 1, it tries rule 2 ...... etc.

If it goes through all of the rules on the INPUT chain, and matches none of them, the
default policy is applied to it.

What do iptables rules look like?

iptables -P INPUT DROP

iptables -A INPUT -i eth0 -p icmp -j ACCEPT

iptables 6 Vincent Ryan


Default chains in tables

Source:https://www.digitalocean.com/community/tutorials/a-deep-dive-into-iptables-and-netfilter-architecture

iptables 7 Vincent Ryan


Order of Packet Processing

We now look at the way packets are handled by iptables.


Suppose a TCP packet from the Internet arrives at the firewall’s interface on Network
A, and it wishes to create a data connection.

See the diagram on the next page.

The packet is first examined by your rules in the mangle table’s PREROUTING
chain, if any. It is then inspected by the rules in the nat table’s PREROUTING chain
to see whether the packet requires DNAT. It is then routed.

a) If the packet is destined for a protected network, then it is filtered by the rules
in the FORWARD chain of the filter table and, if necessary, the packet
undergoes SNAT before arriving at Network B. When the destination server
decides to reply, the packet undergoes the same sequence of steps.

b) If the packet is destined for the firewall itself, then it is filtered by the rules in
the INPUT chain of the filter table before being processed by the intended
application on the firewall.
At some point, the firewall will probably need to reply. This reply is
inspected by your rules in the OUTPUT chain of the mangle table, if any.
The rules in the OUTPUT chain of the nat table determine whether
address translation is required and the rules in the OUTPUT chain of the
filter table are then inspected before the packet is routed back to the
Internet.

iptables 8 Vincent Ryan


iptables 9 Vincent Ryan
TARGETS AND JUMPS (-j option)

Each firewall rule


a) inspects each IP packet and then
b) tries to identify it as the target of some sort of operation.
Once a target is identified, the packet needs to jump to it for further processing.

sample iptables rule:

iptables -A INPUT -s 172.16.3.66 -i eth0 -d 192.168.1.1 -p tcp -j ACCEPT

In this rule, iptables is being configured to allow the firewall to accept TCP packets
coming in on interface eth0 from IP address 172.16.3.66 which is destined for the
firewall’s IP address of 192.168.1.1.

The target is usually preceded by -j

iptables 10 Vincent Ryan


The following lists the built-in targets that iptables uses.

Target Description Most Common Options


ACCEPT The packet is handed over to the end N/A
application or the operating system
for processing.
iptables stops further processing.
DROP The packet is blocked. N/A
iptables stops further processing.
REJECT Works like the DROP target, but also --reject-with qualifier
returns an error message to the host The qualifier tells what
sending the packet that the packet was type of reject message is
blocked. returned.
iptables stops further processing.
Qualifiers include
icmp-port-unreachable
(default)
icmp-net-unreachable
icmp-host-unreachable
icmp-proto-unreachable
icmp-net-prohibited
icmp-host-prohibited
tcp-reset
echo-reply
LOG The packet information is sent to the --log-prefix “string”
syslog daemon for logging.
iptables continues processing the next Tells iptables to prefix all
rule in the table. messages with a user
As you can’t log and drop at the same defined string.
time, it is common to have two similar Frequently used to tell why
rules in sequence. The first logs the the logged packet was
packet, the second drops it. dropped.

iptables 11 Vincent Ryan


Examples

iptables -A INPUT -s 192.168.10.6 -i eth0 -d 192.168.10.1 -p icmp -j DROP

iptables -A INPUT -s 192.168.10.6 -i eth0 -d 192.168.10.1 -p icmp \


-j REJECT --reject-with icmp-net-prohibited

iptables 12 Vincent Ryan


Some important iptables command switches

The following list the most common iptables options:

iptables Command Description


Switch
-t <table> If you don’t specify a table, then the filter table is assumed.
The possible built-in tables include: filter, nat, mangle,raw.
-j <target> Jump to the specified target chain when the packet
matches the current rule.
-A Append rule to end of a chain.
-I <num> Insert rule at position <num>
-F Flush. Deletes all the rules in the selected table.
-p <protocol-type> Match protocol. Types include icmp, tcp, udp and all.
-s <ip-address> Match source IP address.
-d <ip-address> Match destination IP address.
-i <interface-name> Match input interface on which the packet enters.
-o <interface-name> Match output interface on which the packet exits.

Example

iptables -R INPUT 5 -s 192.168.10.6 -i eth0 -d 192.168.10.1 -p icmp -j


DROP

iptables 13 Vincent Ryan


Example:

to stop the firewall and delete all rules:

iptables -F
iptables -X (deletes any user-defined chains)
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -t raw -F
iptables -t raw -X
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

iptables 14 Vincent Ryan


Examples:
Delete/Insert/Replace Firewall Rules

First find its line number:


iptables -L INPUT -n --line-numbers

To delete rule number 4 , say, :


iptables -D INPUT 4

To insert a new rule between rules 1 and 2:


iptables -I INPUT 2 -s 202.54.1.2 -j DROP

To Replace Rule 5 with a rule that drops incoming icmp:


iptables -R INPUT 5 -p icmp -j DROP

Example
Drop Private Network Address on public facing interface eth1

Packets with non-routable source addresses should be rejected using the following
syntax:

iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP


iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

IPv4 Address Ranges For Private Networks (make sure you block them on public
interface)

• 10.0.0.0/8 -j (A)
• 172.16.0.0/12 (B)
• 192.168.0.0/16 (C)
• 224.0.0.0/4 (MULTICAST D)
• 240.0.0.0/5 (E)
• 127.0.0.0/8 (LOOPBACK)

iptables 15 Vincent Ryan


Sample Personal Firewall using iptables:
Here's a script that will create a very minimalistic personal firewall configuration
(Source: https://www.hackinglinuxexposed.com/articles/20030709.html)

# Flush the INPUT chain


iptables -F INPUT

# Set the default policy for the INPUT chain to be 'DROP'


iptables -P INPUT DROP

# Set the default policy for the OUTPUT chain to be 'ACCEPT' – we are allowing
# everything that the computer sends out to go out unchecked and unlogged!
iptables -P OUTPUT ACCEPT

# Allow unrestricted connections over the local interface


iptables -A INPUT -i lo -j ACCEPT

# Allow tcp packets associated with established connections


iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

# Allow DNS replies


iptables -A INPUT -p udp --source-port 53 -j ACCEPT

# Allow DHCP
iptables -A INPUT -p udp --destination-port 68 -j ACCEPT

# Allow some helpful ICMP packets. (Feel free to remove some of these)
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type source-quench -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
iptables -A INPUT -p icmp --icmp-type parameter-problem -j ACCEPT
iptables -A INPUT -p icmp --icmp-type redirect -j ACCEPT
iptables -A INPUT -p icmp --icmp-type router-advertisement -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

# Log all dropped packets


# iptables -A INPUT -j LOG --log-prefix “dropped by firewall”

# This is redundant since the policy is to DROP.


iptables -A INPUT -j DROP

# Show our tables.


iptables -vnL
#
# End of script.

iptables 16 Vincent Ryan


Common TCP and UDP Match Criteria : ports

Switch Description
-p tcp --sport <port> TCP source port; can be a single value or a range in the
format:start-port-number: end-port-number
-p tcp --dport <port> TCP destination port; can be a single value or a range in
the format: starting-port: ending-port
-p tcp --syn Used to identify a new connection request;
! --syn means, not a new connection request
-p udp --sport UDP source port; Can be a single value or a range in the
<port> format: starting-port: ending-port
-p udp --dport UDP destination port; can be a single value or a range in
<port> the format: starting-port: ending-port

Rule Example:

iptables -A FORWARD -i eth0 -d 192.168.1.58 -o eth1 \


-p tcp --sport 1024:65535 --dport 80 -j ACCEPT

iptables is being configured to allow the firewall to accept TCP packets for routing
when they enter on interface eth0 from any IP address and are destined for an IP
address of 192.168.1.58 that is reachable via interface eth1. The source port is in the
range 1024 to 65535 and the destination port is port 80 (www/http).

iptables 17 Vincent Ryan


Examples : Block or Open Common Ports using iptables
The following shows syntax for opening and closing common TCP and UDP ports:

Assume that the LAN is 192.168.1.0/24

Replace ACCEPT with DROP to block port.

## open port ssh tcp port 22 ##


iptables -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT

## open cups (printing service) udp/tcp port 631 for LAN users ##
iptables -A INPUT -s 192.168.1.0/24 -p udp --dport 631 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 631 -j ACCEPT

## allow time sync via NTP for lan users (open udp port 123) ##
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j
ACCEPT

## open tcp port 25 (smtp) for all ##


iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT

# open dns server ports for all ##


iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT

## open http/https (Apache) server port to all ##


iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT

iptables 18 Vincent Ryan


## open tcp port 110 (pop3) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT

## open tcp port 143 (imap) for all ##


iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT

## open access to Samba/ file server for lan users only ##


iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j
ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j
ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j
ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j
ACCEPT

## open access to mysql server for lan users only ##


iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 3306 -j ACCEPT

## open RDP access lan users only ##


iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 3389 -j ACCEPT

iptables 19 Vincent Ryan


Common ICMP Match Criteria

Matches used with --icmp- Description


type
--icmp-type <type> The most commonly used types are echo-reply and
echo-request

Example:
iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

iptables is being configured to allow the firewall to send ICMP echo-requests (pings)
and in turn, accept the expected ICMP echo-replies.

Valid ICMP Types: (use iptables -p icmp -h to see)

any redirect
echo-reply (pong) network-redirect
destination-unreachable host-redirect
network-unreachable TOS-network-redirect
host-unreachable TOS-host-redirect
protocol-unreachable echo-request (ping)
port-unreachable router-advertisement
fragmentation-needed router-solicitation
source-route-failed time-exceeded (ttl-exceeded)
network-unknown ttl-zero-during-transit
host-unknown ttl-zero-during-reassembly
network-prohibited parameter-problem
host-prohibited ip-header-bad
TOS-network-unreachable required-option-missing
TOS-host-unreachable timestamp-request
communication-prohibited timestamp-reply
host-precedence-violation address-mask-request
precedence-cutoff address-mask-reply
source-quench

Example
To allow TTL exceeded in transit ICMP messages in:

iptables -A INPUT -p icmp --icmp-type ttl-zero-during-transit -j ACCEPT

iptables 20 Vincent Ryan


Rate Limiting

Example: (using rate limiting)

iptables -A INPUT -p icmp --icmp-type echo-request \


-m limit --limit 1/s -i eth0 -j ACCEPT

iptables -A INPUT -p icmp --icmp-type echo-request \


-i eth0 -j LOG --log-prefix “too many Pings”

iptables -A INPUT -p icmp --icmp-type echo-request \


-i eth0 -j DROP

The limit feature in iptables specifies the maximum average number of matches to
allow per second. You can specify time intervals in the format /second, /minute,
/hour, or /day, or you can use abbreviations so that 3/second is the same as 3/s.
Here, ICMP echo requests are restricted to no more than one per second. When tuned
correctly, this feature allows you to filter unusually high volumes of traffic that
characterize denial of service (DOS) attacks and Internet worms.

Example:

iptables -A INPUT -p tcp --syn -m limit --limit 5/s -i eth0 -j ACCEPT

You can expand on the limit feature of iptables to reduce your vulnerability to certain
types of denial of service attacks. Here a defence for SYN flood attacks was created
by limiting the acceptance of TCP segments with the SYN bit set to no more than five
per second.

iptables 21 Vincent Ryan


Common Extended Match Criteria (-m switch)

Switch Description
-m multiport --sport A variety of TCP/UDP source ports separated by commas.
<port, port> Unlike when -m isn’t used, they do not have to be within a
range.
-m multiport --dport A variety of TCP/UDP destination ports separated by
<port, port> commas. Unlike when -m isn’t used, they do not have to be
within a range.
-m multiport --ports A variety of TCP/UDP ports separated by commas. Source
<port, port> and destination ports are assumed to be the same and they
do not have to be within a range.
-m state --state The most frequently tested states are:
<state> ● ESTABLISHED: The packet is part of a connection
that has seen packets in both directions.
● NEW: The packet is the start of a new connection.
● RELATED: The packet is starting a new secondary
connection. This is a common feature of such
protocols as an FTP data transfer, or an ICMP
error.
● INVALID: The packet couldn’t be identified.
Could be due to insufficient system resources or
ICMP errors that don’t match an existing data flow.

Example:

This is an expansion on the previous example:

iptables -A FORWARD -i eth0 -d 192.168.1.58 \


-o eth1 -p tcp --sport 1024:65535 -m multiport \
--dport 80,443 -j ACCEPT

iptables -A FORWARD -o eth0 -s 192.168.1.58 \


-i eth1 -p tcp -m state --state ESTABLISHED -j ACCEPT

Here iptables is being configured to allow the firewall to accept TCP packets to be
routed when they enter on interface eth0 from any IP address destined for IP address
of 192.168.1.58 that is reachable via interface eth1. The source port is in the range
1024 to 65535 and the destination ports are port 80 (www/http) and 443 (https). The
return packets from 192.168.1.58 are allowed to be accepted too.

Instead of stating the source and destination ports, you can simply allow packets
related to established connections using the -m state and --state ESTABLISHED
options.

iptables 22 Vincent Ryan


Important: order of the rules

This has been mentioned already, but we need to emphasise the point.

When creating an iptables ruleset, it is critical to remember that the order of the rules
is important.
For example, if one rule that specifies that any packets from the local
192.168.100.0/24 subnet be dropped, and then another rule is appended (-A) to allow
packets from 192.168.100.13 (which is within the dropped restricted subnet), then the
second rule is ignored, as it is never reached.
An incoming packet from 192.168.100.13 will match the first rule, and that rule will
be applied to the packet.
You must set a rule to allow 192.168.100.13 first, and then set a drop rule on the
subnet.
To arbitrarily insert a rule in an existing chain of rules, use -I, followed by the chain in
which to insert the rule, and a rule number (1,2,3,...,n) for where the rule should
reside. For example:

iptables -I INPUT 1 -i lo -p all -j ACCEPT

The rule is inserted as the first rule in the INPUT chain to allow local loopback device
traffic. (This is the default if the rule-number is omitted.)

iptables 23 Vincent Ryan


More on Syntax and Use of iptables
Additional documentation can be found in the iptables man pages.

iptables has the following options to manage whole chains:

· -N — Create a new chain.

· -X — Delete a user-defined chain (that is empty)

· -P — Change the policy for a built-in chain.

· -L — List the rules in a chain.

· -F — Flush the rules out of a chain.

· -Z — Zero the packet and byte counters.

The following are ways to manipulate rules inside the chain:

· -A — Append a new rule.

· -I — Insert a new rule.

· -R — Replace a rule.

· -D — Delete a rule.

The command:

iptables -P <chain name> <policy>

sets the default policy for the chain, either ACCEPT or DROP (DENY).

Only built-in chains (INPUT, OUTPUT, and FORWARD) have policies.

e.g.

iptables -P INPUT DROP

iptables 24 Vincent Ryan


Some more IPTABLES rules examples

Block fragmented packets:


iptables -A INPUT -f -j DROP

To enable loopback interface:


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

You might want to allow ICMP. To limit ICMP to 3 packets per hour:
iptables -A INPUT -p icmp -m limit --limit 3/hour -j ACCEPT

You need to get your requested information back in to you. i.e. if you try and check
your mail, it can't get in. For this to work, we must enable replies on established TCP
connections. This is done by the following...

iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT

The following rule will add a rule in position 10 of your INPUT chain.
iptables -I INPUT 10 -p tcp --dport 22 -j DROP

Flushing all rules:

iptables -F #will delete all rules from filter table


iptables -F -t nat #will delete all rules from nat table
iptables -F -t mangle #will delete all rules from mangle table
iptables -F -t raw #will delete all rules from raw table

iptables 25 Vincent Ryan


Filtering by MAC address:
The rule:

iptables -A INPUT -m state --state NEW -m mac \

--mac-source 00:C7:8F:72:14:A3 -j ACCEPT

allows only packets from a known MAC address, given in colon-separated hex
notation. Note however that MAC addresses can easily be spoofed.

The following can be used to bind a MAC address to a source address:

iptables -A INPUT -m state --state NEW -s 192.168.1.10 \

-m mac --mac-source 00:C7:8F:72:14:A3 -j ACCEPT

iptables 26 Vincent Ryan


User-Defined Chains
We have been using inbuilt chains such as INPUT, OUTPUT, FORWARD etc.
One can also configure iptables to have user-defined chains. This feature is frequently
used to help streamline the processing of packets.

The following example illustrates the use of a user-defined chain.

Here, we create a chain called badflags to compartmentalize the firewalling of


packets with unusual TCP flag combinations.

# Drop those packets that have TCP flags combinations that should never occur in the

# wild. All of these are illegal combinations that are used to attack a box in various

# ways, so we just log them and drop them here.

iptables -A INPUT -p tcp --tcp-flags ALL FIN,URG,PSH -j badflags

iptables -A INPUT -p tcp --tcp-flags ALL ALL -j badflags

iptables -A INPUT -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j badflags

iptables -A INPUT -p tcp --tcp-flags ALL NONE -j badflags

iptables -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j badflags

iptables -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j badflags

iptables -N badflags

iptables -A badflags -m limit --limit 15/minute -j LOG \


--log-prefix ‘Packets-with-bad-flags:’
iptables -A badflags -j DROP

iptables 27 Vincent Ryan


Logging

iptables -A INPUT -s 157.190.0.1 -m limit --limit 1/second -j LOG

limits the rate of writes to the logs to one per second.

Specific matches can be labelled. For example, log entries might be labelled:

iptables -A INPUT -s 157.190.5.254 -j LOG --log-prefix \

' From Botnet Herder '

The logfile entry will look like:

Aug 1 14:58:39 mymachine kernel: From Botnet Herder \

IN=eth0 OUT= MAC=00:f0:28:2c:69:67:00:00:7a:93:5e:62:08:00 \

SRC=157.190.5.254 DST=157.190.1.254 LEN=40 TOS=0x00 PREC=0x00 \

TTL=247 ID=21864 DF PROTO=TCP SPT=42300 DPT=23


WINDOW=8760 RES=0x0

0 RST URGP=0

iptables 28 Vincent Ryan


Sending log messages to a different file (uses syslog config file)

You may also want to configure the --log-level to log dropped packets to a separate
file instead of /var/log/messages (say /var/log/iptables):

Add the following towards the end of your iptables script:

# Log and Drop all other traffic


/sbin/iptables -A INPUT -j LOG --log-prefix “dropped by fw” --log-level debug
/sbin/iptables -A INPUT -j DROP

In /etc/syslog.conf or /etc/rsyslog.conf (Kali) change:


# Send iptables LOG messages to /var/log/iptables
*.=debug -/var/log/iptables

Reload the syslogd service for the change to take effect.

/etc/init.d/rsyslog restart (Kali/Ubuntu)

iptables 29 Vincent Ryan


Note : Log levels

You can select how verbose the log output will be.
You may either use the numerical value or the case-insensitive string as explained in
the table below.
E.g. 5 and notice are equivalent.
Set the log level to -1 to disable logging completely.
Use a value from 0 through 7 to generate increasingly verbose log output.

The definitions of the log levels are taken from the include file syslog.h:

level verbose explanation


0 emerg system is unusable
1 alert action must be taken immediately
2 crit the system is in a critical condition
3 err there is an error condition
4 warning there is a warning condition
5 notice a normal but significant condition
6 info a purely informational message
7 debug messages generated to debug the application

Setting the log level to a given value means that all messages with a priority level up
to the given value will be logged. E.g. if you set the log level to 6 (which is a
reasonable default value), all messages with a priority from 0 through 6 will be
logged, whereas messages with a priority level of 7 will be ignored.
Note: One should use log level 7 with caution. The amount of log messages is
considerable and sufficient to slow down an application. One should not use this level
for everyday use, only to track down bugs or user errors that you may encounter.

*.=warning -/var/log/messages

The default log level for iptables is 4 (warning).

iptables 30 Vincent Ryan


NAT

Recall: iptables has 4 builtin tables : filter, nat, mangle and raw.

iptables -t nat -A POSTROUTING -j SNAT --to-source <new-IP-Addr>

The following jumps are relevant to the nat table:

Target Description Most Common Options


DNAT Used to perform destination network --to-destination ipaddress
address translation, rewriting the Tells iptables what the
destination IP address of the packet. destination IP address
should be.
SNAT Used to perform source network address --to-source <address>
translation, rewriting the source IP [-<address>][:<port>-
address of the packet. <port>]

The source IP address is


user defined. Specifies the
source IP address and
ports to be used by SNAT.
REDIRECT A special case of DNAT. Used to redirect --to-ports port[-port]
the incoming packets to a different port. specifies a destination
port or range of ports to
use
MASQUER Used to perform source network address [--to-ports <port>[-
ADE translation. By default the source IP <port>]] Specifies the
address is the same as that used by the range of source ports to
firewall’s interface. which the original source
port can be mapped.

iptables 31 Vincent Ryan


DNAT Examples

Example:

Change the destination address of HTTP packets going to 10.0.1.1 to 10.0.1.100 and
port 8080

iptables -t nat -A PREROUTING -p tcp -d 10.0.1.1 --dport 80 \

-j DNAT --to-destination 10.0.1.100:8080

Example

If you have a network gateway which is running Linux you might sometimes want to
allow access to machines behind it from the internet.

Normally you'd deny all incoming connections to a gateway machine as opening up


services and ports could be a security risk.

If you have a gateway machine and wish to forward connections on port 80 to an


internal machine then you'd create the following rules:

iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 80 -j DNAT \

--to 157.190.1.50:80

iptables -A FORWARD -p tcp -m state --state NEW --dport 80 \

-d 157.190.1.50 -i eth1 -j ACCEPT

(assumes default policy for FORWARD is DROP)

These two rules are explained as follows:

The first says that all incoming tcp connections arriving destined for port 80 should be
sent to the internal machine 157.190.1.50 (also on port 80).

This rule alone doesn't do the job though, we also have to accept the incoming
connection. This is the job of the second rule which says that new connections on port
80 should be accepted on the external device eth1.

iptables 32 Vincent Ryan


Source NAT Examples

Source NAT is specified using -j SNAT, and the --to-source option specifies an IP
address, a range of IP addresses, and an optional port or range of ports (for UDP and
TCP protocols only).
## Change source addresses to 1.2.3.4.
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 1.2.3.4

## Change source addresses to 1.2.3.4, 1.2.3.5 or 1.2.3.6


iptables -t nat -A POSTROUTING -o eth0 -j SNAT \
--to-source 1.2.3.4-1.2.3.6

## Change source addresses to 1.2.3.4, ports 1-1023


iptables -t nat -A POSTROUTING -p tcp -o eth0 \

-j SNAT --to-source 1.2.3.4:1-1023

Masquerading

Masquerading is a specialized case of Source NAT.


It should only be used for dynamically-assigned IP addresses, such as standard
dialups (for static IP addresses, use SNAT above).
You don't need to put in the source address explicitly with masquerading: it will use
the source address of the interface the packet is going out from. But more importantly,
if the link goes down, the connections (which are now lost anyway) are forgotten,
meaning fewer glitches when connection comes back up with a new IP address.

## Masquerade everything that is going out eth0.

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

iptables 33 Vincent Ryan


Redirection

a specialized case of Destination NAT


it is a simple convenience which is exactly equivalent to doing DNAT to the address
of the incoming interface.
## Send incoming port-80 web traffic to our port 3128
iptables -t nat -A PREROUTING -i eth1 -p tcp \
--dport 80 -j REDIRECT --to-ports 3128

(Port 3128 is usually used by 'squid', a very popular web proxy server that is also able
to proxy other protocols (e.g. ftp).)

iptables 34 Vincent Ryan


Using iptables to rate-limit incoming
connections – use of hitcount and the
recent module

The way the recent module works is as follows:

You basically add IP addresses to a list, which can then be used in the future to test
connection attempts against.

This allows you to limit the number of connections against either a number of
seconds, or connection attempts.

In our examples, we'll do both.

The rules include -m recent

iptables 35 Vincent Ryan


SYNTAX for the recent module:
iptables -A INPUT -m recent --set
This creates a new list entry in the named recent list, which contains a timestamp and
the source IP address of the host that triggered the rule. This match will always
return success, unless it is preceded by a ! sign, in which case it will return failure.
The name of the list is DEFAULT, unless we add a --name option to the rule.

iptables -A INPUT -m recent --name examplelist –rcheck


The --rcheck option will check if the source IP address of the packet is in the named
list. If it is, the match will return true, otherwise it returns false.

iptables -A INPUT -m recent --name examplelist --update


This match is true if the source combination is available in the specified list and it
also updates the last-seen time in the list.

iptables -A INPUT -m recent --name examplelist --remove


This match will try to find the source address of the packet in the list, and returns true
if the packet is there. It will also remove the corresponding list entry from the list.

iptables -A INPUT -m recent --name examplelist --rcheck --seconds 60


This match is only valid together with the --rcheck and --update matches. The --
seconds match is used to specify how long since the "last seen" column was updated
in the recent list. If the last seen column was older than this amount in seconds, the
match returns false. Other than this the recent match works as normal, so the source
address must still be in the list for a true return of the match.

Note : --rcheck is used to see if the address is in the list and --update is like
--rcheck, but updates the timestamp for tracking hits also.

iptables 36 Vincent Ryan


iptables -A INPUT -m recent --name examplelist --rcheck --hitcount 20
The --hitcount match must be used together with the --rcheck or --update matches
and it will limit the match to only include packets that have seen at least the hitcount
amount of packets. If this match is used together with the --seconds match, it will
require the specified hitcount packets to be seen in the specific timeframe. This match
may also be reversed by adding a ! sign in front of the match. Together with the --
seconds match, this means that a maximum of this amount of packets may have been
seen during the specified timeframe. If both of the matches are inversed, then a
maximum of this amount of packets may have been seen during the last minimum of
seconds.

iptables -A INPUT -m recent --name examplelist --rsource

The --rsource match is used to tell the recent match to save the source address and
port in the recent list. This is the default behaviour of the recent match.

iptables -A INPUT -m recent --name examplelist --rdest

The --rdest match is the opposite of the --rsource match in that it tells the recent
match to save the destination address and port to the recent list.

iptables -A INPUT -m recent --name examplelist --rcheck --rttl

Thev --rttl match is used to verify that the TTL value of the current packet is the
same as the original packet that was used to set the original entry in the recent list.
This can be used to help verify that people are not spoofing their source address to
deny others access to your servers by making use of the recent match.

Example
"-m recent --rcheck --seconds 90 --hitcount 1" as part of a rule, would give an
attacker one try to login every 90 seconds.

iptables 37 Vincent Ryan


Example 1
If a host tries to send a packet to 127.0.0.0/8 on eth0, drop the packet, and drop
any other packets that this host sends for the next 60 seconds

iptables -A FORWARD -m recent --rcheck --seconds 60 -j DROP

iptables -A FORWARD -i eth0 -d 127.0.0.0/8 -m recent --set -j DROP

iptables is processing a packet, which has a source address (as all packets have).

The first rule checks if the source address was in the recent list in the last 60 seconds,
and drops it if it was. Clearly, the first time a packet arrives from any source address,
it will NOT match the first rule (as it is the first packet from this address), so it not
match rule # 1, and it will be dealt with by the second rule.

The second rule matches any packet which tries to send data to 127.0.0.0/8 on our
eth0 interface (which should never legitimately happen). It will create a recent list and
add the source address of the packet to it, and note the timestamp.

Thus, the first packet packet which tries to send data to 127.0.0.0/8 on eth0 will make
it past the first rule and then be caught by the second rule and that address will be put
into the recent list and the packet dropped.

Any subsequent packets for the next 60 seconds that show up from that IP address
will be dropped by the first rule, regardless of destination address, destination port,
etc.

iptables 38 Vincent Ryan


Example 2

iptables -A FORWARD -m recent --update --seconds 60 -j DROP


iptables -A FORWARD -i eth0 -d 127.0.0.0/8 -m recent --set -j DROP

The only difference from Example 1 is the use of --update instead of --rcheck.

This is identical to example 1 except that for every subsequent packet received from
this source address the 'last seen' status will be updated in the table. Therefore there
must be a 'quiet time' of 60 seconds before another packet from this address will even
be considered.

iptables 39 Vincent Ryan


Example 3
Protecting against SSH brute force attacks using
iptables and the recent module

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent \

--set --name SSH-LIST -j ACCEPT

iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 \


--hitcount 4 --rttl --name SSH-LIST \
-j LOG --log-prefix "SSH_brute_force"

iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 \

--hitcount 4 --rttl --name SSH-LIST -j DROP

In this example, we are giving the list a name (SSH-LIST).

These rules will allow three port 22 connections from any given IP address within a
60 second period, and require 60 seconds of no subsequent connection attempts before
it will resume allowing connections again.

The --rttl option also takes into account the TTL of the datagram when matching
packets, so as to endeavour to mitigate against spoofed source addresses.

iptables 40 Vincent Ryan


Saving your iptables rules

To save firewall rules under CentOS / RHEL / Fedora Linux, enter:

# service iptables save

In this example, drop an IP and save firewall rules:

# iptables -A INPUT -s 202.5.4.1 -j DROP


# service iptables save

For all other distros use the iptables-save command:

# iptables-save > /root/my.active.firewall.rules


# cat /root/my.active.firewall.rules

To restore firewall rules form a file called


/root/my.active.firewall.rules, enter:

# iptables-restore < /root/my.active.firewall.rules

To restore firewall rules under CentOS / RHEL / Fedora


Linux, enter:

# service iptables restart

iptables 41 Vincent Ryan


Links

Full iptables firewall at


https://bitbucket.org/schwartz1375/firewall/src/8aa2f7713b16b70abf5b49e259cbedd0
da5bc5e9/firewall?at=master

Netfilter Homepage:
http://www.netfilter.org

man page at
https://linux.die.net/man/8/iptables

iptables Tutorial by Oskar Andreasson:


http://www.faqs.org/docs/iptables/index.html

Linux Advanced Routing and Traffic Control HOWTO:


http://lartc.org/lartc.html

iptables Tutorial :
https://github.com/frznlogic/iptables-tutorial

Kernel Packet Travelling Diagram:


http://www.docum.org/docum.org/kptd

iptables 42 Vincent Ryan

You might also like