/
cli.py
executable file
·1837 lines (1606 loc) · 77.6 KB
/
cli.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
#!/usr/bin/env python2
# cli.py
#
# This file is meant to be executed by the user in order to start
# an interactive CLI. It creates an instance of the framework and
# enters a command loop which is implemented using cmd2.
# Commands entered by the user are automatically matched
# to functions starting with do_* and executed accordingly.
#
# Copyright (c) 2018 Dennis Mantz. (MIT License)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# - The Software is provided "as is", without warranty of any kind, express or
# implied, including but not limited to the warranties of merchantability,
# fitness for a particular purpose and noninfringement. In no event shall the
# authors or copyright holders be liable for any claim, damages or other
# liability, whether in an action of contract, tort or otherwise, arising from,
# out of or in connection with the Software or the use or other dealings in the
# Software.
from __future__ import print_function
import argparse
import binascii
import inspect
import os
import re
import select
import struct
import subprocess
import sys
import time
from builtins import str
from curses.ascii import isprint
from threading import Timer
from functools import wraps
import cmd2
from cmd2 import Fg, style
from . import Address
from .hci import HCI_COMND
from .utils import bytes_to_hex, flat, yesno
from .utils.packing import p8, p16, p32, u32
from .utils.progress_logger import ProgressLogger
from .utils.internalblue_logger import getInternalBlueLogger
from .hcicore import HCICore
from .adbcore import ADBCore
try:
import typing
from typing import List, Optional, Any, TYPE_CHECKING, Type, cast
from internalblue.core import InternalBlue
from . import DeviceTuple
if TYPE_CHECKING:
from internalblue.core import InternalBlue
from internalblue import Record, BluetoothAddress, Address
except ImportError:
pass
try:
from pwnlib import context
from pwnlib.asm import disasm, asm
from pwnlib.exception import PwnlibException
context.context.arch = 'thumb'
except ImportError:
context = disasm = asm = PwnlibException = None
_has_pwnlib = False
else:
_has_pwnlib = True
def needs_pwnlib(func):
# this decorator copies over
# function name, docstring,
# arguments list etc. so our
# help command still works
@wraps(func)
def inner(*args, **kwargs):
if not _has_pwnlib:
raise ImportError("pwnlib is required for this function.")
return func(*args, **kwargs)
return inner
def auto_int(x):
""" Convert a string (either decimal number or hex number) into an integer.
"""
# remove leading zeros as this doesn't work with int(), issue 20
# but only for integers (023), not for hex (0x23)
if not ('x' in x):
x = x.lstrip('0')
return int(x, 0)
def read(path, count=-1, skip=0):
r"""read(path, count=-1, skip=0) -> str
Open file, return content.
Examples:
>>> read('/proc/self/exe')[:4]
b'\x7fELF'
"""
path = os.path.expanduser(os.path.expandvars(path))
with open(path, 'rb') as fd:
if skip:
fd.seek(skip)
return fd.read(count)
class InternalBlueCLI(cmd2.Cmd):
def __init__(self, main_args, core: InternalBlue = None):
# get and store 'InternalBlue' logger
self.logger = getInternalBlueLogger()
# create progress logger
self.progress_log = None
# set prompt
self.prompt = '> '
# Prints an intro banner once upon application startup
banner = r" ____ __ _____ __ " + "\n" \
+ r" / _/__ / /____ _______ ___ _/ / _ )/ /_ _____" + "\n" \
+ r" _/ // _ \/ __/ -_) __/ _ \/ _ `/ / _ / / // / -_)" + "\n" \
+ r"/___/_//_/\__/\__/_/ /_//_/\_,_/_/____/_/\_,_/\__/" + "\n" + "\n" \
+ "type <help -v> for usage information!"
self.intro = style(banner, fg=Fg.BLUE)
# History file
if main_args.data_directory is not None:
data_directory = main_args.data_directory
else:
data_directory = os.path.expanduser("~") + "/.internalblue"
if not os.path.exists(data_directory):
os.mkdir(data_directory)
# Define shortcuts for commands (before call to super())
shortcuts = dict(cmd2.DEFAULT_SHORTCUTS)
shortcuts.update({
'bye': 'exit',
'verbosity': 'loglevel', 'log_level': 'loglevel',
'wireshark': 'monitor',
'watch': 'repeat',
'memdump': 'dumpmem',
'memsearch': 'searchmem',
'hd': 'hexdump', 'readmem': 'hexdump',
'disassemble': 'disasm',
'asm': 'writeasm',
'execute': 'exec',
'show': 'info',
'tp': 'tracepoint',
'bp': 'breakpoint',
'heap': 'memorypool', 'pool': 'memorypool',
'leconnect': 'connectle', 'cle': 'connectle', 'lec': 'connectle',
'sendh4': 'diag'})
super().__init__(shortcuts=shortcuts, persistent_history_file=data_directory + "/_internalblue.hist")
# Aliases have to be used instead of shortcuts
# When the alias is equal with the beginning
# of a command name. Has to be called after super().
self.runcmds_plus_hooks(["alias create break breakpoint > /dev/null",
"alias create trace tracepoint > /dev/null",
"alias create tel telescope > /dev/null",
"alias create disas disasm > /dev/null",
"alias create d disasm > /dev/null",
"alias create i info > /dev/null",
"alias create q quit > /dev/null"],
add_to_history=False)
# Settings
if main_args.verbose:
log_level = "debug"
else:
log_level = "info"
HookClass = None
if main_args.trace:
from .socket_hooks import hook
from internalblue import socket_hooks
HookClass = getattr(socket_hooks, main_args.trace)
hook(HCICore, HookClass)
hook(ADBCore, HookClass)
elif main_args.save:
from .socket_hooks import hook, TraceToFileHook
hook(HCICore, TraceToFileHook, filename=main_args.save)
hook(ADBCore, TraceToFileHook, filename=main_args.save)
# Connection method passed in constructor (POCs)
if core is not None:
self.internalblue = core
return
# Connection methods for replay script
elif main_args.replay:
connection_methods: List[InternalBlue] = self._get_connection_methods_replay(main_args, log_level, data_directory)
# Connection methods for normal operation
else:
connection_methods: List[InternalBlue] = self._get_connection_methods_normal(main_args, log_level, data_directory, HookClass)
devices = [] # type: List[DeviceTuple]
for connection_method in connection_methods:
devices.extend(connection_method.device_list())
device = None # type: Optional[DeviceTuple]
if len(devices) > 0:
if main_args.replay:
# There should only be one device that was created when --replay was passed
device = devices[0]
elif main_args.device:
matching_devices = [dev for dev in devices if dev[1] == main_args.device]
if len(matching_devices) > 1:
self.logger.critical("Found multiple matching devices")
exit(-1)
elif len(matching_devices) == 1:
self.logger.info("Found device is: {}".format(matching_devices[0]))
device = matching_devices[0]
else:
self.logger.critical("No matching devices found")
exit(-1)
elif len(devices) == 1:
device = devices[0]
else:
i = self.options("Please specify device:", [d[2] for d in devices])
device = devices[i]
# Setup device
self.internalblue = device[0]
self.internalblue.interface = device[1]
# Connect to device
if not self.internalblue.connect():
self.logger.critical("No connection to target device.")
exit(-1)
# now we have firmware info and can set firmware-specific variables
self.memory_image_template_filename = (
self.internalblue.data_directory + "/memdump_" + self.internalblue.fw.FW_NAME + "_template.bin"
)
self.memory_image: Optional[bytes] = None
# Enter command loop (runs until user quits)
self.logger.info("Starting commandLoop for self.internalblue {}".format(self.internalblue))
def _get_connection_methods_replay(self, main_args, log_level, data_directory) -> [InternalBlue]:
from .socket_hooks import hook, ReplaySocket
from .macoscore import macOSCore
replay_devices = ["macos_replay", "adb_replay", "hci_replay", "ios_replay"]
if main_args.device == "macos_replay":
from .macoscore import macOSCore
hook(macOSCore, ReplaySocket, filename=main_args.replay)
connection_methods = [
macOSCore(
log_level=log_level, data_directory=data_directory, replay=True
)
]
elif main_args.device == "hci_replay":
hook(HCICore, ReplaySocket, filename=main_args.replay)
connection_methods = [
HCICore(log_level=log_level, data_directory=data_directory, replay=True)
]
elif main_args.device == "adb_replay":
hook(ADBCore, ReplaySocket, filename=main_args.replay)
connection_methods = [
ADBCore(log_level=log_level, data_directory=data_directory, replay=True)
]
elif main_args.device == "ios_replay":
raise NotImplementedError("ios replay is not implemented yet")
else:
raise ValueError(
"--device is required with --replay and has to be one of {}".format(
replay_devices
)
)
return connection_methods
def _get_connection_methods_normal(self, main_args, log_level, data_directory, HookClass):
from internalblue.socket_hooks import TraceToFileHook
# if /var/run/usbmuxd exists, we can check for iOS devices
connection_methods = []
if os.path.exists("/var/run/usbmuxd"):
from .ioscore import iOSCore
connection_methods.append(iOSCore(log_level=log_level, data_directory=data_directory))
if sys.platform == "darwin":
try:
from .macoscore import macOSCore
connection_methods.append(macOSCore(log_level=log_level, data_directory=data_directory,
replay=(main_args.replay and main_args.device == "mac")))
except ImportError:
macOSCore = None
self.logger.warning("Couldn't import macOSCore. Is IOBluetoothExtended.framework installed?")
if main_args.trace:
from .socket_hooks import hook
hook(macOSCore, HookClass)
elif main_args.save:
from .socket_hooks import hook
hook(macOSCore, TraceToFileHook, filename=main_args.save)
else:
connection_methods.append(HCICore(log_level=log_level, data_directory=data_directory))
# ADB core can always be used
connection_methods.append(ADBCore(log_level=log_level, data_directory=data_directory, serial=main_args.serialsu))
return connection_methods
"""
$$$$$$$$$$$$$$$$$
$ CUSTOM CUSTOM $
$$$$$$$$$$$$$$$$$
"""
@staticmethod
def bt_addr_to_str(bt_addr):
# type: (BluetoothAddress) -> str
""" Convert a Bluetooth address (6 bytes) into a human readable format. """
return ":".join(format(x, "02x") for x in bytearray(bt_addr))
def parse_bt_addr(self, bt_addr):
# type: (Any) -> Optional[BluetoothAddress]
""" Convert Bluetooth address argument and check lengths. """
addr = bt_addr
if ":" in addr:
addr = addr.replace(":", "")
if len(addr) != 12:
self.logger.info("BT Address needs to be 6 hex-bytes")
return None
# Convert to byte string (little endian)
try:
addr = bytearray.fromhex(addr)
except TypeError:
self.logger.info("BT Address must consist of only hex digests!")
return None
return addr
# noinspection PyUnusedLocal
@staticmethod
def hexdump(data: bytes, begin: int = 0, highlight: bytes = None):
red = "\x1b[31m"
green = "\x1b[32m"
blue = "\x1b[34m"
reset = "\x1b[0m"
dump = ''
for i, byte in enumerate(data):
if i % 16 == 0:
dump += '{:08x}: '.format(i + begin)
abyte = '{:02x} '.format(byte)
if byte == 0x00 or byte == 0x0a:
dump += f'{red}{abyte}{reset}'
elif byte == 0xff:
dump += f'{green}{abyte}{reset}'
elif not isprint(byte):
dump += f'{blue}{abyte}{reset}'
else:
dump += f'{reset}{abyte}{reset}'
if i % 4 == 3:
dump += ' '
if i % 16 == 15:
dump += ' |'
dump += ''.join(
[(f'{reset}{chr(c)}{reset}' if 32 <= c <= 127 else f'{red if c == 0x00 or c == 0x0a else blue}·{reset}') + ('|' if j % 4 == 3 else '')
for j, c in enumerate(data[i - 15:i+1])])
dump += '\n'
try:
if dump[-1] != '\n':
dump += '\n'
except:
pass
sys.stdout.write(dump)
@staticmethod
def options(message: str, choices: [str]) -> int:
option_string = f"[🍺] {message}\n "
for i, choice in enumerate(choices):
option_string += f"\t{i + 1}) {choice}\n"
option_string += "Choice [1]\n"
while True:
selection = input(option_string)
if selection == "":
return 0
try:
num = int(selection)
except ValueError:
continue
if num <= len(choices):
return num - 1
"""
#### Previously Cmd Functions: ####
"""
@staticmethod
def getCmdList():
""" Returns a list of all CLI commands which are defined in this file."""
return [name for name, obj in inspect.getmembers(InternalBlueCLI, predicate=inspect.isfunction) if name.startswith("do_")]
def findCmd(self, keyword):
# type: (str) -> Optional[Type['Cmd']]
""" Find and return a Cmd subclass for a given keyword. """
command_list = self.getCmdList()
matching_cmds = [cmd for cmd in command_list if keyword in cmd]
if len(matching_cmds) == 0:
return None
if len(matching_cmds) > 1:
self.logger.warning("Multiple commands match: " + str(matching_cmds))
return None
return matching_cmds[0]
def isAddressInSections(self, address, length=0, sectiontype=""):
# type: (int, int, str) -> bool
if not self.internalblue.fw:
return False
for section in self.internalblue.fw.SECTIONS:
if (sectiontype.upper() == "ROM" and not section.is_rom) or (
sectiontype.upper() == "RAM" and not section.is_ram
):
continue
if section.start_addr <= address <= section.end_addr:
if address + length <= section.end_addr:
return True
else:
return False
return False
def readMem(self, address, length, progress_log=None, bytes_done=0, bytes_total=0):
# type: (Address, int, Optional[Any], int, int) -> Optional[bytes]
return self.internalblue.readMem(
address, length, progress_log, bytes_done, bytes_total
)
def writeMem(self, address, data, progress_log=None, bytes_done=0, bytes_total=0):
# type: (Address, bytes, Optional[Any], int, int) -> bool
return self.internalblue.writeMem(
address, data, progress_log, bytes_done, bytes_total
)
def initMemoryImage(self):
# type: () -> None
"""
Initially read out a chip's memory, all sections (RAM+ROM).
:return:
"""
# initialize the ROM
bytes_done = 0
if not os.path.exists(self.memory_image_template_filename):
self.logger.info("No template found. Need to read ROM sections as well!")
self.logger.info(
"Writing chip-specific template to "
+ self.memory_image_template_filename
+ "..."
)
bytes_total = sum([s.size() for s in self.internalblue.fw.SECTIONS])
self.progress_log = self.progress("Initialize internal memory image")
dumped_sections = {}
for section in self.internalblue.fw.SECTIONS:
# pwntools workaround: dump only rom, extend image
# dd if=/dev/zero bs=10M count=1 >>memdump_xxx_template.bin
# if section.is_rom:
dumped_sections[section.start_addr] = bytes(self.readMem(
section.start_addr,
section.size(),
self.progress_log,
bytes_done,
bytes_total,
))
bytes_done += section.size()
self.progress_log.success("Received Data: complete")
self.memory_image = flat(dumped_sections, filler=0x00)
f = open(self.memory_image_template_filename, "wb")
f.write(self.memory_image)
f.close()
# otherwise read the RAM
else:
self.logger.info(
self.memory_image_template_filename
+ " exists. Updating non-ROM sections!"
)
self.memory_image = read(self.memory_image_template_filename)
self.refreshMemoryImage()
def refreshMemoryImage(self):
# type: () -> None
"""
Update an existing memory dump, only RAM sections.
:return:
"""
bytes_done = 0
bytes_total = sum(
[s.size() for s in self.internalblue.fw.SECTIONS if not s.is_rom]
)
self.progress_log = self.progress("Refresh internal memory image")
for section in self.internalblue.fw.SECTIONS:
if not section.is_rom:
sectiondump = self.readMem(
section.start_addr,
section.size(),
self.progress_log,
bytes_done,
bytes_total,
)
if sectiondump and self.memory_image:
self.memory_image = (
self.memory_image[0:section.start_addr]
+ sectiondump
+ self.memory_image[section.end_addr:]
)
bytes_done += section.size()
self.progress_log.success("Received Data: complete")
def getMemoryImage(self, refresh=False):
# type: (bool) -> Any
if self.memory_image is None:
self.initMemoryImage()
elif refresh:
self.refreshMemoryImage()
return self.memory_image
def launchRam(self, address):
return self.internalblue.launchRam(address)
# noinspection PyUnusedLocal
def progress(self, message, status='', *args, **kwargs):
return ProgressLogger(self.logger, message, status, kwargs)
"""
###################################################################################
### Start of commands ###
###################################################################################
"""
# noinspection PyUnusedLocal
def do_exit(self, args):
"""Exit the program."""
self.internalblue.exit_requested = True
self.internalblue.shutdown()
# [IMPORTANT] for you, yes you, reading this:
# in all Cmd2 commands (functions starting with
# do_*), `return True` exits the command loop.
# So if you just want to return that a command
# exited successfully, return `None` instead.
# You can see in `do_repeat` that we just check
# for a return code of `None` to verify everything
# went fine and there were no errors.
# Only here, we return True to exit InternalBlue.
return True
loglevel_parser = argparse.ArgumentParser()
loglevel_parser.add_argument('level', help='New log level (CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARN, WARNING)')
@cmd2.with_argparser(loglevel_parser)
def do_loglevel(self, args):
"""Change the verbosity of log messages."""
log_levels = ["CRITICAL", "DEBUG", "ERROR", "INFO", "NOTSET", "WARN", "WARNING"]
loglevel = args.level
if loglevel.upper() in log_levels:
self.internalblue.log_level = loglevel
self.logger.info("New log level: " + str(self.internalblue.log_level))
return None
else:
self.logger.warning("Not a valid log level: " + loglevel)
return False
monitor_parser = argparse.ArgumentParser()
monitor_parser.add_argument('command', nargs='+', help='One of: start, stop, kill')
@cmd2.with_argparser(monitor_parser)
def do_monitor(self, args):
"""Controlling the monitor."""
class MonitorController(object):
instance = None
@staticmethod
def getMonitorController(internalblue):
if MonitorController.instance is None:
# Encapsulation type: Bluetooth H4 with linux header (99) None:
MonitorController.instance = MonitorController.__MonitorController(
internalblue, 0xC9
)
return MonitorController.instance
# noinspection PyPep8Naming,SpellCheckingInspection
class __MonitorController(object):
def __init__(self, internalblue, pcap_data_link_type):
self.internalblue = internalblue
self.running = False
self.wireshark_process = None
self.poll_timer = None
self.pcap_data_link_type = pcap_data_link_type
def _spawnWireshark(self):
# Global Header Values
# noinspection PyUnusedLocal
PCAP_GLOBAL_HEADER_FMT = "@ I H H i I I I "
PCAP_MAGICAL_NUMBER = 2712847316
PCAP_MJ_VERN_NUMBER = 2
PCAP_MI_VERN_NUMBER = 4
PCAP_LOCAL_CORECTIN = 0
PCAP_ACCUR_TIMSTAMP = 0
PCAP_MAX_LENGTH_CAP = 65535
PCAP_DATA_LINK_TYPE = self.pcap_data_link_type
pcap_header = struct.pack(
"@ I H H i I I I ",
PCAP_MAGICAL_NUMBER,
PCAP_MJ_VERN_NUMBER,
PCAP_MI_VERN_NUMBER,
PCAP_LOCAL_CORECTIN,
PCAP_ACCUR_TIMSTAMP,
PCAP_MAX_LENGTH_CAP,
PCAP_DATA_LINK_TYPE,
)
# On Linux/hcitool we can directly run wireshark -k -i bluetooth0
# FIXME move the monitor class to the according cores
DEVNULL = open(os.devnull, "wb")
# Check if wireshark or wireshark-gtk is installed. If both are
# present, default to wireshark.
if os.path.isfile("/usr/bin/wireshark"):
wireshark_binary = "wireshark"
elif os.path.isfile("/usr/bin/wireshark-gtk"):
wireshark_binary = "wireshark-gtk"
elif os.path.isfile("/Applications/Wireshark.app/Contents/MacOS/Wireshark"):
wireshark_binary = "/Applications/Wireshark.app/Contents/MacOS/Wireshark"
else:
self.internalblue.logger.warning("Wireshark not found!")
return False
if self.internalblue.__class__.__name__ == "HCICore":
wireshark_interface = self.internalblue.interface.replace(
"hci", "bluetooth"
)
self.internalblue.logger.info("Starting Wireshark on interface %s" % wireshark_interface)
self.wireshark_process = subprocess.Popen(
[wireshark_binary, "-k", "-i", wireshark_interface],
stderr=DEVNULL,
)
else:
self.wireshark_process = subprocess.Popen(
[wireshark_binary, "-k", "-i", "-"],
stdin=subprocess.PIPE,
stderr=DEVNULL,
)
self.wireshark_process.stdin.write(pcap_header)
self.poll_timer = Timer(3, self._pollTimer, ())
self.poll_timer.start()
return True
def _pollTimer(self):
if self.running and self.wireshark_process is not None:
if self.wireshark_process.poll() == 0:
# Process has ended
self.internalblue.logger.debug("_pollTimer: Wireshark has terminated")
self.stopMonitor()
self.wireshark_process = None
else:
# schedule new timer
self.poll_timer = Timer(3, self._pollTimer, ())
self.poll_timer.start()
def startMonitor(self):
if self.running:
self.internalblue.logger.warning("HCI Monitor already running!")
return False
if self.wireshark_process is None:
if not self._spawnWireshark():
self.internalblue.logger.info("Unable to start HCI Monitor.")
return False
self.running = True
# If we are running on adbcore, we need to forward all HCI packets
# to wireshark (-> use an hci callback):
if self.internalblue.__class__.__name__ == "ADBCore":
self.internalblue.registerHciCallback(self.adbhciCallback)
self.internalblue.logger.info("HCI Monitor started.")
return None
def stopMonitor(self):
if not self.running:
self.internalblue.logger.warning("HCI Monitor is not running!")
return False
if self.internalblue.__class__.__name__ == "ADBCore":
self.internalblue.unregisterHciCallback(self.adbhciCallback)
self.running = False
self.internalblue.logger.info("HCI Monitor stopped.")
return None
def killMonitor(self):
if self.running:
self.stopMonitor()
if self.poll_timer is not None:
self.poll_timer.cancel()
self.poll_timer = None
if self.wireshark_process is not None:
self.internalblue.logger.info("Killing Wireshark process...")
try:
self.wireshark_process.terminate()
self.wireshark_process.wait()
except OSError:
self.internalblue.logger.warning("Error during wireshark process termination")
self.wireshark_process = None
def adbhciCallback(self, record):
# type: (Record) -> None
hcipkt, orig_len, inc_len, flags, drops, recvtime = record
dummy = b"\x00\x00\x00" # TODO: Figure out purpose of these fields
direction = p8(flags & 0x01)
packet = dummy + direction + hcipkt.getRaw()
length = len(packet)
ts_sec = (
recvtime.second
) # + timestamp.minute*60 + timestamp.hour*60*60 #FIXME timestamp not set
ts_usec = recvtime.microsecond
pcap_packet = (
struct.pack("@ I I I I", ts_sec, ts_usec, length, length) + packet
)
try:
self.wireshark_process.stdin.write(pcap_packet)
self.wireshark_process.stdin.flush()
self.internalblue.logger.debug("HciMonitorController._callback: done")
except IOError as e:
self.internalblue.logger.warning("HciMonitorController._callback: broken pipe. terminate." f"{e}")
self.killMonitor()
monitorController = MonitorController.getMonitorController(
self.internalblue
)
if args.command[0] == "start":
monitorController.startMonitor()
elif args.command[0] == "stop":
monitorController.stopMonitor()
elif args.command[0] == "kill":
monitorController.killMonitor()
else:
self.logger.warning("Unknown subcommand: " + str(args.command[0]))
repeat_parser = argparse.ArgumentParser()
repeat_parser.add_argument('timeout', type=int, help='idle time (in milliseconds) between repetitions.')
repeat_parser.add_argument('command', nargs='+', help='Command which shall be repeated.')
@cmd2.with_argparser(repeat_parser)
def do_repeat(self, args):
"""Repeat a given command until user stops it.
Put the command to be repeated in quotes."""
try:
timeout = int(args.timeout)
# command has to be a string (in quotes)
# and is then split into an array
command = args.command[0].split()
repcmdline = " ".join(command[1:])
cmdclass = self.findCmd(command[0])
except ValueError:
self.logger.info("Not a number: " + args.timeout)
return False
except IndexError:
self.logger.info("Command may not be empty.")
return False
if cmdclass is None:
self.logger.warning("Unknown command: " + command[0])
return False
while True:
# Check for keypresses by user:
if select.select([sys.stdin], [], [], 0.0)[0]:
self.logger.info("Repeat aborted by user!")
return None
# instantiate and run cmd
cmd_instance = getattr(self, cmdclass)
if not cmd_instance(repcmdline) is None:
self.logger.warning("Command failed: " + str(cmd_instance))
return False
time.sleep(timeout * 0.001)
dumpmem_parser = argparse.ArgumentParser()
dumpmem_parser.add_argument('-n', '--norefresh', action='store_true', help='Do not refresh internal memory image before dumping to file.')
dumpmem_parser.add_argument('-r', '--ram', action='store_true', help='Only dump the two RAM sections.')
dumpmem_parser.add_argument('-f', '--file', default='memdump.bin', help='Filename of memory dump (default: %(default)s)')
dumpmem_parser.add_argument('--overwrite', action='store_true')
@cmd2.with_argparser(dumpmem_parser)
def do_dumpmem(self, args):
"""Dumps complete memory image into a file."""
# Store pure RAM image
if args.ram:
bytes_total = sum(
[s.size() for s in self.internalblue.fw.SECTIONS if s.is_ram]
)
bytes_done = 0
self.progress_log = self.progress("Downloading RAM sections...")
for section in [s for s in self.internalblue.fw.SECTIONS if s.is_ram]:
filename = args.file + "_" + hex(section.start_addr)
if os.path.exists(filename):
if not (args.overwrite or yesno("Update '%s'?" % filename)):
self.logger.info("Skipping section @%s" % hex(section.start_addr))
bytes_done += section.size()
continue
ram = self.readMem(
section.start_addr,
section.size(),
self.progress_log,
bytes_done,
bytes_total,
)
f = open(filename, "wb")
f.write(ram)
f.close()
bytes_done += section.size()
self.progress_log.success("Done")
return None
# Get complete memory image
if os.path.exists(args.file):
if not (
args.overwrite or yesno("Update '%s'?" % os.path.abspath(args.file))
):
return False
dump = self.getMemoryImage(refresh=not args.norefresh)
f = open(args.file, "wb")
f.write(dump)
f.close()
self.logger.info("Memory dump saved in '%s'!" % os.path.abspath(args.file))
return None
searchmem_parser = argparse.ArgumentParser()
searchmem_parser.add_argument('-r', '--refresh', action='store_true', help='Refresh internal memory image before searching.')
searchmem_parser.add_argument('--hex', action='store_true', help='Interpret pattern as hex string (e.g. ff000a20...)')
searchmem_parser.add_argument('-a', '--address', action='store_true', help='Interpret pattern as address (hex)')
searchmem_parser.add_argument('-c', '--context', type=auto_int, default=0,
help='Length of the hexdump before and after the matching pattern (default: %(default)s).')
searchmem_parser.add_argument('pattern', nargs='*', help='Search Pattern')
@cmd2.with_argparser(searchmem_parser)
def do_searchmem(self, args):
"""Search a pattern (string or hex) in the memory image."""
pattern = " ".join(args.pattern)
highlight = pattern
if args.hex:
try:
pattern = bytearray.fromhex(pattern)
highlight = pattern
except TypeError as e:
self.logger.warning("Search pattern cannot be converted to bytestring: " + str(e))
return False
elif args.address:
pattern = p32(int(pattern, 16))
highlight = [x for x in pattern if x != "\x00"]
memimage = self.getMemoryImage(refresh=args.refresh)
matches = [m.start(0) for m in re.finditer(re.escape(pattern), memimage)]
# noinspection PyUnusedLocal
hexdumplen = (len(pattern) + 16) & 0xFFFF0
for match in matches:
startaddr = (match & 0xFFFFFFF0) - args.context
endaddr = (match + len(pattern) + 16 & 0xFFFFFFF0) + args.context
self.logger.info("Match at 0x%08x:" % match)
self.hexdump(memimage[startaddr:endaddr], begin=startaddr, highlight=highlight)
return None
hexdump_parser = argparse.ArgumentParser()
hexdump_parser.add_argument('-l', '--length', type=auto_int, default=256, help='Length of the hexdump (default: %(default)s).')
hexdump_parser.add_argument('-a', '--aligned', action='store_true', help='Access the memory strictly 4-byte aligned.')
hexdump_parser.add_argument('address', type=auto_int, help='Start address of the hexdump.')
@cmd2.with_argparser(hexdump_parser)
def do_hexdump(self, args):
"""Display a hexdump of a specified region in the memory."""
# if not self.isAddressInSections(args.address, args.length):
# answer = yesno("Warning: Address 0x%08x (len=0x%x) is not inside a valid section. Continue?" % (args.address, args.length))
# if not answer:
# return False
if args.aligned:
dump = self.internalblue.readMemAligned(args.address, args.length)
else:
dump = self.readMem(args.address, args.length)
if dump is None:
return False
# self.logger.hexdump(bytes(dump), begin=args.address)
self.hexdump(bytes(dump), begin=args.address)
return None
telescope_parser = argparse.ArgumentParser()
telescope_parser.add_argument('-l', '--length', type=auto_int, default=64, help='Length of the telescope dump (default: %(default)s).')
telescope_parser.add_argument('-d', '--depth', type=auto_int, default=4, help='Depth of the telescope dump (default: %(default)s).')
telescope_parser.add_argument('address', type=auto_int, help='Start address of the telescope dump.')
@cmd2.with_argparser(telescope_parser)
def do_telescope(self, args):
"""Display a specified region in the memory and follow pointers to valid addresses."""
def telescope(data, depth):
val = u32(data[0:4])
if val == 0:
return [val, ""]
if depth > 0 and self.isAddressInSections(val, 0x20):
newdata = self.readMem(val, 0x20)
recursive_result = telescope(newdata, depth - 1)
recursive_result.insert(0, val)
return recursive_result
else:
s = ""
for c in data:
if isprint(c):
s += str(c)
else:
break
return [val, s]
if not self.isAddressInSections(args.address, args.length):
answer = yesno(
"Warning: Address 0x%08x (len=0x%x) is not inside a valid section. Continue?"
% (args.address, args.length)
)
if not answer:
return False
dump = self.readMem(args.address, args.length + 4)
if dump is None:
return False
for index in range(0, len(dump) - 4, 4):
chain = telescope(dump[index:], args.depth)
output = "0x%08x: " % (args.address + index)
output += " -> ".join(["0x%08x" % x for x in chain[:-1]])
output += ' "' + chain[-1] + '"'
self.logger.info(output)
return None
disasm_parser = argparse.ArgumentParser()
disasm_parser.add_argument('-l', '--length', type=auto_int, default=128, help='Length of the disassembly (default: %(default)s).')
disasm_parser.add_argument('address', type=auto_int, help='Start address of the disassembly.')
@cmd2.with_argparser(disasm_parser)
@needs_pwnlib
def do_disasm(self, args):
"""Display a disassembly of a specified region in the memory."""
if not self.isAddressInSections(args.address, args.length):
answer = yesno(
"Warning: Address 0x%08x (len=0x%x) is not inside a valid section. Continue?"
% (args.address, args.length)
)
if not answer:
return False
dump = self.readMem(args.address, args.length)
if dump is None:
return False
else:
# PyCharm thinks disasm wants a str and not bytes
# so until pwnlib gets type annotations we just trick the type checker to to prevent a false positive
if TYPE_CHECKING:
d = str(dump)
else:
d = dump
print(disasm(d, vma=args.address)) # type: ignore
return None
writemem_parser = argparse.ArgumentParser()
writemem_parser.add_argument('--hex', action='store_true', help='Interpret data as hex string (e.g. ff000a20...)')
writemem_parser.add_argument('--int', action='store_true', help='Interpret data as 32 bit integer (e.g. 0x123)')
writemem_parser.add_argument('-f', '--file', help='Read data from this file instead.')
writemem_parser.add_argument('-r', '--repeat', default=1, type=auto_int, help='Number of times to repeat the data (default: %(default)s)')
writemem_parser.add_argument('address', type=auto_int, help='Destination address')
writemem_parser.add_argument('data', nargs='*', help='Data as string (or hexstring/integer, see --hex, --int)')