6 Commits
2.1.7 ... 2.1.9

Author SHA1 Message Date
derv82
a157132387 2.1.9: --pmkid option, cleaned up --cracked, other bug fixes.
PMKID:

* `--pmkid` option only attacks WPA networks with PMKID capture + crack
* Decreased PMKID capture time from 60 seconds to 15 seconds.
* Ignores PMKID attack if `--wps-only` is set.

WPS:

* Ctrl+C while waiting for `bully` to fetch PSK = remembers PIN, PSK is unknown.

Misc:

* `--cracked` prints results on single lines (much easier to read)
* Fixed typo when required dependencies are not found (closes #127)
2018-08-19 10:37:27 -07:00
derv82
ebb7cac91c Removing the last of the double-quoted strings (now single-quoted) 2018-08-18 03:01:52 -07:00
derv82
c4ed911490 Rewrote --crack behavior; supports multiple handshakes at once. 2018-08-18 02:55:12 -07:00
derv82
0977f48d0c Documentation, code-formatting, and refactoring.
* Added some docs, updated existing docs.
* Use single-quotes for strings when possible.
* Color.pexception() prints exception and stack trace.
2018-08-17 03:46:58 -07:00
derv82
6adca64154 2.1.8: Check hashcat tools before trying PMKID attack.
Should resolve #124.

Also, capturing PMKID will skip WPA handshake capture.
2018-08-16 11:10:03 -07:00
derv82
7ed30f0973 Making all .py files executable 2018-08-16 01:56:42 -07:00
36 changed files with 935 additions and 702 deletions

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python
from wifite import wifite from wifite import wifite
wifite.entry_point()
wifite.run()

0
wifite/__init__.py Normal file → Executable file
View File

View File

@@ -9,7 +9,8 @@ class Arguments(object):
''' Holds arguments used by the Wifite ''' ''' Holds arguments used by the Wifite '''
def __init__(self, configuration): def __init__(self, configuration):
self.verbose = any(['-v' in word for word in sys.argv]) # Hack: Check for -v before parsing args; so we know which commands to display.
self.verbose = '-v' in sys.argv or '-hv' in sys.argv or '-vh' in sys.argv
self.config = configuration self.config = configuration
self.args = self.get_arguments() self.args = self.get_arguments()
@@ -142,18 +143,20 @@ class Arguments(object):
action='store', action='store',
type=int, type=int,
dest='num_deauths', dest='num_deauths',
metavar="[num]", metavar='[num]',
default=None, default=None,
help=self._verbose('Number of deauth packets to send (default: {G}%d{W})' % self.config.num_deauths)) help=self._verbose('Number of deauth packets to send (default: {G}%d{W})' % self.config.num_deauths))
def _add_eviltwin_args(self, group): def _add_eviltwin_args(self, group):
group.add_argument('-ev', pass
'--eviltwin', '''
group.add_argument('--eviltwin',
action='store_true', action='store_true',
dest='use_eviltwin', dest='use_eviltwin',
help=Color.s('Use the "Evil Twin" attack against all targets (default: {G}off{W})')) help=Color.s('Use the "Evil Twin" attack against all targets (default: {G}off{W})'))
# TODO: Args to specify deauth interface, server port, etc. # TODO: Args to specify deauth interface, server port, etc.
'''
def _add_wep_args(self, wep): def _add_wep_args(self, wep):
@@ -277,6 +280,12 @@ class Arguments(object):
help=self._verbose('Time to wait before failing WPA attack (default: {G}%d sec{W})' % self.config.wpa_attack_timeout)) help=self._verbose('Time to wait before failing WPA attack (default: {G}%d sec{W})' % self.config.wpa_attack_timeout))
wpa.add_argument('-wpat', help=argparse.SUPPRESS, action='store', dest='wpa_attack_timeout', type=int) wpa.add_argument('-wpat', help=argparse.SUPPRESS, action='store', dest='wpa_attack_timeout', type=int)
wpa.add_argument('--pmkid',
'-pmkid',
action='store_true',
dest='use_pmkid_only',
help=Color.s('ONLY use PMKID capture on WPA endpoints (default: {G}off{W})'))
wpa.add_argument('--new-hs', wpa.add_argument('--new-hs',
action='store_true', action='store_true',
dest='ignore_old_handshakes', dest='ignore_old_handshakes',
@@ -345,7 +354,7 @@ class Arguments(object):
# Alias # Alias
wps.add_argument('-wpst', help=argparse.SUPPRESS, action='store', dest='wps_pixie_timeout', type=int) wps.add_argument('-wpst', help=argparse.SUPPRESS, action='store', dest='wps_pixie_timeout', type=int)
# Maximum number of "failures" (WPSFail) # Maximum number of 'failures' (WPSFail)
wps.add_argument('--wps-fails', wps.add_argument('--wps-fails',
action='store', action='store',
dest='wps_fail_threshold', dest='wps_fail_threshold',
@@ -355,7 +364,7 @@ class Arguments(object):
# Alias # Alias
wps.add_argument('-wpsf', help=argparse.SUPPRESS, action='store', dest='wps_fail_threshold', type=int) wps.add_argument('-wpsf', help=argparse.SUPPRESS, action='store', dest='wps_fail_threshold', type=int)
# Maximum number of "timeouts" # Maximum number of 'timeouts'
wps.add_argument('--wps-timeouts', wps.add_argument('--wps-timeouts',
action='store', action='store',
dest='wps_timeout_threshold', dest='wps_timeout_threshold',

0
wifite/attack/__init__.py Normal file → Executable file
View File

63
wifite/attack/all.py Normal file → Executable file
View File

@@ -1,18 +1,17 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from .wep import AttackWEP
from .wpa import AttackWPA
from .wps import AttackWPS
from .pmkid import AttackPMKID
from ..config import Configuration from ..config import Configuration
from ..util.color import Color from ..util.color import Color
from ..util.input import raw_input
class AttackAll(object): class AttackAll(object):
@classmethod @classmethod
def attack_multiple(cls, targets): def attack_multiple(cls, targets):
'''
Attacks all given `targets` (list[wifite.model.target]) until user interruption.
Returns: Number of targets that were attacked (int)
'''
attacked_targets = 0 attacked_targets = 0
targets_remaining = len(targets) targets_remaining = len(targets)
for index, target in enumerate(targets, start=1): for index, target in enumerate(targets, start=1):
@@ -20,7 +19,7 @@ class AttackAll(object):
targets_remaining -= 1 targets_remaining -= 1
bssid = target.bssid bssid = target.bssid
essid = target.essid if target.essid_known else "{O}ESSID unknown{W}" essid = target.essid if target.essid_known else '{O}ESSID unknown{W}'
Color.pl('\n{+} ({G}%d{W}/{G}%d{W})' % (index, len(targets)) + Color.pl('\n{+} ({G}%d{W}/{G}%d{W})' % (index, len(targets)) +
' starting attacks against {C}%s{W} ({C}%s{W})' % (bssid, essid)) ' starting attacks against {C}%s{W} ({C}%s{W})' % (bssid, essid))
@@ -33,45 +32,53 @@ class AttackAll(object):
@classmethod @classmethod
def attack_single(cls, target, targets_remaining): def attack_single(cls, target, targets_remaining):
'''
Attacks a single `target` (wifite.model.target).
Returns: True if attacks should continue, False otherwise.
'''
from .wep import AttackWEP
from .wpa import AttackWPA
from .wps import AttackWPS
from .pmkid import AttackPMKID
attacks = [] attacks = []
if Configuration.use_eviltwin: if Configuration.use_eviltwin:
pass # TODO:EvilTwin attack # TODO: EvilTwin attack
pass
elif 'WEP' in target.encryption: elif 'WEP' in target.encryption:
attacks.append(AttackWEP(target)) attacks.append(AttackWEP(target))
elif 'WPA' in target.encryption: elif 'WPA' in target.encryption:
# WPA can have multiple attack vectors # WPA can have multiple attack vectors:
if target.wps: if target.wps:
# WPS
attacks.append(AttackWPS(target)) attacks.append(AttackWPS(target))
# PMKID
attacks.append(AttackPMKID(target)) attacks.append(AttackPMKID(target))
# Handshake capture
attacks.append(AttackWPA(target)) attacks.append(AttackWPA(target))
if len(attacks) == 0: if len(attacks) == 0:
Color.pl("{!} {R}Error: {O}unable to attack: encryption not WEP or WPA") Color.pl('{!} {R}Error: {O}unable to attack: encryption not WEP or WPA')
return return
for attack in attacks: while len(attacks) > 0:
attack = attacks.pop(0)
try: try:
result = attack.run() result = attack.run()
if result and attack.success: if result:
break # We cracked it. break # Attack was successful, stop other attacks.
except Exception as e: except Exception as e:
Color.pl("\n{!} {R}Error: {O}%s" % str(e)) Color.pexception(e)
if Configuration.verbose > 0 or Configuration.print_stack_traces:
Color.pl('\n{!} {O}Full stack trace below')
from traceback import format_exc
Color.p('\n{!} ')
err = format_exc().strip()
err = err.replace('\n', '\n{W}{!} {W} ')
err = err.replace(' File', '{W}{D}File')
err = err.replace(' Exception: ', '{R}Exception: {O}')
Color.pl(err)
continue continue
except KeyboardInterrupt: except KeyboardInterrupt:
Color.pl('\n{!} {O}interrupted{W}\n') Color.pl('\n{!} {O}interrupted{W}\n')
if not cls.user_wants_to_continue(targets_remaining, 1): if not cls.user_wants_to_continue(targets_remaining, len(attacks)):
return False # Stop attacking other targets return False # Stop attacking other targets
if attack.success: if attack.success:
@@ -82,10 +89,13 @@ class AttackAll(object):
@classmethod @classmethod
def user_wants_to_continue(cls, targets_remaining, attacks_remaining=0): def user_wants_to_continue(cls, targets_remaining, attacks_remaining=0):
''' Asks user if attacks should continue onto other targets ''' '''
Asks user if attacks should continue onto other targets
Returns:
True if user wants to continue, False otherwise.
'''
if attacks_remaining == 0 and targets_remaining == 0: if attacks_remaining == 0 and targets_remaining == 0:
# No targets or attacksleft, drop out return # No targets or attacksleft, drop out
return
prompt_list = [] prompt_list = []
if attacks_remaining > 0: if attacks_remaining > 0:
@@ -98,6 +108,7 @@ class AttackAll(object):
prompt = Color.s('{+} type {G}c{W} to {G}continue{W}' + prompt = Color.s('{+} type {G}c{W} to {G}continue{W}' +
' or {R}s{W} to {R}stop{W}: ') ' or {R}s{W} to {R}stop{W}: ')
from ..util.input import raw_input
if raw_input(prompt).lower().startswith('s'): if raw_input(prompt).lower().startswith('s'):
return False return False
else: else:

72
wifite/attack/pmkid.py Normal file → Executable file
View File

@@ -5,7 +5,6 @@ from ..model.attack import Attack
from ..config import Configuration from ..config import Configuration
from ..tools.hashcat import HcxDumpTool, HcxPcapTool, Hashcat from ..tools.hashcat import HcxDumpTool, HcxPcapTool, Hashcat
from ..util.color import Color from ..util.color import Color
from ..util.process import Process
from ..util.timer import Timer from ..util.timer import Timer
from ..model.pmkid_result import CrackResultPMKID from ..model.pmkid_result import CrackResultPMKID
@@ -55,18 +54,43 @@ class AttackPMKID(Attack):
def run(self): def run(self):
# TODO: Check ./hs/ for previously-captured PMKID, skip to crack if found. '''
Performs PMKID attack, if possible.
1) Captures PMKID hash (or re-uses existing hash if found).
2) Cracks the hash.
Returns:
True if handshake is captured. False otherwise.
'''
# Skip if user only wants to run PixieDust attack
if Configuration.wps_only and self.target.wps:
Color.pl('\r{!} {O}Skipping PMKID attack on {R}%s{O} because {R}--wps-only{O} is set{W}' % self.target.essid)
self.success = False
return False
from ..util.process import Process
# Check that we have all hashcat programs
dependencies = [
Hashcat.dependency_name,
HcxDumpTool.dependency_name,
HcxPcapTool.dependency_name
]
missing_deps = [dep for dep in dependencies if not Process.exists(dep)]
if len(missing_deps) > 0:
Color.pl('{!} Skipping PMKID attack, missing required tools: {O}%s{W}' % ', '.join(missing_deps))
return False
pmkid_file = None pmkid_file = None
# Load exisitng has from filesystem
if Configuration.ignore_old_handshakes == False: if Configuration.ignore_old_handshakes == False:
# Load exisitng PMKID hash from filesystem
pmkid_file = self.get_existing_pmkid_file(self.target.bssid) pmkid_file = self.get_existing_pmkid_file(self.target.bssid)
if pmkid_file is not None: if pmkid_file is not None:
Color.pattack('PMKID', self.target, 'CAPTURE', Color.pattack('PMKID', self.target, 'CAPTURE',
'Loaded {C}existing{W} PMKID hash: {C}%s{W}\n' % pmkid_file) 'Loaded {C}existing{W} PMKID hash: {C}%s{W}\n' % pmkid_file)
# Capture hash from live target.
if pmkid_file is None: if pmkid_file is None:
# Capture hash from live target.
pmkid_file = self.capture_pmkid() pmkid_file = self.capture_pmkid()
if pmkid_file is None: if pmkid_file is None:
@@ -74,12 +98,18 @@ class AttackPMKID(Attack):
# Crack it. # Crack it.
self.success = self.crack_pmkid_file(pmkid_file) self.success = self.crack_pmkid_file(pmkid_file)
return self.success
return True # Even if we don't crack it, capturing a PMKID is 'successful'
def capture_pmkid(self): def capture_pmkid(self):
'''
Runs hashcat's hcxpcaptool to extract PMKID hash from the .pcapng file.
Returns:
The PMKID hash (str) if found, otherwise None.
'''
self.keep_capturing = True self.keep_capturing = True
self.timer = Timer(60) self.timer = Timer(15)
# Start hcxdumptool # Start hcxdumptool
t = Thread(target=self.dumptool_thread) t = Thread(target=self.dumptool_thread)
@@ -102,7 +132,7 @@ class AttackPMKID(Attack):
if pmkid_hash is None: if pmkid_hash is None:
Color.pattack('PMKID', self.target, 'CAPTURE', Color.pattack('PMKID', self.target, 'CAPTURE',
'{R}Failed{O} to capture PMKID\n') '{R}Failed{O} to capture PMKID\n')
Color.pl("") Color.pl('')
return None # No hash found. return None # No hash found.
Color.clear_entire_line() Color.clear_entire_line()
@@ -113,27 +143,33 @@ class AttackPMKID(Attack):
def crack_pmkid_file(self, pmkid_file): def crack_pmkid_file(self, pmkid_file):
''' '''
Cracks file containing PMKID hash (*.16800). Runs hashcat containing PMKID hash (*.16800).
If cracked, saves results in self.crack_result If cracked, saves results in self.crack_result
Returns: Returns:
True if cracked, False otherwise. True if cracked, False otherwise.
''' '''
# Check that wordlist exists before cracking. # Check that wordlist exists before cracking.
if Configuration.wordlist is None: if Configuration.wordlist is None:
Color.pl('\n{!} {O}Not cracking because {R}wordlist{O} is not found.') Color.pl('\n{!} {O}Not cracking PMKID ' +
Color.pl('{!} {O}Run Wifite with the {R}--crack{O} and {R}--dict{O} options to try again.') 'because there is no {R}wordlist{O} (re-run with {C}--dict{O})')
# TODO: Uncomment once --crack is updated to support recracking PMKIDs.
#Color.pl('{!} {O}Run Wifite with the {R}--crack{O} and {R}--dict{O} options to try again.')
key = None key = None
else: else:
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack('PMKID', self.target, 'CRACK', 'Cracking PMKID...\n') Color.pattack('PMKID', self.target, 'CRACK', 'Cracking PMKID using {C}%s{W} ...\n' % Configuration.wordlist)
key = Hashcat.crack_pmkid(pmkid_file) key = Hashcat.crack_pmkid(pmkid_file)
if key is None: if key is None:
# Failed to crack. # Failed to crack.
Color.clear_entire_line() if Configuration.wordlist is not None:
Color.pattack('PMKID', self.target, '{R}CRACK', Color.clear_entire_line()
'{R}Failed{O} to crack PMKID\n') Color.pattack('PMKID', self.target, '{R}CRACK',
Color.pl("") '{R}Failed {O}Passphrase not found in dictionary.\n')
Color.pl('')
return False return False
else: else:
# Successfully cracked. # Successfully cracked.
@@ -147,6 +183,7 @@ class AttackPMKID(Attack):
def dumptool_thread(self): def dumptool_thread(self):
'''Runs hashcat's hcxdumptool until it dies or `keep_capturing == False`'''
dumptool = HcxDumpTool(self.target, self.pcapng_file) dumptool = HcxDumpTool(self.target, self.pcapng_file)
# Let the dump tool run until we have the hash. # Let the dump tool run until we have the hash.
@@ -157,9 +194,7 @@ class AttackPMKID(Attack):
def save_pmkid(self, pmkid_hash): def save_pmkid(self, pmkid_hash):
''' '''Saves a copy of the pmkid (handshake) to hs/ directory.'''
Saves a copy of the pmkid (handshake) to hs/
'''
# Create handshake dir # Create handshake dir
if not os.path.exists(Configuration.wpa_handshake_dir): if not os.path.exists(Configuration.wpa_handshake_dir):
os.mkdir(Configuration.wpa_handshake_dir) os.mkdir(Configuration.wpa_handshake_dir)
@@ -177,3 +212,4 @@ class AttackPMKID(Attack):
pmkid_handle.write('\n') pmkid_handle.write('\n')
return pmkid_file return pmkid_file

View File

@@ -18,7 +18,7 @@ class AttackWEP(Attack):
Contains logic for attacking a WEP-encrypted access point. Contains logic for attacking a WEP-encrypted access point.
''' '''
fakeauth_wait = 5 fakeauth_wait = 5 # TODO: Configuration?
def __init__(self, target): def __init__(self, target):
super(AttackWEP, self).__init__(target) super(AttackWEP, self).__init__(target)
@@ -69,7 +69,7 @@ class AttackWEP(Attack):
# Use our interface's MAC address for the attacks. # Use our interface's MAC address for the attacks.
client_mac = Ifconfig.get_mac(Configuration.interface) client_mac = Ifconfig.get_mac(Configuration.interface)
# Keep us authenticated # Keep us authenticated
fakeauth_proc = Aireplay(self.target, "fakeauth") fakeauth_proc = Aireplay(self.target, 'fakeauth')
elif len(airodump_target.clients) == 0: elif len(airodump_target.clients) == 0:
# Failed to fakeauth, can't use our MAC. # Failed to fakeauth, can't use our MAC.
# And there are no associated clients. Use one and tell the user. # And there are no associated clients. Use one and tell the user.
@@ -108,16 +108,16 @@ class AttackWEP(Attack):
current_ivs = airodump_target.ivs current_ivs = airodump_target.ivs
total_ivs = previous_ivs + current_ivs total_ivs = previous_ivs + current_ivs
status = "%d/{C}%d{W} IVs" % (total_ivs, Configuration.wep_crack_at_ivs) status = '%d/{C}%d{W} IVs' % (total_ivs, Configuration.wep_crack_at_ivs)
if fakeauth_proc: if fakeauth_proc:
if fakeauth_proc and fakeauth_proc.status: if fakeauth_proc and fakeauth_proc.status:
status += ", {G}fakeauth{W}" status += ', {G}fakeauth{W}'
else: else:
status += ", {R}no-auth{W}" status += ', {R}no-auth{W}'
if aireplay.status is not None: if aireplay.status is not None:
status += ", %s" % aireplay.status status += ', %s' % aireplay.status
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WEP", airodump_target, "%s" % attack_name, status) Color.pattack('WEP', airodump_target, '%s' % attack_name, status)
# Check if we cracked it. # Check if we cracked it.
if aircrack and aircrack.is_cracked(): if aircrack and aircrack.is_cracked():
@@ -141,7 +141,7 @@ class AttackWEP(Attack):
if aircrack and aircrack.is_running(): if aircrack and aircrack.is_running():
# Aircrack is running in the background. # Aircrack is running in the background.
Color.p("and {C}cracking{W}") Color.p('and {C}cracking{W}')
# Check number of IVs, crack if necessary # Check number of IVs, crack if necessary
if total_ivs > Configuration.wep_crack_at_ivs: if total_ivs > Configuration.wep_crack_at_ivs:
@@ -180,7 +180,7 @@ class AttackWEP(Attack):
# If .xor is not there, the process failed. # If .xor is not there, the process failed.
Color.pl('\n{!} {O}%s attack{R} did not generate a .xor file' % attack_name) Color.pl('\n{!} {O}%s attack{R} did not generate a .xor file' % attack_name)
# XXX: For debugging # XXX: For debugging
Color.pl('{?} {O}Command: {R}%s{W}' % " ".join(aireplay.cmd)) Color.pl('{?} {O}Command: {R}%s{W}' % ' '.join(aireplay.cmd))
Color.pl('{?} {O}Output:\n{R}%s{W}' % aireplay.get_output()) Color.pl('{?} {O}Output:\n{R}%s{W}' % aireplay.get_output())
break break
@@ -193,8 +193,8 @@ class AttackWEP(Attack):
if replay_file: if replay_file:
Color.pl('{+} {C}forged packet{W},' + Color.pl('{+} {C}forged packet{W},' +
' {G}replaying...{W}') ' {G}replaying...{W}')
wep_attack_type = WEPAttackType("forgedreplay") wep_attack_type = WEPAttackType('forgedreplay')
attack_name = "forgedreplay" attack_name = 'forgedreplay'
aireplay = Aireplay(self.target, aireplay = Aireplay(self.target,
'forgedreplay', 'forgedreplay',
client_mac=client_mac, client_mac=client_mac,
@@ -206,7 +206,7 @@ class AttackWEP(Attack):
break break
else: else:
Color.pl('\n{!} {O}aireplay-ng exited unexpectedly{W}') Color.pl('\n{!} {O}aireplay-ng exited unexpectedly{W}')
Color.pl('{?} {O}Command: {R}%s{W}' % " ".join(aireplay.cmd)) Color.pl('{?} {O}Command: {R}%s{W}' % ' '.join(aireplay.cmd))
Color.pl('{?} {O}Output:\n{R}%s{W}' % aireplay.get_output()) Color.pl('{?} {O}Output:\n{R}%s{W}' % aireplay.get_output())
break # Continue to other attacks break # Continue to other attacks
@@ -251,16 +251,7 @@ class AttackWEP(Attack):
return self.success return self.success
except Exception as e: except Exception as e:
Color.pl("\n{!} {R}Error: {O}%s" % str(e)) Color.pexception(e)
if Configuration.verbose > 0 or Configuration.print_stack_traces:
Color.pl('\n{!} {O}Full stack trace below')
from traceback import format_exc
Color.p('\n{!} ')
err = format_exc().strip()
err = err.replace('\n', '\n{!} {C} ')
err = err.replace(' File', '{W}File')
err = err.replace(' Exception: ', '{R}Exception: {O}')
Color.pl(err)
continue continue
# End of big try-catch # End of big try-catch
# End of for-each-attack-type loop # End of for-each-attack-type loop
@@ -273,33 +264,33 @@ class AttackWEP(Attack):
def user_wants_to_stop(self, current_attack, attacks_remaining, target): def user_wants_to_stop(self, current_attack, attacks_remaining, target):
''' '''
Ask user what attack to perform next (re-orders attacks_remaining, returns False), Ask user what attack to perform next (re-orders attacks_remaining, returns False),
or if we should stop attacking this target (returns True). or if we should stop attacking this target (returns True).
''' '''
if target is None: if target is None:
Color.pl("") Color.pl('')
return True return True
target_name = target.essid if target.essid_known else target.bssid target_name = target.essid if target.essid_known else target.bssid
Color.pl("\n\n{!} {O}Interrupted") Color.pl('\n\n{!} {O}Interrupted')
Color.pl("{+} {W}Next steps:") Color.pl('{+} {W}Next steps:')
# Deauth clients & retry # Deauth clients & retry
attack_index = 1 attack_index = 1
Color.pl(" {G}1{W}: {O}Deauth clients{W} and {G}retry{W} {C}%s attack{W} against {G}%s{W}" % (current_attack, target_name)) Color.pl(' {G}1{W}: {O}Deauth clients{W} and {G}retry{W} {C}%s attack{W} against {G}%s{W}' % (current_attack, target_name))
# Move onto a different WEP attack # Move onto a different WEP attack
for attack_name in attacks_remaining: for attack_name in attacks_remaining:
attack_index += 1 attack_index += 1
Color.pl(" {G}%d{W}: Start new {C}%s attack{W} against {G}%s{W}" % (attack_index, attack_name, target_name)) Color.pl(' {G}%d{W}: Start new {C}%s attack{W} against {G}%s{W}' % (attack_index, attack_name, target_name))
# Stop attacking entirely # Stop attacking entirely
attack_index += 1 attack_index += 1
Color.pl(" {G}%d{W}: {R}Stop attacking, {O}Move onto next target{W}" % attack_index) Color.pl(' {G}%d{W}: {R}Stop attacking, {O}Move onto next target{W}' % attack_index)
while True: while True:
answer = raw_input(Color.s("{?} Select an option ({G}1-%d{W}): " % attack_index)) answer = raw_input(Color.s('{?} Select an option ({G}1-%d{W}): ' % attack_index))
if not answer.isdigit() or int(answer) < 1 or int(answer) > attack_index: if not answer.isdigit() or int(answer) < 1 or int(answer) > attack_index:
Color.pl("{!} {R}Invalid input: {O}Must enter a number between {G}1-%d{W}" % attack_index) Color.pl('{!} {R}Invalid input: {O}Must enter a number between {G}1-%d{W}' % attack_index)
continue continue
answer = int(answer) answer = int(answer)
break break
@@ -309,7 +300,7 @@ class AttackWEP(Attack):
deauth_count = 1 deauth_count = 1
Color.clear_entire_line() Color.clear_entire_line()
Color.p("\r{+} {O}Deauthenticating *broadcast*{W} (all clients)...") Color.p('\r{+} {O}Deauthenticating *broadcast*{W} (all clients)...')
Aireplay.deauth(target.bssid, essid=target.essid) Aireplay.deauth(target.bssid, essid=target.essid)
attacking_mac = Ifconfig.get_mac(Configuration.interface) attacking_mac = Ifconfig.get_mac(Configuration.interface)
@@ -318,13 +309,13 @@ class AttackWEP(Attack):
continue # Don't deauth ourselves. continue # Don't deauth ourselves.
Color.clear_entire_line() Color.clear_entire_line()
Color.p("\r{+} {O}Deauthenticating client {C}%s{W}..." % client.station) Color.p('\r{+} {O}Deauthenticating client {C}%s{W}...' % client.station)
Aireplay.deauth(target.bssid, client_mac=client.station, essid=target.essid) Aireplay.deauth(target.bssid, client_mac=client.station, essid=target.essid)
deauth_count += 1 deauth_count += 1
Color.clear_entire_line() Color.clear_entire_line()
Color.pl("\r{+} Sent {C}%d {O}deauths{W}" % deauth_count) Color.pl('\r{+} Sent {C}%d {O}deauths{W}' % deauth_count)
# Re-insert current attack to top of list of attacks remaining # Re-insert current attack to top of list of attacks remaining
attacks_remaining.insert(0, current_attack) attacks_remaining.insert(0, current_attack)
@@ -336,11 +327,11 @@ class AttackWEP(Attack):
attacks_remaining.insert(0, attacks_remaining.pop(answer-2)) attacks_remaining.insert(0, attacks_remaining.pop(answer-2))
return False # Don't stop return False # Don't stop
def fake_auth(self): def fake_auth(self):
''' '''
Attempts to fake-authenticate with target. Attempts to fake-authenticate with target.
Returns: True if successful, Returns: True if successful, False is unsuccessful.
False is unsuccessful.
''' '''
Color.p('\r{+} attempting {G}fake-authentication{W} with {C}%s{W}...' % self.target.bssid) Color.p('\r{+} attempting {G}fake-authentication{W} with {C}%s{W}...' % self.target.bssid)
fakeauth = Aireplay.fakeauth(self.target, timeout=AttackWEP.fakeauth_wait) fakeauth = Aireplay.fakeauth(self.target, timeout=AttackWEP.fakeauth_wait)
@@ -363,11 +354,10 @@ class AttackWEP(Attack):
return fakeauth return fakeauth
if __name__ == '__main__': if __name__ == '__main__':
Configuration.initialize(True) Configuration.initialize(True)
from ..model.target import Target from ..model.target import Target
fields = "A4:2B:8C:16:6B:3A, 2015-05-27 19:28:44, 2015-05-27 19:28:46, 6, 54e,WEP, WEP, , -58, 2, 0, 0. 0. 0. 0, 9, Test Router Please Ignore, ".split(',') fields = 'A4:2B:8C:16:6B:3A, 2015-05-27 19:28:44, 2015-05-27 19:28:46, 6, 54e,WEP, WEP, , -58, 2, 0, 0. 0. 0. 0, 9, Test Router Please Ignore, '.split(',')
target = Target(fields) target = Target(fields)
wep = AttackWEP(target) wep = AttackWEP(target)
wep.run() wep.run()

View File

@@ -24,13 +24,14 @@ class AttackWPA(Attack):
self.success = False self.success = False
def run(self): def run(self):
''' '''Initiates full WPA handshake capture attack.'''
Initiates full WPA handshake capture attack.
'''
# Check if user only wants to run PixieDust attack if Configuration.use_pmkid_only:
self.success = False
return False
# Skip if user only wants to run PixieDust attack
if Configuration.wps_only and self.target.wps: if Configuration.wps_only and self.target.wps:
Color.pl('\r{!} {O}--wps-only{R} set, ignoring WPA-handshake attack on {O}%s{W}' % self.target.essid) Color.pl('\r{!} {O}Skipping WPA-Handshake attack on {R}%s{O} because {R}--wps-only{O} is set{W}' % self.target.essid)
self.success = False self.success = False
return self.success return self.success
@@ -56,8 +57,9 @@ class AttackWPA(Attack):
self.success = True self.success = True
return self.success return self.success
def capture_handshake(self): def capture_handshake(self):
''' Returns captured or stored handshake, otherwise None ''' '''Returns captured or stored handshake, otherwise None.'''
handshake = None handshake = None
# First, start Airodump process # First, start Airodump process
@@ -67,7 +69,7 @@ class AttackWPA(Attack):
output_file_prefix='wpa') as airodump: output_file_prefix='wpa') as airodump:
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPA", self.target, "Handshake capture", "Waiting for target to appear...") Color.pattack('WPA', self.target, 'Handshake capture', 'Waiting for target to appear...')
airodump_target = self.wait_for_target(airodump) airodump_target = self.wait_for_target(airodump)
self.clients = [] self.clients = []
@@ -78,7 +80,7 @@ class AttackWPA(Attack):
essid = airodump_target.essid if airodump_target.essid_known else None essid = airodump_target.essid if airodump_target.essid_known else None
handshake = self.load_handshake(bssid=bssid, essid=essid) handshake = self.load_handshake(bssid=bssid, essid=essid)
if handshake: if handshake:
Color.pattack("WPA", self.target, "Handshake capture", "found {G}existing handshake{W} for {C}%s{W}" % handshake.essid) Color.pattack('WPA', self.target, 'Handshake capture', 'found {G}existing handshake{W} for {C}%s{W}' % handshake.essid)
Color.pl('\n{+} Using handshake from {C}%s{W}' % handshake.capfile) Color.pl('\n{+} Using handshake from {C}%s{W}' % handshake.capfile)
return handshake return handshake
@@ -88,10 +90,10 @@ class AttackWPA(Attack):
while handshake is None and not timeout_timer.ended(): while handshake is None and not timeout_timer.ended():
step_timer = Timer(1) step_timer = Timer(1)
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPA", Color.pattack('WPA',
airodump_target, airodump_target,
"Handshake capture", 'Handshake capture',
"Listening. (clients:{G}%d{W}, deauth:{O}%s{W}, timeout:{R}%s{W})" % (len(self.clients), deauth_timer, timeout_timer)) 'Listening. (clients:{G}%d{W}, deauth:{O}%s{W}, timeout:{R}%s{W})' % (len(self.clients), deauth_timer, timeout_timer))
# Find .cap file # Find .cap file
cap_files = airodump.find_files(endswith='.cap') cap_files = airodump.find_files(endswith='.cap')
@@ -111,7 +113,12 @@ class AttackWPA(Attack):
handshake = Handshake(temp_file, bssid=bssid, essid=essid) handshake = Handshake(temp_file, bssid=bssid, essid=essid)
if handshake.has_handshake(): if handshake.has_handshake():
# We got a handshake # We got a handshake
Color.pl('\n\n{+} {G}successfully captured handshake{W}') Color.clear_entire_line()
Color.pattack('WPA',
airodump_target,
'Handshake capture',
'{G}Captured handshake{W}')
Color.pl('')
break break
# There is no handshake # There is no handshake
@@ -124,11 +131,11 @@ class AttackWPA(Attack):
for client in airodump_target.clients: for client in airodump_target.clients:
if client.station not in self.clients: if client.station not in self.clients:
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPA", Color.pattack('WPA',
airodump_target, airodump_target,
"Handshake capture", 'Handshake capture',
"Discovered new client: {G}%s{W}" % client.station) 'Discovered new client: {G}%s{W}' % client.station)
Color.pl("") Color.pl('')
self.clients.append(client.station) self.clients.append(client.station)
# Send deauth to a client or broadcast # Send deauth to a client or broadcast
@@ -143,44 +150,48 @@ class AttackWPA(Attack):
if handshake is None: if handshake is None:
# No handshake, attack failed. # No handshake, attack failed.
Color.pl("\n{!} {O}WPA handshake capture {R}FAILED:{O} Timed out after %d seconds" % (Configuration.wpa_attack_timeout)) Color.pl('\n{!} {O}WPA handshake capture {R}FAILED:{O} Timed out after %d seconds' % (Configuration.wpa_attack_timeout))
return handshake return handshake
else: else:
# Save copy of handshake to ./hs/ # Save copy of handshake to ./hs/
self.save_handshake(handshake) self.save_handshake(handshake)
return handshake return handshake
def crack_handshake(self, handshake, wordlist): @staticmethod
def crack_handshake(handshake, wordlist, verbose=False):
'''Tries to crack a handshake. Returns WPA key if found, otherwise None.''' '''Tries to crack a handshake. Returns WPA key if found, otherwise None.'''
if wordlist is None: if wordlist is None:
Color.pl("{!} {O}Not cracking handshake because" + Color.pl('{!} {O}Not cracking handshake because' +
" wordlist ({R}--dict{O}) is not set") ' wordlist ({R}--dict{O}) is not set')
return None return None
elif not os.path.exists(wordlist): elif not os.path.exists(wordlist):
Color.pl("{!} {O}Not cracking handshake because" + Color.pl('{!} {O}Not cracking handshake because' +
" wordlist {R}%s{O} was not found" % wordlist) ' wordlist {R}%s{O} was not found' % wordlist)
return None return None
Color.pl("\n{+} {C}Cracking WPA Handshake:{W} Using {C}aircrack-ng{W} via" + if not verbose:
" {C}%s{W} wordlist" % os.path.split(wordlist)[-1]) Color.pl('\n{+} {C}Cracking WPA Handshake:{W} Using {C}aircrack-ng{W} via' +
' {C}%s{W} wordlist' % os.path.split(wordlist)[-1])
key_file = Configuration.temp('wpakey.txt') key_file = Configuration.temp('wpakey.txt')
command = [ command = [
"aircrack-ng", 'aircrack-ng',
"-a", "2", '-a', '2',
"-w", wordlist, '-w', wordlist,
"--bssid", handshake.bssid, '--bssid', handshake.bssid,
"-l", key_file, '-l', key_file,
handshake.capfile handshake.capfile
] ]
if verbose:
Color.pl('{+} {D}Running: {W}{P}%s{W}' % ' '.join(command))
crack_proc = Process(command) crack_proc = Process(command)
# Report progress of cracking # Report progress of cracking
aircrack_nums_re = re.compile(r"(\d+)/(\d+) keys tested.*\(([\d.]+)\s+k/s") aircrack_nums_re = re.compile(r'(\d+)/(\d+) keys tested.*\(([\d.]+)\s+k/s')
aircrack_key_re = re.compile(r"Current passphrase:\s*([^\s].*[^\s])\s*$") aircrack_key_re = re.compile(r'Current passphrase:\s*([^\s].*[^\s])\s*$')
num_tried = num_total = 0 num_tried = num_total = 0
percent = num_kps = 0.0 percent = num_kps = 0.0
eta_str = "unknown" eta_str = 'unknown'
current_key = '' current_key = ''
while crack_proc.poll() is None: while crack_proc.poll() is None:
line = crack_proc.pid.stdout.readline() line = crack_proc.pid.stdout.readline()
@@ -198,26 +209,30 @@ class AttackWPA(Attack):
else: else:
continue continue
status = "\r{+} {C}Cracking WPA Handshake: %0.2f%%{W}" % percent status = '\r{+} {C}Cracking WPA Handshake: %0.2f%%{W}' % percent
status += " ETA: {C}%s{W}" % eta_str status += ' ETA: {C}%s{W}' % eta_str
status += " @ {C}%0.1fkps{W}" % num_kps status += ' @ {C}%0.1fkps{W}' % num_kps
#status += " ({C}%d{W}/{C}%d{W} keys)" % (num_tried, num_total) #status += ' ({C}%d{W}/{C}%d{W} keys)' % (num_tried, num_total)
status += " (current key: {C}%s{W})" % current_key status += ' (current key: {C}%s{W})' % current_key
Color.clear_entire_line() if not verbose:
Color.p(status) Color.clear_entire_line()
Color.p(status)
if not verbose:
Color.pl('')
Color.pl("")
# Check crack result # Check crack result
if os.path.exists(key_file): if os.path.exists(key_file):
with open(key_file, "r") as fid: with open(key_file, 'r') as fid:
key = fid.read().strip() key = fid.read().strip()
os.remove(key_file) os.remove(key_file)
Color.pl("{+} {G}Cracked WPA Handshake{W} PSK: {G}%s{W}\n" % key) if not verbose:
Color.pl('{+} {G}Cracked WPA Handshake{W} PSK: {G}%s{W}\n' % key)
return key return key
else: else:
Color.pl("{!} {R}Failed to crack handshake:" + if not verbose:
" {O}%s{R} did not contain password{W}" % wordlist.split(os.sep)[-1]) Color.pl('{!} {R}Failed to crack handshake: {O}%s{R} did not contain password{W}' % wordlist.split(os.sep)[-1])
return None return None
def load_handshake(self, bssid, essid): def load_handshake(self, bssid, essid):
@@ -250,14 +265,17 @@ class AttackWPA(Attack):
os.mkdir(Configuration.wpa_handshake_dir) os.mkdir(Configuration.wpa_handshake_dir)
# Generate filesystem-safe filename from bssid, essid and date # Generate filesystem-safe filename from bssid, essid and date
essid_safe = re.sub('[^a-zA-Z0-9]', '', handshake.essid) if handshake.essid and type(handshake.essid) is str:
essid_safe = re.sub('[^a-zA-Z0-9]', '', handshake.essid)
else:
essid_safe = 'UnknownEssid'
bssid_safe = handshake.bssid.replace(':', '-') bssid_safe = handshake.bssid.replace(':', '-')
date = time.strftime('%Y-%m-%dT%H-%M-%S') date = time.strftime('%Y-%m-%dT%H-%M-%S')
cap_filename = 'handshake_%s_%s_%s.cap' % (essid_safe, bssid_safe, date) cap_filename = 'handshake_%s_%s_%s.cap' % (essid_safe, bssid_safe, date)
cap_filename = os.path.join(Configuration.wpa_handshake_dir, cap_filename) cap_filename = os.path.join(Configuration.wpa_handshake_dir, cap_filename)
if Configuration.wpa_strip_handshake: if Configuration.wpa_strip_handshake:
Color.p("{+} {C}stripping{W} non-handshake packets, saving to {G}%s{W}..." % cap_filename) Color.p('{+} {C}stripping{W} non-handshake packets, saving to {G}%s{W}...' % cap_filename)
handshake.strip(outfile=cap_filename) handshake.strip(outfile=cap_filename)
Color.pl('{G}saved{W}') Color.pl('{G}saved{W}')
else: else:
@@ -279,25 +297,25 @@ class AttackWPA(Attack):
for index, client in enumerate([None] + self.clients): for index, client in enumerate([None] + self.clients):
if client is None: if client is None:
target_name = "*broadcast*" target_name = '*broadcast*'
else: else:
target_name = client target_name = client
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPA", Color.pattack('WPA',
target, target,
"Handshake capture", 'Handshake capture',
"Deauthing {O}%s{W}" % target_name) 'Deauthing {O}%s{W}' % target_name)
Aireplay.deauth(target.bssid, client_mac=client, timeout=2) Aireplay.deauth(target.bssid, client_mac=client, timeout=2)
if __name__ == '__main__': if __name__ == '__main__':
Configuration.initialize(True) Configuration.initialize(True)
from ..model.target import Target from ..model.target import Target
fields = "A4:2B:8C:16:6B:3A, 2015-05-27 19:28:44, 2015-05-27 19:28:46, 11, 54e,WPA, WPA, , -58, 2, 0, 0. 0. 0. 0, 9, Test Router Please Ignore, ".split(',') fields = 'A4:2B:8C:16:6B:3A, 2015-05-27 19:28:44, 2015-05-27 19:28:46, 11, 54e,WPA, WPA, , -58, 2, 0, 0. 0. 0. 0, 9, Test Router Please Ignore, '.split(',')
target = Target(fields) target = Target(fields)
wpa = AttackWPA(target) wpa = AttackWPA(target)
try: try:
wpa.run() wpa.run()
except KeyboardInterrupt: except KeyboardInterrupt:
Color.pl("") Color.pl('')
pass pass
Configuration.exit_gracefully(0) Configuration.exit_gracefully(0)

