I'm trying to automate the creation and deletion of rules with a bash script.
Currently, I have a rule like this:
iptables -t nat -I PREROUTING -p udp -d {IPDESTINATION} --dport {PORTDESTINATION} -m u32 --u32 '0>>22&0x3C@8=0xFFFFFFFF && 0>>22&0x3C@12=0x54536F75 && 0>>22&0x3C@16=0x72636520 && 0>>22&0x3C@20=0x456E6769 && 0>>22&0x3C@24=0x6E652051 && 0>>22&0x3C@28=0x75657279' -j REDIRECT --to-port {REDIRECTPORT}
I'm needing to be able to delete this rule by specifying the IP Destination and Port Destination. I've attempted something like below:
iptables -D PREROUTING -s {IPDESTINATION} -t nat
Even without supplying a port destination, I'm unable to remove this rule as it responds with the error
iptables: Bad rule (does a matching rule exist in that chain?).
Is this possible with nat rules? {IPDESTINATION} etc are all filled in with valid details.
If you can't delete this rule by doing : iptables -t nat -D PREROUTING 1
A workaround is to create a file who contains all your rules :
1) create a bash file like 'rulesFW.sh'
#!/bin/bash
iptables -F -t nat
2) In your script, each time you add a rule into iptables, append the bash file with the command.
3) If you want to remove a rule, delete the line who match your rule (with the destination IP and other parameters...) in the file
4) Restart the script
Just replace the with the ip and the with the port. This should only delete the rule with the matching ip address. I'm sure others can make the command more efficient, but this is currently working for me. Runs as a single command line, so it can probably be executed in a script over a for loop if you want
rulenumber=`/sbin/iptables -L -n --line-number | grep <x.x.x.x> | grep <portnumber>| awk '{print $1}'` && [ -n "$rulenumber" ] && [ $rulenumber -gt 0 ] && /sbin/iptables -D INPUT $rulenumber
User contributions licensed under CC BY-SA 3.0