Part of administrating a server is dealing with all the illicit attacks against said server. While looking at the listing of log files for one of my servers I realized the /var/log/secure log had over 200,000 entries for a single IP Address that had tried to gain entry to my server without being friendly to me. At that moment, I realized I had forgotten a pretty important sysadmin skill: creating and deleting iptables rules for security. So, as I often do, since I had to take the time to look it up in the iptables man page, I thought I would post what I found here.

Creating and Deleting IPTables Rules

Logging and Blocking IP Addresses

Turn on kernel logging of matching packets with the target of your log file and block the ip address by using these two commands:

/sbin/iptables -i {adapter i.e. eth0} -A INPUT -s {IP Address} -j LOG --log-prefix "IP DROPPED IN IPTABLES:"
/sbin/iptables -i {adapter i.e. eth0} -A INPUT -s {IP Address} -j DROP

Notice: Most people will have iptables in their PATH variable so you may not need the preceeding /sbin/.

Viewing Blocked IP Addresses

You can get the blocked IP Addresses by using this command:

/sbin/iptables -L INPUT -v -n

The result of that should look something like this:

Chain INPUT (policy ACCEPT 1346K packets, 577M bytes)
pkts bytes target prot opt in out source destination
20543 1240K LOG all -- eth0 * 1.1.1.1 0.0.0.0/0 LOG flags 0 level 4 prefix "IP DROPPED IN IPTABLES:"
20505 1236K DROP all -- eth0 * 1.1.1.1 0.0.0.0/0

Searching For a Blocked IP Address in IPTables

Using grep is probably the best way to find a blocked IP Address in IPTables. Using the same command we used above, we will pipe (|) and use grep like so:

/sbin/iptables -L INPUT -v -n | grep 1.1.1.1

That will give you output similar to this:

20543 1240K LOG all -- eth0 * 113.195.145.52 0.0.0.0/0 LOG flags 0 level 4 prefix "IP DROPPED IN IPTABLES:"
20505 1236K DROP all -- eth0 * 113.195.145.52 0.0.0.0/0

Deleting Blocked IP Addresses

It’s pretty easy to delete blocked ip addresses in iptables. There are people who suggest doing it other ways to see the rules you’re deleting, but I really don’t see the need as long as you verify the IP Address before you press enter. To delete blocked IP Addresses, use this command:

iptables -D INPUT -s 1.1.1.1 -j DROP

Goodbye, for now

While this is a pretty simple post, I think it easily shows the basic steps in creating and deleting iptables rules. Should you be interested in forking my page for this on GitHub, you can clone that repository. If you have any questions/comments, feel free to post them below!