View File

@@ -4,8 +4,6 @@
from ..model.attack import Attack from ..model.attack import Attack
from ..util.color import Color from ..util.color import Color
from ..config import Configuration from ..config import Configuration
from ..tools.bully import Bully
from ..tools.reaver import Reaver
class AttackWPS(Attack): class AttackWPS(Attack):
def __init__(self, target): def __init__(self, target):
@@ -17,31 +15,45 @@ class AttackWPS(Attack):
''' Run all WPS-related attacks ''' ''' Run all WPS-related attacks '''
# Drop out if user specified to not use Reaver/Bully # Drop out if user specified to not use Reaver/Bully
if Configuration.use_pmkid_only:
self.success = False
return False
if Configuration.no_wps: if Configuration.no_wps:
Color.pl('\r{!} {O}--no-wps{R} set, ignoring WPS attack on {O}%s{W}' % self.target.essid) Color.pl('\r{!} {O}--no-wps{R} set, ignoring WPS attack on {O}%s{W}' % self.target.essid)
self.success = False self.success = False
return self.success return False
###################
# Pixie-Dust attack
if Configuration.use_bully: if Configuration.use_bully:
# Bully: Pixie-dust return self.run_bully()
bully = Bully(self.target)
bully.run()
bully.stop()
self.crack_result = bully.crack_result
self.success = self.crack_result is not None
return self.success
else: else:
reaver = Reaver(self.target) return self.run_reaver()
if reaver.is_pixiedust_supported():
# Reaver: Pixie-dust
reaver = Reaver(self.target)
reaver.run()
self.crack_result = reaver.crack_result
self.success = self.crack_result is not None
return self.success
else:
Color.pl("{!} {R}your version of 'reaver' does not support the {O}WPS pixie-dust attack{W}")
return False return False
def run_bully(self):
# Bully: Pixie-dust
from ..tools.bully import Bully
bully = Bully(self.target)
bully.run()
bully.stop()
self.crack_result = bully.crack_result
self.success = self.crack_result is not None
return self.success
def run_reaver(self):
from ..tools.reaver import Reaver
reaver = Reaver(self.target)
if not reaver.is_pixiedust_supported():
Color.pl('{!} {R}your version of "reaver" does not support the {O}WPS pixie-dust attack{W}')
return False
else:
# Reaver: Pixie-dust
reaver = Reaver(self.target)
reaver.run()
self.crack_result = reaver.crack_result
self.success = self.crack_result is not None
return self.success

