How to block an IP in Linux
I run Debian on my server, and I often find that my server is being attacked by other computers. Brute force SSH attacks, viruses scanning for the ability to spread, things like that. I’ll go into the SSH brute force defenses in a later post, but for now I’ll cover how to easily block an IP address.
First, I’ll assume you are already using iptables. If you need help setting that up, use Google, Debian comes with it out of the box.
I have a small script called “block” which looks like this:
#!/bin/bash sudo iptables -I INPUT -s $1 -j DROP sudo bash -c "iptables-save > /etc/network/iptables.save"
Whenever I find a “bad” IP in my logs or notifications, I just run:
block bad.ip.add.18
Substituting the bad ip for that nonesense above. This adds it to the list of IP address which iptables will simply drop any incoming packets from, and saves the in memory iptables configuration, so that it is preserved through reboots.
Then in your /etc/network/interfaces file, just add this at the bottom:
post-up iptables-restore /etc/network/iptables.save
You can get country IP blocks freely and use in your firewall as well.
[...] also recommend using the script in my post on blocking IP addresses using iptables to deal with any persistent folks, or people poking too hard on your web site, or other [...]
Apparently you can also do something like:
ip ro add blackhole 87.106.97.229
How would you go about adding these blocks to a separate log file? Say /var/log/iptables.log.
Thanks.
If you use this method all of the blocked IPs end up in this file: /etc/network/iptables.save so you can easily see them. If you’re asking more generally how to get firewall/iptables log entries segregated into their own log then I recommend using syslog-ng and setting things up a bit like this:
…..
destination firewall { file(“/var/log/firewall.log”); };
……
filter f_firewall { match(“Firewall”); };
……
filter f_kernel { facility(kern) and not filter(f_firewall); };
……
log {
source(s_sys);
filter(f_firewall);
destination(firewall);
};
Thanks for the quick reply!
Sorry, I was reading many of your articles and ended up posting that comment on the wrong article; it was meant for “Using IPTables to Prevent SSH Brute Force Attacks”.
Please delete it if you wish, I’ll repost in the correct one if that is Ok.
Thanks again.