Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
derv82
GitHub Repository: derv82/wifite2
Path: blob/master/wifite/util/scanner.py
412 views
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
4
from ..util.color import Color
5
from ..tools.airodump import Airodump
6
from ..util.input import raw_input, xrange
7
from ..model.target import Target, WPSState
8
from ..config import Configuration
9
10
from time import sleep, time
11
12
class Scanner(object):
13
''' Scans wifi networks & provides menu for selecting targets '''
14
15
# Console code for moving up one line
16
UP_CHAR = '\x1B[1F'
17
18
def __init__(self):
19
'''
20
Scans for targets via Airodump.
21
Loops until scan is interrupted via user or config.
22
Note: Sets this object's `targets` attrbute (list[Target]) upon interruption.
23
'''
24
self.previous_target_count = 0
25
self.targets = []
26
self.target = None # Target specified by user (based on ESSID/BSSID)
27
28
max_scan_time = Configuration.scan_time
29
30
self.err_msg = None
31
32
# Loads airodump with interface/channel/etc from Configuration
33
try:
34
with Airodump() as airodump:
35
# Loop until interrupted (Ctrl+C)
36
scan_start_time = time()
37
38
while True:
39
if airodump.pid.poll() is not None:
40
return # Airodump process died
41
42
self.targets = airodump.get_targets(old_targets=self.targets)
43
44
if self.found_target():
45
return # We found the target we want
46
47
if airodump.pid.poll() is not None:
48
return # Airodump process died
49
50
for target in self.targets:
51
if target.bssid in airodump.decloaked_bssids:
52
target.decloaked = True
53
54
self.print_targets()
55
56
target_count = len(self.targets)
57
client_count = sum(len(t.clients) for t in self.targets)
58
59
outline = '\r{+} Scanning'
60
if airodump.decloaking:
61
outline += ' & decloaking'
62
outline += '. Found'
63
outline += ' {G}%d{W} target(s),' % target_count
64
outline += ' {G}%d{W} client(s).' % client_count
65
outline += ' {O}Ctrl+C{W} when ready '
66
Color.clear_entire_line()
67
Color.p(outline)
68
69
if max_scan_time > 0 and time() > scan_start_time + max_scan_time:
70
return
71
72
sleep(1)
73
74
except KeyboardInterrupt:
75
pass
76
77
78
def found_target(self):
79
'''
80
Detect if we found a target specified by the user (optional).
81
Sets this object's `target` attribute if found.
82
Returns: True if target was specified and found, False otherwise.
83
'''
84
bssid = Configuration.target_bssid
85
essid = Configuration.target_essid
86
87
if bssid is None and essid is None:
88
return False # No specific target from user.
89
90
for target in self.targets:
91
if Configuration.wps_only and target.wps not in [WPSState.UNLOCKED, WPSState.LOCKED]:
92
continue
93
if bssid and target.bssid and bssid.lower() == target.bssid.lower():
94
self.target = target
95
break
96
if essid and target.essid and essid.lower() == target.essid.lower():
97
self.target = target
98
break
99
100
if self.target:
101
Color.pl('\n{+} {C}found target{G} %s {W}({G}%s{W})'
102
% (self.target.bssid, self.target.essid))
103
return True
104
105
return False
106
107
108
def print_targets(self):
109
'''Prints targets selection menu (1 target per row).'''
110
if len(self.targets) == 0:
111
Color.p('\r')
112
return
113
114
if self.previous_target_count > 0:
115
# We need to 'overwrite' the previous list of targets.
116
if Configuration.verbose <= 1:
117
# Don't clear screen buffer in verbose mode.
118
if self.previous_target_count > len(self.targets) or \
119
Scanner.get_terminal_height() < self.previous_target_count + 3:
120
# Either:
121
# 1) We have less targets than before, so we can't overwrite the previous list
122
# 2) The terminal can't display the targets without scrolling.
123
# Clear the screen.
124
from ..util.process import Process
125
Process.call('clear')
126
else:
127
# We can fit the targets in the terminal without scrolling
128
# 'Move' cursor up so we will print over the previous list
129
Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count))
130
131
self.previous_target_count = len(self.targets)
132
133
# Overwrite the current line
134
Color.p('\r{W}{D}')
135
136
# First row: columns
137
Color.p(' NUM')
138
Color.p(' ESSID')
139
if Configuration.show_bssids:
140
Color.p(' BSSID')
141
Color.pl(' CH ENCR POWER WPS? CLIENT')
142
143
# Second row: separator
144
Color.p(' ---')
145
Color.p(' -------------------------')
146
if Configuration.show_bssids:
147
Color.p(' -----------------')
148
Color.pl(' --- ---- ----- ---- ------{W}')
149
150
# Remaining rows: targets
151
for idx, target in enumerate(self.targets, start=1):
152
Color.clear_entire_line()
153
Color.p(' {G}%s ' % str(idx).rjust(3))
154
Color.pl(target.to_str(Configuration.show_bssids))
155
156
@staticmethod
157
def get_terminal_height():
158
import os
159
(rows, columns) = os.popen('stty size', 'r').read().split()
160
return int(rows)
161
162
@staticmethod
163
def get_terminal_width():
164
import os
165
(rows, columns) = os.popen('stty size', 'r').read().split()
166
return int(columns)
167
168
def select_targets(self):
169
'''
170
Returns list(target)
171
Either a specific target if user specified -bssid or --essid.
172
Otherwise, prompts user to select targets and returns the selection.
173
'''
174
175
if self.target:
176
# When user specifies a specific target
177
return [self.target]
178
179
if len(self.targets) == 0:
180
if self.err_msg is not None:
181
Color.pl(self.err_msg)
182
183
# TODO Print a more-helpful reason for failure.
184
# 1. Link to wireless drivers wiki,
185
# 2. How to check if your device supporst monitor mode,
186
# 3. Provide airodump-ng command being executed.
187
raise Exception('No targets found.'
188
+ ' You may need to wait longer,'
189
+ ' or you may have issues with your wifi card')
190
191
# Return all targets if user specified a wait time ('pillage').
192
if Configuration.scan_time > 0:
193
return self.targets
194
195
# Ask user for targets.
196
self.print_targets()
197
Color.clear_entire_line()
198
199
if self.err_msg is not None:
200
Color.pl(self.err_msg)
201
202
input_str = '{+} select target(s)'
203
input_str += ' ({G}1-%d{W})' % len(self.targets)
204
input_str += ' separated by commas, dashes'
205
input_str += ' or {G}all{W}: '
206
207
chosen_targets = []
208
209
for choice in raw_input(Color.s(input_str)).split(','):
210
choice = choice.strip()
211
if choice.lower() == 'all':
212
chosen_targets = self.targets
213
break
214
if '-' in choice:
215
# User selected a range
216
(lower,upper) = [int(x) - 1 for x in choice.split('-')]
217
for i in xrange(lower, min(len(self.targets), upper + 1)):
218
chosen_targets.append(self.targets[i])
219
elif choice.isdigit():
220
choice = int(choice) - 1
221
chosen_targets.append(self.targets[choice])
222
223
return chosen_targets
224
225
226
if __name__ == '__main__':
227
# 'Test' script will display targets and selects the appropriate one
228
Configuration.initialize()
229
try:
230
s = Scanner()
231
targets = s.select_targets()
232
except Exception as e:
233
Color.pl('\r {!} {R}Error{W}: %s' % str(e))
234
Configuration.exit_gracefully(0)
235
for t in targets:
236
Color.pl(' {W}Selected: %s' % t)
237
Configuration.exit_gracefully(0)
238
239
240