View File

@@ -8,7 +8,7 @@ from .tools.macchanger import Macchanger
class Configuration(object): class Configuration(object):
''' Stores configuration variables and functions for Wifite. ''' ''' Stores configuration variables and functions for Wifite. '''
version = '2.1.7' version = '2.1.9'
initialized = False # Flag indicating config has been initialized initialized = False # Flag indicating config has been initialized
temp_dir = None # Temporary directory temp_dir = None # Temporary directory
@@ -66,7 +66,7 @@ class Configuration(object):
cls.require_fakeauth = False cls.require_fakeauth = False
cls.wep_restart_stale_ivs = 11 # Seconds to wait before restarting cls.wep_restart_stale_ivs = 11 # Seconds to wait before restarting
# Aireplay if IVs don't increaes. # Aireplay if IVs don't increaes.
# "0" means never restart. # '0' means never restart.
cls.wep_restart_aircrack = 30 # Seconds to give aircrack to crack cls.wep_restart_aircrack = 30 # Seconds to give aircrack to crack
# before restarting the process. # before restarting the process.
cls.wep_crack_at_ivs = 10000 # Number of IVS to start cracking cls.wep_crack_at_ivs = 10000 # Number of IVS to start cracking
@@ -76,9 +76,10 @@ class Configuration(object):
cls.wpa_filter = False # Only attack WPA networks cls.wpa_filter = False # Only attack WPA networks
cls.wpa_deauth_timeout = 15 # Wait time between deauths cls.wpa_deauth_timeout = 15 # Wait time between deauths
cls.wpa_attack_timeout = 500 # Wait time before failing cls.wpa_attack_timeout = 500 # Wait time before failing
cls.wpa_handshake_dir = "hs" # Dir to store handshakes cls.wpa_handshake_dir = 'hs' # Dir to store handshakes
cls.wpa_strip_handshake = False # Strip non-handshake packets cls.wpa_strip_handshake = False # Strip non-handshake packets
cls.ignore_old_handshakes = False # Always fetch a new handshake cls.ignore_old_handshakes = False # Always fetch a new handshake
cls.use_pmkid_only = False # Only use PMKID Capture+Crack attack
# Default dictionary for cracking # Default dictionary for cracking
cls.wordlist = None cls.wordlist = None
@@ -177,9 +178,11 @@ class Configuration(object):
Color.pl('{+} {C}option:{W} kill conflicting processes {G}enabled{W}') Color.pl('{+} {C}option:{W} kill conflicting processes {G}enabled{W}')
# EvilTwin # EvilTwin
'''
if args.use_eviltwin: if args.use_eviltwin:
cls.use_eviltwin = True cls.use_eviltwin = True
Color.pl('{+} {C}option:{W} using {G}eviltwin attacks{W} against all targets') Color.pl('{+} {C}option:{W} using {G}eviltwin attacks{W} against all targets')
'''
# WEP # WEP
if args.wep_filter: if args.wep_filter:
@@ -224,13 +227,16 @@ class Configuration(object):
Color.pl('{+} {C}option:{W} will stop WPA handshake capture after {G}%d seconds{W}' % args.wpa_attack_timeout) Color.pl('{+} {C}option:{W} will stop WPA handshake capture after {G}%d seconds{W}' % args.wpa_attack_timeout)
if args.ignore_old_handshakes: if args.ignore_old_handshakes:
cls.ignore_old_handshakes = True cls.ignore_old_handshakes = True
Color.pl("{+} {C}option:{W} will {O}ignore{W} existing handshakes (force capture)") Color.pl('{+} {C}option:{W} will {O}ignore{W} existing handshakes (force capture)')
if args.use_pmkid_only:
cls.use_pmkid_only = True
Color.pl('{+} {C}option:{W} will ONLY use {C}PMKID{W} attack on WPA networks')
if args.wpa_handshake_dir: if args.wpa_handshake_dir:
cls.wpa_handshake_dir = args.wpa_handshake_dir cls.wpa_handshake_dir = args.wpa_handshake_dir
Color.pl('{+} {C}option:{W} will store handshakes to {G}%s{W}' % args.wpa_handshake_dir) Color.pl('{+} {C}option:{W} will store handshakes to {G}%s{W}' % args.wpa_handshake_dir)
if args.wpa_strip_handshake: if args.wpa_strip_handshake:
cls.wpa_strip_handshake = True cls.wpa_strip_handshake = True
Color.pl("{+} {C}option:{W} will {G}strip{W} non-handshake packets") Color.pl('{+} {C}option:{W} will {G}strip{W} non-handshake packets')
# WPS # WPS
if args.wps_filter: if args.wps_filter:
@@ -364,7 +370,7 @@ class Configuration(object):
for (key,val) in sorted(cls.__dict__.items()): for (key,val) in sorted(cls.__dict__.items()):
if key.startswith('__') or type(val) == staticmethod or val is None: if key.startswith('__') or type(val) == staticmethod or val is None:
continue continue
result += Color.s("{G}%s {W} {C}%s{W}\n" % (key.ljust(max_len),val)) result += Color.s('{G}%s {W} {C}%s{W}\n' % (key.ljust(max_len),val))
return result return result
if __name__ == '__main__': if __name__ == '__main__':

0
wifite/model/__init__.py Normal file → Executable file
View File

View File

@@ -12,7 +12,7 @@ class Attack(object):
self.target = target self.target = target
def run(self): def run(self):
raise Exception("Unimplemented method: run") raise Exception('Unimplemented method: run')
def wait_for_target(self, airodump): def wait_for_target(self, airodump):
'''Waits for target to appear in airodump.''' '''Waits for target to appear in airodump.'''

View File

@@ -3,7 +3,7 @@
class Client(object): class Client(object):
''' '''
Holds details for a "Client" - a wireless device (e.g. computer) Holds details for a 'Client' - a wireless device (e.g. computer)
that is associated with an Access Point (e.g. router) that is associated with an Access Point (e.g. router)
''' '''

View File

@@ -9,19 +9,23 @@ from ..tools.pyrit import Pyrit
import re, os import re, os
class Handshake(object): class Handshake(object):
def __init__(self, capfile, bssid=None, essid=None): def __init__(self, capfile, bssid=None, essid=None):
self.capfile = capfile self.capfile = capfile
self.bssid = bssid self.bssid = bssid
self.essid = essid self.essid = essid
def divine_bssid_and_essid(self): def divine_bssid_and_essid(self):
''' '''
Tries to find BSSID and ESSID from cap file. Tries to find BSSID and ESSID from cap file.
Sets this instances 'bssid' and 'essid' instance fields. Sets this instances 'bssid' and 'essid' instance fields.
''' '''
# We can get BSSID from the .cap filename if Wifite captured it.
# ESSID is stripped of non-printable characters, so we can't rely on that.
if self.bssid is None: if self.bssid is None:
hs_regex = re.compile(r"^.*handshake_\w+_([0-9A-F\-]{17})_.*\.cap$", re.IGNORECASE) hs_regex = re.compile(r'^.*handshake_\w+_([0-9A-F\-]{17})_.*\.cap$', re.IGNORECASE)
match = hs_regex.match(self.capfile) match = hs_regex.match(self.capfile)
if match: if match:
self.bssid = match.group(1).replace('-', ':') self.bssid = match.group(1).replace('-', ':')
@@ -33,7 +37,8 @@ class Handshake(object):
pairs = self.pyrit_handshakes() # Find bssid/essid pairs that have handshakes in Pyrit pairs = self.pyrit_handshakes() # Find bssid/essid pairs that have handshakes in Pyrit
if len(pairs) == 0 and not self.bssid and not self.essid: if len(pairs) == 0 and not self.bssid and not self.essid:
raise Exception("Cannot find BSSID or ESSID in cap file") # Tshark and Pyrit failed us, nothing else we can do. # Tshark and Pyrit failed us, nothing else we can do.
raise Exception('Cannot find BSSID or ESSID in cap file')
if not self.essid and not self.bssid: if not self.essid and not self.bssid:
# We do not know the bssid nor the essid # We do not know the bssid nor the essid
@@ -60,6 +65,7 @@ class Handshake(object):
self.essid = essid self.essid = essid
break break
def has_handshake(self): def has_handshake(self):
if not self.bssid or not self.essid: if not self.bssid or not self.essid:
self.divine_bssid_and_essid() self.divine_bssid_and_essid()
@@ -75,27 +81,26 @@ class Handshake(object):
def tshark_handshakes(self): def tshark_handshakes(self):
''' Returns True if tshark identifies a handshake, False otherwise ''' '''Returns list[tuple] of BSSID & ESSID pairs (ESSIDs are always `None`).'''
tshark_bssids = Tshark.bssids_with_handshakes(self.capfile, bssid=self.bssid) tshark_bssids = Tshark.bssids_with_handshakes(self.capfile, bssid=self.bssid)
return [(bssid, None) for bssid in tshark_bssids] return [(bssid, None) for bssid in tshark_bssids]
def cowpatty_command(self): def cowpatty_handshakes(self):
return [ '''Returns list[tuple] of BSSID & ESSID pairs (BSSIDs are always `None`).'''
if not Process.exists('cowpatty'):
return []
if not self.essid:
return [] # We need a essid for cowpatty :(
command = [
'cowpatty', 'cowpatty',
'-r', self.capfile, '-r', self.capfile,
'-s', self.essid, '-s', self.essid,
'-c' # Check for handshake '-c' # Check for handshake
] ]
def cowpatty_handshakes(self): proc = Process(command, devnull=False)
''' Returns True if cowpatty identifies a handshake, False otherwise '''
if not Process.exists('cowpatty'):
return []
if not self.essid:
return [] # We need a essid for cowpatty :(
proc = Process(self.cowpatty_command(), devnull=False)
for line in proc.stdout().split('\n'): for line in proc.stdout().split('\n'):
if 'Collected all necessary data to mount crack against WPA' in line: if 'Collected all necessary data to mount crack against WPA' in line:
return [(None, self.essid)] return [(None, self.essid)]
@@ -103,14 +108,15 @@ class Handshake(object):
def pyrit_handshakes(self): def pyrit_handshakes(self):
''' Returns list of BSSID,ESSID tuples if pyrit identifies a handshake''' '''Returns list[tuple] of BSSID & ESSID pairs.'''
return Pyrit.bssid_essid_with_handshakes(self.capfile, bssid=self.bssid, essid=self.essid) return Pyrit.bssid_essid_with_handshakes(
self.capfile, bssid=self.bssid, essid=self.essid)
def aircrack_handshakes(self): def aircrack_handshakes(self):
'''Returns tuple (BSSID,None) if aircrack thinks self.capfile contains a handshake / can be cracked''' '''Returns tuple (BSSID,None) if aircrack thinks self.capfile contains a handshake / can be cracked'''
if not self.bssid: if not self.bssid:
return [] # Aircrack requires BSSID return [] # Aircrack requires BSSID
command = 'echo "" | aircrack-ng -a 2 -w - -b %s "%s"' % (self.bssid, self.capfile) command = 'echo "" | aircrack-ng -a 2 -w - -b %s "%s"' % (self.bssid, self.capfile)
(stdout, stderr) = Process.call(command) (stdout, stderr) = Process.call(command)
@@ -125,9 +131,15 @@ class Handshake(object):
'''Prints analysis of handshake capfile''' '''Prints analysis of handshake capfile'''
self.divine_bssid_and_essid() self.divine_bssid_and_essid()
Handshake.print_pairs(self.tshark_handshakes(), self.capfile, 'tshark') if Tshark.exists():
Handshake.print_pairs(self.pyrit_handshakes(), self.capfile, 'pyrit') Handshake.print_pairs(self.tshark_handshakes(), self.capfile, 'tshark')
Handshake.print_pairs(self.cowpatty_handshakes(), self.capfile, 'cowpatty')
if Pyrit.exists():
Handshake.print_pairs(self.pyrit_handshakes(), self.capfile, 'pyrit')
if Process.exists('cowpatty'):
Handshake.print_pairs(self.cowpatty_handshakes(), self.capfile, 'cowpatty')
Handshake.print_pairs(self.aircrack_handshakes(), self.capfile, 'aircrack') Handshake.print_pairs(self.aircrack_handshakes(), self.capfile, 'aircrack')
@@ -171,7 +183,7 @@ class Handshake(object):
tool_str = '{C}%s{W}: ' % tool.rjust(8) tool_str = '{C}%s{W}: ' % tool.rjust(8)
if len(pairs) == 0: if len(pairs) == 0:
Color.pl("{!} %s.cap file {R}does not{O} contain a valid handshake{W}" % (tool_str)) Color.pl('{!} %s.cap file {R}does not{O} contain a valid handshake{W}' % (tool_str))
return return
for (bssid, essid) in pairs: for (bssid, essid) in pairs:
@@ -208,24 +220,27 @@ class Handshake(object):
hs.analyze() hs.analyze()
Color.pl('') Color.pl('')
if __name__ == '__main__': if __name__ == '__main__':
print('With BSSID & ESSID specified:') print('With BSSID & ESSID specified:')
hs = Handshake('./tests/files/handshake_has_1234.cap', bssid='18:d6:c7:6d:6b:18', essid='YZWifi') hs = Handshake('./tests/files/handshake_has_1234.cap', bssid='18:d6:c7:6d:6b:18', essid='YZWifi')
hs.analyze() hs.analyze()
print("has_hanshake() =", hs.has_handshake()) print('has_hanshake() =', hs.has_handshake())
print('\nWith BSSID, but no ESSID specified:') print('\nWith BSSID, but no ESSID specified:')
hs = Handshake('./tests/files/handshake_has_1234.cap', bssid='18:d6:c7:6d:6b:18') hs = Handshake('./tests/files/handshake_has_1234.cap', bssid='18:d6:c7:6d:6b:18')
hs.analyze() hs.analyze()
print("has_hanshake() =", hs.has_handshake()) print('has_hanshake() =', hs.has_handshake())
print('\nWith ESSID, but no BSSID specified:') print('\nWith ESSID, but no BSSID specified:')
hs = Handshake('./tests/files/handshake_has_1234.cap', essid='YZWifi') hs = Handshake('./tests/files/handshake_has_1234.cap', essid='YZWifi')
hs.analyze() hs.analyze()
print("has_hanshake() =", hs.has_handshake()) print('has_hanshake() =', hs.has_handshake())
print('\nWith neither BSSID nor ESSID specified:') print('\nWith neither BSSID nor ESSID specified:')
hs = Handshake('./tests/files/handshake_has_1234.cap') hs = Handshake('./tests/files/handshake_has_1234.cap')
hs.analyze() try:
print("has_hanshake() =", hs.has_handshake()) hs.analyze()
print('has_hanshake() =', hs.has_handshake())
except Exception as e:
Color.pl('{O}Error during Handshake.analyze(): {R}%s{W}' % e)

7
wifite/model/pmkid_result.py Normal file → Executable file
View File

@@ -30,6 +30,13 @@ class CrackResultPMKID(CrackResult):
else: else:
Color.pl('{!} %s {O}key unknown{W}' % ''.rjust(19)) Color.pl('{!} %s {O}key unknown{W}' % ''.rjust(19))
def print_single_line(self, longest_essid):
self.print_single_line_prefix(longest_essid)
Color.p('{G}%s{W}' % 'PMKID'.ljust(5))
Color.p(' ')
Color.p('Key: {G}%s{W}' % self.key)
Color.pl('')
def to_dict(self): def to_dict(self):
return { return {
'type' : self.result_type, 'type' : self.result_type,

View File

@@ -11,16 +11,30 @@ class CrackResult(object):
''' Abstract class containing results from a crack session ''' ''' Abstract class containing results from a crack session '''
# File to save cracks to, in PWD # File to save cracks to, in PWD
cracked_file = "cracked.txt" cracked_file = 'cracked.txt'
def __init__(self): def __init__(self):
self.date = int(time.time()) self.date = int(time.time())
self.readable_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.date))
def dump(self): def dump(self):
raise Exception("Unimplemented method: dump()") raise Exception('Unimplemented method: dump()')
def to_dict(self): def to_dict(self):
raise Exception("Unimplemented method: to_dict()") raise Exception('Unimplemented method: to_dict()')
def print_single_line(self, longest_essid):
raise Exception('Unimplemented method: print_single_line()')
def print_single_line_prefix(self, longest_essid):
essid = self.essid if self.essid else 'N/A'
Color.p('{W} ')
Color.p('{C}%s{W}' % essid.ljust(longest_essid))
Color.p(' ')
Color.p('{GR}%s{W}' % self.bssid.ljust(17))
Color.p(' ')
Color.p('{D}%s{W}' % self.readable_date.ljust(19))
Color.p(' ')
def save(self): def save(self):
''' Adds this crack result to the cracked file and saves it. ''' ''' Adds this crack result to the cracked file and saves it. '''
@@ -52,18 +66,38 @@ class CrackResult(object):
if len(cracked_targets) == 0: if len(cracked_targets) == 0:
Color.pl('{!} {R}no results found in {O}%s{W}' % name) Color.pl('{!} {R}no results found in {O}%s{W}' % name)
else: return
Color.pl('{+} displaying {G}%d {C}cracked target(s){W}\n' % len(cracked_targets))
for item in cracked_targets: Color.pl('\n{+} Displaying {G}%d{W} cracked target(s) from {C}%s{W}\n' % (
cr = cls.load(item) len(cracked_targets), name))
cr.dump()
Color.pl('') results = sorted([cls.load(item) for item in cracked_targets], key=lambda x: x.date, reverse=True)
longest_essid = max([len(result.essid or 'ESSID') for result in results])
# Header
Color.p('{D} ')
Color.p('ESSID'.ljust(longest_essid))
Color.p(' ')
Color.p('BSSID'.ljust(17))
Color.p(' ')
Color.p('DATE'.ljust(19))
Color.p(' ')
Color.p('TYPE'.ljust(5))
Color.p(' ')
Color.p('KEY')
Color.pl('{D}')
Color.p(' ' + '-' * (longest_essid + 17 + 19 + 5 + 11 + 12))
Color.pl('{W}')
# Results
for result in results:
result.print_single_line(longest_essid)
Color.pl('')
@classmethod @classmethod
def load_all(cls): def load_all(cls):
if not os.path.exists(cls.cracked_file): return [] if not os.path.exists(cls.cracked_file): return []
with open(cls.cracked_file, "r") as json_file: with open(cls.cracked_file, 'r') as json_file:
json = loads(json_file.read()) json = loads(json_file.read())
return json return json
@@ -97,6 +131,7 @@ class CrackResult(object):
json['pmkid_file'], json['pmkid_file'],
json['key']) json['key'])
result.date = json['date'] result.date = json['date']
result.readable_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(result.date))
return result return result
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -7,7 +7,7 @@ import re
class Target(object): class Target(object):
''' '''
Holds details for a "Target" aka Access Point (e.g. router). Holds details for a 'Target' aka Access Point (e.g. router).
''' '''
def __init__(self, fields): def __init__(self, fields):
@@ -56,7 +56,7 @@ class Target(object):
if self.essid == '\\x00' * self.essid_len or \ if self.essid == '\\x00' * self.essid_len or \
self.essid == 'x00' * self.essid_len or \ self.essid == 'x00' * self.essid_len or \
self.essid.strip() == '': self.essid.strip() == '':
# Don't display "\x00..." for hidden ESSIDs # Don't display '\x00...' for hidden ESSIDs
self.essid = None # '(%s)' % self.bssid self.essid = None # '(%s)' % self.bssid
self.essid_known = False self.essid_known = False
@@ -70,26 +70,26 @@ class Target(object):
def validate(self): def validate(self):
''' Checks that the target is valid. ''' ''' Checks that the target is valid. '''
if self.channel == "-1": if self.channel == '-1':
raise Exception("Ignoring target with Negative-One (-1) channel") raise Exception('Ignoring target with Negative-One (-1) channel')
# Filter broadcast/multicast BSSIDs, see https://github.com/derv82/wifite2/issues/32 # Filter broadcast/multicast BSSIDs, see https://github.com/derv82/wifite2/issues/32
bssid_broadcast = re.compile(r"^(ff:ff:ff:ff:ff:ff|00:00:00:00:00:00)$", re.IGNORECASE) bssid_broadcast = re.compile(r'^(ff:ff:ff:ff:ff:ff|00:00:00:00:00:00)$', re.IGNORECASE)
if bssid_broadcast.match(self.bssid): if bssid_broadcast.match(self.bssid):
raise Exception("Ignoring target with Broadcast BSSID (%s)" % self.bssid) raise Exception('Ignoring target with Broadcast BSSID (%s)' % self.bssid)
bssid_multicast = re.compile(r"^(01:00:5e|01:80:c2|33:33)", re.IGNORECASE) bssid_multicast = re.compile(r'^(01:00:5e|01:80:c2|33:33)', re.IGNORECASE)
if bssid_multicast.match(self.bssid): if bssid_multicast.match(self.bssid):
raise Exception("Ignoring target with Multicast BSSID (%s)" % self.bssid) raise Exception('Ignoring target with Multicast BSSID (%s)' % self.bssid)
def to_str(self, show_bssid=False): def to_str(self, show_bssid=False):
''' '''
*Colored* string representation of this Target. *Colored* string representation of this Target.
Specifically formatted for the "scanning" table view. Specifically formatted for the 'scanning' table view.
''' '''
max_essid_len = 24 max_essid_len = 24
essid = self.essid if self.essid_known else "(%s)" % self.bssid essid = self.essid if self.essid_known else '(%s)' % self.bssid
# Trim ESSID (router name) if needed # Trim ESSID (router name) if needed
if len(essid) > max_essid_len: if len(essid) > max_essid_len:
essid = essid[0:max_essid_len-3] + '...' essid = essid[0:max_essid_len-3] + '...'
@@ -98,30 +98,30 @@ class Target(object):
if self.essid_known: if self.essid_known:
# Known ESSID # Known ESSID
essid = Color.s("{C}%s" % essid) essid = Color.s('{C}%s' % essid)
else: else:
# Unknown ESSID # Unknown ESSID
essid = Color.s("{O}%s" % essid) essid = Color.s('{O}%s' % essid)
# Add a "*" if we decloaked the ESSID # Add a '*' if we decloaked the ESSID
decloaked_char = '*' if self.decloaked else ' ' decloaked_char = '*' if self.decloaked else ' '
essid += Color.s("{P}%s" % decloaked_char) essid += Color.s('{P}%s' % decloaked_char)
if show_bssid: if show_bssid:
bssid = Color.s('{O}%s ' % self.bssid) bssid = Color.s('{O}%s ' % self.bssid)
else: else:
bssid = '' bssid = ''
channel_color = "{G}" channel_color = '{G}'
if int(self.channel) > 14: if int(self.channel) > 14:
channel_color = "{C}" channel_color = '{C}'
channel = Color.s("%s%s" % (channel_color, str(self.channel).rjust(3))) channel = Color.s('%s%s' % (channel_color, str(self.channel).rjust(3)))
encryption = self.encryption.rjust(4) encryption = self.encryption.rjust(4)
if 'WEP' in encryption: if 'WEP' in encryption:
encryption = Color.s("{G}%s" % encryption) encryption = Color.s('{G}%s' % encryption)
elif 'WPA' in encryption: elif 'WPA' in encryption:
encryption = Color.s("{O}%s" % encryption) encryption = Color.s('{O}%s' % encryption)
power = '%sdb' % str(self.power).rjust(3) power = '%sdb' % str(self.power).rjust(3)
if self.power > 50: if self.power > 50:
@@ -146,14 +146,14 @@ class Target(object):
result = '%s %s%s %s %s %s %s' % ( result = '%s %s%s %s %s %s %s' % (
essid, bssid, channel, encryption, power, wps, clients) essid, bssid, channel, encryption, power, wps, clients)
result += Color.s("{W}") result += Color.s('{W}')
return result return result
if __name__ == '__main__': if __name__ == '__main__':
fields = 'AA:BB:CC:DD:EE:FF,2015-05-27 19:28:44,2015-05-27 19:28:46,1,54,WPA2,CCMP TKIP,PSK,-58,2,0,0.0.0.0,9,HOME-ABCD,'.split(',') fields = 'AA:BB:CC:DD:EE:FF,2015-05-27 19:28:44,2015-05-27 19:28:46,1,54,WPA2,CCMP TKIP,PSK,-58,2,0,0.0.0.0,9,HOME-ABCD,'.split(',')
t = Target(fields) t = Target(fields)
t.clients.append("asdf") t.clients.append('asdf')
t.clients.append("asdf") t.clients.append('asdf')
print(t.to_str()) print(t.to_str())

View File

