Iptables – How to delete all ufw rules for a certain port

bashiptablesufw

I am using ansible to configure ufw on my DB servers to only let accept connections from certain servers connection to a specific port (lets say 1234).

When a server that used to have access is taken out of the pool, it might be forgotten to remove the access rule for that server.

My solution: When setting up the rules, I want to delete all rules for port 1234, and then recreate them with the servers from the current pool.

Unfortunately ufw delete requires to precisely specify the rule to be deleted (port,protocol, scr IP,…).

I tried a solution like ufw delete $(ufw status numbered | grep 1234 | <get all the numbers of the rules> ), but it got really ugly, really fast.

Is there a better way to delete all rules for a certain port?

Best Answer

There are two problems that need to be solved here:

  1. generate a list of ufw rule numbers which match a desired string.
  2. have the shell expand this list and tack it on the end of a sequence of 'ufw delete [rule number]' commands.

I think I have a solution for problem #1 via this one liner in bash:

ufw status numbered |(grep '80/tcp'|awk -F"[][]" '{print $2}')

The example above matches any firewall rule for the string '80/tcp' and prints just the rule number with the brackets stripped.

I have not solved problem #2 yet because as best I can tell, the 'ufw delete' command does not have a switch that suppresses the '(y|n)' confirmation prompt, thus foiling automation.

You can run the command below however and manually hammer out each rule deletion by hitting the 'y' key to confirm and then up arrow => enter to rinse and repeat

ufw delete $(ufw status numbered |(grep '80/tcp'|awk -F"[][]" '{print $2}'))