Wednesday, June 18, 2008

Introduction to Iptables (Part 2)

In my previous post i explained some general packet matching with Iptables, now i am going to explain the TCP packet matching generalities, where the commands displayed following, all match specific values from the TCP packet headers, for example the source and destination ports, tcp options, tcp flags (for example the syn, fin, etc).

You use the --protocol argument to match TCP packets, and optionally, the source port of the packet can be specified with "--sport (--source-port) ", the source port can be a numeric value or the name of the port, that should match the port number we want in the /etc/services file.

Here are two examples:
iptables -A INPUT -p tcp --sport 23 -j REJECT
iptables -A INPUT -p tcp --sport telnet -j REJECT

This rules do the same, they reject the inbound traffic from the TCP port 23 of the remote host). The usage of port names instead of the number, creates a little more cpu consume and could be told as "speed penalty" in large rulesets.

It is possible also to specify a range of ports in the rules, lower and upper port separated by a colon. Here i filter all the ports between 10 and 999:
iptables -A OUTPUT -p tcp --sport 10:999 -j REJECT

All TCP source ports except the 80 are accepted with this rule:
iptables -A INPUT -p tcp --sport ! 80 -j ACCEPT

The same can be done with a range of ports:
iptables -A INPUT -p tcp --sport ! 1024:40000 -j LOG

If the first port is numerically higher than the second, iptables swaps both numbers around automatically.

To specify a TCP destination port, the "-dport (--destination-port) [port]" is used, and its rules are the same than in TCP source port matching.

For example, to stop users in your private network to connect to IRC, supposing that IRC uses the ports between 6667 to 66670, you may want to add this rule:
iptables -A OUTPUT -p tcp --dport 6667:6670 -j REJECT

To match a specific flag in the TCP header, you have to make use of "--tcp-flags [mask] [flags]".

The [mask] argument is a list of flags separated by commas, which should be matched.
The [flags] argument is a list of flags that must be set, any flag listed in the [mask] argument, but not in the second, this means that the flag must be unset.

The possible flags are: SYN, ACK, FIN, RST, PSH and URG. ALL and NONE are also possible.

In this example, the SYN,ACK and FIN flags are the mask, and the SYN flag is the one that has to be set:
iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN SYN -j ACCEPT

The mask can also be inverted, meaning that the ACK and FIN should be set, but not the SYN:
iptables -A FORWARD -p tcp --tcp-flags ! SYN,ACK,FIN SYN -j ACCEPT

Matching a particular TCP flag:
This is accomplished with the "--syn" flag, it is usefull because the SYN flag is the TCP start sequence also known as the "3 way handshake", explained in this picture:

iptables -A FORWARD -p tcp --syn -j ACCEPT iptables -A FORWARD -p tcp ! --syn -j ACCEPT

0 comentarios: