-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwardriver.py
1469 lines (1342 loc) · 66.6 KB
/
wardriver.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import re
import sqlite3
import os
from datetime import datetime, timezone
import toml
from threading import Lock
import json
import requests
from PIL import Image, ImageOps
import pwnagotchi.plugins as plugins
from pwnagotchi.ui.components import LabeledValue, Widget
from pwnagotchi.ui.view import BLACK
import pwnagotchi.ui.fonts as fonts
from flask import abort
from flask import render_template_string
import socket
import time
try:
import websockets
import asyncio
except:
pass
class Database():
def __init__(self, path):
self.__path = path
self.__db_connect()
self.remove_empty_sessions() # Remove old sessions that don't have networks
def __db_connect(self):
logging.info('[WARDRIVER] Setting up database connection...')
self.__connection = sqlite3.connect(self.__path, check_same_thread = False, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = self.__connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS sessions ("id" INTEGER, "created_at" TEXT DEFAULT CURRENT_TIMESTAMP, "wigle_uploaded" INTEGER DEFAULT 0, PRIMARY KEY("id" AUTOINCREMENT))') # sessions table contains wardriving sessions
cursor.execute('CREATE TABLE IF NOT EXISTS networks ("id" INTEGER, "mac" TEXT NOT NULL, "ssid" TEXT, PRIMARY KEY ("id" AUTOINCREMENT))') # networks table contains seen networks without coordinates/sessions info
cursor.execute('CREATE TABLE IF NOT EXISTS wardrive ("id" INTEGER, "session_id" INTEGER NOT NULL, "network_id" INTEGER NOT NULL, "auth_mode" TEXT NOT NULL, "latitude" TEXT NOT NULL, "longitude" TEXT NOT NULL, "altitude" TEXT NOT NULL, "accuracy" INTEGER NOT NULL, "channel" INTEGER NOT NULL, "rssi" INTEGER NOT NULL, "seen_timestamp" TEXT DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY("id" AUTOINCREMENT), FOREIGN KEY("session_id") REFERENCES sessions("id"), FOREIGN KEY("network_id") REFERENCES networks("id"))') # wardrive table contains the relations between sessions and networks with timestamp and coordinates
cursor.close()
self.__connection.commit()
logging.info('[WARDRIVER] Succesfully connected to db')
def disconnect(self):
self.__connection.commit()
self.__connection.close()
logging.info('[WARDRIVER] Closed db connection')
def new_wardriving_session(self, timestamp = None, wigle_uploaded = False):
cursor = self.__connection.cursor()
if timestamp:
cursor.execute('INSERT INTO sessions(created_at, wigle_uploaded) VALUES (?, ?)', [timestamp, wigle_uploaded])
else:
cursor.execute('INSERT INTO sessions(wigle_uploaded) VALUES (?)', [wigle_uploaded]) # using default values
session_id = cursor.lastrowid
cursor.close()
self.__connection.commit()
return session_id
def add_wardrived_network(self, session_id, mac, ssid, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi, seen_timestamp = None):
cursor = self.__connection.cursor()
cursor.execute('SELECT id FROM networks WHERE mac = ? AND ssid = ?', [mac, ssid])
network = cursor.fetchone()
network_id = network[0] if network else None
if(not network_id):
cursor.execute('INSERT INTO networks(mac, ssid) VALUES (?, ?)', [mac, ssid])
network_id = cursor.lastrowid
if seen_timestamp:
cursor.execute('INSERT INTO wardrive(session_id, network_id, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi, seen_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [session_id, network_id, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi, seen_timestamp])
else:
cursor.execute('INSERT INTO wardrive(session_id, network_id, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [session_id, network_id, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi])
cursor.close()
self.__connection.commit()
def session_networks_count(self, session_id):
'''
Return the total networks count for a wardriving session given its id
'''
cursor = self.__connection.cursor()
cursor.execute('SELECT COUNT(wardrive.id) FROM wardrive JOIN networks ON wardrive.network_id = networks.id WHERE wardrive.session_id = ? GROUP BY wardrive.session_id', [session_id])
row = cursor.fetchone()
cursor.close()
return row[0] if row else 0
def session_networks(self, session_id):
'''
Return networks data for a wardriving session given its id
'''
cursor = self.__connection.cursor()
networks = []
cursor.execute('SELECT networks.mac, networks.ssid, wardrive.auth_mode, wardrive.latitude, wardrive.longitude, wardrive.altitude, wardrive.accuracy, wardrive.channel, wardrive.rssi, wardrive.seen_timestamp FROM wardrive JOIN networks ON wardrive.network_id = networks.id WHERE wardrive.session_id = ?', [session_id])
rows = cursor.fetchall()
for row in rows:
mac, ssid, auth_mode, latitude, longitude, altitude, accuracy, channel, rssi, seen_timestamp = row
networks.append({
'mac': mac,
'ssid': ssid,
'auth_mode': auth_mode,
'latitude': latitude,
'longitude': longitude,
'altitude': altitude,
'accuracy': accuracy,
'channel': channel,
'rssi': rssi,
'seen_timestamp': seen_timestamp
})
cursor.close()
return networks
def session_uploaded_to_wigle(self, session_id):
cursor = self.__connection.cursor()
cursor.execute('UPDATE sessions SET "wigle_uploaded" = 1 WHERE id = ?', [session_id])
cursor.close()
self.__connection.commit()
def wigle_sessions_not_uploaded(self, current_session_id):
'''
Return the list of ids of sessions that haven't got uploaded on WiGLE excluding `current_session_id`
'''
cursor = self.__connection.cursor()
sessions_ids = []
cursor.execute('SELECT id FROM sessions WHERE wigle_uploaded = 0 AND id <> ?', [current_session_id])
rows = cursor.fetchall()
for row in rows:
sessions_ids.append(row[0])
cursor.close()
return sessions_ids
def remove_empty_sessions(self):
'''
Remove all sessions that doesn't have any network
'''
cursor = self.__connection.cursor()
cursor.execute('DELETE FROM sessions WHERE sessions.id NOT IN (SELECT wardrive.session_id FROM wardrive GROUP BY wardrive.session_id)')
cursor.close()
self.__connection.commit()
# Web UI queries
def general_stats(self):
cursor = self.__connection.cursor()
cursor.execute('SELECT COUNT(id) FROM networks')
total_networks = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(id) FROM sessions')
total_sessions = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(id) FROM sessions WHERE wigle_uploaded = 1')
sessions_uploaded = cursor.fetchone()[0]
cursor.close()
return {
'total_networks': total_networks,
'total_sessions': total_sessions,
'sessions_uploaded': sessions_uploaded
}
def sessions(self):
cursor = self.__connection.cursor()
cursor.execute('SELECT sessions.*, COUNT(wardrive.id) FROM sessions JOIN wardrive ON sessions.id = wardrive.session_id GROUP BY sessions.id')
rows = cursor.fetchall()
sessions = []
for row in rows:
sessions.append({
'id': row[0],
'created_at': row[1],
'wigle_uploaded': row[2] == 1,
'networks': row[3]
})
cursor.close()
return sessions
def current_session_stats(self, session_id):
cursor = self.__connection.cursor()
cursor.execute('SELECT created_at FROM sessions WHERE id = ?', [session_id])
created_at = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(id) FROM wardrive WHERE session_id = ?', [session_id])
networks = cursor.fetchone()[0]
cursor.close()
return {
"id": session_id,
"created_at": created_at,
"networks": networks
}
def networks(self):
cursor = self.__connection.cursor()
cursor.execute('SELECT n.*, MIN(w.seen_timestamp), MIN(w.session_id), MAX(w.seen_timestamp), MAX(w.session_id), COUNT(n.id) FROM networks n JOIN wardrive w ON n.id = w.network_id GROUP BY n.id')
rows = cursor.fetchall()
networks = []
for row in rows:
id, mac, ssid, first_seen, first_session, last_seen, last_session, sessions_count = row
networks.append({
"id": id,
"mac": mac,
"ssid": ssid,
"first_seen": first_seen,
"first_session": first_session,
"last_seen": last_seen,
"last_session": last_session,
"sessions_count": sessions_count
})
cursor.close()
return networks
def map_networks(self):
cursor = self.__connection.cursor()
cursor.execute('SELECT n.mac, n.ssid, w.latitude, w.longitude, w.altitude, w.accuracy FROM networks n JOIN wardrive w ON n.id = w.network_id')
rows = cursor.fetchall()
networks = []
for row in rows:
mac, ssid, latitude, longitude, altitude, accuracy = row
networks.append({
"mac": mac,
"ssid": ssid,
"latitude": float(latitude),
"longitude": float(longitude),
"altitude": float(altitude),
"accuracy": int(accuracy)
})
cursor.close()
return networks
class CSVGenerator():
def __init__(self):
self.__wigle_info()
def __wigle_info(self):
'''
Return info used in CSV pre-header
'''
try:
with open('/etc/pwnagotchi/config.toml', 'r') as config_file:
data = toml.load(config_file)
# Pwnagotchi name
device = data['main']['name']
# Pwnagotchi display model
display = data['ui']['display']['type'] # Pwnagotchi display
except Exception:
device = 'pwnagotchi'
display = 'unknown'
# Preheader formatting
file_format = 'WigleWifi-1.4'
app_release = Wardriver.__version__
# Device model
try:
with open('/sys/firmware/devicetree/base/model', 'r') as model_info:
model = model_info.read()
except Exception:
model = 'unknown'
# OS version
try:
with open('/etc/os-release', 'r') as release_info:
release = release_info.read().split('\n')[0].split('=')[-1].replace('"', '')
except Exception:
release = 'unknown'
# CPU model
try:
with open('/proc/cpuinfo', 'r') as cpu_model:
board = cpu_model.read().split('\n')[1].split(':')[1][1:]
except Exception:
board = 'unknown'
# Brand: currently set equal to model
brand = model
self.__wigle_file_format = file_format
self.__wigle_app_release = app_release
self.__wigle_model = model
self.__wigle_release = release
self.__wigle_device = device
self.__wigle_display = display
self.__wigle_board = board
self.__wigle_brand = brand
def __csv_header(self):
return 'MAC,SSID,AuthMode,FirstSeen,Channel,RSSI,CurrentLatitude,CurrentLongitude,AltitudeMeters,AccuracyMeters,Type\n'
def __csv_network(self, network):
return f'{network["mac"]},{network["ssid"]},{network["auth_mode"]},{network["seen_timestamp"]},{network["channel"]},{network["rssi"]},{network["latitude"]},{network["longitude"]},{network["altitude"]},{network["accuracy"]},WIFI\n'
def networks_to_csv(self, networks):
csv = self.__csv_header()
for network in networks:
csv += self.__csv_network(network)
return csv
def networks_to_wigle_csv(self, networks):
pre_header = f'{self.__wigle_file_format},{self.__wigle_app_release},{self.__wigle_model},{self.__wigle_release},{self.__wigle_device},{self.__wigle_display},{self.__wigle_board},{self.__wigle_brand}\n'
return pre_header + self.networks_to_csv(networks)
# Credits to Rai68: /~https://github.com/rai68/gpsd-easy
class GpsdClient():
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 2947
MAX_RETRIES = 5
def __init__(self, host, port):
self.host = host
self.port = port
self.__gpsd_socket = None
self.__gpsd_stream = None
def connect(self):
logging.debug('[WARDRIVER] Connecting to GPSD socket')
for attempt in range(self.MAX_RETRIES):
try:
self.__gpsd_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__gpsd_socket.connect((self.host, self.port))
self.__gpsd_stream = self.__gpsd_socket.makefile(mode="rw")
self.__gpsd_stream.write('?WATCH={"enable":true}\n')
self.__gpsd_stream.flush()
response_raw = self.__gpsd_stream.readline()
response = json.loads(response_raw)
if response['class'] != 'VERSION':
raise Exception('Invalid response received from GPSD socket')
logging.info('[WARDRIVER] Connected to GPSD socket')
return
except Exception as e:
logging.debug(f'[WARDRIVER] Failed connecting to GPSD socket (attempt {attempt + 1}/{self.MAX_RETRIES}): {e}')
time.sleep(5) # Sleep 5s between each try
def disconnect(self):
if self.__gpsd_socket:
self.__gpsd_socket.close()
self.__gpsd_socket = None
self.__gpsd_stream = None
def get_coordinates(self):
for attempt in range(self.MAX_RETRIES):
try:
self.__gpsd_stream.write('?POLL;\n')
self.__gpsd_stream.flush()
response_raw = self.__gpsd_stream.readline().strip()
if response_raw is None or response_raw == '':
continue
response = json.loads(response_raw)
if 'class' in response and response['class'] == 'POLL' and 'tpv' in response and len(response['tpv']) > 0:
return {
'Latitude': response['tpv'][0].get('lat', None),
'Longitude': response['tpv'][0].get('lon', None),
'Altitude': response['tpv'][0].get('alt', None)
}
except:
logging.error('[WARDRIVER] GPSD socket error. Reconnecting...')
self.disconnect()
try:
self.connect()
except:
return None
return None
# Credits to Jayofelony: /~https://github.com/jayofelony/pwnagotchi-torch-plugins/blob/main/pwndroid.py
class PwndroidClient:
DEFAULT_HOST = '192.168.44.1'
DEFAULT_PORT = 8080
def __init__(self, host='192.168.44.1', port=8080):
self.host = host
self.port = port
self.coordinates = {
'Latitude': None,
'Longitude': None,
'Altitude': None
}
self.__destroy = False
self.__websocket = None
async def connect(self):
while not self.__websocket and not self.__destroy:
try:
self.__websocket = await websockets.connect(f'ws://{self.host}:{self.port}')
logging.info('[WARDRIVER] Connected to pwndroid websocket')
await self.__get_gps_coordinates()
except Exception as e:
logging.critical('[WARDRIVER] Failed to connect to pwndroid websocket')
self.__websocket = None
await asyncio.sleep(10) # Wait 10 seconds between each retry
async def disconnect(self):
if self.__websocket:
await self.__websocket.close()
logging.info('[WARDRIVER] Closed connection to pwndroid websocket')
self.__websocket = None
self.__destroy = True
else:
logging.debug('[WARDRIVER] Cannot close websocket connection. No connection estabilished')
def is_connected(self):
return self.__websocket is not None
async def __get_gps_coordinates(self):
while self.__websocket:
try:
message = await self.__websocket.recv()
data = json.loads(message)
if 'Latitude' in data and 'Longitude' in data and 'Altitude' in data:
self.coordinates['Latitude'] = data['Latitude']
self.coordinates['Longitude'] = data['Longitude']
self.coordinates['Altitude'] = data['Altitude']
else:
logging.debug(f'[WARDRIVER] Invalid GPS data received from websocket: {json.dumps(data)}')
await asyncio.sleep(5) # Sleep for 5 seconds
except websockets.exceptions.ConnectionClosed:
logging.critical('[WARDRIVER] Websocket connection closed by pwndroid application. Will try to restabilish connection')
self.__websocket = None
except json.JSONDecodeError:
logging.debug('[WARDRIVER] Invalid data. Cannot decode as JSON data')
except Exception as e:
logging.error(f'[WARDRIVER] Error while getting GPS position. {e}')
class Wardriver(plugins.Plugin):
__author__ = 'CyberArtemio'
__version__ = '2.3'
__license__ = 'GPL3'
__description__ = 'A wardriving plugin for pwnagotchi. Saves all networks seen and uploads data to WiGLE once internet is available'
DEFAULT_PATH = '/root/wardriver' # SQLite database default path
DATABASE_NAME = 'wardriver.db' # SQLite database file name
ASSETS_URL = [
{
"name": "icon_error.bmp",
"url": "https://raw.githubusercontent.com/cyberartemio/wardriver-pwnagotchi-plugin/refs/heads/main/wardriver_assets/icon_error.bmp"
},
{
"name": "icon_working.bmp",
"url": "https://raw.githubusercontent.com/cyberartemio/wardriver-pwnagotchi-plugin/refs/heads/main/wardriver_assets/icon_working.bmp"
}
]
def __init__(self):
logging.debug('[WARDRIVER] Plugin created')
self.__db = None
self.__current_icon = ""
self.ready = False
self.__downloaded_assets = True
self.__agent_mode = None
self.__last_gps = {
"latitude": '-',
"longitude": '-',
"altitude": '-'
}
def on_loaded(self):
logging.info('[WARDRIVER] Plugin loaded (join the Discord server: https://discord.gg/5vrJbbW3ve)')
self.__lock = Lock()
self.__gps_available = True
try:
self.__path = self.options['path']
except Exception:
self.__path = self.DEFAULT_PATH
try:
self.__ui_enabled = self.options['ui']['enabled']
except Exception:
self.__ui_enabled = False
try:
self.__icon = self.options['ui']['icon']
except Exception:
self.__icon = True
self.__assets_path = os.path.join(os.path.dirname(__file__), "wardriver_assets")
os.makedirs(self.__assets_path, exist_ok=True)
for asset in self.ASSETS_URL:
if not os.path.isfile(os.path.join(self.__assets_path, asset["name"])):
logging.critical(f'[WARDRIVER] Asset {asset["name"]} is missing. Once internet is available it will be downloaded from GitHub')
self.__downloaded_assets = False
self.__icon = False
try:
self.__reverse = self.options['ui']['icon_reverse']
except Exception:
self.__reverse = False
try:
self.__ui_position = (self.options['ui']['position']['x'], self.options['ui']['position']['y'])
except Exception:
self.__ui_position = (7, 95)
try:
self.__whitelist = self.options['whitelist']
except Exception:
self.__whitelist = []
try:
self.__wigle_api_key = self.options['wigle']['api_key']
except Exception:
self.__wigle_api_key = None
try:
self.__wigle_donate = self.options['wigle']['donate']
except Exception:
self.__wigle_donate = False
try:
self.__wigle_enabled = self.options['wigle']['enabled']
if self.__wigle_enabled and (not self.__wigle_api_key or self.__wigle_api_key == ''):
logging.error('[WARDRIVER] Wigle enabled but no api key provided!')
self.__wigle_enabled = False
except Exception:
self.__wigle_enabled = False
self.__gps_config = dict()
try:
self.__gps_config['method'] = self.options['gps']['method']
if self.__gps_config['method'] not in ['bettercap', 'gpsd', 'pwndroid']:
logging.critical('[WARDRIVER] Invalid GPS method provided! Switching back to bettercap (default)')
raise Error()
except:
self.__gps_config['method'] = 'bettercap'
if not os.path.exists(self.__path):
os.makedirs(self.__path)
logging.warning('[WARDRIVER] Created db directory')
self.__db = Database(os.path.join(self.__path, self.DATABASE_NAME))
self.__csv_generator = CSVGenerator()
self.__session_reported = []
self.__last_ap_refresh = None
self.__last_ap_reported = []
logging.info(f'[WARDRIVER] Wardriver DB can be found in {self.__path}')
self.__load_global_whitelist()
if len(self.__whitelist) > 0:
logging.info(f'[WARDRIVER] Ignoring {len(self.__whitelist)} networks')
if self.__wigle_enabled:
logging.info('[WARDRIVER] Previous sessions will be uploaded to WiGLE once internet is available')
logging.info('[WARDRIVER] Join the WiGLE group: search "The crew of the Black Pearl" and start wardriving with us!')
self.__session_id = self.__db.new_wardriving_session()
self.ready = True
if self.__gps_config['method'] == 'gpsd':
try:
self.__gps_config['host'] = self.options['gps']['host']
self.__gps_config['port'] = self.options['gps']['port']
except:
self.__gps_config['host'] = GpsdClient.DEFAULT_HOST
self.__gps_config['port'] = GpsdClient.DEFAULT_PORT
try:
self.__gpsd_client = GpsdClient(host=self.__gps_config['host'], port=self.__gps_config['port'])
self.__gpsd_client.connect()
except:
logging.critical('[WARDRIVER] Failed connecting to GPSD. Will try again soon.')
elif self.__gps_config['method'] == 'pwndroid':
try:
self.__gps_config['host'] = self.options['gps']['host']
self.__gps_config['port'] = self.options['gps']['port']
except:
self.__gps_config['host'] = PwndroidClient.DEFAULT_HOST
self.__gps_config['port'] = PwndroidClient.DEFAULT_PORT
try:
self.__pwndroid_client = PwndroidClient(self.__gps_config['host'], self.__gps_config['port'])
asyncio.run(self.__pwndroid_client.connect())
except Exception as e:
logging.critical(f'[WARDRIVER] Unexpected error while connecting to pwndroid. Error: {e}')
def on_ready(self, agent):
self.__agent_mode = agent.mode
def __load_global_whitelist(self):
try:
with open('/etc/pwnagotchi/config.toml', 'r') as config_file:
data = toml.load(config_file)
for ssid in data['main']['whitelist']:
if ssid not in self.__whitelist:
self.__whitelist.append(ssid)
except Exception as e:
logging.critical('[WARDRIVER] Cannot read global config. Networks in global whitelist will NOT be ignored')
def on_ui_setup(self, ui):
if self.__ui_enabled:
logging.info('[WARDRIVER] Adding status text to ui')
wardriver_text_pos = (self.__ui_position[0] + 13, self.__ui_position[1]) if self.__icon else self.__ui_position
wardriver_text_label = '' if self.__icon else 'wardrive:'
ui.add_element('wardriver', LabeledValue(color = BLACK,
label = wardriver_text_label,
value = "Not started",
position = wardriver_text_pos,
label_font = fonts.Small,
text_font = fonts.Small))
if self.__icon:
ui.add_element('wardriver_icon', WardriverIcon(path = f'{self.__assets_path}/icon_working.bmp', xy = self.__ui_position, reverse = self.__reverse))
self.__current_icon = 'icon_working'
def on_ui_update(self, ui):
if self.__gps_config['method'] == 'gpsd' and self.ready:
self.__gpsd_client.get_coordinates() # Poll to keep the socket open
if self.__ui_enabled and self.ready and self.__agent_mode and self.__agent_mode != "manual":
ui.set('wardriver', f'{self.__db.session_networks_count(self.__session_id)} {"networks" if self.__icon else "nets"}')
if self.__gps_available and self.__current_icon == 'icon_error':
ui.remove_element('wardriver_icon')
ui.add_element('wardriver_icon', WardriverIcon(path = f'{self.__assets_path}/icon_working.bmp', xy = self.__ui_position, reverse = self.__reverse))
self.__current_icon = 'icon_working'
elif not self.__gps_available and self.__current_icon == 'icon_working':
ui.remove_element('wardriver_icon')
ui.add_element('wardriver_icon', WardriverIcon(path = f'{self.__assets_path}/icon_error.bmp', xy = self.__ui_position, reverse = self.__reverse))
self.__current_icon = 'icon_error'
def on_unload(self, ui):
if self.__ui_enabled:
with ui._lock:
ui.remove_element('wardriver')
if self.__icon:
ui.remove_element('wardriver_icon')
if self.__gps_config['method'] == 'gpsd':
self.__gpsd_client.disconnect()
if self.__gps_config['method'] == 'pwndroid':
asyncio.run(self.__pwndroid_client.disconnect())
self.__db.disconnect()
logging.info('[WARDRIVER] Plugin unloaded')
def __filter_whitelist_aps(self, unfiltered_aps):
'''
Filter whitelisted networks
'''
filtered_aps = [ ap for ap in unfiltered_aps if ap['hostname'] not in self.__whitelist ]
return filtered_aps
def __filter_reported_aps(self, unfiltered_aps):
'''
Filter already reported networks
'''
filtered_aps = [ ap for ap in unfiltered_aps if (ap['mac'], ap['hostname']) not in self.__session_reported ]
return filtered_aps
def on_unfiltered_ap_list(self, agent, aps):
gps_data = None
if not self.ready: # it is ready once the session file has been initialized with pre-header and header
logging.error('[WARDRIVER] Plugin not ready... skip wardriving log')
return
if self.__gps_config['method'] == 'bettercap':
info = agent.session()
gps_data = info["gps"]
if self.__gps_config['method'] == 'gpsd':
try:
gps_data = self.__gpsd_client.get_coordinates()
except:
gps_data = None
if self.__gps_config['method'] == 'pwndroid':
if self.__pwndroid_client.is_connected():
gps_data = self.__pwndroid_client.coordinates
if gps_data and all([ gps_data["Latitude"], gps_data["Longitude"] ]):
self.__gps_available = True
self.__last_ap_refresh = datetime.now()
self.__last_ap_reported = []
coordinates = {
'latitude': gps_data["Latitude"],
'longitude': gps_data["Longitude"],
'altitude': gps_data["Altitude"],
'accuracy': 50 # TODO: how can this be calculated?
}
self.__last_gps['latitude'] = gps_data['Latitude']
self.__last_gps['longitude'] = gps_data['Longitude']
self.__last_gps['altitude'] = gps_data['Altitude']
filtered_aps = self.__filter_whitelist_aps(aps)
filtered_aps = self.__filter_reported_aps(filtered_aps)
if len(filtered_aps) > 0:
logging.info(f'[WARDRIVER] Discovered {len(filtered_aps)} new networks')
for ap in filtered_aps:
mac = ap['mac']
ssid = ap['hostname'] if ap['hostname'] != '<hidden>' else ''
capabilities = ''
if ap['encryption'] != '':
capabilities = f'{capabilities}[{ap["encryption"]}]'
if ap['cipher'] != '':
capabilities = f'{capabilities}[{ap["cipher"]}]'
if ap['authentication'] != '':
capabilities = f'{capabilities}[{ap["authentication"]}]'
channel = ap['channel']
rssi = ap['rssi']
self.__last_ap_reported.append({
"mac": mac,
"ssid": ssid,
"capabilities": capabilities,
"channel": channel,
"rssi": rssi
})
self.__session_reported.append((mac, ssid))
self.__db.add_wardrived_network(session_id = self.__session_id,
mac = mac,
ssid = ssid,
auth_mode = capabilities,
channel = channel,
rssi = rssi,
latitude = coordinates['latitude'],
longitude = coordinates['longitude'],
altitude = coordinates['altitude'],
accuracy = coordinates['accuracy'])
else:
self.__gps_available = False
self.__last_gps['latitude'] = '-'
self.__last_gps['longitude'] = '-'
self.__last_gps['altitude'] = '-'
logging.warning("[WARDRIVER] GPS not available... skip wardriving log")
def __upload_session_to_wigle(self, session_id):
if self.__wigle_api_key != '':
headers = {
'Authorization': f'Basic {self.__wigle_api_key}',
'Accept': 'application/json'
}
networks = self.__db.session_networks(session_id)
csv = self.__csv_generator.networks_to_wigle_csv(networks)
data = {
'donate': 'on' if self.__wigle_donate else 'off'
}
file_form = {
'file': (f'session_{session_id}.csv', csv)
}
try:
response = requests.post(
url = 'https://api.wigle.net/api/v2/file/upload',
headers = headers,
data = data,
files = file_form,
timeout = 300
)
response.raise_for_status()
self.__db.session_uploaded_to_wigle(session_id)
logging.info(f'[WARDRIVER] Uploaded successfully session with id {session_id} on WiGLE')
return True
except Exception as e:
logging.error(f'[WARDRIVER] Failed uploading session with id {session_id}: {e}')
return False
else:
return False
def on_internet_available(self, agent):
if not self.__lock.locked() and self.ready:
with self.__lock:
if not self.__downloaded_assets:
logging.info(f'[WARDRIVER] Dowloading wardriver assets from Github')
self.__downloaded_assets = True
for asset in self.ASSETS_URL:
try:
response = requests.get(asset["url"])
response.raise_for_status()
with open(os.path.join(self.__assets_path, asset["name"]), 'wb') as f:
f.write(response.content)
except Exception as e:
logging.error(f'[WARDRIVER] Failed downloading {asset["name"]}: {e}')
self.__downloaded_assets = False
if self.__wigle_enabled:
sessions_to_upload = self.__db.wigle_sessions_not_uploaded(self.__session_id)
if len(sessions_to_upload) > 0:
logging.info(f'[WARDRIVER] Uploading previous sessions on WiGLE ({len(sessions_to_upload)} sessions) - current session will not be uploaded')
for session_id in sessions_to_upload:
self.__upload_session_to_wigle(session_id)
def on_webhook(self, path, request):
if request.method == 'GET':
if path == '/' or not path:
return render_template_string(HTML_PAGE, plugin_version = self.__version__)
elif path == 'current-session':
if not self.__agent_mode or self.__agent_mode == "manual":
return json.dumps({
"id": -1,
"created_at": None,
"networks": None,
"last_ap_refresh": None,
"last_ap_reported": None,
'gps': self.__last_gps
})
else:
data = self.__db.current_session_stats(self.__session_id)
data['last_ap_refresh'] = self.__last_ap_refresh.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") if self.__last_ap_refresh else None
data['last_ap_reported'] = self.__last_ap_reported
data['gps'] = self.__last_gps
return json.dumps(data)
elif path == 'general-stats':
stats = self.__db.general_stats()
stats['config'] = {
'wigle_enabled': self.__wigle_enabled,
'whitelist': self.__whitelist,
'db_path': self.__path,
'ui_enabled': self.__ui_enabled,
'wigle_api_key': self.__wigle_api_key,
'gps': self.__gps_config
}
return json.dumps(stats)
elif "csv/" in path:
session_id = path.split('/')[-1]
networks = self.__db.session_networks(session_id)
csv = self.__csv_generator.networks_to_csv(networks)
return csv
elif path == 'sessions':
sessions = self.__db.sessions()
return json.dumps(sessions)
elif 'upload/' in path:
session_id = path.split('/')[-1]
result = self.__upload_session_to_wigle(session_id)
logging.info(result)
return '{ "status": "Success" }' if result else'{ "status": "Error! Check the logs" }'
elif path == 'networks':
networks = self.__db.networks()
return json.dumps(networks)
elif path == 'map-networks':
networks = self.__db.map_networks()
center = ['-', '-']
if self.__last_gps['latitude'] != "-" and self.__last_gps['longitude'] != "-":
center[0] = self.__last_gps['latitude']
center[1] = self.__last_gps['longitude']
elif len(networks) > 0:
center[0] = networks[0]['latitude']
center[1] = networks[0]['longitude']
map_data = {
'center': center,
'networks': networks
}
return json.dumps(map_data)
else:
abort(404)
abort(404)
class WardriverIcon(Widget):
def __init__(self, path, xy, reverse, color = 0):
super().__init__(xy, color)
self.image = Image.open(path)
if(reverse):
self.image = ImageOps.invert(self.image.convert('L'))
def draw(self, canvas, drawer):
canvas.paste(self.image, self.xy)
HTML_PAGE = '''
{% extends "base.html" %}
{% set active_page = "plugins" %}
{% block title %}
Wardriver
{% endblock %}
{% block meta %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=0" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossorigin=""/>
{% endblock %}
{% block styles %}
{{ super() }}
<style>
.container {
margin-top: 10px;
margin-bottom: 30px;
}
header i {
font-size: 20px;
margin-top: 10px;
margin-right: 10px;
}
.center {
text-align: center;
}
#menu {
margin-top: 30px;
}
#menu div p {
cursor: pointer;
}
.visible {
display: initial;
}
.hidden {
display: none;
}
#map_networks {
height: 600px;
}
#sessions-table i {
cursor: pointer;
margin-right: 15px;
font-size: 16px;
}
#manu-alert p {
background-color: #fff5a5;
padding: 10px 20px!important;
text-align: center;
margin: auto!important;
border-radius: var(--pico-border-radius);
color: #000;
width: fit-content!important;
margin-bottom: 20px!important;
}
</style>
{% endblock %}
{% block content %}
<div class="container" data-theme="light">
<header>
<hgroup class="center">
<h1>Wardriver plugin</h1>
<p>v{{ plugin_version }} by <a href="/~https://github.com/cyberartemio/" target="_blank">cyberartemio</a></p>
<a href="https://discord.gg/5vrJbbW3ve" target="_blank"><i class="fa-brands fa-discord"></i></a>
<a href="/~https://github.com/cyberartemio/wardriver-pwnagotchi-plugin" target="_blank"><i class="fa-brands fa-github"></i></a>
</hgroup>
</header>
<main>
<div class="grid center" id="menu">
<div>
<p id="menu-current-session"><a><i class="fa-solid fa-satellite-dish"></i> Current session</a></p>
</div>
<div>
<p id="menu-stats"><a><i class="fa-solid fa-chart-line"></i> Stats</a></p>
</div>
<div>
<p id="menu-sessions"><a><i class="fa-solid fa-table"></i> Sessions</a></p>
</div>
<div>
<p id="menu-networks"><a><i class="fa-solid fa-wifi"></i> Networks</a></p>
</div>
<div>
<p id="menu-map"><a><i class="fa-solid fa-map-location-dot"></i> Map</a></p>
</div>
</div>
<div id="data-container">
<div id="current-session">
<h3>Current session</h3>
<div id="manu-alert" class="hidden">
<p><i class="fa-solid fa-triangle-exclamation"></i> Pwnagotchi is in MANU mode, therefore currently it's not scanning. Restart in AUTO/AI mode to start a new wardriving session</p>
</div>
<div class="grid">
<div>
<article class="center">
<header>Session id</header>
<span id="current-session-id">-</span>
</article>
</div>
<div>
<article class="center">
<header>Started at </header>
<span id="current-session-start">-</span>
</article>
</div>
<div>
<article class="center">
<header>Networks count</header>
<span id="current-session-networks">-</span>
</article>
</div>
<div>
<article class="center">
<header>Last APs refresh</header>
<span id="current-session-last-update">-</span>
</article>
</div>
</div>
<div class="grid">
<div>
<article class="center">
<header>Latitude</header>
<span id="current-session-gps-latitude">-</span>
</article>
</div>
<div>
<article class="center">
<header>Longitude</header>
<span id="current-session-gps-longitude">-</span>
</article>
</div>
<div>
<article class="center">
<header>Altitude</header>
<span id="current-session-gps-altitude">-</span>
</article>
</div>