forked from infobyte/wardriving
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_wigle.py
348 lines (305 loc) · 11.6 KB
/
import_wigle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
"""
Faraday Penetration Test IDE
Copyright (C) 2013 Infobyte LLC (http://www.infobytesec.com/)
See the file 'doc/LICENSE' for the license information
"""
import os
import time
from base64 import b64encode
from tempfile import NamedTemporaryFile
from collections import defaultdict
try:
from staticmap import StaticMap, CircleMarker
except ImportError:
print('Please install staticmap with: pip install staticmap')
from persistence.server import models
from persistence.server.server import _save_to_couch
from persistence.server.server_io_exceptions import ConflictInDatabase, CantCommunicateWithServerError, ResourceDoesNotExist
from model.common import factory
from math import radians, cos, sin, asin, sqrt
factory.register(models.Host)
factory.register(models.Vuln)
factory.register(models.Service)
factory.register(models.Interface)
__description__ = 'Import every AP found in a PCAP file'
__prettyname__ = 'Import Wardriving PCAP'
access_point_data = defaultdict(dict)
created_objs = defaultdict(set)
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
try:
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
except ValueError:
return 9999
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def save_objs(workspace_name):
"""
This function uses a set to avoid hitting too much couchdb.
Wifi packets usually are repeated, for example for beacons.
:param workspace_name:
:return:
"""
order = ['Host', 'Interface', 'Service', 'Vulnerability']
saved_ids = set()
tmp = created_objs
iterable = tmp.items()
for type in order:
for key, objs in iterable:
if key == type:
try:
if key == 'Host':
print('Total {0}: {1}'.format(key, len(objs)))
for obj in objs:
if obj.id in saved_ids:
models.update_host(workspace_name, obj)
else:
models.create_host(workspace_name, obj)
saved_ids.add(obj.id)
if key == 'Service':
print('Total {0}: {1}'.format(key, len(objs)))
for obj in objs:
if obj.id in saved_ids:
models.update_service(workspace_name, obj)
else:
models.create_service(workspace_name, obj)
saved_ids.add(obj.id)
if key == 'Vulnerability':
print('Total {0}: {1}'.format(key, len(objs)))
for obj in objs:
if obj.id in saved_ids:
models.update_vuln(workspace_name, obj)
else:
models.create_vuln(workspace_name, obj)
if key == 'Interface':
print('Total {0}: {1}'.format(key, len(objs)))
for obj in objs:
if obj.id in saved_ids:
models.update_interface(workspace_name, obj)
else:
models.create_interface(workspace_name, obj)
saved_ids.add(obj.id)
except ConflictInDatabase as e:
print('Document already exists skipping.')
print(e)
continue
except CantCommunicateWithServerError as e:
print('error')
print(e)
except ResourceDoesNotExist as e:
print('Missing DB {0}'.format(workspace_name))
print(e)
continue
except Exception as e:
print(e)
def draw_map():
m = StaticMap(4000, 4000)
for key, access_point in access_point_data.items():
if not ('lat' in access_point and 'lng' in access_point):
continue
coords = (access_point['lat'], access_point['lng'])
if access_point['lng'] - -34.611944444444 > 0.1:
continue
if access_point['lat'] - -58.364722222222 > 0.1:
continue
colors = {
'open': 'red',
'wep': 'red',
'wpa': 'yellow',
'wpa2': 'green'
}
marker_outline = CircleMarker(coords, colors[access_point['encryption']], 18)
marker = CircleMarker(coords, colors[access_point['encryption']], 12)
m.add_marker(marker_outline)
m.add_marker(marker)
image = m.render(zoom=15)
temp_file = NamedTemporaryFile(suffix='.png')
image.save(temp_file.name)
image.save('/home/lcubo/test1.png')
return temp_file
def create_host_interface_and_vuln(workspace_name, access_point):
bssid = access_point['bssid']
try:
essid = access_point['essid'].encode('utf8')
except Exception:
return
encryption = access_point['encryption']
host = factory.createModelObject(
models.Host.class_signature,
essid,
workspace_name=workspace_name,
os=encryption,
mac=bssid,
parent_id=None)
access_point['host'] = host
if host.id not in map(lambda host: host.id, created_objs['Host']):
created_objs['Host'].add(host)
interface = factory.createModelObject(
models.Interface.class_signature,
'',
workspace_name,
mac=bssid,
ipv4_address='',
ipv4_gateway='',
ipv4_mask='',
ipv4_dns='',
ipv6_address='',
ipv6_gateway='',
ipv6_prefix='',
ipv6_dns='',
network_segment='',
parent_id=host.id)
if interface.id not in map(lambda interface: interface.id, created_objs['Interface']):
created_objs['Interface'].add(interface)
access_point['interface'] = interface
service = factory.createModelObject(
models.Service.class_signature,
encryption,
workspace_name,
protocol='802.11',
status='open',
description='Access point encryption',
ports=[0],
version='',
service='open',
parent_id=interface.id
)
if service.id not in map(lambda service: service.id, created_objs['Service']):
created_objs['Service'].add(service)
if encryption in ['open', 'wep']:
vuln = factory.createModelObject(
models.Vuln.class_signature,
'Insecure WiFi {0} found'.format(essid),
workspace_name,
severity='critical',
confirmed='true',
status='open',
desc='WiFi using {0} was found. Please change your router configuration.'.format(encryption),
parent_id=host.id
)
if vuln.id not in map(lambda vuln: vuln.id, created_objs['Vulnerability']):
created_objs['Vulnerability'].add(vuln)
def process_wigle_sqlite(workspace_name, wigle_filename):
try:
import sqlite3
except ImportError:
print('For using wigle import, sqlite3 is required. Please install it with: pip install sqlite3')
conn = sqlite3.connect(wigle_filename)
cursor = conn.execute('SELECT bssid, ssid, capabilities, bestlat, bestlon from network')
for network in cursor:
bssid = network[0]
essid = network[1]
capability = network[2].lower()
lat = network[4]
lng = network[3]
access_point = access_point_data[bssid]
if 'wpa' in capability and 'wpa2' not in capability:
encryption = 'wpa'
if 'wpa2' in capability:
encryption = 'wpa2'
if 'wep' in capability:
encryption = 'wep'
if 'open' in capability:
encryption = 'open'
access_point['essid'] = essid
access_point['bssid'] = bssid
access_point['encryption'] = encryption
access_point['lat'] = lat
access_point['lng'] = lng
create_host_interface_and_vuln(workspace_name, access_point)
map_file = draw_map()
map_file.seek(0)
now_timestamp = time.time()
host = factory.createModelObject(
models.Host.class_signature,
'War driving results',
workspace_name=workspace_name,
parent_id=None)
interface = factory.createModelObject(
models.Interface.class_signature,
'',
workspace_name,
mac=bssid,
ipv4_address='',
ipv4_gateway='',
ipv4_mask='',
ipv4_dns='',
ipv6_address='',
ipv6_gateway='',
ipv6_prefix='',
ipv6_dns='',
network_segment='',
parent_id=host.id)
service = factory.createModelObject(
models.Service.class_signature,
encryption,
workspace_name,
protocol='802.11',
status='open',
description='Access point encryption',
ports=[0],
version='',
service='open',
parent_id=interface.id
)
try:
models.create_host(workspace_name, host)
except ConflictInDatabase:
pass
try:
models.create_interface(workspace_name, interface)
except ConflictInDatabase:
pass
try:
models.create_service(workspace_name, service)
except ConflictInDatabase:
pass
name = 'Wardriving Map'
description = 'See evidence for war driving map.'
parent_id = host.id
raw_obj = {
"metadata": {"update_time": now_timestamp, "update_user": "", "update_action": 0, "creator": "UI Web",
"create_time": now_timestamp, "update_controller_action": "UI Web New", "owner": ""},
"obj_id": "0c41d85f6dc71044518eea211bfbd12f2bad6f73", "owner": "",
"parent": parent_id, "type": "Vulnerability", "ws": "wifi", "confirmed": True,
"data": "", "desc": description, "easeofresolution": "",
"impact": {"accountability": False, "availability": False, "confidentiality": False, "integrity": False},
"name": name, "owned": False, "policyviolations": [], "refs": [], "resolution": "", "severity": "info",
"status": "opened",
"_attachments": {
"map.png": {
"content_type": "image/png",
"data": b64encode(map_file.read())}},
"protocol": "", "version": ""}
obj = models.ModelBase(raw_obj, workspace_name)
obj.setID(parent_id, name, description)
vuln_id = obj.id
raw_obj.update({"_id": vuln_id})
try:
_save_to_couch(workspace_name, vuln_id, **raw_obj)
except ConflictInDatabase:
pass
map_file.close()
def main(workspace='', args=None, parser=None):
parser.add_argument('--dry-run', action='store_true', help='Do not touch the database. Only print the object ID')
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output from the pcapfile library.')
parser.add_argument('wigle_sqlite', help='Wigle sqlite for gps coordinates'),
parsed_args = parser.parse_args(args)
if not os.path.isfile(parsed_args.wigle_sqlite):
print("wigle sqlite file not found: %s" % parsed_args.wigle_sqlite)
return 2, None
process_wigle_sqlite(workspace, parsed_args.wigle_sqlite)
if not parsed_args.dry_run:
save_objs(workspace)
return 0, None