Program to block an IP temporarily with iptables

5

3

Is there a program on Debian to block an IP address temporarily just by launching a command (specifying the IP and the duration)?

With iptables/ip6tables alone I can create a rule, but I would then have to delete manually. I also use fail2ban, but I don't think I can block an arbitrary IP address that did not satisfy any of the fail2ban rules.

JoeWhite

Posted 2015-06-26T16:18:49.280

Reputation: 262

1For example create the rule and schedule with at the rule deletion command, something like echo "iptables -d rest_of_rule" | at now+30m – Dan – 2015-06-26T17:23:26.817

@Dan This sound like a good solution. Actually, if you write an answer in the form of a little bash script that can take the IP and the duration as input parameters, I would accept it! – JoeWhite – 2015-06-27T07:35:25.893

Answers

5

You need to create an ipset so iptables can match against it. Note timeout 0 means the default is never expire.

ipset create temp_hosts hash:ip timeout 0
iptables -I INPUT 1 -m set -j DROP  --match-set temp_hosts src
iptables -I FORWARD 1 -m set -j DROP  --match-set temp_hosts src

Now that our set is created we can start adding ip addresses (timeout unit: seconds).

ipset add temp_hosts 1.1.1.2 timeout 400

Note should you need these to survive a reboot you need to save and load the rules.

ipset save -f /path/ipset.save
ipset restore -f /path/ipset.save

These can be automated with cron or systemd.

cybernard

Posted 2015-06-26T16:18:49.280

Reputation: 11 200

2

Try this script, inspired by Dan's comment:

#!/bin/bash
iptables -I INPUT -s $1 -j DROP
at ${2:-now+1hour} <<<"iptables -D INPUT -s $1 -j DROP"

Save it as /usr/local/sbin/blockip and run blockip 1.2.3.4 or blockip 1.2.3.4 now+2hours. By default the IP is blocked for 1 hour.

You can replace DROP with REJECT if you prefer REJECT semantics.

user49740

Posted 2015-06-26T16:18:49.280

Reputation: 2 850

If you intend on a long lists of rejects, having a lot of rules will slow iptables down a lot. ipset has you covered all options together. You could end up with hundreds of cron jobs which is also less than ideal. – cybernard – 2016-12-31T05:21:30.823