@@ -24,6 +24,15 @@ class CrackResultWEP(CrackResult):
if self.ascii_key: if self.ascii_key:
Color.pl('{+} Ascii Key: {G}%s{W}' % self.ascii_key) Color.pl('{+} Ascii Key: {G}%s{W}' % self.ascii_key)
def print_single_line(self, longest_essid):
self.print_single_line_prefix(longest_essid)
Color.p('{G}%s{W}' % 'WEP'.ljust(5))
Color.p(' ')
Color.p('Hex: {G}%s{W}' % self.hex_key.replace(':', ''))
if self.ascii_key:
Color.p(' (ASCII: {G}%s{W})' % self.ascii_key)
Color.pl('')
def to_dict(self): def to_dict(self):
return { return {
'type' : self.result_type, 'type' : self.result_type,

View File

@@ -30,6 +30,13 @@ class CrackResultWPA(CrackResult):
else: else:
Color.pl('{!} %s {O}key unknown{W}' % ''.rjust(19)) Color.pl('{!} %s {O}key unknown{W}' % ''.rjust(19))
def print_single_line(self, longest_essid):
self.print_single_line_prefix(longest_essid)
Color.p('{G}%s{W}' % 'WPA'.ljust(5))
Color.p(' ')
Color.p('Key: {G}%s{W}' % self.key)
Color.pl('')
def to_dict(self): def to_dict(self):
return { return {
'type' : self.result_type, 'type' : self.result_type,

View File

@@ -27,6 +27,15 @@ class CrackResultWPS(CrackResult):
Color.pl('{+} %s: {G}%s{W}' % ( 'WPS PIN'.rjust(12), self.pin)) Color.pl('{+} %s: {G}%s{W}' % ( 'WPS PIN'.rjust(12), self.pin))
Color.pl('{+} %s: {G}%s{W}' % ('PSK/Password'.rjust(12), psk)) Color.pl('{+} %s: {G}%s{W}' % ('PSK/Password'.rjust(12), psk))
def print_single_line(self, longest_essid):
self.print_single_line_prefix(longest_essid)
Color.p('{G}%s{W}' % 'WPS'.ljust(5))
Color.p(' ')
if self.psk:
Color.p('Key: {G}%s{W} ' % self.psk)
Color.p('PIN: {G}%s{W}' % self.pin)
Color.pl('')
def to_dict(self): def to_dict(self):
return { return {
'type' : self.result_type, 'type' : self.result_type,

View File

@@ -65,7 +65,7 @@ class Aircrack(Dependency):
hex_chars.append(byt) hex_chars.append(byt)
byt_int = int(byt, 16) byt_int = int(byt, 16)
if byt_int < 32 or byt_int > 127 or ascii_key is None: if byt_int < 32 or byt_int > 127 or ascii_key is None:
ascii_key = None # Not printable ascii_key = None # Not printable
else: else:
ascii_key += chr(byt_int) ascii_key += chr(byt_int)
@@ -91,17 +91,17 @@ if __name__ == '__main__':
Configuration.initialize(False) Configuration.initialize(False)
ivs_file = 'tests/files/wep-crackable.ivs' ivs_file = 'tests/files/wep-crackable.ivs'
print("Running aircrack on %s ..." % ivs_file) print('Running aircrack on %s ...' % ivs_file)
aircrack = Aircrack(ivs_file) aircrack = Aircrack(ivs_file)
while aircrack.is_running(): while aircrack.is_running():
sleep(1) sleep(1)
assert aircrack.is_cracked(), "Aircrack should have cracked %s" % ivs_file assert aircrack.is_cracked(), 'Aircrack should have cracked %s' % ivs_file
print("aircrack process completed.") print('aircrack process completed.')
(hexkey, asciikey) = aircrack.get_key_hex_ascii() (hexkey, asciikey) = aircrack.get_key_hex_ascii()
print("aircrack found HEX key: (%s) and ASCII key: (%s)" % (hexkey, asciikey)) print('aircrack found HEX key: (%s) and ASCII key: (%s)' % (hexkey, asciikey))
assert hexkey == '75:6E:63:6C:65', 'hexkey was "%s", expected "75:6E:63:6C:65"' % hexkey assert hexkey == '75:6E:63:6C:65', 'hexkey was "%s", expected "75:6E:63:6C:65"' % hexkey
assert asciikey == 'uncle', 'asciikey was "%s", expected "uncle"' % asciikey assert asciikey == 'uncle', 'asciikey was "%s", expected "uncle"' % asciikey

View File

@@ -36,7 +36,7 @@ class WEPAttackType(object):
self.name = name self.name = name
self.value = value self.value = value
return return
raise Exception("Attack number %d not found" % var) raise Exception('Attack number %d not found' % var)
elif type(var) is str: elif type(var) is str:
for (name,value) in WEPAttackType.__dict__.items(): for (name,value) in WEPAttackType.__dict__.items():
if type(value) is int: if type(value) is int:
@@ -44,12 +44,12 @@ class WEPAttackType(object):
self.name = name self.name = name
self.value = value self.value = value
return return
raise Exception("Attack name %s not found" % var) raise Exception('Attack name %s not found' % var)
elif type(var) == WEPAttackType: elif type(var) == WEPAttackType:
self.name = var.name self.name = var.name
self.value = var.value self.value = var.value
else: else:
raise Exception("Attack type not supported") raise Exception('Attack type not supported')
def __str__(self): def __str__(self):
return self.name return self.name
@@ -65,13 +65,13 @@ class Aireplay(Thread, Dependency):
Starts aireplay process. Starts aireplay process.
Args: Args:
target - Instance of Target object, AP to attack. target - Instance of Target object, AP to attack.
attack_type - str, e.g. "fakeauth", "arpreplay", etc. attack_type - str, e.g. 'fakeauth', 'arpreplay', etc.
client_mac - MAC address of an associated client. client_mac - MAC address of an associated client.
''' '''
super(Aireplay, self).__init__() # Init the parent Thread super(Aireplay, self).__init__() # Init the parent Thread
self.target = target self.target = target
self.output_file = Configuration.temp("aireplay_%s.output" % attack_type) self.output_file = Configuration.temp('aireplay_%s.output' % attack_type)
self.attack_type = WEPAttackType(attack_type).value self.attack_type = WEPAttackType(attack_type).value
self.error = None self.error = None
self.status = None self.status = None
@@ -90,7 +90,7 @@ class Aireplay(Thread, Dependency):
def stop(self): def stop(self):
''' Stops aireplay process ''' ''' Stops aireplay process '''
if hasattr(self, "pid") and self.pid and self.pid.poll() is None: if hasattr(self, 'pid') and self.pid and self.pid.poll() is None:
self.pid.interrupt() self.pid.interrupt()
def get_output(self): def get_output(self):
@@ -104,7 +104,7 @@ class Aireplay(Thread, Dependency):
time.sleep(0.1) time.sleep(0.1)
if not os.path.exists(self.output_file): continue if not os.path.exists(self.output_file): continue
# Read output file & clear output file # Read output file & clear output file
with open(self.output_file, "r+") as fid: with open(self.output_file, 'r+') as fid:
lines = fid.read() lines = fid.read()
self.stdout += lines self.stdout += lines
fid.seek(0) fid.seek(0)
@@ -114,51 +114,51 @@ class Aireplay(Thread, Dependency):
from ..util.color import Color from ..util.color import Color
Color.pl('\n{P} [?] aireplay output:\n %s{W}' % lines.strip().replace('\n', '\n ')) Color.pl('\n{P} [?] aireplay output:\n %s{W}' % lines.strip().replace('\n', '\n '))
for line in lines.split("\n"): for line in lines.split('\n'):
line = line.replace("\r", "").strip() line = line.replace('\r', '').strip()
if line == "": continue if line == '': continue
if "Notice: got a deauth/disassoc packet" in line: if 'Notice: got a deauth/disassoc packet' in line:
self.error = "Not associated (needs fakeauth)" self.error = 'Not associated (needs fakeauth)'
if self.attack_type == WEPAttackType.fakeauth: if self.attack_type == WEPAttackType.fakeauth:
# Look for fakeauth status. Potential Output lines: # Look for fakeauth status. Potential Output lines:
# (START): 00:54:58 Sending Authentication Request (Open System) # (START): 00:54:58 Sending Authentication Request (Open System)
if "Sending Authentication Request " in line: if 'Sending Authentication Request ' in line:
self.status = None # Reset self.status = None # Reset
# (????): Please specify an ESSID (-e). # (????): Please specify an ESSID (-e).
elif "Please specify an ESSID" in line: elif 'Please specify an ESSID' in line:
self.status = None self.status = None
# (FAIL): 00:57:43 Got a deauthentication packet! (Waiting 3 seconds) # (FAIL): 00:57:43 Got a deauthentication packet! (Waiting 3 seconds)
elif "Got a deauthentication packet!" in line: elif 'Got a deauthentication packet!' in line:
self.status = False self.status = False
# (PASS): 20:17:25 Association successful :-) (AID: 1) # (PASS): 20:17:25 Association successful :-) (AID: 1)
# (PASS): 20:18:55 Reassociation successful :-) (AID: 1) # (PASS): 20:18:55 Reassociation successful :-) (AID: 1)
elif "association successful :-)" in line.lower(): elif 'association successful :-)' in line.lower():
self.status = True self.status = True
elif self.attack_type == WEPAttackType.chopchop: elif self.attack_type == WEPAttackType.chopchop:
# Look for chopchop status. Potential output lines: # Look for chopchop status. Potential output lines:
# (START) Read 178 packets... # (START) Read 178 packets...
read_re = re.compile(r"Read (\d+) packets") read_re = re.compile(r'Read (\d+) packets')
matches = read_re.match(line) matches = read_re.match(line)
if matches: if matches:
self.status = "Waiting for packet (read %s)..." % matches.group(1) self.status = 'Waiting for packet (read %s)...' % matches.group(1)
# Sent 1912 packets, current guess: 70... # Sent 1912 packets, current guess: 70...
sent_re = re.compile(r"Sent (\d+) packets, current guess: (\w+)...") sent_re = re.compile(r'Sent (\d+) packets, current guess: (\w+)...')
matches = sent_re.match(line) matches = sent_re.match(line)
if matches: if matches:
self.status = "Generating .xor (%s)... current guess: %s" % (self.xor_percent, matches.group(2)) self.status = 'Generating .xor (%s)... current guess: %s' % (self.xor_percent, matches.group(2))
# (DURING) Offset 52 (54% done) | xor = DE | pt = E0 | 152 frames written in 2782ms # (DURING) Offset 52 (54% done) | xor = DE | pt = E0 | 152 frames written in 2782ms
offset_re = re.compile(r"Offset.*\(\s*(\d+%) done\)") offset_re = re.compile(r'Offset.*\(\s*(\d+%) done\)')
matches = offset_re.match(line) matches = offset_re.match(line)
if matches: if matches:
self.xor_percent = matches.group(1) self.xor_percent = matches.group(1)
self.status = "Generating .xor (%s)..." % self.xor_percent self.status = 'Generating .xor (%s)...' % self.xor_percent
# (DONE) Saving keystream in replay_dec-0516-202246.xor # (DONE) Saving keystream in replay_dec-0516-202246.xor
saving_re = re.compile(r"Saving keystream in (.*\.xor)") saving_re = re.compile(r'Saving keystream in (.*\.xor)')
matches = saving_re.match(line) matches = saving_re.match(line)
if matches: if matches:
self.status = matches.group(1) self.status = matches.group(1)
@@ -171,17 +171,17 @@ class Aireplay(Thread, Dependency):
# Parse fragment output, update self.status # Parse fragment output, update self.status
# (START) Read 178 packets... # (START) Read 178 packets...
read_re = re.compile(r"Read (\d+) packets") read_re = re.compile(r'Read (\d+) packets')
matches = read_re.match(line) matches = read_re.match(line)
if matches: if matches:
self.status = "Waiting for packet (read %s)..." % matches.group(1) self.status = 'Waiting for packet (read %s)...' % matches.group(1)
# 01:08:15 Waiting for a data packet... # 01:08:15 Waiting for a data packet...
if 'Waiting for a data packet' in line: if 'Waiting for a data packet' in line:
self.status = 'waiting for packet' self.status = 'waiting for packet'
# Read 207 packets... # Read 207 packets...
trying_re = re.compile(r"Trying to get (\d+) bytes of a keystream") trying_re = re.compile(r'Trying to get (\d+) bytes of a keystream')
matches = trying_re.match(line) matches = trying_re.match(line)
if matches: if matches:
self.status = 'trying to get %sb of a keystream' % matches.group(1) self.status = 'trying to get %sb of a keystream' % matches.group(1)
@@ -195,7 +195,7 @@ class Aireplay(Thread, Dependency):
self.status = 'sending another packet' self.status = 'sending another packet'
# XX:XX:XX Trying to get 1500 bytes of a keystream # XX:XX:XX Trying to get 1500 bytes of a keystream
trying_re = re.compile(r"Trying to get (\d+) bytes of a keystream") trying_re = re.compile(r'Trying to get (\d+) bytes of a keystream')
matches = trying_re.match(line) matches = trying_re.match(line)
if matches: if matches:
self.status = 'trying to get %sb of a keystream' % matches.group(1) self.status = 'trying to get %sb of a keystream' % matches.group(1)
@@ -209,7 +209,7 @@ class Aireplay(Thread, Dependency):
self.status = 'relayed packet was our' self.status = 'relayed packet was our'
# XX:XX:XX Saving keystream in fragment-0124-161129.xor # XX:XX:XX Saving keystream in fragment-0124-161129.xor
saving_re = re.compile(r"Saving keystream in (.*\.xor)") saving_re = re.compile(r'Saving keystream in (.*\.xor)')
matches = saving_re.match(line) matches = saving_re.match(line)
if matches: if matches:
self.status = 'saving keystream to %s' % matches.group(1) self.status = 'saving keystream to %s' % matches.group(1)
@@ -220,14 +220,14 @@ class Aireplay(Thread, Dependency):
# Parse Packets Sent & PacketsPerSecond. Possible output lines: # Parse Packets Sent & PacketsPerSecond. Possible output lines:
# Read 55 packets (got 0 ARP requests and 0 ACKs), sent 0 packets...(0 pps) # Read 55 packets (got 0 ARP requests and 0 ACKs), sent 0 packets...(0 pps)
# Read 4467 packets (got 1425 ARP requests and 1417 ACKs), sent 1553 packets...(100 pps) # Read 4467 packets (got 1425 ARP requests and 1417 ACKs), sent 1553 packets...(100 pps)
read_re = re.compile(r"Read (\d+) packets \(got (\d+) ARP requests and (\d+) ACKs\), sent (\d+) packets...\((\d+) pps\)") read_re = re.compile(r'Read (\d+) packets \(got (\d+) ARP requests and (\d+) ACKs\), sent (\d+) packets...\((\d+) pps\)')
matches = read_re.match(line) matches = read_re.match(line)
if matches: if matches:
pps = matches.group(5) pps = matches.group(5)
if pps == "0": if pps == '0':
self.status = "Waiting for packet..." self.status = 'Waiting for packet...'
else: else:
self.status = "Replaying @ %s/sec" % pps self.status = 'Replaying @ %s/sec' % pps
pass pass
def __del__(self): def __del__(self):
@@ -248,10 +248,10 @@ class Aireplay(Thread, Dependency):
# Interface is required at this point # Interface is required at this point
Configuration.initialize() Configuration.initialize()
if Configuration.interface is None: if Configuration.interface is None:
raise Exception("Wireless interface must be defined (-i)") raise Exception('Wireless interface must be defined (-i)')
cmd = ["aireplay-ng"] cmd = ['aireplay-ng']
cmd.append("--ignore-negative-one") cmd.append('--ignore-negative-one')
if client_mac is None and len(target.clients) > 0: if client_mac is None and len(target.clients) > 0:
# Client MAC wasn't specified, but there's an associated client. Use that. # Client MAC wasn't specified, but there's an associated client. Use that.
@@ -263,87 +263,87 @@ class Aireplay(Thread, Dependency):
if attack_type == WEPAttackType.fakeauth: if attack_type == WEPAttackType.fakeauth:
cmd.extend([ cmd.extend([
"--fakeauth", "30", # Fake auth every 30 seconds '--fakeauth', '30', # Fake auth every 30 seconds
"-Q", # Send re-association packets '-Q', # Send re-association packets
"-a", target.bssid '-a', target.bssid
]) ])
if target.essid_known: if target.essid_known:
cmd.extend(["-e", target.essid]) cmd.extend(['-e', target.essid])
elif attack_type == WEPAttackType.replay: elif attack_type == WEPAttackType.replay:
cmd.extend([ cmd.extend([
"--arpreplay", '--arpreplay',
"-b", target.bssid, '-b', target.bssid,
"-x", str(Configuration.wep_pps) '-x', str(Configuration.wep_pps)
]) ])
if client_mac: if client_mac:
cmd.extend(["-h", client_mac]) cmd.extend(['-h', client_mac])
elif attack_type == WEPAttackType.chopchop: elif attack_type == WEPAttackType.chopchop:
cmd.extend([ cmd.extend([
"--chopchop", '--chopchop',
"-b", target.bssid, '-b', target.bssid,
"-x", str(Configuration.wep_pps), '-x', str(Configuration.wep_pps),
#"-m", "60", # Minimum packet length (bytes) #'-m', '60', # Minimum packet length (bytes)
#"-n", "82", # Maximum packet length #'-n', '82', # Maximum packet length
"-F" # Automatically choose first packet '-F' # Automatically choose first packet
]) ])
if client_mac: if client_mac:
cmd.extend(["-h", client_mac]) cmd.extend(['-h', client_mac])
elif attack_type == WEPAttackType.fragment: elif attack_type == WEPAttackType.fragment:
cmd.extend([ cmd.extend([
"--fragment", '--fragment',
"-b", target.bssid, '-b', target.bssid,
"-x", str(Configuration.wep_pps), '-x', str(Configuration.wep_pps),
"-m", "100", # Minimum packet length (bytes) '-m', '100', # Minimum packet length (bytes)
"-F" # Automatically choose first packet '-F' # Automatically choose first packet
]) ])
if client_mac: if client_mac:
cmd.extend(["-h", client_mac]) cmd.extend(['-h', client_mac])
elif attack_type == WEPAttackType.caffelatte: elif attack_type == WEPAttackType.caffelatte:
if len(target.clients) == 0: if len(target.clients) == 0:
# Unable to carry out caffe-latte attack # Unable to carry out caffe-latte attack
raise Exception("Client is required for caffe-latte attack") raise Exception('Client is required for caffe-latte attack')
cmd.extend([ cmd.extend([
"--caffe-latte", '--caffe-latte',
"-b", target.bssid, '-b', target.bssid,
"-h", target.clients[0].station '-h', target.clients[0].station
]) ])
elif attack_type == WEPAttackType.p0841: elif attack_type == WEPAttackType.p0841:
cmd.extend([ cmd.extend([
"--arpreplay", '--arpreplay',
"-b", target.bssid, '-b', target.bssid,
"-c", "ff:ff:ff:ff:ff:ff", '-c', 'ff:ff:ff:ff:ff:ff',
"-x", str(Configuration.wep_pps), '-x', str(Configuration.wep_pps),
"-F", # Automatically choose first packet '-F', # Automatically choose first packet
"-p", "0841" '-p', '0841'
]) ])
if client_mac: if client_mac:
cmd.extend(["-h", client_mac]) cmd.extend(['-h', client_mac])
elif attack_type == WEPAttackType.hirte: elif attack_type == WEPAttackType.hirte:
if client_mac is None: if client_mac is None:
# Unable to carry out hirte attack # Unable to carry out hirte attack
raise Exception("Client is required for hirte attack") raise Exception('Client is required for hirte attack')
cmd.extend([ cmd.extend([
"--cfrag", '--cfrag',
"-h", client_mac '-h', client_mac
]) ])
elif attack_type == WEPAttackType.forgedreplay: elif attack_type == WEPAttackType.forgedreplay:
if client_mac is None or replay_file is None: if client_mac is None or replay_file is None:
raise Exception("Client_mac and Replay_File are required for arp replay") raise Exception('Client_mac and Replay_File are required for arp replay')
cmd.extend([ cmd.extend([
"--arpreplay", '--arpreplay',
"-b", target.bssid, '-b', target.bssid,
"-h", client_mac, '-h', client_mac,
"-r", replay_file, '-r', replay_file,
"-F", # Automatically choose first packet '-F', # Automatically choose first packet
"-x", str(Configuration.wep_pps) '-x', str(Configuration.wep_pps)
]) ])
else: else:
raise Exception("Unexpected attack type: %s" % attack_type) raise Exception('Unexpected attack type: %s' % attack_type)
cmd.append(Configuration.interface) cmd.append(Configuration.interface)
return cmd return cmd
@@ -388,18 +388,18 @@ class Aireplay(Thread, Dependency):
def deauth(target_bssid, essid=None, client_mac=None, num_deauths=None, timeout=2): def deauth(target_bssid, essid=None, client_mac=None, num_deauths=None, timeout=2):
num_deauths = num_deauths or Configuration.num_deauths num_deauths = num_deauths or Configuration.num_deauths
deauth_cmd = [ deauth_cmd = [
"aireplay-ng", 'aireplay-ng',
"-0", # Deauthentication '-0', # Deauthentication
str(num_deauths), str(num_deauths),
"--ignore-negative-one", '--ignore-negative-one',
"-a", target_bssid, # Target AP '-a', target_bssid, # Target AP
"-D" # Skip AP detection '-D' # Skip AP detection
] ]
if client_mac is not None: if client_mac is not None:
# Station-specific deauth # Station-specific deauth
deauth_cmd.extend(["-c", client_mac]) deauth_cmd.extend(['-c', client_mac])
if essid: if essid:
deauth_cmd.extend(["-e", essid]) deauth_cmd.extend(['-e', essid])
deauth_cmd.append(Configuration.interface) deauth_cmd.append(Configuration.interface)
proc = Process(deauth_cmd) proc = Process(deauth_cmd)
while proc.poll() is None: while proc.poll() is None:
@@ -450,23 +450,3 @@ if __name__ == '__main__':
t = WEPAttackType(t) t = WEPAttackType(t)
print(t.name, type(t.name), t.value) print(t.name, type(t.name), t.value)
from ..model.target import Target
fields = 'A4:2B:8C:16:6B:3A, 2015-05-27 19:28:44, 2015-05-27 19:28:46, 6, 54e, WEP, WEP, , -58, 2, 0, 0. 0. 0. 0, 9, Test Router Please Ignore, '.split(',')
t = Target(fields)
'''
aireplay = Aireplay(t, 'replay')
while aireplay.is_running():
from time import sleep
sleep(0.1)
stdout, stderr = aireplay.get_output()
print("STDOUT>", stdout)
print("STDERR>", stderr)
'''
'''
forge = Aireplay.forge_packet('/tmp/replay_dec-0605-060243.xor', \
'A4:2B:8C:16:6B:3A', \
'00:C0:CA:4E:CA:E0')
print(forge)
'''

View File

@@ -75,7 +75,7 @@ class Airmon(Dependency):
''' Prints menu ''' ''' Prints menu '''
print(AirmonIface.menu_header()) print(AirmonIface.menu_header())
for idx, iface in enumerate(self.interfaces, start=1): for idx, iface in enumerate(self.interfaces, start=1):
Color.pl(" {G}%d{W}. %s" % (idx, iface)) Color.pl(' {G}%d{W}. %s' % (idx, iface))
def get(self, index): def get(self, index):
''' Gets interface at index (starts at 1) ''' ''' Gets interface at index (starts at 1) '''
@@ -166,10 +166,10 @@ class Airmon(Dependency):
iface_name = iface iface_name = iface
driver = None driver = None
# Remember this as the "base" interface. # Remember this as the 'base' interface.
Airmon.base_interface = iface_name Airmon.base_interface = iface_name
Color.p("{+} enabling {G}monitor mode{W} on {C}%s{W}... " % iface_name) Color.p('{+} enabling {G}monitor mode{W} on {C}%s{W}... ' % iface_name)
airmon_output = Process(['airmon-ng', 'start', iface_name]).stdout() airmon_output = Process(['airmon-ng', 'start', iface_name]).stdout()
@@ -180,22 +180,22 @@ class Airmon(Dependency):
enabled_iface = Airmon.start_bad_driver(iface_name) enabled_iface = Airmon.start_bad_driver(iface_name)
if enabled_iface is None: if enabled_iface is None:
Color.pl("{R}failed{W}") Color.pl('{R}failed{W}')
monitor_interfaces = Iwconfig.get_interfaces(mode='Monitor') monitor_interfaces = Iwconfig.get_interfaces(mode='Monitor')
# Assert that there is an interface in monitor mode # Assert that there is an interface in monitor mode
if len(monitor_interfaces) == 0: if len(monitor_interfaces) == 0:
Color.pl("{R}failed{W}") Color.pl('{R}failed{W}')
raise Exception("Cannot find any interfaces in Mode:Monitor") raise Exception('Cannot find any interfaces in Mode:Monitor')
# Assert that the interface enabled by airmon-ng is in monitor mode # Assert that the interface enabled by airmon-ng is in monitor mode
if enabled_iface not in monitor_interfaces: if enabled_iface not in monitor_interfaces:
Color.pl("{R}failed{W}") Color.pl('{R}failed{W}')
raise Exception("Cannot find %s with Mode:Monitor" % enabled_iface) raise Exception('Cannot find %s with Mode:Monitor' % enabled_iface)
# No errors found; the device 'enabled_iface' was put into Mode:Monitor. # No errors found; the device 'enabled_iface' was put into Mode:Monitor.
Color.pl("{G}enabled {C}%s{W}" % enabled_iface) Color.pl('{G}enabled {C}%s{W}' % enabled_iface)
return enabled_iface return enabled_iface
@@ -216,7 +216,7 @@ class Airmon(Dependency):
@staticmethod @staticmethod
def stop(iface): def stop(iface):
Color.p("{!} {R}disabling {O}monitor mode{O} on {R}%s{O}... " % iface) Color.p('{!} {R}disabling {O}monitor mode{O} on {R}%s{O}... ' % iface)
airmon_output = Process(['airmon-ng', 'stop', iface]).stdout() airmon_output = Process(['airmon-ng', 'stop', iface]).stdout()
@@ -307,7 +307,7 @@ class Airmon(Dependency):
choice = 1 choice = 1
else: else:
# Multiple interfaces found # Multiple interfaces found
question = Color.s("{+} select interface ({G}1-%d{W}): " % (count)) question = Color.s('{+} select interface ({G}1-%d{W}): ' % (count))
choice = raw_input(question) choice = raw_input(question)
iface = a.get(choice) iface = a.get(choice)
@@ -368,26 +368,26 @@ class Airmon(Dependency):
@staticmethod @staticmethod
def put_interface_up(iface): def put_interface_up(iface):
Color.p("{!} {O}putting interface {R}%s up{O}..." % (iface)) Color.p('{!} {O}putting interface {R}%s up{O}...' % (iface))
Ifconfig.up(iface) Ifconfig.up(iface)
Color.pl(" {G}done{W}") Color.pl(' {G}done{W}')
@staticmethod @staticmethod
def start_network_manager(): def start_network_manager():
Color.p("{!} {O}restarting {R}NetworkManager{O}...") Color.p('{!} {O}restarting {R}NetworkManager{O}...')
if Process.exists('service'): if Process.exists('service'):
cmd = 'service network-manager start' cmd = 'service network-manager start'
proc = Process(cmd) proc = Process(cmd)
(out, err) = proc.get_output() (out, err) = proc.get_output()
if proc.poll() != 0: if proc.poll() != 0:
Color.pl(" {R}Error executing {O}%s{W}" % cmd) Color.pl(' {R}Error executing {O}%s{W}' % cmd)
if out is not None and out.strip() != "": if out is not None and out.strip() != '':
Color.pl("{!} {O}STDOUT> %s{W}" % out) Color.pl('{!} {O}STDOUT> %s{W}' % out)
if err is not None and err.strip() != "": if err is not None and err.strip() != '':
Color.pl("{!} {O}STDERR> %s{W}" % err) Color.pl('{!} {O}STDERR> %s{W}' % err)
else: else:
Color.pl(" {G}done{W} ({C}%s{W})" % cmd) Color.pl(' {G}done{W} ({C}%s{W})' % cmd)
return return
if Process.exists('systemctl'): if Process.exists('systemctl'):
@@ -395,20 +395,20 @@ class Airmon(Dependency):
proc = Process(cmd) proc = Process(cmd)
(out, err) = proc.get_output() (out, err) = proc.get_output()
if proc.poll() != 0: if proc.poll() != 0:
Color.pl(" {R}Error executing {O}%s{W}" % cmd) Color.pl(' {R}Error executing {O}%s{W}' % cmd)
if out is not None and out.strip() != "": if out is not None and out.strip() != '':
Color.pl("{!} {O}STDOUT> %s{W}" % out) Color.pl('{!} {O}STDOUT> %s{W}' % out)
if err is not None and err.strip() != "": if err is not None and err.strip() != '':
Color.pl("{!} {O}STDERR> %s{W}" % err) Color.pl('{!} {O}STDERR> %s{W}' % err)
else: else:
Color.pl(" {G}done{W} ({C}%s{W})" % cmd) Color.pl(' {G}done{W} ({C}%s{W})' % cmd)
return return
else: else:
Color.pl(" {R}can't restart NetworkManager: {O}systemctl{R} or {O}service{R} not found{W}") Color.pl(' {R}cannot restart NetworkManager: {O}systemctl{R} or {O}service{R} not found{W}')
if __name__ == '__main__': if __name__ == '__main__':
Airmon.terminate_conflicting_processes() Airmon.terminate_conflicting_processes()
iface = Airmon.ask() iface = Airmon.ask()
(disabled_iface, enabled_iface) = Airmon.stop(iface) (disabled_iface, enabled_iface) = Airmon.stop(iface)
print("Disabled:", disabled_iface) print('Disabled:', disabled_iface)
print("Enabled:", enabled_iface) print('Enabled:', enabled_iface)

View File

@@ -27,7 +27,7 @@ class Airodump(Dependency):
if interface is None: if interface is None:
interface = Configuration.interface interface = Configuration.interface
if interface is None: if interface is None:
raise Exception("Wireless interface must be defined (-i)") raise Exception('Wireless interface must be defined (-i)')
self.interface = interface self.interface = interface
self.targets = [] self.targets = []
@@ -206,22 +206,22 @@ class Airodump(Dependency):
hit_clients = False hit_clients = False
for row in csv_reader: for row in csv_reader:
# Each "row" is a list of fields for a target/client # Each 'row' is a list of fields for a target/client
if len(row) == 0: continue if len(row) == 0: continue
if row[0].strip() == 'BSSID': if row[0].strip() == 'BSSID':
# This is the "header" for the list of Targets # This is the 'header' for the list of Targets
hit_clients = False hit_clients = False
continue continue
elif row[0].strip() == 'Station MAC': elif row[0].strip() == 'Station MAC':
# This is the "header" for the list of Clients # This is the 'header' for the list of Clients
hit_clients = True hit_clients = True
continue continue
if hit_clients: if hit_clients:
# The current row corresponds to a "Client" (computer) # The current row corresponds to a 'Client' (computer)
try: try:
client = Client(row) client = Client(row)
except (IndexError, ValueError) as e: except (IndexError, ValueError) as e:
@@ -239,7 +239,7 @@ class Airodump(Dependency):
break break
else: else:
# The current row corresponds to a "Target" (router) # The current row corresponds to a 'Target' (router)
try: try:
target = Target(row) target = Target(row)
targets.append(target) targets.append(target)

View File

@@ -23,7 +23,7 @@ class Bully(Attack, Dependency):
self.total_timeouts = 0 self.total_timeouts = 0
self.total_failures = 0 self.total_failures = 0
self.locked = False self.locked = False
self.state = "{O}Waiting for beacon{W}" self.state = '{O}Waiting for beacon{W}'
self.start_time = time.time() self.start_time = time.time()
self.cracked_pin = self.cracked_key = self.cracked_bssid = self.cracked_essid = None self.cracked_pin = self.cracked_key = self.cracked_bssid = self.cracked_essid = None
@@ -35,17 +35,17 @@ class Bully(Attack, Dependency):
if Process.exists('stdbuf'): if Process.exists('stdbuf'):
self.cmd.extend([ self.cmd.extend([
"stdbuf", "-o0" # No buffer. See https://stackoverflow.com/a/40453613/7510292 'stdbuf', '-o0' # No buffer. See https://stackoverflow.com/a/40453613/7510292
]) ])
self.cmd.extend([ self.cmd.extend([
"bully", 'bully',
"--bssid", target.bssid, '--bssid', target.bssid,
"--channel", target.channel, '--channel', target.channel,
"--detectlock", # Detect WPS lockouts unreported by AP '--detectlock', # Detect WPS lockouts unreported by AP
"--force", '--force',
"-v", "4", '-v', '4',
"--pixiewps", '--pixiewps',
Configuration.interface Configuration.interface
]) ])
@@ -58,7 +58,7 @@ class Bully(Attack, Dependency):
skip_wps=True, skip_wps=True,
output_file_prefix='wps_pin') as airodump: output_file_prefix='wps_pin') as airodump:
# Wait for target # Wait for target
self.pattack("Waiting for target to appear...") self.pattack('Waiting for target to appear...')
self.target = self.wait_for_target(airodump) self.target = self.wait_for_target(airodump)
# Start bully # Start bully
@@ -111,7 +111,7 @@ class Bully(Attack, Dependency):
raise e raise e
if self.crack_result is None: if self.crack_result is None:
self.pattack("{R}Failed{W}", newline=True) self.pattack('{R}Failed{W}', newline=True)
def pattack(self, message, newline=False): def pattack(self, message, newline=False):
@@ -119,12 +119,12 @@ class Bully(Attack, Dependency):
time_left = Configuration.wps_pixie_timeout - self.running_time() time_left = Configuration.wps_pixie_timeout - self.running_time()
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPS", Color.pattack('WPS',
self.target, self.target,
'Pixie-Dust', 'Pixie-Dust',
'{W}[{C}%s{W}] %s' % (Timer.secs_to_str(time_left), message)) '{W}[{C}%s{W}] %s' % (Timer.secs_to_str(time_left), message))
if newline: if newline:
Color.pl("") Color.pl('')
def running_time(self): def running_time(self):
@@ -136,13 +136,13 @@ class Bully(Attack, Dependency):
meta_statuses = [] meta_statuses = []
if self.total_timeouts > 0: if self.total_timeouts > 0:
meta_statuses.append("{O}Timeouts:%d{W}" % self.total_timeouts) meta_statuses.append('{O}Timeouts:%d{W}' % self.total_timeouts)
if self.total_failures > 0: if self.total_failures > 0:
meta_statuses.append("{O}WPSFail:%d{W}" % self.total_failures) meta_statuses.append('{O}WPSFail:%d{W}' % self.total_failures)
if self.locked: if self.locked:
meta_statuses.append("{R}Locked{W}") meta_statuses.append('{R}Locked{W}')
if len(meta_statuses) > 0: if len(meta_statuses) > 0:
main_status += ' (%s)' % ', '.join(meta_statuses) main_status += ' (%s)' % ', '.join(meta_statuses)
@@ -151,9 +151,9 @@ class Bully(Attack, Dependency):
def parse_line_thread(self): def parse_line_thread(self):
for line in iter(self.bully_proc.pid.stdout.readline, b""): for line in iter(self.bully_proc.pid.stdout.readline, b''):
if line == "": continue if line == '': continue
line = line.replace("\r", "").replace("\n", "").strip() line = line.replace('\r', '').replace('\n', '').strip()
if Configuration.verbose > 1: if Configuration.verbose > 1:
Color.pe('\n{P} [bully:stdout] %s' % line) Color.pe('\n{P} [bully:stdout] %s' % line)
@@ -189,9 +189,9 @@ class Bully(Attack, Dependency):
if self.cracked_pin is not None: if self.cracked_pin is not None:
# Mention the PIN & that we're not done yet. # Mention the PIN & that we're not done yet.
self.pattack("{G}Cracked PIN: {C}%s{W}" % self.cracked_pin, newline=True) self.pattack('{G}Cracked PIN: {C}%s{W}' % self.cracked_pin, newline=True)
self.state = "{G}Finding PSK...{C}" self.state = '{G}Finding PSK...{C}'
time.sleep(2) time.sleep(2)
########################### ###########################
@@ -201,13 +201,13 @@ class Bully(Attack, Dependency):
self.cracked_key = key_re.group(1) self.cracked_key = key_re.group(1)
if not self.crack_result and self.cracked_pin and self.cracked_key: if not self.crack_result and self.cracked_pin and self.cracked_key:
self.pattack("{G}Cracked PSK: {C}%s{W}" % self.cracked_key, newline=True) self.pattack('{G}Cracked PSK: {C}%s{W}' % self.cracked_key, newline=True)
self.crack_result = CrackResultWPS( self.crack_result = CrackResultWPS(
self.target.bssid, self.target.bssid,
self.target.essid, self.target.essid,
self.cracked_pin, self.cracked_pin,
self.cracked_key) self.cracked_key)
Color.pl("") Color.pl('')
self.crack_result.dump() self.crack_result.dump()
return self.crack_result return self.crack_result
@@ -220,14 +220,14 @@ class Bully(Attack, Dependency):
got_beacon = re.search(r".*Got beacon for '(.*)' \((.*)\)", line) got_beacon = re.search(r".*Got beacon for '(.*)' \((.*)\)", line)
if got_beacon: if got_beacon:
# group(1)=ESSID, group(2)=BSSID # group(1)=ESSID, group(2)=BSSID
state = "Got beacon" state = 'Got beacon'
# [+] Last State = 'NoAssoc' Next pin '48855501' # [+] Last State = 'NoAssoc' Next pin '48855501'
last_state = re.search(r".*Last State = '(.*)'\s*Next pin '(.*)'", line) last_state = re.search(r".*Last State = '(.*)'\s*Next pin '(.*)'", line)
if last_state: if last_state:
# group(1)=result, group(2)=PIN # group(1)=result, group(2)=PIN
pin = last_state.group(2) pin = last_state.group(2)
state = "Trying PIN {C}%s{W} (%s)" % (pin, last_state.group(1)) state = 'Trying PIN {C}%s{W} (%s)' % (pin, last_state.group(1))
# [+] Tx( Auth ) = 'Timeout' Next pin '80241263' # [+] Tx( Auth ) = 'Timeout' Next pin '80241263'
mx_result_pin = re.search(r".*[RT]x\(\s*(.*)\s*\) = '(.*)'\s*Next pin '(.*)'", line) mx_result_pin = re.search(r".*[RT]x\(\s*(.*)\s*\) = '(.*)'\s*Next pin '(.*)'", line)
@@ -238,42 +238,42 @@ class Bully(Attack, Dependency):
result = mx_result_pin.group(2) # NoAssoc, WPSFail, Pin1Bad, Pin2Bad result = mx_result_pin.group(2) # NoAssoc, WPSFail, Pin1Bad, Pin2Bad
pin = mx_result_pin.group(3) pin = mx_result_pin.group(3)
if result == "Timeout": if result == 'Timeout':
self.total_timeouts += 1 self.total_timeouts += 1
result = "{O}%s{W}" % result result = '{O}%s{W}' % result
elif result == "WPSFail": elif result == 'WPSFail':
self.total_failures += 1 self.total_failures += 1
result = "{O}%s{W}" % result result = '{O}%s{W}' % result
elif result == "NoAssoc": elif result == 'NoAssoc':
result = "{O}%s{W}" % result result = '{O}%s{W}' % result
else: else:
result = "{R}%s{W}" % result result = '{R}%s{W}' % result
result = "{P}%s{W}:%s" % (m_state.strip(), result.strip()) result = '{P}%s{W}:%s' % (m_state.strip(), result.strip())
state = "Trying PIN {C}%s{W} (%s)" % (pin, result) state = 'Trying PIN {C}%s{W} (%s)' % (pin, result)
# [!] WPS lockout reported, sleeping for 43 seconds ... # [!] WPS lockout reported, sleeping for 43 seconds ...
re_lockout = re.search(r".*WPS lockout reported, sleeping for (\d+) seconds", line) re_lockout = re.search(r".*WPS lockout reported, sleeping for (\d+) seconds", line)
if re_lockout: if re_lockout:
self.locked = True self.locked = True
sleeping = re_lockout.group(1) sleeping = re_lockout.group(1)
state = "{R}WPS Lock-out: {O}Waiting %s seconds{W}" % sleeping state = '{R}WPS Lock-out: {O}Waiting %s seconds{W}' % sleeping
# [Pixie-Dust] WPS pin not found # [Pixie-Dust] WPS pin not found
re_pin_not_found = re.search(r".*\[Pixie-Dust\] WPS pin not found", line) re_pin_not_found = re.search(r".*\[Pixie-Dust\] WPS pin not found", line)
if re_pin_not_found: if re_pin_not_found:
state = "{R}Failed: {O}Bully says 'WPS pin not found'{W}" state = '{R}Failed: {O}Bully says "WPS pin not found"{W}'
# [+] Running pixiewps with the information, wait ... # [+] Running pixiewps with the information, wait ...
re_running_pixiewps = re.search(r".*Running pixiewps with the information", line) re_running_pixiewps = re.search(r".*Running pixiewps with the information", line)
if re_running_pixiewps: if re_running_pixiewps:
state = "{G}Running pixiewps...{W}" state = '{G}Running pixiewps...{W}'
return state return state
def stop(self): def stop(self):
if hasattr(self, "pid") and self.pid and self.pid.poll() is None: if hasattr(self, 'pid') and self.pid and self.pid.poll() is None:
self.pid.interrupt() self.pid.interrupt()
@@ -283,7 +283,7 @@ class Bully(Attack, Dependency):
@staticmethod @staticmethod
def get_psk_from_pin(target, pin): def get_psk_from_pin(target, pin):
# Fetches PSK from a Target assuming "pin" is the correct PIN # Fetches PSK from a Target assuming 'pin' is the correct PIN
''' '''
bully --channel 1 --bssid 34:21:09:01:92:7C --pin 01030365 --bruteforce wlan0mon bully --channel 1 --bssid 34:21:09:01:92:7C --pin 01030365 --bruteforce wlan0mon
PIN : '01030365' PIN : '01030365'
@@ -319,7 +319,7 @@ if __name__ == '__main__':
fields = '34:21:09:01:92:7C,2015-05-27 19:28:44,2015-05-27 19:28:46,1,54,WPA2,CCMP TKIP,PSK,-58,2,0,0.0.0.0,9,AirLink89300,'.split(',') fields = '34:21:09:01:92:7C,2015-05-27 19:28:44,2015-05-27 19:28:46,1,54,WPA2,CCMP TKIP,PSK,-58,2,0,0.0.0.0,9,AirLink89300,'.split(',')
target = Target(fields) target = Target(fields)
psk = Bully.get_psk_from_pin(target, '01030365') psk = Bully.get_psk_from_pin(target, '01030365')
print("psk", psk) print('psk', psk)
''' '''
stdout = " [*] Pin is '11867722', key is '9a6f7997'" stdout = " [*] Pin is '11867722', key is '9a6f7997'"

15
wifite/tools/dependency.py Normal file → Executable file
View File

@@ -9,7 +9,7 @@ class Dependency(object):
for attr_name in cls.required_attr_names: for attr_name in cls.required_attr_names:
if not attr_name in cls.__dict__: if not attr_name in cls.__dict__:
raise NotImplementedError( raise NotImplementedError(
"Attribute '{}' has not been overridden in class '{}'" \ 'Attribute "{}" has not been overridden in class "{}"' \
.format(attr_name, cls.__name__) .format(attr_name, cls.__name__)
) )
@@ -30,6 +30,7 @@ class Dependency(object):
from .pyrit import Pyrit from .pyrit import Pyrit
from .tshark import Tshark from .tshark import Tshark
from .macchanger import Macchanger from .macchanger import Macchanger
from .hashcat import Hashcat, HcxDumpTool, HcxPcapTool
apps = [ apps = [
# Aircrack # Aircrack
@@ -40,6 +41,8 @@ class Dependency(object):
Reaver, Bully, Reaver, Bully,
# Cracking/handshakes # Cracking/handshakes
Pyrit, Tshark, Pyrit, Tshark,
# Hashcat
Hashcat, HcxDumpTool, HcxPcapTool,
# Misc # Misc
Macchanger Macchanger
] ]
@@ -47,7 +50,7 @@ class Dependency(object):
missing_required = any([app.fails_dependency_check() for app in apps]) missing_required = any([app.fails_dependency_check() for app in apps])
if missing_required: if missing_required:
Color.pl('{!} {R}required app(s) were not found, exiting.{W}') Color.pl('{!} {O}At least 1 Required app is missing. Wifite needs Required apps to run{W}')
import sys import sys
sys.exit(-1) sys.exit(-1)
@@ -61,11 +64,11 @@ class Dependency(object):
return False return False
if cls.dependency_required: if cls.dependency_required:
Color.pl('{!} {R}error: required app {O}%s{R} was not found' % cls.dependency_name) Color.p('{!} {O}Error: Required app {R}%s{O} was not found' % cls.dependency_name)
Color.pl(' {W}install @ {C}%s{W}' % cls.dependency_url) Color.pl('. {W}install @ {C}%s{W}' % cls.dependency_url)
return True return True
else: else:
Color.pl('{!} {O}warning: recommended app {R}%s{O} was not found' % cls.dependency_name) Color.p('{!} {O}Warning: Recommended app {R}%s{O} was not found' % cls.dependency_name)
Color.pl(' {W}install @ {C}%s{W}' % cls.dependency_url) Color.pl('. {W}install @ {C}%s{W}' % cls.dependency_url)
return False return False

16
wifite/tools/hashcat.py Normal file → Executable file
View File

@@ -15,7 +15,7 @@ class Hashcat(Dependency):
dependency_url = 'https://hashcat.net/hashcat/' dependency_url = 'https://hashcat.net/hashcat/'
@staticmethod @staticmethod
def crack_pmkid(pmkid_file): def crack_pmkid(pmkid_file, verbose=False):
''' '''
Cracks a given pmkid_file using the PMKID/WPA2 attack (-m 16800) Cracks a given pmkid_file using the PMKID/WPA2 attack (-m 16800)
Returns: Returns:
@@ -36,6 +36,8 @@ class Hashcat(Dependency):
Configuration.wordlist Configuration.wordlist
] ]
command.extend(additional_arg) command.extend(additional_arg)
if verbose and additional_arg == []:
Color.pl('{+} {D}Running: {W}{P}%s{W}' % ' '.join(command))
# TODO: Check status of hashcat (%); it's impossible with --quiet # TODO: Check status of hashcat (%); it's impossible with --quiet
@@ -71,12 +73,12 @@ class HcxDumpTool(Dependency):
os.remove(pcapng_file) os.remove(pcapng_file)
command = [ command = [
"hcxdumptool", 'hcxdumptool',
"-i", Configuration.interface, '-i', Configuration.interface,
"--filterlist", filterlist, '--filterlist', filterlist,
"--filtermode", "2", '--filtermode', '2',
"-c", str(target.channel), '-c', str(target.channel),
"-o", pcapng_file '-o', pcapng_file
] ]
self.proc = Process(command) self.proc = Process(command)

