#!/bin/bash
#
# Count the number of hosts of each OS and creates
# a file _IP_OS.txt mapping every IP to its OS.
#
# Note that p0f require a fingerprints file (p0f.fp), the location of which can
# be specified using the '-f' option. Version 2 looks first in the current
# directoy, then in /etc/p0f. Version 3 looks only in the current directory.
#
# Example output (tab separated)
#   Windows  28
#   Linux    45
#   UNKNOWN  11
#
# Usage: ./osStat file [n=topN]

source "$(dirname "$0")/t2utils.sh"

check_dependency p0f

POF="$(which p0f)"       # p0f
POFFP="/etc/p0f/p0f.fp"  # fingerprints file

# Check for dependencies
[ ! -z "$POF" ] || { printerr "p0f dependency not found"; exit 1; }
[ -f "$POFFP" ] || { printerr "p0f fingerprints could not be found"; exit 1; }

# Make sure p0f finds the fingerprints
POF="$POF -f $POFFP"

# Usage
if [ ! -f "$1" ]; then
    echo "Usage: $SNAME file.pcap [n=topN]"
    exit 1
fi

FILE="$1"

_cleanup() {
    local ret=$1
    #echo "Cleaning temporary files"
    rm -f "$TMPFILE"
    exit $ret
}

trap "trap - SIGTERM && _cleanup 1" HUP INT QUIT TERM
trap "_cleanup 0" EXIT

# Returns a list of IP-OS pairs (tab separated)
if [ -z "$($POF 2> /dev/null | grep "p0f 3.")" ]; then
    IPOS=$($POF -lSqvDNs "$FILE" 2> /dev/null | perl -pe 's/^([^:]+):\d+ - ([^ ]+) .+$/\1\t\2/' | sort -u)
else
    TMPFILE=$(mktemp)
    $POF -r "$FILE" -o "$TMPFILE" &> /dev/null
    IPOS=$(grep os "$TMPFILE" | $AWK -F'|' -v OFS="\t" '{
        colcli = 0
        colsrv = 0
        colos  = 0
        colsub = 0
        for (i = 1; i <= NF; i++) {
                 if (match($i, /^cli=/ )) colcli = i
            else if (match($i, /^srv=/ )) colsrv = i
            else if (match($i, /^os=/  )) colos  = i
            else if (match($i, /^subj=/)) colsub = i
        }
        if (colcli && colsrv && colos && colsub) {
            split($colsub, d, "=")
            if (d[2] == "cli") ipp = $colcli
            else ipp = $colsrv
            split(ipp, _ip, "=")
            split(_ip[2], ip, "/")
            split($colos, os, "=")
            printf "%s\t%s\n", ip[1], os[2]
        }
    }' | sort -u)
fi

if [ -z "$IPOS" ]; then
    printerr "Failed to run p0f"
    exit 1
fi

declare -A NUMOS

# Merge duplicate entries
IPOS=$($AWK -F"\t" -v OFS="\t" '{
    if (os[$1]) os[$1] = os[$1] "," $2
    else os[$1] = $2
} END {
    for (ip in os) {
        l = split(os[ip], o, ",")
        if (l == 1) print ip,os[ip]
        else {
            printf "%s", ip
            for (i = 1; i <= l; i++) { # FIXME: what if l > 2
                if (o[i] != "UNKNOWN" && o[i] != "???") printf "\t%s", o[i]
            }
            printf "\n"
        }
    }
}' <<< "$IPOS" | sort -Vu)

# print the list of IP-OS
echo "$IPOS" > "${FILE}_IP_OS.txt"

# Count the number of hosts of each OS
while read -r line; do
    i=$($AWK -F"\t" '{ print $2 }' <<< "$line")
    NUMOS[$i]=$((NUMOS[$i]+1))
done <<< "$IPOS"

# Print the number of hosts of each OS
OUT=$(for i in "${!NUMOS[@]}"; do
    if [ "$i" == "???" ]; then
        echo -e "UNKNOWN\t" ${NUMOS[$i]}
    else
        echo -e "$i\t" ${NUMOS[$i]}
    fi
done)

# Sort by number of hosts
sort -rnk2 -t$'\t' <<< "$OUT" | head -"$2"

unset -v NUMOS
