Here at Cloud 66 we do a lot with firewalls, and because we manage servers across a variety of cloud providers not all of whom support native firewall configurations, we manage the firewalls on our user’s servers directly.

After a whole lot of testing we settled on the Uncomplicated Firewall (UFW) as our firewall management tool. We feel that it is feature complete enough to provide us the correct level of abstraction over direct iptables commands; essentially meaning that we can automate firewall management more safely!

In the last few years through thousands upon thousands of server (and firewall) deployments we’ve only come across one really annoying bug while using UFW. Essentially, if the UFW command is interrupted during an operation it is possible that it leaves behind a test iptables rule chain. A simple cause of this interruption could be a connection drop caused by the servers cloud provider (which happens more frequently than you’d imagine!). Anyway, this leftover chain doesn’t get cleaned up, and subsequent calls to use UFW will result in the error:

ERROR: initcaps [Errno 2] iptables: Chain already exists.

We’re not the only ones who've seen this, but existing solutions to this problem essentially advocate a full firewall reset - ie. remove all existing chains/rules and re-initialise. That may work when managing the firewall manually, but in the case of automated management it can get really painful. Imagine the docker daemon for instance which creates its own iptable firewall rules directly and dynamically - in most cases you’d need to restart the daemon/containers to get those rules back.

The solution we found instead was to delete the test chain directly which seems to do the trick!

sudo ufw disable sudo iptables -F ufw-caps-test sudo iptables -X ufw-caps-test sudo iptables -Z ufw-caps-test … <<add/amend your rules and re-enable>>

In conclusion, using UFW is a great and powerful way to handle firewall rules without getting into the complexity of issuing direct iptables commands, however, keep your eyes open for this little gotcha above!

UPDATE (2015-04-22)

Don't forget to get the test ipv6 rules too!