View File

@@ -56,7 +56,7 @@ class Pyrit(Dependency):
elif current_bssid is not None and current_essid is not None: elif current_bssid is not None and current_essid is not None:
# We hit an AP that we care about. # We hit an AP that we care about.
# Line does not contain AccessPoint, see if it's "good" # Line does not contain AccessPoint, see if it's 'good'
if ', good' in line: if ', good' in line:
bssid_essid_pairs.add( (current_bssid, current_essid) ) bssid_essid_pairs.add( (current_bssid, current_essid) )

View File

@@ -81,7 +81,7 @@ class Reaver(Attack, Dependency):
output_file_prefix='pixie') as airodump: output_file_prefix='pixie') as airodump:
# Wait for target # Wait for target
self.pattack("Waiting for target to appear...") self.pattack('Waiting for target to appear...')
self.target = self.wait_for_target(airodump) self.target = self.wait_for_target(airodump)
# Start reaver # Start reaver
@@ -125,13 +125,13 @@ class Reaver(Attack, Dependency):
meta_statuses = [] meta_statuses = []
if self.total_timeouts > 0: if self.total_timeouts > 0:
meta_statuses.append("{O}Timeouts:%d{W}" % self.total_timeouts) meta_statuses.append('{O}Timeouts:%d{W}' % self.total_timeouts)
if self.total_wpsfails > 0: if self.total_wpsfails > 0:
meta_statuses.append("{O}WPSFail:%d{W}" % self.total_wpsfails) meta_statuses.append('{O}WPSFail:%d{W}' % self.total_wpsfails)
if self.locked: if self.locked:
meta_statuses.append("{R}Locked{W}") meta_statuses.append('{R}Locked{W}')
if len(meta_statuses) > 0: if len(meta_statuses) > 0:
main_status += ' (%s)' % ', '.join(meta_statuses) main_status += ' (%s)' % ', '.join(meta_statuses)
@@ -157,9 +157,13 @@ class Reaver(Attack, Dependency):
# Try to derive PSK from PIN using Bully # Try to derive PSK from PIN using Bully
self.pattack('{W}Retrieving PSK using {C}bully{W}...') self.pattack('{W}Retrieving PSK using {C}bully{W}...')
psk = Bully.get_psk_from_pin(self.target, pin) psk = None
try:
psk = Bully.get_psk_from_pin(self.target, pin)
except KeyboardInterrupt:
pass
if psk is None: if psk is None:
Color.pl("") Color.pl('')
self.pattack('{R}Failed {O}to get PSK using bully', newline=True) self.pattack('{R}Failed {O}to get PSK using bully', newline=True)
else: else:
self.pattack('{G}Cracked WPS PSK: {C}%s' % psk, newline=True) self.pattack('{G}Cracked WPS PSK: {C}%s' % psk, newline=True)
@@ -231,12 +235,12 @@ class Reaver(Attack, Dependency):
time_left = Configuration.wps_pixie_timeout - self.running_time() time_left = Configuration.wps_pixie_timeout - self.running_time()
Color.clear_entire_line() Color.clear_entire_line()
Color.pattack("WPS", Color.pattack('WPS',
self.target, self.target,
'Pixie-Dust', 'Pixie-Dust',
'{W}[{C}%s{W}] %s' % (Timer.secs_to_str(time_left), message)) '{W}[{C}%s{W}] %s' % (Timer.secs_to_str(time_left), message))
if newline: if newline:
Color.pl("") Color.pl('')
def running_time(self): def running_time(self):
@@ -256,19 +260,19 @@ class Reaver(Attack, Dependency):
# Check for PSK. # Check for PSK.
# Note: Reaver 1.6.x does not appear to return PSK (?) # Note: Reaver 1.6.x does not appear to return PSK (?)
regex = re.search("WPA PSK: *'(.+)'", stdout) regex = re.search(r"WPA PSK: *'(.+)'", stdout)
if regex: if regex:
psk = regex.group(1) psk = regex.group(1)
# Check for SSID # Check for SSID
"""1.x [Reaver Test] [+] AP SSID: 'Test Router' """ '''1.x [Reaver Test] [+] AP SSID: 'Test Router' '''
regex = re.search(r"AP SSID:\s*'(.*)'", stdout) regex = re.search(r"AP SSID:\s*'(.*)'", stdout)
if regex: if regex:
ssid = regex.group(1) ssid = regex.group(1)
# Check (again) for SSID # Check (again) for SSID
if ssid is None: if ssid is None:
"""1.6.x [+] Associated with EC:1A:59:37:70:0E (ESSID: belkin.00e)""" '''1.6.x [+] Associated with EC:1A:59:37:70:0E (ESSID: belkin.00e)'''
regex = re.search(r"Associated with [0-9A-F:]+ \(ESSID: (.*)\)", stdout) regex = re.search(r"Associated with [0-9A-F:]+ \(ESSID: (.*)\)", stdout)
if regex: if regex:
ssid = regex.group(1) ssid = regex.group(1)
@@ -349,15 +353,15 @@ executing pixiewps -e d0141b15656e96b85fcead2e8e76330d2b1ac1576bb026e7a328c0e1ba
(pin, psk, ssid) = Reaver.get_pin_psk_ssid(old_stdout) (pin, psk, ssid) = Reaver.get_pin_psk_ssid(old_stdout)
assert pin == '12345678', 'pin was "%s", should have been "12345678"' % pin assert pin == '12345678', 'pin was "%s", should have been "12345678"' % pin
assert psk == 'Test PSK', 'psk was "%s", should have been "Test PSK"' % psk assert psk == 'Test PSK', 'psk was "%s", should have been "Test PSK"' % psk
assert ssid == "Test Router", 'ssid was %s, should have been Test Router' % repr(ssid) assert ssid == 'Test Router', 'ssid was %s, should have been Test Router' % repr(ssid)
result = CrackResultWPS('AA:BB:CC:DD:EE:FF', ssid, pin, psk) result = CrackResultWPS('AA:BB:CC:DD:EE:FF', ssid, pin, psk)
result.dump() result.dump()
print("") print('')
(pin, psk, ssid) = Reaver.get_pin_psk_ssid(new_stdout) (pin, psk, ssid) = Reaver.get_pin_psk_ssid(new_stdout)
assert pin == '11867722', 'pin was "%s", should have been "11867722"' % pin assert pin == '11867722', 'pin was "%s", should have been "11867722"' % pin
assert psk == None, 'psk was "%s", should have been "None"' % psk assert psk == None, 'psk was "%s", should have been "None"' % psk
assert ssid == "belkin.00e", 'ssid was "%s", should have been "belkin.00e"' % repr(ssid) assert ssid == 'belkin.00e', 'ssid was "%s", should have been "belkin.00e"' % repr(ssid)
result = CrackResultWPS('AA:BB:CC:DD:EE:FF', ssid, pin, psk) result = CrackResultWPS('AA:BB:CC:DD:EE:FF', ssid, pin, psk)
result.dump() result.dump()

