iptables -i lo vs. -s localhost and -j REJECT vs. -P INPUT REJECT

Bruno Bronosky asked:

Preface

Just like everything in Linux I’m sure there are a lot of ways to get an intended result with iptables. I’d like to limit answers to the following categories:

  1. What is the difference between the options?
  2. Which option is best (or are they the same)?
  3. Why do you prefer one over the other?

And please be clear what category you are speaking to. It’s okay to state preferences, but don’t imply that it is best.

e.g.

I prefer to put --jump as the first argument because I think it reads better to have the intent first and I like to vertically align like arguments of multiple commands.

Question

Is one of these better than the other?

iptables -I INPUT --jump ACCEPT --in-interface lo
iptables -I INPUT --jump ACCEPT --source localhost

Is one of these better than the other?

iptables -A INPUT --jump REJECT
iptables -P INPUT REJECT

My answer:


In both cases, the two iptables commands you are comparing have different semantics and behave differently to each other. It’s not necessarily a matter of which is “best” but of what behavior you are trying to match or provide.

First:

iptables -I INPUT --jump ACCEPT --in-interface lo
iptables -I INPUT --jump ACCEPT --source localhost

The first of these accepts all local traffic, on the lo interface, regardless of its IP address. The second one accepts all traffic from 127.0.0.1, regardless of what interface it arrives on.

In this case the first one is clearly better. In the first case, local traffic doesn’t necessarily use 127.0.0.1 as its IP address but you probably want to accept it, (the best known of these is Debian’s odd 127.0.1.1, but it’s possible for global IP addresses to be attached to lo) and in the second case, someone could send you spoofed packets with 127.0.0.1 as its source address and you probably don’t want to accept that.

Second:

iptables -A INPUT --jump REJECT
iptables -P INPUT REJECT

These are usually functionally identical, except:

When someone adds more rules to the end of the INPUT chain, the rules will not have any effect. The archives here have numerous examples of people confused by this. So you might want to use the second form.

The chain policy can’t accept arguments, but the REJECT target does accept arguments. If you want to specify the reject reason, or want to give different reject reasons in different circumstances, you must use the first form (see the iptables-extensions man page for the list of reject reasons).


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.