1

I want to add a rule using iptables, but only if it does not exist already.

There's option -C which will allow us to check if a rule specification exists already. The option is described in this Q&A as well.

From that Q&A, this specific answer says how one could use -D (delete) option instead, which will delete the rule if exists, or it'll exit with code 1 if it doesn't. (Which is exactly what -C does if the rule doesn't exist, so it won't be a problem).

And to me it feels more convenient to do

ip6tables -D OUTPUT -p icmpv6 --icmpv6-type destination-unreachable -j DROP
ip6tables -A OUTPUT -p icmpv6 --icmpv6-type destination-unreachable -j DROP

Rather than checking if exists, deleting it if it does, and only then adding the new rule.

However, someone in the comment mentioned that it opens a hole in the firewall and I fail to see how.

Bottom line: why shouldn't I blindly delete and append the rule rather than checking before deleting & adding?

Adelin
  • 109
  • 10
  • Would it be possible to generate your iptables config from scratch? You could manage the complete config and use `iptables-restore` to apply it. It has a commit option to make it atomic, and it saves the hassle of dynamic/incremental iptables configuration (which I hate: imagine you have `fail2ban`, `docker` and `iptables-persistent`. They don't know about each other manipulating iptables, so it will become a big mess. – Halfgaar Oct 03 '18 at 15:50

2 Answers2

3

Well, the problem with this approach (delete, then add) is that these two operations do not happen at once, they have some time between them and during this time your system is exposed to the unwanted traffic your DROP rule has been preventing. This may seem harmless in your case with ipv6 unreachables, but consider you're getting slammed by traffic that renders some applications or devices unresponsive - from my experience sometimes even a split-second drop of the firewall rule that prevented it could have some long-lasting consequences.

Peter Zhabin
  • 2,696
  • 9
  • 10
  • It will also reset the packets/bandwidth counters against that rule, if you care about that sort of thing. – bodgit Oct 03 '18 at 15:07
0

The fact that blocking rule can be deleted and open something for unwanted traffic could be less of the problem then deleting the rule which actually lets you in. In this case you may not get a chance to reinstate it.

Tomek
  • 3,390
  • 1
  • 16
  • 10