View File

@@ -20,7 +20,7 @@ class Tshark(Dependency):
@staticmethod @staticmethod
def _extract_src_dst_index_total(line): def _extract_src_dst_index_total(line):
# Extract BSSIDs, handshake # (1-4) and handshake "total" (4) # Extract BSSIDs, handshake # (1-4) and handshake 'total' (4)
mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1] mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1]
match = re.search('(%s)\s*.*\s*(%s).*Message.*(\d).*of.*(\d)' % (mac_regex, mac_regex), line) match = re.search('(%s)\s*.*\s*(%s).*Message.*(\d).*of.*(\d)' % (mac_regex, mac_regex), line)
if match is None: if match is None:
@@ -135,7 +135,7 @@ class Tshark(Dependency):
(src, dst, essid) = match.groups() (src, dst, essid) = match.groups()
if dst.lower() == "ff:ff:ff:ff:ff:ff": if dst.lower() == 'ff:ff:ff:ff:ff:ff':
continue # Skip broadcast packets continue # Skip broadcast packets
if bssid is not None: if bssid is not None:

View File

@@ -33,7 +33,7 @@ class Color(object):
''' '''
Prints text using colored format on same line. Prints text using colored format on same line.
Example: Example:
Color.p("{R}This text is red. {W} This text is white") Color.p('{R}This text is red. {W} This text is white')
''' '''
sys.stdout.write(Color.s(text)) sys.stdout.write(Color.s(text))
sys.stdout.flush() sys.stdout.flush()
@@ -62,7 +62,7 @@ class Color(object):
for (key,value) in Color.replacements.items(): for (key,value) in Color.replacements.items():
output = output.replace(key, value) output = output.replace(key, value)
for (key,value) in Color.colors.items(): for (key,value) in Color.colors.items():
output = output.replace("{%s}" % key, value) output = output.replace('{%s}' % key, value)
return output return output
@staticmethod @staticmethod
@@ -76,7 +76,8 @@ class Color(object):
def clear_entire_line(): def clear_entire_line():
import os import os
(rows, columns) = os.popen('stty size', 'r').read().split() (rows, columns) = os.popen('stty size', 'r').read().split()
Color.p("\r" + (" " * int(columns)) + "\r") Color.p('\r' + (' ' * int(columns)) + '\r')
@staticmethod @staticmethod
def pattack(attack_type, target, attack_name, progress): def pattack(attack_type, target, attack_name, progress):
@@ -86,13 +87,31 @@ class Color(object):
ESSID (Pwr) Attack_Type: Progress ESSID (Pwr) Attack_Type: Progress
e.g.: Router2G (23db) WEP replay attack: 102 IVs e.g.: Router2G (23db) WEP replay attack: 102 IVs
''' '''
essid = "{C}%s{W}" % target.essid if target.essid_known else "{O}unknown{W}" essid = '{C}%s{W}' % target.essid if target.essid_known else '{O}unknown{W}'
Color.p("\r{+} {G}%s{W} ({C}%sdb{W}) {G}%s {C}%s{W}: %s " % ( Color.p('\r{+} {G}%s{W} ({C}%sdb{W}) {G}%s {C}%s{W}: %s ' % (
essid, target.power, attack_type, attack_name, progress)) essid, target.power, attack_type, attack_name, progress))
if __name__ == '__main__':
Color.pl("{R}Testing{G}One{C}Two{P}Three{W}Done") @staticmethod
print(Color.s("{C}Testing{P}String{W}")) def pexception(exception):
Color.pl("{+} Good line") '''Prints an exception. Includes stack trace if necessary.'''
Color.pl("{!} Danger") Color.pl('\n{!} {R}Error: {O}%s' % str(exception))
from ..config import Configuration
if Configuration.verbose > 0 or Configuration.print_stack_traces:
Color.pl('\n{!} {O}Full stack trace below')
from traceback import format_exc
Color.p('\n{!} ')
err = format_exc().strip()
err = err.replace('\n', '\n{!} {C} ')
err = err.replace(' File', '{W}File')
err = err.replace(' Exception: ', '{R}Exception: {O}')
Color.pl(err)
if __name__ == '__main__':
Color.pl('{R}Testing{G}One{C}Two{P}Three{W}Done')
print(Color.s('{C}Testing{P}String{W}'))
Color.pl('{+} Good line')
Color.pl('{!} Danger')

View File

@@ -5,138 +5,213 @@ from ..util.process import Process
from ..util.color import Color from ..util.color import Color
from ..util.input import raw_input from ..util.input import raw_input
from ..config import Configuration from ..config import Configuration
from ..model.result import CrackResult
from datetime import datetime from datetime import datetime
import os import os
class CrackHandshake(object):
def __init__(self):
self.wordlist = Configuration.wordlist or "path_to_wordlist_here"
if os.path.exists(self.wordlist):
self.wordlist = os.path.abspath(self.wordlist)
handshake = self.choose_handshake() # TODO: Bring back the 'print' option, for easy copy/pasting. Just one-liners people can paste into terminal.
self.crack_handshake(handshake)
def crack_handshake(self, handshake): # TODO: Do not show handshake files that are in cracked.txt with a key (match on filename).
cap_file = handshake["handshake_file"]
bssid = handshake["bssid"]
Color.pl("\n Below are commands to crack the handshake {C}%s{W}:" % cap_file)
self.print_aircrack(cap_file, bssid)
self.print_pyrit(cap_file, bssid)
self.print_john(cap_file)
self.print_oclhashcat(cap_file)
Color.pl("")
# TODO: cowpatty, oclhashcat
def print_aircrack(self, cap_file, bssid): class CrackHelper:
Color.pl("") '''Manages handshake retrieval, selection, and running the cracking commands.'''
if not Process.exists("aircrack-ng"):
Color.pl(" {R}aircrack-ng not found.");
Color.pl(" {O}More info on installing {R}Aircrack{O} here: {C}https://www.aircrack-ng.org/downloads.html{W}");
return
Color.pl(" {O}# AIRCRACK: CPU-based cracking. Slow.")
Color.pl(" {G}aircrack-ng {W}-a {C}2 {W}-b {C}%s {W}-w {C}%s %s{W}" % (bssid, self.wordlist, cap_file))
def print_pyrit(self, cap_file, bssid): TYPES = {
Color.pl("") '4-WAY': 'WPA 4-Way Handshake',
if not Process.exists("pyrit"): 'PMKID': 'WPA PKID Hash'
Color.pl(" {R}pyrit not found."); }
Color.pl(" {O}More info on installing {R}Pyrit{O} here: {C}https://github.com/JPaulMora/Pyrit{W}");
return
Color.pl(" {O}# PYRIT: GPU-based cracking. Fast.")
Color.pl(" {G}pyrit {W}-b {C}%s {W}-i {C}%s {W}-r {C}%s {W}attack_passthrough{W}" % (bssid, self.wordlist, cap_file))
def print_john(self, cap_file):
Color.pl("")
Color.pl(" {O}# JOHN: CPU or GPU-based cracking. Fast.")
if not Process.exists("john"):
Color.pl(" {O}# {R}john{O} is not installed. More info on installing {R}John The Ripper{O} here: {C}http://www.openwall.com/john/{W}");
else:
Color.pl(" {O}# Use --format=wpapsk-cuda (or wpapsk-opengl) to enable GPU acceleration")
Color.pl(" {O}# See http://openwall.info/wiki/john/WPA-PSK for more info on this process")
Color.pl(" {O}# Generate hccap file:")
Color.pl(" {G}aircrack-ng {W}-J hccap {C}%s{W}" % cap_file)
Color.pl(" {O}# Convert hccap file to john file:")
Color.pl(" {G}hccap2john {C}hccap.hccap {W}> {C}%s.john{W}" % cap_file)
Color.pl(" {O}# Crack john file:")
Color.pl(" {G}john {W}--wordlist {C}\"%s\" {W}--format=wpapsk {C}\"%s.john\"{W}" % (self.wordlist, cap_file))
def print_oclhashcat(self, cap_file): @classmethod
Color.pl("") def run(cls):
if not Process.exists("hashcat"): Configuration.initialize(False)
Color.pl(" {R}hashcat {O}not found.");
Color.pl(" {O}More info on installing {R}hashcat{O} here: {C}https://hashcat.net/hashcat/");
return
Color.pl(" {O}# HASHCAT: GPU-based cracking. Fast.")
Color.pl(" {O}# See {C}https://hashcat.net/wiki/doku.php?id=cracking_wpawpa2 {O}for more info")
Color.pl(" {O}# Step 1: Generate .hccapx file")
hccapx_file = "/tmp/generated.hccapx" if not Configuration.wordlist:
cap2hccapx = "/usr/lib/hashcat-utils/cap2hccapx.bin" Color.p('\n{+} Enter wordlist file to use for cracking: {G}')
if os.path.exists(cap2hccapx): Configuration.wordlist = raw_input()
Color.pl(" {G} %s {W}%s {C}%s{W}" % (cap2hccapx, cap_file, hccapx_file)) if not os.path.exists(Configuration.wordlist):
else: Color.pl('{!} {R}Wordlist {O}%s{R} not found. Exiting.' % Configuration.wordlist)
Color.pl(" {O}# Install {R}cap2hccapx{O}: {C}https://hashcat.net/wiki/doku.php?id=hashcat_utils") return
Color.pl(" {G}./cap2hccapx.bin {W}%s {C}%s{W}" % (cap_file, hccapx_file)) Color.pl('')
Color.pl(" {O}# OR visit https://hashcat.net/cap2hccapx to generate a .hccapx file{W}")
Color.pl(" {O}# Then click BROWSE -> %s -> CONVERT and save to %s" % (cap_file, hccapx_file))
Color.pl(" {O}# Step 2: Crack the .hccapx file")
Color.pl(" {G}hashcat {W}-m 2500 {C}%s %s{W}" % (hccapx_file, self.wordlist))
def choose_handshake(self):
hs_dir = Configuration.wpa_handshake_dir
Color.pl("{+} Listing captured handshakes from {C}%s{W}\n" % os.path.realpath(hs_dir))
handshakes = []
for hs_file in os.listdir(hs_dir):
if not hs_file.endswith('.cap') or hs_file.count("_") != 3:
continue
name, essid, bssid, date = hs_file.split("_")
if name != 'handshake':
continue
handshakes.append({
'essid': essid,
'bssid': bssid.replace('-', ':'),
'date': date.replace('.cap', '').replace('T', ' '),
'handshake_file': os.path.realpath(os.path.join(hs_dir, hs_file))
})
handshakes.sort(key=lambda x: x['date'], reverse=True)
handshakes = cls.get_handshakes()
if len(handshakes) == 0: if len(handshakes) == 0:
raise Exception("No handshakes found in %s" % os.path.realpath(hs_dir)) Color.pl('{!} {O}No handshakes found{W}')
return
hs_to_crack = cls.get_user_selection(handshakes)
# Handshakes Header # TODO: Ask what method to use for WPA (aircrack, pyrit, john, hashcat, cowpatty)
max_essid_len = max(max([len(hs["essid"]) for hs in handshakes]), len('(truncated) ESSDID'))
Color.p(" NUM") for hs in hs_to_crack:
Color.p(" " + "ESSID (truncated)".ljust(max_essid_len)) cls.crack(hs)
Color.p(" " + "BSSID".ljust(17))
Color.p(" DATE CAPTURED\n") @classmethod
Color.p(" ---") def get_handshakes(cls):
Color.p(" " + ("-" * max_essid_len)) handshakes = []
Color.p(" " + ("-" * 17))
Color.p(" " + ("-" * 19) + "\n") skipped_pmkid_files = 0
# Print all handshakes
for idx, hs in enumerate(handshakes, start=1): hs_dir = Configuration.wpa_handshake_dir
bssid = hs["bssid"] if not os.path.exists(hs_dir) or not os.path.isdir(hs_dir):
essid = hs["essid"] Color.pl('\n{!} {O}directory not found: {R}%s{W}' % hs_dir)
date = hs["date"] return []
Color.p(" {G}%s{W}" % str(idx).rjust(3))
Color.p(" {C}%s{W}" % essid.ljust(max_essid_len)) Color.pl('\n{+} Listing captured handshakes from {C}%s{W} ...\n' % os.path.abspath(hs_dir))
Color.p(" {O}%s{W}" % bssid) for hs_file in os.listdir(hs_dir):
Color.p(" {W}%s{W}\n" % date) if hs_file.count('_') != 3:
# Get number from user continue
hs_index = raw_input(Color.s("\n{+} Select handshake num to crack ({G}1-%d{W}): " % len(handshakes)))
if not hs_index.isdigit(): if hs_file.endswith('.cap'):
raise ValueError("Handshake NUM must be numeric, got (%s)" % hs_index) # WPA Handshake
hs_index = int(hs_index) hs_type = '4-WAY'
if hs_index < 1 or hs_index > len(handshakes): elif hs_file.endswith('.16800'):
raise Exception("Handshake NUM must be between 1 and %d" % len(handshakes)) # PMKID hash
if not Process.exists('hashcat'):
skipped_pmkid_files += 1
continue
hs_type = 'PMKID'
else:
continue
name, essid, bssid, date = hs_file.split('_')
date = date.rsplit('.', 1)[0]
days,hours = date.split('T')
hours = hours.replace('-', ':')
date = '%s %s' % (days, hours)
handshake = {
'filename': os.path.join(hs_dir, hs_file),
'bssid': bssid.replace('-', ':'),
'essid': essid,
'date': date,
'type': hs_type
}
if hs_file.endswith('.cap'):
# WPA Handshake
handshake['type'] = '4-WAY'
elif hs_file.endswith('.16800'):
# PMKID hash
handshake['type'] = 'PMKID'
else:
continue
handshakes.append(handshake)
if skipped_pmkid_files > 0:
Color.pl('{!} {O}Skipping %d {R}*.16800{O} files because {R}hashcat{O} is missing.' % skipped_pmkid_files)
# Sort by Date (Descending)
return sorted(handshakes, key=lambda x: x.get('date'), reverse=True)
@classmethod
def print_handshakes(cls, handshakes):
# Header
max_essid_len = max([len(hs['essid']) for hs in handshakes] + [len('ESSID (truncated)')])
Color.p('{D} NUM')
Color.p(' ' + 'ESSID (truncated)'.ljust(max_essid_len))
Color.p(' ' + 'BSSID'.ljust(17))
Color.p(' ' + 'TYPE'.ljust(5))
Color.p(' ' + 'DATE CAPTURED\n')
Color.p(' ---')
Color.p(' ' + ('-' * max_essid_len))
Color.p(' ' + ('-' * 17))
Color.p(' ' + ('-' * 6))
Color.p(' ' + ('-' * 19) + '{W}\n')
# Handshakes
for index, handshake in enumerate(handshakes, start=1):
bssid = handshake['bssid']
date = handshake['date']
Color.p(' {G}%s{W}' % str(index).rjust(3))
Color.p(' {C}%s{W}' % handshake['essid'].ljust(max_essid_len))
Color.p(' {O}%s{W}' % handshake['bssid'].ljust(17))
Color.p(' {C}%s{W}' % handshake['type'].ljust(5))
Color.p(' {W}%s{W}\n' % handshake['date'])
@classmethod
def get_user_selection(cls, handshakes):
cls.print_handshakes(handshakes)
Color.p('{+} Select handshake(s) to crack ({G}%d{W}-{G}%d{W}, select multiple with {C},{W} or {C}-{W}): {G}' % (1, len(handshakes)))
choices = raw_input()
selection = []
for choice in choices.split(','):
if '-' in choice:
first, last = [int(x) for x in choice.split('-')]
for index in range(first, last + 1):
selection.append(handshakes[index-1])
else:
index = int(choice)
selection.append(handshakes[index-1])
return selection
@classmethod
def crack(cls, hs):
Color.pl('\n{+} Cracking {C}%s{W} ({C}%s{W}) using {G}%s{W} method' % (hs['essid'], hs['bssid'], hs['type']))
if hs['type'] == 'PMKID':
crack_result = cls.crack_pmkid(hs)
elif hs['type'] == '4-WAY':
crack_result = cls.crack_4way(hs)
else:
raise ValueError('Cannot crack handshake: Type is not PMKID or 4-WAY. Handshake=%s' % hs)
if crack_result is None:
# Failed to crack
Color.pl('{!} {R}Failed to crack {O}%s{R} ({O}%s{R}): Passphrase not in dictionary' % (
hs['essid'], hs['bssid']))
else:
# Cracked, replace existing entry (if any), or add to
Color.pl('{+} {G}Cracked{W} {C}%s{W} ({C}%s{W}). Key: "{G}%s{W}"' % (
hs['essid'], hs['bssid'], crack_result.key))
crack_result.save()
@classmethod
def crack_4way(cls, hs):
from ..attack.wpa import AttackWPA
from ..model.handshake import Handshake
from ..model.wpa_result import CrackResultWPA
handshake = Handshake(hs['filename'],
bssid=hs['bssid'],
essid=hs['essid'])
key = None
try:
key = AttackWPA.crack_handshake(handshake, Configuration.wordlist, verbose=True)
except KeyboardInterrupt:
Color.pl('\n{!} Interrupted')
if key is not None:
return CrackResultWPA(hs['bssid'], hs['essid'], hs['filename'], key)
else:
return None
@classmethod
def crack_pmkid(cls, hs):
from ..tools.hashcat import Hashcat
from ..model.pmkid_result import CrackResultPMKID
key = None
try:
key = Hashcat.crack_pmkid(hs['filename'], verbose=True)
except KeyboardInterrupt:
Color.pl('\n{!} Interrupted')
if key is not None:
return CrackResultPMKID(hs['bssid'], hs['essid'], hs['filename'], key)
else:
return None
if __name__ == '__main__':
CrackHelper.run()
return handshakes[hs_index - 1]

