#!/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]
#

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

# Check for dependencies
[ ! -z "$POF" ] || { echo "p0f dependency not found"; exit 1; }
[ -f "$POFFP" ] || { echo "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: $0 file [n=topN]"
    exit 1
fi

FILE=$1;

# 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
    echo "Failed to run p0f"
    exit 1
fi

declare -A NUMOS

# Merge duplicate entries
IPOS=$(echo "$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"
        }
    }
}' | 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=$(echo "$line" | awk -F'\t' '{print $2}')
    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
echo "$OUT" | sort -rnk2 -t$'\t' | head -"$2"

unset -v NUMOS

if [ ! -z "$TMPFILE" ] && [ -f "$TMPFILE" ]; then
    rm -f "$TMPFILE"
fi
