2

Right now I'm using /etc/rc.local to add some iptables rules on my Linux router on boot however some of the rules aren't added. I assume this is because the interface hasn't come up yet.

This is what I have in there:

sudo /sbin/iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
sudo /sbin/iptables -A FORWARD -i ppp0 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo /sbin/iptables -A FORWARD -i eth0 -o ppp0 -j ACCEPT

I think the ppp0 interface must take a while to come up on boot and iptables might refuse to add the rule since the ppp0 interface doesn't exist. Is there a way to force iptables to add the rule anyway? I thought I would check this before I introduce a loop into the script to wait for the interface to exist before adding the rules.

I've also observed iptables doesn't remove the rule when the interface disappears and comes back after the rule was already added (which is good behaviour in my case).

  • 2
    iptables will happily add rules for interfaces that don't exist yet. iptables -I INPUT -i Eimoexu1 -j ACCEPT works here (that's a random string used as an interface name). iptables -vL INPUT then shows the rule. – derobert Jun 5 '14 at 17:09
2

Use post-up in /etc/network/interfaces on any Debian-based distro. That allows you to run the script right after it was brought up by ifup. More in the man page for interfaces.

Side-note: post-down can be used to remove the rules, of course.

And if that doesn't work, because your system brings up ppp0 via some script, you can use the hook scripts in the *.d subfolders of /etc/network corresponding to the aforementioned actions. Several variables will be supplied to you in the script, such as IFACE, ADDRFAM etc. The man pages are really detailed.

On another note, internally up == post-up and down == post-down, so the correct subfolders would be if-down.d and if-up.d respectively.

And if you want to "debug" that process of bringing up an interface that is declared in /etc/network/interfaces (or sourced from there), ifup(8) has the details. In particular you'll want ifup -nvl (and perhaps the interface name). Can also be run unprivileged, because it doesn't do anything, just mimics the process.

Possible caveat

This won't work on Debian-based but Network-Manager-driven setups. But with you mentioning a router, I think it's unlikely to be driven by Network Manager.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.