View File

@@ -29,11 +29,11 @@ class Process(object):
if type(command) is not str or ' ' in command or shell: if type(command) is not str or ' ' in command or shell:
shell = True shell = True
if Configuration.verbose > 1: if Configuration.verbose > 1:
Color.pe("\n {C}[?] {W} Executing (Shell): {B}%s{W}" % command) Color.pe('\n {C}[?] {W} Executing (Shell): {B}%s{W}' % command)
else: else:
shell = False shell = False
if Configuration.verbose > 1: if Configuration.verbose > 1:
Color.pe("\n {C}[?]{W} Executing: {B}%s{W}" % command) Color.pe('\n {C}[?]{W} Executing: {B}%s{W}' % command)
pid = Popen(command, cwd=cwd, stdout=PIPE, stderr=PIPE, shell=shell) pid = Popen(command, cwd=cwd, stdout=PIPE, stderr=PIPE, shell=shell)
pid.wait() pid.wait()
@@ -45,9 +45,9 @@ class Process(object):
if Configuration.verbose > 1 and stdout is not None and stdout.strip() != '': if Configuration.verbose > 1 and stdout is not None and stdout.strip() != '':
Color.pe("{P} [stdout] %s{W}" % '\n [stdout] '.join(stdout.strip().split('\n'))) Color.pe('{P} [stdout] %s{W}' % '\n [stdout] '.join(stdout.strip().split('\n')))
if Configuration.verbose > 1 and stderr is not None and stderr.strip() != '': if Configuration.verbose > 1 and stderr is not None and stderr.strip() != '':
Color.pe("{P} [stderr] %s{W}" % '\n [stderr] '.join(stderr.strip().split('\n'))) Color.pe('{P} [stderr] %s{W}' % '\n [stderr] '.join(stderr.strip().split('\n')))
return (stdout, stderr) return (stdout, stderr)
@@ -73,7 +73,7 @@ class Process(object):
self.command = command self.command = command
if Configuration.verbose > 1: if Configuration.verbose > 1:
Color.pe("\n {C}[?] {W} Executing: {B}%s{W}" % ' '.join(command)) Color.pe('\n {C}[?] {W} Executing: {B}%s{W}' % ' '.join(command))
self.out = None self.out = None
self.err = None self.err = None
@@ -103,14 +103,14 @@ class Process(object):
''' Waits for process to finish, returns stdout output ''' ''' Waits for process to finish, returns stdout output '''
self.get_output() self.get_output()
if Configuration.verbose > 1 and self.out is not None and self.out.strip() != '': if Configuration.verbose > 1 and self.out is not None and self.out.strip() != '':
Color.pe("{P} [stdout] %s{W}" % '\n [stdout] '.join(self.out.strip().split('\n'))) Color.pe('{P} [stdout] %s{W}' % '\n [stdout] '.join(self.out.strip().split('\n')))
return self.out return self.out
def stderr(self): def stderr(self):
''' Waits for process to finish, returns stderr output ''' ''' Waits for process to finish, returns stderr output '''
self.get_output() self.get_output()
if Configuration.verbose > 1 and self.err is not None and self.err.strip() != '': if Configuration.verbose > 1 and self.err is not None and self.err.strip() != '':
Color.pe("{P} [stderr] %s{W}" % '\n [stderr] '.join(self.err.strip().split('\n'))) Color.pe('{P} [stderr] %s{W}' % '\n [stderr] '.join(self.err.strip().split('\n')))
return self.err return self.err
def stdoutln(self): def stdoutln(self):
@@ -135,7 +135,7 @@ class Process(object):
return (self.out, self.err) return (self.out, self.err)
def poll(self): def poll(self):
''' Returns exit code if process is dead, otherwise "None" ''' ''' Returns exit code if process is dead, otherwise 'None' '''
return self.pid.poll() return self.pid.poll()
def wait(self): def wait(self):
@@ -202,8 +202,8 @@ if __name__ == '__main__':
# Test on never-ending process # Test on never-ending process
p = Process('yes') p = Process('yes')
print("Running yes...") print('Running yes...')
time.sleep(1) time.sleep(1)
print("yes should stop now") print('yes should stop now')
# After program loses reference to instance in 'p', process dies. # After program loses reference to instance in 'p', process dies.

View File

@@ -1,8 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from ..tools.airodump import Airodump
from ..util.color import Color from ..util.color import Color
from ..tools.airodump import Airodump
from ..util.input import raw_input, xrange from ..util.input import raw_input, xrange
from ..model.target import Target from ..model.target import Target
from ..config import Configuration from ..config import Configuration
@@ -17,16 +17,18 @@ class Scanner(object):
def __init__(self): def __init__(self):
''' '''
Starts scan, prints as it goes. Scans for targets via Airodump.
Upon interrupt, sets 'targets'. Loops until scan is interrupted via user or config.
Note: Sets this object's `targets` attrbute (list[Target]) upon interruption.
''' '''
self.previous_target_count = 0 self.previous_target_count = 0
self.targets = [] self.targets = []
self.target = None # Specific target (based on ESSID/BSSID) self.target = None # Target specified by user (based on ESSID/BSSID)
max_scan_time = Configuration.scan_time
self.err_msg = None self.err_msg = None
Color.pl("")
# Loads airodump with interface/channel/etc from Configuration # Loads airodump with interface/channel/etc from Configuration
try: try:
with Airodump() as airodump: with Airodump() as airodump:
@@ -35,18 +37,15 @@ class Scanner(object):
while True: while True:
if airodump.pid.poll() is not None: if airodump.pid.poll() is not None:
# Airodump process died return # Airodump process died
return
self.targets = airodump.get_targets(old_targets=self.targets) self.targets = airodump.get_targets(old_targets=self.targets)
if self.found_target(): if self.found_target():
# We found the target we want return # We found the target we want
return
if airodump.pid.poll() is not None: if airodump.pid.poll() is not None:
# Airodump process died return # Airodump process died
return
for target in self.targets: for target in self.targets:
if target.bssid in airodump.decloaked_bssids: if target.bssid in airodump.decloaked_bssids:
@@ -55,20 +54,19 @@ class Scanner(object):
self.print_targets() self.print_targets()
target_count = len(self.targets) target_count = len(self.targets)
client_count = sum( client_count = sum([len(t.clients) for t in self.targets])
[len(t.clients)
for t in self.targets]) outline = '\r{+} Scanning'
outline = "\r{+} Scanning"
if airodump.decloaking: if airodump.decloaking:
outline += " & decloaking" outline += ' & decloaking'
outline += ". Found" outline += '. Found'
outline += " {G}%d{W} target(s)," % target_count outline += ' {G}%d{W} target(s),' % target_count
outline += " {G}%d{W} client(s)." % client_count outline += ' {G}%d{W} client(s).' % client_count
outline += " {O}Ctrl+C{W} when ready " outline += ' {O}Ctrl+C{W} when ready '
Color.clear_entire_line() Color.clear_entire_line()
Color.p(outline) Color.p(outline)
if Configuration.scan_time > 0 and time() > scan_start_time + Configuration.scan_time: if max_scan_time > 0 and time() > scan_start_time + max_scan_time:
return return
sleep(1) sleep(1)
@@ -76,17 +74,18 @@ class Scanner(object):
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
def found_target(self): def found_target(self):
''' '''
Check if we discovered the target AP Detect if we found a target specified by the user (optional).
Returns: the Target if found, Sets this object's `target` attribute if found.
Otherwise None. Returns: True if target was specified and found, False otherwise.
''' '''
bssid = Configuration.target_bssid bssid = Configuration.target_bssid
essid = Configuration.target_essid essid = Configuration.target_essid
if bssid is None and essid is None: if bssid is None and essid is None:
return False return False # No specific target from user.
for target in self.targets: for target in self.targets:
if Configuration.wps_only and target.wps != True: if Configuration.wps_only and target.wps != True:
@@ -105,16 +104,15 @@ class Scanner(object):
return False return False
def print_targets(self): def print_targets(self):
''' '''Prints targets selection menu (1 target per row).'''
Prints targets to console
'''
if len(self.targets) == 0: if len(self.targets) == 0:
Color.p('\r') Color.p('\r')
return return
if self.previous_target_count > 0: if self.previous_target_count > 0:
# We need to "overwrite" the previous list of targets. # We need to 'overwrite' the previous list of targets.
if Configuration.verbose <= 1: if Configuration.verbose <= 1:
# Don't clear screen buffer in verbose mode. # Don't clear screen buffer in verbose mode.
if self.previous_target_count > len(self.targets) or \ if self.previous_target_count > len(self.targets) or \
@@ -127,7 +125,7 @@ class Scanner(object):
Process.call('clear') Process.call('clear')
else: else:
# We can fit the targets in the terminal without scrolling # We can fit the targets in the terminal without scrolling
# "Move" cursor up so we will print over the previous list # 'Move' cursor up so we will print over the previous list
Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count)) Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count))
self.previous_target_count = len(self.targets) self.previous_target_count = len(self.targets)
@@ -168,7 +166,15 @@ class Scanner(object):
return int(columns) return int(columns)
def select_targets(self): def select_targets(self):
''' Asks user to select target(s) ''' '''
Returns list(target)
Either a specific target if user specified -bssid or --essid.
Otherwise, prompts user to select targets and returns the selection.
'''
if self.target:
# When user specifies a specific target
return [self.target]
if len(self.targets) == 0: if len(self.targets) == 0:
if self.err_msg is not None: if self.err_msg is not None:
@@ -178,13 +184,15 @@ class Scanner(object):
# 1. Link to wireless drivers wiki, # 1. Link to wireless drivers wiki,
# 2. How to check if your device supporst monitor mode, # 2. How to check if your device supporst monitor mode,
# 3. Provide airodump-ng command being executed. # 3. Provide airodump-ng command being executed.
raise Exception("No targets found." raise Exception('No targets found.'
+ " You may need to wait longer," + ' You may need to wait longer,'
+ " or you may have issues with your wifi card") + ' or you may have issues with your wifi card')
# Return all targets if user specified a wait time ('pillage').
if Configuration.scan_time > 0: if Configuration.scan_time > 0:
return self.targets return self.targets
# Ask user for targets.
self.print_targets() self.print_targets()
Color.clear_entire_line() Color.clear_entire_line()
@@ -211,12 +219,12 @@ class Scanner(object):
elif choice.isdigit(): elif choice.isdigit():
choice = int(choice) - 1 choice = int(choice) - 1
chosen_targets.append(self.targets[choice]) chosen_targets.append(self.targets[choice])
else:
pass
return chosen_targets return chosen_targets
if __name__ == '__main__': if __name__ == '__main__':
# Example displays targets and selects the appropriate one # 'Test' script will display targets and selects the appropriate one
Configuration.initialize() Configuration.initialize()
try: try:
s = Scanner() s = Scanner()
@@ -225,6 +233,6 @@ if __name__ == '__main__':
Color.pl('\r {!} {R}Error{W}: %s' % str(e)) Color.pl('\r {!} {R}Error{W}: %s' % str(e))
Configuration.exit_gracefully(0) Configuration.exit_gracefully(0)
for t in targets: for t in targets:
Color.pl(" {W}Selected: %s" % t) Color.pl(' {W}Selected: %s' % t)
Configuration.exit_gracefully(0) Configuration.exit_gracefully(0)

View File

@@ -32,8 +32,8 @@ class Timer(object):
mins = (rem % 3600) / 60 mins = (rem % 3600) / 60
secs = rem % 60 secs = rem % 60
if hours > 0: if hours > 0:
return "%dh%dm%ds" % (hours, mins, secs) return '%dh%dm%ds' % (hours, mins, secs)
elif mins > 0: elif mins > 0:
return "%dm%ds" % (mins, secs) return '%dm%ds' % (mins, secs)
else: else:
return "%ds" % secs return '%ds' % secs

View File

@@ -6,64 +6,56 @@ try:
except (ValueError, ImportError) as e: except (ValueError, ImportError) as e:
raise Exception('You may need to run wifite from the root directory (which includes README.md)', e) raise Exception('You may need to run wifite from the root directory (which includes README.md)', e)
from .util.scanner import Scanner
from .util.process import Process
from .util.color import Color from .util.color import Color
from .util.crack import CrackHandshake
from .util.input import raw_input
from .attack.all import AttackAll
from .model.result import CrackResult
from .model.handshake import Handshake
from .tools.dependency import Dependency
import os import os
import sys import sys
class Wifite(object): class Wifite(object):
def main(self): def __init__(self):
''' Either performs action based on arguments, or starts attack scanning ''' '''
Initializes Wifite. Checks for root permissions and ensures dependencies are installed.
'''
if os.getuid() != 0: self.print_banner()
Color.pl('{!} {R}error: {O}wifite{R} must be run as {O}root{W}')
Color.pl('{!} {O}re-run as: sudo ./Wifite.py{W}')
Configuration.exit_gracefully(0)
Configuration.initialize(load_interface=False) Configuration.initialize(load_interface=False)
if os.getuid() != 0:
Color.pl('{!} {R}error: {O}wifite{R} must be run as {O}root{W}')
Color.pl('{!} {R}re-run with {O}sudo{W}')
Configuration.exit_gracefully(0)
from .tools.dependency import Dependency
Dependency.run_dependency_check() Dependency.run_dependency_check()
def start(self):
'''
Starts target-scan + attack loop, or launches utilities dpeending on user input.
'''
from .model.result import CrackResult
from .model.handshake import Handshake
from .util.crack import CrackHelper
if Configuration.show_cracked: if Configuration.show_cracked:
CrackResult.display() CrackResult.display()
elif Configuration.check_handshake: elif Configuration.check_handshake:
Handshake.check() Handshake.check()
elif Configuration.crack_handshake: elif Configuration.crack_handshake:
CrackHandshake() CrackHelper.run()
else: else:
Configuration.get_monitor_mode_interface() Configuration.get_monitor_mode_interface()
self.run() self.scan_and_attack()
def run(self):
'''
Main program.
1) Scans for targets, asks user to select targets
2) Attacks each target
'''
s = Scanner()
if s.target:
# We found the target we want
targets = [s.target]
else:
targets = s.select_targets()
attacked_targets = AttackAll.attack_multiple(targets)
Color.pl("{+} Finished attacking {C}%d{W} target(s), exiting" % attacked_targets)
def print_banner(self): def print_banner(self):
""" Displays ASCII art of the highest caliber. """ '''Displays ASCII art of the highest caliber.'''
Color.pl(r'{G} . {GR}{D} {W}{G} . {W}') Color.pl(r'{G} . {GR}{D} {W}{G} . {W}')
Color.pl(r'{G}.´ · .{GR}{D} {W}{G}. · `. {G}wifite {D}%s{W}' % Configuration.version) Color.pl(r'{G}.´ · .{GR}{D} {W}{G}. · `. {G}wifite {D}%s{W}' % Configuration.version)
Color.pl(r'{G}: : : {GR}{D} (¯) {W}{G} : : : {W}{D}automated wireless auditor{W}') Color.pl(r'{G}: : : {GR}{D} (¯) {W}{G} : : : {W}{D}automated wireless auditor{W}')
@@ -72,49 +64,35 @@ class Wifite(object):
Color.pl('') Color.pl('')
def user_wants_to_continue(self, targets_remaining, attacks_remaining=0): def scan_and_attack(self):
''' Asks user if attacks should continue onto other targets ''' '''
if attacks_remaining == 0 and targets_remaining == 0: 1) Scans for targets, asks user to select targets
# No targets or attacksleft, drop out 2) Attacks each target
return '''
from .util.scanner import Scanner
from .attack.all import AttackAll
prompt_list = [] Color.pl('')
if attacks_remaining > 0:
prompt_list.append(Color.s('{C}%d{W} attack(s)' % attacks_remaining))
if targets_remaining > 0:
prompt_list.append(Color.s('{C}%d{W} target(s)' % targets_remaining))
prompt = ' and '.join(prompt_list)
Color.pl('{+} %s remain, do you want to continue?' % prompt)
prompt = Color.s('{+} type {G}c{W} to {G}continue{W}' + # Scan
' or {R}s{W} to {R}stop{W}: ') s = Scanner()
targets = s.select_targets()
if raw_input(prompt).lower().startswith('s'): # Attack
return False attacked_targets = AttackAll.attack_multiple(targets)
else:
return True Color.pl('{+} Finished attacking {C}%d{W} target(s), exiting' % attacked_targets)
def run(): ##############################################################
w = Wifite()
w.print_banner()
def entry_point():
try: try:
w.main() wifite = Wifite()
wifite.start()
except Exception as e: except Exception as e:
Color.pl('\n{!} {R}Error:{O} %s{W}' % str(e)) Color.pexception(e)
if Configuration.verbose > 0 or True:
Color.pl('\n{!} {O}Full stack trace below')
from traceback import format_exc
Color.p('\n{!} ')
err = format_exc().strip()
err = err.replace('\n', '\n{W}{!} {W} ')
err = err.replace(' File', '{W}{D}File')
err = err.replace(' Exception: ', '{R}Exception: {O}')
Color.pl(err)
Color.pl('\n{!} {R}Exiting{W}\n') Color.pl('\n{!} {R}Exiting{W}\n')
except KeyboardInterrupt: except KeyboardInterrupt:
@@ -122,5 +100,6 @@ def run():
Configuration.exit_gracefully(0) Configuration.exit_gracefully(0)
if __name__ == '__main__': if __name__ == '__main__':
run() entry_point()