Most commonly iptables is used to allow, block, or redirect connections. However, it also has a logging feature that can be very useful for network traffic analysis and system security.

In the example below I will get a list of network services listening on my server and create iptables inbound connection logging rules. And then I’ll use some basic shell scripting to analyze collected data.

Here’s how you can get a list of listening network ports and service names:

Let’s say we want iptables to log all inbound traffic for port 443. Here’s the rule for this:

Save the rules and reload iptables service and in /var/log/messages you should now be able to see entries like these:

Seeing the source IP is useful but, perhaps, seeing the source hostname, country of origin, and organization would be even better. Here’s how this can be accomplished:

The result might look something like this:

Useful stuff, except you would probably want to exclude your private network addresses from this list. So here’s an enhanced version of the previous command:

So, what practical uses does this information have? Let’s imagine that for some reason I don’t want Zscaler connecting to my server. I run the previous command and save the output to a temporary file /tmp/iplog, and the do something like this:

In this data sample, this one external IP is responsible for more than half of all requests to my Web server. So blocking it may be a good idea. This command here will give you a list of organizations accessing your server:

And this command will count how many time each organization accessed your server:

You can also get a count by country of origin:

So when they tell you it’s the Russians and the Chinese who are breaking your server, take such information with a grain of salt. Most attacks originate from the US networks.

Perhaps unrelated to our topic of logging, here are a couple of iptables tricks I find useful – both having to do with cleaning up your rules from time to time. Let’s say I banned a particular IP or range and now I want let those guys back in. Here’s an example:

Now, let’s imagine you blacklist some IPs, but you want them to be removed from your blacklist in a few days. Automatically, of course. Well, iptables rules have a handy comment option, allowing you to insert some arbitrary text into the rule without affecting its functionality. So our comment will be a date in epoch format that will show when this particular rule is supposed to expire. Here’s what I mean:

The command below will go through your iptables rules, pick those with what looks like an epoch timestamp, and delete any expired rules:

 

Leave A Reply

Please enter your comment!
Please enter your name here