Skip to content
Advertisement

Is iptables thread safe?

This seems to me to be a basic question, but google and SO fail to give me an answer. As the title says, is iptables thread safe? If I have multiple processes making calls to iptables, should I create a lock for myself?

There seems to be some threads from 2009 querying if netfilter is thread-safe, with no solid resolution. I’m loathe to go check the actual code

Advertisement

Answer

You’re calling iptables, a userspace linux program, so threads don’t even come into it, it’s a completely separate process for each invocation. The processes are isolated from each other. The calls iptables makes to the kernel to update the underlying data structures will be protected.

If you have a multi-threaded program that’s spawning all of these processes, then you may run into trouble, depending on your own program’s logic. For example what happens if you add a rule, and immediately delete it? Whose to say that the rule addition will run before the rule deletion? One way round, the rule is added, and then deleted. The other way round, the rule is deleted (which fails because it doesn’t yet exist), and then it’s added (which works, but the end result is that the tables have a rule that they shouldn’t). To illustrate, here’s an example:

spawn iptables -A ... (process 1)
spawn iptables -D ... (process 2)
1: starting
2: starting
2: call kernel to delete rule (this is atomic)
1: call kernal to add rule (this is atomic)
2: done
1: done

In other words, the atomicity is there to protect the internal data structures of the kernel. It doesn’t help protect the logic of your program.

iptables-restore

Can I also recommend the use of iptables-restore. You can then generate a complete ruleset into a file, and load the whole lot in a single atomic operation. This means that you can never get into a state where what you assume the current ruleset to be is different from what it actually is. It also means that you are never in a weird internediate state, halfway through updating the rules.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement