-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfix_services_ng.py
541 lines (492 loc) · 21.4 KB
/
fix_services_ng.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
import logging
import re
import subprocess
import time
import random
from io import TextIOWrapper
import pwnagotchi
from pwnagotchi import plugins
import pwnagotchi.ui.faces as faces
from pwnagotchi.bettercap import Client
class FixServices_ng(plugins.Plugin):
__GitHub__ = ""
__author__ = "(edited by: itsdarklikehell [email protected]), jayofelony"
__version__ = "1.0"
__license__ = "GPL3"
__description__ = "Fix blindness, firmware crashes and brain not being loaded"
__name__ = "Fix_Services_ng"
__help__ = """
Reload brcmfmac module when blindbug is detected, instead of rebooting. Adapted from WATCHDOG.
"""
__defaults__ = {
"enabled": True,
}
def __init__(self):
self.options = dict()
self.pattern1 = re.compile(r"wifi error while hopping to channel")
self.pattern2 = re.compile(r"Firmware has halted or crashed")
self.pattern3 = re.compile(
r"error 400: could not find interface wlan0mon")
self.isReloadingMon = False
self.connection = None
self.LASTTRY = 0
self._count = 0
def on_loaded(self):
"""
Gets called when the plugin gets loaded
"""
logging.info(f"[{self.__class__.__name__}] plugin loaded")
def on_ready(self, agent):
last_lines = self.get_last_lines("journalctl", ["-n10", "-k"], 10)
try:
cmd_output = subprocess.check_output(
"ip link show wlan0mon", shell=True)
logging.debug(
f"[{self.__class__.__name__}] [ip link show wlan0mon]: %s"
% repr(cmd_output)
)
if ",UP," in str(cmd_output):
logging.info("wlan0mon is up.")
logging.info(f"[{self.__class__.__name__}] Logs look good!")
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [ip link show wlan0mon]: %s" % repr(
err)
)
try:
self._tryTurningItOffAndOnAgain(agent)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [OffNOn]: %s" % repr(err))
# bettercap sys_log event
# search syslog events for the brcmf channel fail, and reset when it shows up
# apparently this only gets messages from bettercap going to syslog, not from syslog
def on_bcap_sys_log(self, agent, event):
if re.search("wifi error while hopping to channel", event["data"]["Message"]):
logging.info(
f"[{self.__class__.__name__}]SYSLOG MATCH: %s"
% event["data"]["Message"]
)
logging.info(
f"[{self.__class__.__name__}]**** restarting wifi.recon")
try:
result = agent.run("wifi.recon off; wifi.recon on")
if result["success"]:
logging.info(
f"[{self.__class__.__name__}] wifi.recon flip: success!"
)
if hasattr(agent, "view"):
display = agent.view()
if display:
display.update(
force=True,
new_data={
"status": "Wifi recon flipped!",
"face": faces.COOL,
},
)
else:
print("Wifi recon flipped")
else:
logging.warning(
f"[{self.__class__.__name__}] wifi.recon flip: FAILED: %s"
% repr(result)
)
self._tryTurningItOffAndOnAgain(agent)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}]SYSLOG wifi.recon flip fail: %s" % err
)
self._tryTurningItOffAndOnAgain(agent)
def get_last_lines(self, command, args, n):
try:
process = subprocess.Popen(
[command] + args, stdout=subprocess.PIPE)
output = TextIOWrapper(process.stdout)
lines = output.readlines()
last_n_lines = "".join(lines[-n:])
return last_n_lines
except Exception as e:
print(f"Error occurred: {e}")
return None
def on_epoch(self, agent, epoch, epoch_data):
last_lines = self.get_last_lines("journalctl", ["-n10", "-k"], 10)
other_last_lines = self.get_last_lines("journalctl", ["-n10"], 10)
other_other_last_lines = self.get_last_lines(
"tail", ["-n10", "/home/pi/logs/pwnagotchi.log"], 10
)
# don't check if we ran a reset recently
logging.debug(f"[{self.__class__.__name__}]**** epoch")
if time.time() - self.LASTTRY > 180:
# get last 10 lines
display = None
logging.debug(f"[{self.__class__.__name__}]**** checking")
# Look for pattern 1
if len(self.pattern1.findall(other_last_lines)) >= 5:
logging.debug(
f"[{self.__class__.__name__}]**** Should trigger a reload of the wlan0mon device:\n%s"
% last_lines
)
if hasattr(agent, "view"):
display = agent.view()
display.set(
"status", "Wifi channel stuck. Restarting recon.")
display.update(force=True)
logging.info(
f"[{self.__class__.__name__}] Wifi channel stuck. Restarting recon."
)
try:
result = agent.run("wifi.recon off; wifi.recon on")
if result["success"]:
logging.info(
f"[{self.__class__.__name__}] wifi.recon flip: success!"
)
if display:
display.update(
force=True,
new_data={
"status": "Wifi recon flipped!",
"face": faces.COOL,
},
)
else:
print("Wifi recon flipped\nthat was easy!")
else:
logging.warning(
f"[{self.__class__.__name__}] wifi.recon flip: FAILED: %s"
% repr(result)
)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [wifi.recon flip] %s" % repr(
err)
)
# Look for pattern 2
elif len(self.pattern2.findall(other_last_lines)) >= 1:
logging.info(
f"[{self.__class__.__name__}] Firmware has halted or crashed. Restarting wlan0mon."
)
if hasattr(agent, "view"):
display = agent.view()
display.set(
"status", "Firmware has halted or crashed. Restarting wlan0mon."
)
display.update(force=True)
try:
# Run the monstart command to restart wlan0mon
cmd_output = subprocess.check_output(
"monstart", shell=True)
logging.debug(
f"[{self.__class__.__name__}] [monstart]: %s" % repr(
cmd_output)
)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [monstart]: %s" % repr(
err)
)
# Look for pattern 3
elif len(self.pattern3.findall(other_other_last_lines)) >= 3:
logging.info(f"[{self.__class__.__name__}] wlan0 is down!")
if hasattr(agent, "view"):
display = agent.view()
display.set("status", "Restarting wlan0 now!")
display.update(force=True)
try:
# Run the monstart command to restart wlan0mon
cmd_output = subprocess.check_output(
"monstart", shell=True)
logging.debug(
f"[{self.__class__.__name__}] [monstart]: %s" % repr(
cmd_output)
)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [monstart]: %s" % repr(
err)
)
else:
print("logs look good")
def logPrintView(self, level, message, ui=None, displayData=None, force=True):
try:
if level == "error":
logging.error(message)
elif level == "warning":
logging.warning(message)
elif level == "debug":
logging.debug(message)
else:
logging.info(message)
if ui:
ui.update(force=force, new_data=displayData)
elif displayData and "status" in displayData:
print(displayData["status"])
else:
print("[%s] %s" % (level, message))
except Exception as err:
logging.error("[logPrintView] ERROR %s" % repr(err))
def _tryTurningItOffAndOnAgain(self, connection):
# avoid overlapping restarts, but allow it if it's been a while
# (in case the last attempt failed before resetting "isReloadingMon")
if self.isReloadingMon and (time.time() - self.LASTTRY) < 180:
logging.info(
f"[{self.__class__.__name__}] Duplicate attempt ignored")
else:
self.isReloadingMon = True
self.LASTTRY = time.time()
if hasattr(connection, "view"):
display = connection.view()
if display:
display.update(
force=True,
new_data={
"status": "I'm blind! Try turning it off and on again",
"face": faces.BORED,
},
)
else:
display = None
# main divergence from WATCHDOG starts here
#
# instead of rebooting, and losing all that energy loading up the AI
# pause wifi.recon, close wlan0mon, reload the brcmfmac kernel module
# then recreate wlan0mon, ..., and restart wifi.recon
# Turn it off
# attempt a sanity check. does wlan0mon exist?
# is it up?
try:
cmd_output = subprocess.check_output(
"ip link show wlan0mon", shell=True
)
logging.debug(
f"[{self.__class__.__name__}] [ip link show wlan0mon]: %s"
% repr(cmd_output)
)
if ",UP," in str(cmd_output):
logging.info("wlan0mon is up. Skip reset?")
# not reliable, so don't skip just yet
# print("wlan0mon is up. Skipping reset.")
# self.isReloadingMon = False
# return
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [ip link show wlan0mon]: %s"
% repr(err)
)
try:
result = connection.run("wifi.recon off")
if "success" in result:
self.logPrintView(
"info",
f"[{self.__class__.__name__}] wifi.recon off: %s!"
% repr(result),
display,
{"status": "Wifi recon paused!", "face": faces.COOL},
)
time.sleep(2)
else:
self.logPrintView(
"warning",
f"[{self.__class__.__name__}] wifi.recon off: FAILED: %s"
% repr(result),
display,
{
"status": "Recon was busted (probably)",
"face": random.choice((faces.BROKEN, faces.DEBUG)),
},
)
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [wifi.recon off] error %s"
% (repr(err))
)
logging.info(
f"[{self.__class__.__name__}] recon paused. Now trying wlan0mon reload"
)
try:
cmd_output = subprocess.check_output("monstop", shell=True)
self.logPrintView(
"info",
f"[{self.__class__.__name__}] wlan0mon down and deleted: %s"
% cmd_output,
display,
{"status": "wlan0mon d-d-d-down!", "face": faces.BORED},
)
except Exception as nope:
logging.error(
f"[{self.__class__.__name__}] [delete wlan0mon] %s" % nope
)
pass
logging.debug(
f"[{self.__class__.__name__}] Now trying modprobe -r")
# Try this sequence 3 times until it is reloaded
#
# Future: while "not fixed yet": blah blah blah. if "max_attemts", then reboot like the old days
#
tries = 0
while tries < 3:
try:
# unload the module
cmd_output = subprocess.check_output(
"sudo modprobe -r brcmfmac", shell=True
)
self.logPrintView(
"info",
f"[{self.__class__.__name__}] unloaded brcmfmac",
display,
{"status": "Turning it off #%s" %
tries, "face": faces.SMART},
)
time.sleep(1 + tries)
# reload the module
try:
# reload the brcmfmac kernel module
cmd_output = subprocess.check_output(
"sudo modprobe brcmfmac", shell=True
)
self.logPrintView(
"info", f"[{self.__class__.__name__}] reloaded brcmfmac"
)
time.sleep(
10 + 4 * tries
) # give it some time for wlan device to stabilize, or whatever
# success! now make the mon0
try:
cmd_output = subprocess.check_output(
"monstart", shell=True)
self.logPrintView(
"info",
f"[{self.__class__.__name__}] [interface add wlan0mon] worked #%s: %s"
% (tries, cmd_output),
)
time.sleep(tries + 5)
try:
# try accessing mon0 in bettercap
result = connection.run(
"set wifi.interface wlan0mon")
if "success" in result:
logging.info(
f"[{self.__class__.__name__}] [set wifi.interface wlan0mon] worked!"
)
self._count = self._count + 1
time.sleep(1)
# stop looping and get back to recon
break
else:
logging.debug(
f"[{self.__class__.__name__}] [set wifi.interfaceface wlan0mon] failed? %s"
% repr(result)
)
except Exception as err:
logging.debug(
f"[{self.__class__.__name__}] [set wifi.interface wlan0mon] except: %s"
% repr(err)
)
except Exception as cerr: #
if not display:
print(
"failed loading wlan0mon attempt #%s: %s"
% (tries, repr(cerr))
)
except Exception as err: # from modprobe
if not display:
print("Failed reloading brcmfmac")
logging.error(
f"[{self.__class__.__name__}] Failed reloading brcmfmac %s"
% repr(err)
)
except Exception as nope: # from modprobe -r
# fails if already unloaded, so probably fine
logging.error(
f"[{self.__class__.__name__}] [#%s modprobe -r] %s"
% (tries, repr(nope))
)
if not display:
print(
f"[{self.__class__.__name__}] [#%s modprobe -r] %s"
% (tries, repr(nope))
)
pass
tries = tries + 1
if tries < 3:
logging.info(
f"[{self.__class__.__name__}] wlan0mon didn't make it. trying again"
)
if not display:
print(" wlan0mon didn't make it. trying again")
else:
logging.info(
f"[{self.__class__.__name__}] wlan0mon loading failed, no choice but to reboot .."
)
pwnagotchi.reboot()
# exited the loop, so hopefully it loaded
if tries < 3:
if display:
display.update(
force=True,
new_data={
"status": "And back on again...",
"face": faces.INTENSE,
},
)
else:
print("And back on again...")
logging.info(f"[{self.__class__.__name__}] wlan0mon back up")
else:
self.LASTTRY = time.time()
time.sleep(
8 + tries * 2
) # give it a bit before restarting recon in bettercap
self.isReloadingMon = False
logging.info(f"[{self.__class__.__name__}] re-enable recon")
try:
result = connection.run("wifi.clear; wifi.recon on")
if "success" in result: # and result["success"] is True:
if display:
display.update(
force=True,
new_data={
"status": "I can see again! (probably)",
"face": faces.HAPPY,
},
)
else:
print("I can see again")
logging.debug(f"[{self.__class__.__name__}] wifi.recon on")
# 2-minute pause until next time.
self.LASTTRY = time.time() + 120
else:
logging.error(
f"[{self.__class__.__name__}] wifi.recon did not start up"
)
self.LASTTRY = time.time() - 300 # failed, so try again ASAP
self.isReloadingMon = False
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] [wifi.recon on] %s" % repr(
err)
)
pwnagotchi.reboot()
def on_unload(self, ui):
with ui._lock:
try:
logging.info(f"[{self.__class__.__name__}] unloaded")
except Exception as err:
logging.error(
f"[{self.__class__.__name__}] unload err %s " % repr(err))
pass
# run from command line to brute force a reload
if __name__ == "__main__":
print("Performing brcmfmac reload and restart wlan0mon in 5 seconds...")
fb = FixServices()
data = {
"Message": "kernel: brcmfmac: brcmf_cfg80211_nexmon_set_channel: Set Channel failed: chspec=1234"
}
event = {"data": data}
agent = Client("localhost", port=8081,
username="pwnagotchi", password="pwnagotchi")
time.sleep(2)
print("3 seconds")
time.sleep(3)
fb.on_epoch(agent, event, None)
# fb._tryTurningItOffAndOnAgain(agent)