11 Iptables
11 Iptables
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.
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.
▪ 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.
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
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.
If it goes through all of the rules on the INPUT chain, and matches none of them, the
default policy is applied to it.
Source:https://www.digitalocean.com/community/tutorials/a-deep-dive-into-iptables-and-netfilter-architecture
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.
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.
Example
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
Example
Drop Private Network Address on public facing interface eth1
Packets with non-routable source addresses should be rejected using the following
syntax:
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)
# 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 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
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 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).
## 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
Example:
iptables -A OUTPUT -p icmp --icmp-type echo-request -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.
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:
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:
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.
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:
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.
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:
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.)
· -R — Replace a rule.
· -D — Delete a rule.
The command:
sets the default policy for the chain, either ACCEPT or DROP (DENY).
e.g.
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...
The following rule will add a rule in position 10 of your INPUT chain.
iptables -I INPUT 10 -p tcp --dport 22 -j DROP
allows only packets from a known MAC address, given in colon-separated hex
notation. Note however that MAC addresses can easily be spoofed.
# 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
iptables -N badflags
Specific matches can be labelled. For example, log entries might be labelled:
0 RST URGP=0
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):
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:
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
Recall: iptables has 4 builtin tables : filter, nat, mangle and raw.
Example:
Change the destination address of HTTP packets going to 10.0.1.1 to 10.0.1.100 and
port 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.
--to 157.190.1.50:80
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.
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
Masquerading
(Port 3128 is usually used by 'squid', a very popular web proxy server that is also able
to proxy other protocols (e.g. ftp).)
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.
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.
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.
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.
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 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.
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.
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.
Netfilter Homepage:
http://www.netfilter.org
man page at
https://linux.die.net/man/8/iptables
iptables Tutorial :
https://github.com/frznlogic/iptables-tutorial