[CentOS] combining iptables parameters

Wed Oct 28 20:57:38 UTC 2009
Ryan Lynch <ryan.b.lynch at gmail.com>

On Wed, Oct 28, 2009 at 16:36, Marcus Moeller <mail at marcus-moeller.de> wrote:
>> You would have to specify the required match space across multiple
>> rules, maybe something like this:
>>
>>  iptables -A OUTPUT -p UDP -d $IP1-j DROP
>>  iptables -A OUTPUT -p TCP -d $IP1 -j DROP
>>  iptables -A OUTPUT -p UDP -d $IP2 -j DROP
>>  iptables -A OUTPUT -p TCP -d $IP2 -j DROP
>
> That's what I am doing atm. Thanks for the update.

BTW, if you have some complex chain of action logic (more than just a
simple -j DROP), you could simplify your rules by creating a custom
chain and having the rules on the builtin chain (OUTPUT, or whatever)
jump to your custom chain instead of DROP.

For example, If I wanted to use the same four rules from above, but I
wanted to both log AND drop the incoming packets, a "naive"
implementation might be something like this:

 iptables -A OUTPUT -p UDP -d $IP1 -j LOG --log-prefix 'MYDROP: '
--log-level notice
 iptables -A OUTPUT -p UDP -d $IP1 -j DROP
 iptables -A OUTPUT -p TCP -d $IP1 -j LOG --log-prefix 'MYDROP: '
--log-level notice
 iptables -A OUTPUT -p TCP -d $IP1 -j DROP
 iptables -A OUTPUT -p UDP -d $IP2 -j LOG --log-prefix 'MYDROP: '
--log-level notice
 iptables -A OUTPUT -p UDP -d $IP2 -j DROP
 iptables -A OUTPUT -p TCP -d $IP2 -j LOG --log-prefix 'MYDROP: '
--log-level notice
 iptables -A OUTPUT -p TCP -d $IP2 -j DROP

You could do the same thing in a much more compact fashion by creating
a custom chain called MYDROP:

 iptables -N MYDROP
 iptables -A MYDROP -j LOG --log-prefix 'MYDROP: ' --log-level notice
 iptables -A MYDROP -j DROP
 iptables -A OUTPUT -p UDP -d $IP1 -j MYDROP
 iptables -A OUTPUT -p TCP -d $IP1 -j MYDROP
 iptables -A OUTPUT -p UDP -d $IP2 -j MYDROP
 iptables -A OUTPUT -p TCP -d $IP2 -j MYDROP

In programming, it would be analogous to factoring duplicative code
into a common function. In this example, you really don't compress the
expression very much (7 lines versus 8 lines). If you imagine a
situation where MYDROP would contain 10 or 15 different actions,
you'll understand how powerful it can be.

-Ryan