#!/bin/sh -u # $0 [count] # Find the most frequent IP addresses attacking this host. # Print the the count, the IP, and the name of the country (from whois). # Searches the kernel log file for the IDAhostsevil lines. # Uses an Internet CSV file to look up the country code. # -Ian! D. Allen - idallen@idallen.ca - www.idallen.com # Standard script header for this course: PATH=/bin:/usr/bin ; export PATH umask 022 # Exit script if more than one argument. if [ $# -gt 1 ] ; then echo 1>&2 "$0: expecting one optional line count, found $# ($*)" echo 1>&2 "Usage $0 [line_count]" exit 1 fi # Set count of number of lines to display on screen; default is 10. count=10 if [ $# -eq 1 ] ; then count=$1 fi # Fetch a CSV table of Country,Code lines # Remove unnecessary CR characters from line ends (DOS format file!). CSV='https://pkgstore.datahub.io/core/country-list/data_csv/data/d7c9d7cfb42cb69f4422dec222dbbaa8/data_csv.csv' table=$( wget -q -O - "$CSV" | tr -d '\r' ) if [ "$table" = "" ] ; then echo 1>&2 "$0: Failed to fetch country code CSV table from: $CSV" exit 1 fi # Search the log file and extract just the IP; count the IPs (attacks); # look up the first country code; look up the country; print a line. # Sometimes the IP is field 12 if the kernel time field is short. fgrep IDAhostsevil /var/log/kern.log \ | awk '{ if ( $6 == "[" ) print $12 else print $11 }' \ | sort \ | uniq -c \ | sort -nr \ | head -n "$count" \ | tr '=' ' ' \ | \ while read count src ip ; do # Validate that $ip looks like a dotted-quad IPv4 address case "$ip" in [0-9]*.[0-9]*.[0-9]*.*[0-9] ) ;; * ) echo 1>&2 "$0: non-IP address skipped: $ip" continue ;; esac # Need case-insensitive to match both country: and Country: cc=$( whois "$ip" | fgrep -i 'country:' | awk '{print $2}' | head -n 1 ) if [ "$cc" = "" ] ; then cc='' fi # Look up the country code after the comma in the lines in the CSV table country=$( echo "$table" | fgrep ",$cc" ) if [ "$country" = "" ] ; then country="UNKNOWN $cc" fi # Format each string nicely using printf: # ('man printf' or see http://www.gnu.org/software/coreutils/printf) printf '%5d attacks from %-15s from %s\n' "$count" "$ip" "$country" # NOT USED: echo "$count attacks from $ip from $country" done