Sunday, January 1, 2012

Simple intrusion detection using standard UNIX commands

After I'm done with configuring and hardening Linux server I'm doing "reference of the server" by writing output from several crucial commands to my laptop:

ps -x -o user,command
netstat -natuw
find / -uid 0 -perm -4000 -print
find / -size +10000k -print
crontab -u root -l

Then using this simple script on regular basis, I have chance to detect compromised boxes:

#!/bin/bash

function usage
{
    echo "Usage: $0 <hostname>"
}

function getSrvAddr
{
    case $1 in
        'hostname1' ) echo "ssh user@srv1.addr"
            ;;
        'hostname2' ) echo "ssh user@srv2.addr"
            ;;
        * ) echo -n ""
    esac
}

HOSTNAME=$1
REFERENCE_PATH=~/lab/configs/myServers/${HOSTNAME}
SERVER=`getSrvAddr "$HOSTNAME"`
CMDS=(
    "ps -x -o user,command"
    "netstat -natuw"
    "find / -uid 0 -perm -4000 -print"
    "find / -size +10000k -print"
    "crontab -u root -l"
)

if [ -z "$SERVER" ]; then
    usage
    exit 1
fi

i=0
for FILE in ${REFERENCE_PATH}/*; do
    echo
    echo "########################################################################"
    echo  ${SERVER} ${CMDS[$i]}
    echo "########################################################################"
    echo
    diff -w -u <(sort $FILE) <(${SERVER} ${CMDS[$i]} 2> /dev/null | sort)
    i=$((i+1))
done

Basically, what the script does is compare server's initial output from several UNIX commands with it's current output. Using this script I can easily extend it for more commands and more servers. It's very simple method of intrusion detection (and by no mean 100% reliable!) but it's good addition to other mechanisms that should be in place.