Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a system command when an IPTables rule is matched

:)

I'm wanting to be able to run a system command when an IPTable rule is hit, passing the IP address of the remote device to it.

I've had a look around but found nothing. I thought of grepping logs, but I'm expecting a lot of traffic..

Any help would be fantastic!

Thanks

(If it helps, Ubuntu Linux is my platform of choice)

like image 933
AndyD Avatar asked Jul 20 '12 18:07

AndyD


People also ask

Which command will show existing iptables rules?

Listing Rules as Tables. Listing the iptables rules in the table view can be useful for comparing different rules against each other. To output all of the active iptables rules in a table, run the iptables command with the -L option: sudo iptables -L.

Are iptables rules immediate?

iptables rules take effect immediately. Because your script is Appending (-A) to the INPUT and OUTPUT chains, your rules are being added to the end of those chains. If you have other terminating rules that precede these rules, then they will take effect (and later rules will not).


2 Answers

Here is how you do it:

iptables -I FORWARD -p tcp --dport 80 -d a.b.c.d -j LOG --log-prefix="TRIGGER ME NOW !!!"

tail -f some-logfile | awk '/some-pattern/ {system("run-some-command")}'

Should be straight forward enough and should be able to deal with lots of traffic, the tail command should be quick enough... Just make sure the file doesn't grow too much.

like image 61
Yannick Avatar answered Oct 28 '22 04:10

Yannick


Do it with knockd instead. You configure a port knocking sequence of just one port, then tell knockd the command you want to run. Normally it's used to add/remove iptables rules -- to open a service (e.g. ssh access) after a certain knock sequence, but I don't see why you couldn't just use it to run a command after a very simple, one packet on one expected port rule.

'apt-get install knockd' on your Ubuntu system and the man page has examples you can easily adapt to this.

like image 23
Craig Constantine Avatar answered Oct 28 '22 03:10

Craig Constantine