Linux, Security

Deleting UFW Rules backwards.

Intro: Sometimes one has a lot of ‘V6’ rules that need to be deleted. UFW does allow to delete the rules but only one by one, which can be time consuming.
Here is a short bash script that does the trick of deleting them.
IMPORTANT NOTE: In order for this script to work as desired one has to tell it the last rule number to the first rule number to be deleted.
Then the script can properly delete them one by one starting by the last one and work its way up.
Find out which serie of rules need to be deleted be this command:

ufw status numbered

Result:
Status: active

To Action From
-- ------ ----
[ 1] Anywhere ALLOW IN 127.0.0.0/16
[ 2] 22 ALLOW IN Anywhere
[ 3] 80 ALLOW IN Anywhere
[ 4] 443 ALLOW IN Anywhere
[ 5] 21/tcp ALLOW IN Anywhere
[ 6] 5109 ALLOW IN Anywhere
[ 7] 1194/udp ALLOW IN Anywhere
[ 8] 25 ALLOW IN Anywhere
[ 9] 587 ALLOW IN Anywhere
[10] 465 ALLOW IN Anywhere
[11] 143 ALLOW IN Anywhere
[12] 993 ALLOW IN Anywhere
[13] Anywhere ALLOW IN 192.168.100.0/24
[14] Anywhere ALLOW IN 88.99.134.136/29
[15] Anywhere ALLOW IN 176.9.104.47
[16] Anywhere ALLOW IN 176.9.104.93
[17] Anywhere ALLOW IN 176.9.104.88
[18] Anywhere ALLOW IN 116.203.34.148

Assuming that we want to delete the rule 13 to 18 then use the following bash script:

for reg in $(seq 18 -1 13); do echo 'y' | ufw delete $reg ; done; ufw status numbered

Another way would be to selectively chose which rules to delete.
Note again, you need to list the rules numbers from the highest number to the lowest.
Example. To delete the rules number ‘5 6 9 11’ one would use the following command:

for reg in 11 9 6 5; do echo 'y' | ufw delete $reg ; done; ufw status numbered

Leave a Reply