I am currently being flooded by requests to /wpad.dat - in a manner that makes it seem to be an attack.
Now, what I would like to do is to trigger iptables for every IP that requests /wpad.dat and then add it to a blacklist. Is there a way to do that? That means that the IP will be able to send one flood request and then none.
Any neat way to do this efficiently?
You might consider that there are other ways to block IP addresses. For example, Fail2ban is designed to scan log files for given patterns and temporarily block IPs.
As mentioned in the comments, you may potentially be adding thousands of IPs to your blacklist. While
iptables
works, each additional rule can increase the processing time for each request. You can useipset
as an alternative, which appears to be much faster when there are many IPs added. It takes a hash approach to speed up matches. See Mass-blocking IP addresses with ipset for details and comparsion betweeniptables
andipset
.If you want to use
iptables
, it would probably depend on how your webserver is set up. Supposing you use apache or nginx, you could set it to trigger a cgi script of some sort to run whenwpad.dat
is requested.For example, if your website already uses php, you might use an internal rewrite to trigger a php script (or ruby/python/java depending on the language you normally use).
Once the script runs, just get it to run something like this on the command line:
The script needs to be executed as root, and it is probably not a good idea to give the web user root privileges, so you can package it up as a shell script,
chown
it as root, and usesetuid
on it.Big Warning: You could accidentally block yourself if you visit that resource, so you might want to set
--dport
to port 80 or something like that. This at least avoids blocking your ssh protocol, so if you manage to block yourself, you can ssh into your server and un-block yourself.Expiry: Since permanently blocking many IP address is rarely a good idea, you might want to keep track of the IP address blocked (perhaps append it in a log file), and create a cron job to delete those IP addresses periodically. You just need to run something like:
Blocking automatically isn't exactly trivial with iptables, but instead you can throttle the connections so it's not hogging all your resources by adding this rule:
iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m limit --limit 50/minute --limit-burst 200 -j ACCEPT