Monday, January 03, 2005

Script to parse IPTables Logs

In a previous post, I demonstrated how to set up IPTables to log incoming traffic. I have created the following script to parse my logs for network traffic, returning IP addresses and associated ports:

(Please see previous post for logging configuration.)


#!/bin/bash
#
# Program: ipports
# Purpose: To list all external IPs that have been logged by the firewall from
# the /var/log/messages file and the associated ports that the IP was
# attempting to connect to.
#
# Author: Josh Miller
# Date: 08/26/2004

LOGFILE='/var/log/messages'
OUTFILE='ipports.out'
TMP='ipports.tmp'

# Default to external logs
PARAM1='EXTERNAL'

echo
echo

# Determine which type of logs to parse and report from if user input present
if [ -n "$1" ] ; then
if [ $1 == "-e" ] ; then
PARAM1='EXTERNAL';
echo "Parsing $LOGFILE for external IP addresses/ports..."
elif [ $1 == "-i" ] ; then
PARAM1="INTERNAL";
echo "Parsing $LOGFILE for internal IP addresses/ports..."
elif [ $1 == "-o" ] ; then
PARAM1="SRC" ; # Select all logs
echo "Parsing $LOGFILE for all IP traffic/ports..."
elif [ $1 == '-h' ] ; then
echo " Usage: $0 [-e | -i | -o | -h ]"
echo
echo " -e: parse logs for external IP sources"
echo " -i: parse logs for internal IP sources"
echo " -o: parse logs for all IP sources"
echo " -h: this help message"
echo
exit ;
fi
else
echo "Parsing $LOGFILE for external IP addresses/ports..."
fi

# Print out each IP address, with two additional fields, one of which will be the Destination Port
COUNTER=0 ;
for i in `cat $LOGFILE | grep $PARAM1 | awk '{print $10 , $19 , $20}' | sort -u` ;
do

# Make certain to loop three times before writing to the outfile
if echo $i | egrep "^DPT=" > /dev/null ; then
DPORT=`echo $i | cut -c5-9` ;
elif echo $i | egrep "^SRC=" > /dev/null ; then
SRCIP=`echo $i | cut -c5-19` ;
fi

let COUNTER+=1 ;

if [ $COUNTER -gt 2 ] ; then
echo "$SRCIP $DPORT" >> $OUTFILE ;
let COUNTER=0 ;
fi
done

# Apply a header to the output file
echo
echo " >>> IP and Port log <<< " > $TMP ;
echo
echo "IP Address Port # " >> $TMP ;
echo "==================================" >> $TMP ;

# Sort the data and reapply to file
cat $OUTFILE | sort -u >> $TMP ;
cat $TMP > $OUTFILE ;

cat $OUTFILE

# Clean up
rm $TMP ;
rm $OUTFILE ;

No comments: