Program to block an IP temporarily with iptables

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.


Solution 1:

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.

Solution 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.