Iptables – Reduce Firewall Rules for TCP and UDP

firewalliptablestcpudp

I have a number of iptables rules on my firewall that look like this:

iptables -A zone_lan_forward -p tcp -d 1.2.3.0/24 -j ACCEPT
iptables -A zone_lan_forward -p udp -d 1.2.3.0/24 -j ACCEPT

Is there a shortcut for having two rules – one for tcp and one for udp – for every address? I mean can I do something like this:

iptables -A zone_lan_forward -p tcp,udp -d 1.2.3.0/24 -j ACCEPT

Best Answer

Create a new chain which will accept any TCP and UDP packets, and jump to that chain from the individual IP/port permissive rules:

iptables -N ACCEPT_TCP_UDP
iptables -A ACCEPT_TCP_UDP -p tcp -j ACCEPT
iptables -A ACCEPT_TCP_UDP -p udp -j ACCEPT

iptables -A zone_lan_forward -d 1.2.3.0/24 -j ACCEPT_TCP_UDP

This adds the overhead of a few extra lines, but halves the number of TCP / UDP rules.

I would not omit the -p argument, because you're not only opening up the firewall for ICMP, but also any other protocol. From the iptables man page on -p:

The specified protocol can be one of tcp, udp, icmp, or all, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from /etc/protocols is also allowed.

You may not be listening on any protocols except for TCP, UDP, and ICMP right now, but who knows what the future may hold. It would be bad practice to leave the firewall open unnecessarily.

Disclaimer: The iptables commands are off the top of my head; I don't have access to a box on which to test them ATM.