/
server.py
423 lines (315 loc) · 12.2 KB
/
server.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# http://flask.pocoo.org/
from flask import Flask
from flask import render_template
from flask_caching import Cache
# JSON Handlers
import json
from bson import json_util
# Pymongo mongoDB connection library
# https://api.mongodb.com/python/current/
from pymongo import MongoClient
# Wigle Swagger API Interface
# https://pypi.org/project/pygle/
from pygle import network
app = Flask(__name__)
# Flask Local caching
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
# MongoDB Connection settings for PYMONGO
MONGO_IP = 'localhost'
MONGO_PORT = 27017
DATABASE = 'probe'
# Main data collection & geolocation collection in DB probe
COLLECTION_MAIN = 'main'
COLLECTION_GEOLOCATE = 'geo'
# collected data fields - projection used to exclude mongoDB document ID from JSON
DATA_FIELDS = {'_id': False, 'packet': True, 'timestamp': True, 'latitude': True, 'longitude': True, 'identifier': True,
'mac': True, 'vendor': True, 'SSID': True}
connection = MongoClient(MONGO_IP, MONGO_PORT)
collectionMain = connection[DATABASE][COLLECTION_MAIN]
collectionGeo = connection[DATABASE][COLLECTION_GEOLOCATE]
@app.route('/geo/<identifier>')
# Example JSON - URL Route = 0.0.0.0:5000/geo/eduroam
# [{"latitude": 41.15621567, "longitude": 1.11557901, "SSID": "eduroam", "BSSID": "00:22:57:48:67:02"},
# {"latitude": 41.15605164, "longitude": 1.11581504, "SSID": "eduroam", "BSSID": "00:22:57:48:69:02"},
# {"latitude": 41.40758133, "longitude": 2.17919087, "SSID": "eduroam", "BSSID": "00:22:57:48:81:02"}...]
def geo_location_json(identifier):
lats = []
lngs = []
ssids = []
netids = []
uniques = []
# First checks geo collection based on SSID field passed from URL route and returns unique instances of BSSID
# Cached Geolocations in collection for if wigle is down + allows to increase results for popular SSIDs as wigle returns only 100 results per request
for i in collectionGeo.find({"SSID": identifier}):
BSSID = i['BSSID']
SSID = i['SSID']
lat = i['latitude']
lng = i['longitude']
if BSSID in uniques:
continue
uniques.append(BSSID)
lats.append(lat)
lngs.append(lng)
ssids.append(SSID)
netids.append(BSSID)
# make search request to Wigle API through pygle library
res = network.search(ssid=identifier)
# if results are returned from Wigle they are checked against database results and new values are appended to JSON for display and also stored in geolocation collection
if res['success']:
for i in res['results']:
lat = i['trilat']
lng = i['trilong']
ssid = i['ssid']
netid = i['netid']
if netid in uniques:
continue
uniques.append(netid)
lats.append(lat)
lngs.append(lng)
ssids.append(ssid)
netids.append(netid)
collectionGeo.insert_one(
{
"BSSID": netid,
"SSID": ssid,
"latitude": lat,
"longitude": lng
})
outputjson = json.dumps([{'BSSID': BSSID, 'SSID': SSID, 'latitude': latitude, 'longitude': longitude} for BSSID, SSID, latitude, longitude in zip(netids, ssids, lats, lngs)])
else:
outputjson = json.dumps([{'BSSID': BSSID, 'SSID': SSID, 'latitude': latitude, 'longitude': longitude} for BSSID, SSID, latitude, longitude in zip(netids, ssids, lats, lngs)])
return outputjson
# Returns Json to url route 0.0.0.0:5000/geoall/<MAC ADDRESS> for for all associated networks
@app.route('/geoall/<identifier>')
def geo_location_all_json(identifier):
lats = []
lngs = []
ssids = []
netids = []
uniqueAP = []
SSIDList2 = dict()
for packet in collectionMain.find({"$and": [{"mac": identifier}, {"packet": 'PR-REQ'}]}):
SSID = packet['SSID']
# Filter only Visible SSIDs
if SSID == 'Broadcast':
continue
# O(1) lookup for data scalability
if SSID in SSIDList2:
continue
else:
SSIDList2[SSID] = True
print (SSID)
for networkz in SSIDList2:
for packet in collectionGeo.find({"SSID": networkz}):
BSSID = packet['BSSID']
SSID = packet['SSID']
lat = packet['latitude']
lng = packet['longitude']
uniqueAP.append(BSSID)
lats.append(lat)
lngs.append(lng)
ssids.append(SSID)
netids.append(BSSID)
for networkSSID in SSIDList2:
res = network.search(ssid=networkSSID)
if res['success']:
for packet in res['results']:
lat = packet['trilat']
lng = packet['trilong']
ssid = packet['ssid']
netid = packet['netid']
if netid in uniqueAP:
continue
uniqueAP.append(netid)
lats.append(lat)
lngs.append(lng)
ssids.append(ssid)
netids.append(netid)
collectionGeo.insert_one(
{
"BSSID": netid,
"SSID": ssid,
"latitude": lat,
"longitude": lng
})
else: continue
outputjson = json.dumps([{'BSSID': BSSID, 'SSID': SSID, 'latitude': latitude, 'longitude': longitude} for
BSSID, SSID, latitude, longitude in zip(netids, ssids, lats, lngs)])
return outputjson
# Returns Json to url route 0.0.0.0:5000/geoall/<MAC ADDRESS> for for all associated networks excluding public networks
@app.route('/geoallnofree/<identifier>')
def geo_location_allnofree_json(identifier):
lats = []
lngs = []
ssids = []
netids = []
uniqueAP = []
SSIDList = []
SSIDList2 = dict()
for packet in collectionMain.find({"$and": [{"mac": identifier}, {"packet": 'PR-REQ'}]}):
SSID = packet['SSID']
# Filter only Visible SSIDs
if SSID == 'Broadcast':
continue
# O(1) lookup for data scalability
if SSID in SSIDList2:
continue
else:
SSIDList2[SSID] = True
SSIDList.append(SSID)
for networkSSID in SSIDList:
res = network.search(ssid=networkSSID)
if res['success']:
for packet in res['results']:
lat = packet['trilat']
lng = packet['trilong']
ssid = packet['ssid']
netid = packet['netid']
freenet = packet['freenet']
paynet = packet['paynet']
if freenet == 'Y':
continue
if paynet == 'Y':
continue
if netid in uniqueAP:
continue
uniqueAP.append(netid)
lats.append(lat)
lngs.append(lng)
ssids.append(ssid)
netids.append(netid)
collectionGeo.insert_one(
{
"BSSID": netid,
"SSID": ssid,
"latitude": lat,
"longitude": lng,
})
else:
continue
outputjson = json.dumps([{'BSSID': BSSID, 'SSID': SSID, 'latitude': latitude, 'longitude': longitude} for
BSSID, SSID, latitude, longitude in zip(netids, ssids, lats, lngs)])
return outputjson
# Three navigation routes
# Render index.html at URL Route /
@app.route("/")
@cache.cached(timeout=5000)
def index():
return render_template("index.html")
# Render vendor.html at URL Route /vendor
@app.route("/vendor")
@cache.cached(timeout=5000)
def vendor_analysis():
return render_template("vendor.html")
# Render ssid.html at URL Route /ssid
@app.route("/ssid")
@cache.cached(timeout=5000)
def ssid_analysis_nl():
return render_template("ssid.html")
# Render ssidnolocal.html at URL Route /ssidnolocal
@app.route("/ssidnolocal")
@cache.cached(timeout=5000)
def ssid_analysis():
return render_template("ssidnolocal.html")
# Dynamic URL route for displaying geolocation map based on SSID
@app.route("/geolocate/<identifier>")
def geo_location(identifier):
return render_template("geo.html")
@app.route("/geolocateall/<identifier>")
def geo_location_all(identifier):
return render_template("geoall.html")
@app.route("/geolocateallnofree/<identifier>")
def geo_location_allnofree(identifier):
return render_template("geoallnofree.html")
# Returns JSON to URL Route = /uniquessidsnolocal based on Collection Query and filter
@app.route("/uniquessidsnolocal")
@cache.cached(timeout=5000, key_prefix='UniSSIDLocal')
def get_uniquessidsnolocal():
uniques = []
APoints = dict()
checkList = dict()
# Retrieves AP Becons and stores unique instances of Network based on SSID and name (SSID useful dimention for filtering probe requests against)
for AP in collectionMain.find({"packet": 'AP-BEC'}):
SSID = AP['SSID']
timestamp = AP['timestamp']
timestampTrim = timestamp[0:14]
# Timestamp = '10/08/2018 13'
# Checks data entry on same day and within same hour (Local range of data collection)
# O(1) lookup for data scalability
if SSID in APoints:
if timestampTrim in APoints[SSID]:
continue
else:
APoints[SSID].append(timestampTrim)
else:
APoints[SSID] = [timestampTrim]
for packet in collectionMain.find({"packet": 'PR-REQ'}):
mac = packet['mac']
SSID = packet['SSID']
timestamp = packet['timestamp']
timestampTrim = timestamp[0:14]
# Filter only Visible SSIDs
if SSID == 'Broadcast':
continue
if SSID in APoints:
if timestampTrim in APoints[SSID]:
continue
# O(1) lookup for data scalability
if mac in checkList:
if SSID in checkList[mac]:
continue
else:
checkList[mac].append(SSID)
uniques.append(packet)
else:
checkList[mac] = [SSID]
uniques.append(packet)
outputjson = json.dumps(uniques, default=json_util.default, separators=(',', ':'))
connection.close()
return outputjson
# Returns JSON to URL Route = /uniquessids based on Collection Query and filter
# One instance of an SSID -> MAC Address
@app.route("/uniquessids")
@cache.cached(timeout=5000, key_prefix='UniSSID')
def get_uniqueSSID():
uniques = []
checkList = dict()
for packet in collectionMain.find({"$and": [{"packet": 'PR-REQ'}, {"SSID": {"$ne": 'Broadcast'}}]}):
ssid = packet['SSID']
mac = packet['mac']
# O(1) lookup for data scalability
if mac in checkList:
if ssid in checkList[mac]:
continue
else:
checkList[mac].append(ssid)
uniques.append(packet)
else:
checkList[mac] = [ssid]
uniques.append(packet)
outputjson = json.dumps(uniques, default=json_util.default, separators=(',', ':'))
connection.close()
return outputjson
# Returns ALL JSON to URL Route = /json based on full Collection Query
@app.route("/json")
@cache.cached(timeout=5000, key_prefix='all_data')
def get_data():
packet_documents = []
for packet in collectionMain.find(projection=DATA_FIELDS):
packet_documents.append(packet)
packet_documents_json = json.dumps(packet_documents, default=json_util.default, separators=(',', ':'))
connection.close()
return packet_documents_json
# Returns ALL JSON to URL Route = /vendorbub removing Unknown Vendors
@app.route("/vendorbub")
@cache.cached(timeout=5000, key_prefix='V_bub')
def vendor_bubble_chart():
packets = collectionMain.find({"vendor": {"$ne": 'Unknown Vendor'}})
packet_documents = []
for packet in packets:
packet_documents.append(packet)
packet_documents_json = json.dumps(packet_documents, default=json_util.default, separators=(',', ':'))
connection.close()
return packet_documents_json
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)