#!/bin/sh

# Generates a series of plots describing how Nmap performs compared to my
# nmap-nsock-scan in various simulated network conditions (right now only
# packet loss is tested while scanning a single host is tested).
#
# For that to run, you need a VM (refered to as scanning VM) listening on port
# 2251 that is connected to another VM, which has an IP address 10.0.0.2
# (scanned VM). The scanned VM has to have fakesyn.scapy script running. The
# host needs gnuplot and pv installed, as well as a lot of free disk space. It
# also needs a passwordless ssh login to the root user of VM listening on 2251
# TCP port. The scanning VM needs to run the following commands successfuly:
#
# cd
# svn co https://svn.nmap.org/nmap
# cd nmap
# ./configure && make
# cd ..
# svn co https://svn.nmap.org/nmap-exp/d33tah
# cd d33tah/nmap-nsock-scan
# ./configure && make
# modprobe sch_netem # in Fedora 20 this can be found in kernel-modules-extra
#                    # package from Fedora "updates" repository.
# tc qdisc add dev eth0 root netem loss 80.0% # might be other than eth0
#
# Author: Jacek Wielemborek

set -e
NUM_PORTS=1000

for DROP in `seq 0 10 90`; do
  echo "DROP=$DROP"
  for BINARY_PATH in "d33tah/nmap-nsock-scan" "nmap"; do
    echo "BINARY_PATH=$BINARY_PATH"
    BINARY_NAME=`echo -n $BINARY_PATH | tr '/' '_'`
    ssh -q root@localhost \
        -o Port=2251 \
        -o UserKnownHostsFile=/dev/null \
        -o StrictHostKeyChecking=no sh -c "
          true && \
          tc qdisc change dev eth0 root netem loss $DROP.0% && \
          cd ~/d33tah/nmap-portscan-tests && \
          ( rm -f *.txt || true ) && \
          ~/$BINARY_PATH/nmap --max-scan-delay=0 -p-$NUM_PORTS -n -Pn -sT -d4 10.0.0.2 -d4 | \
          tee /dev/stderr | \
          ~/d33tah/nmap-portscan-tests/parse-timing.py /dev/stdin | \
          gnuplot > /tmp/plot.png" 2>&1 | \
      tee $BINARY_NAME-$DROP-log.txt | \
      grep --line-buffered '^Discovered open' | \
      pv -l -s $NUM_PORTS >/dev/null
    scp -q -P 2251 root@localhost:/tmp/plot.png $BINARY_NAME-$DROP-plot.png
  done
  echo
done
