-
Notifications
You must be signed in to change notification settings - Fork 1
/
nrf_sniffer_ble.py
executable file
·1025 lines (794 loc) · 36.8 KB
/
nrf_sniffer_ble.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 python3
# Copyright (c) Nordic Semiconductor ASA
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form, except as embedded into a Nordic
# Semiconductor ASA integrated circuit in a product or a software update for
# such product, must reproduce the above copyright notice, this list of
# conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# 3. Neither the name of Nordic Semiconductor ASA nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# 4. This software, with or without modification, must only be used with a
# Nordic Semiconductor ASA integrated circuit.
#
# 5. Any software provided in binary form under this license must not be reverse
# engineered, decompiled, modified and/or disassembled.
#
# THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Wireshark extcap wrapper for the nRF Sniffer for Bluetooth LE by Nordic Semiconductor.
"""
import datetime
import os
import sys
import argparse
import re
import time
import struct
import logging
from pprint import pprint
from SnifferAPI import Logger
from SnifferAPI import Sniffer, UART, Devices, Pcap, Exceptions
try:
import serial
except ImportError:
Logger.initLogger()
logging.error(f'pyserial not found, please run: "{sys.executable} -m pip install -r requirements.txt" and retry')
sys.exit(f'pyserial not found, please run: "{sys.executable} -m pip install -r requirements.txt" and retry')
ERROR_USAGE = 0
ERROR_ARG = 1
ERROR_INTERFACE = 2
ERROR_FIFO = 3
ERROR_INTERNAL = 4
CTRL_CMD_INIT = 0
CTRL_CMD_SET = 1
CTRL_CMD_ADD = 2
CTRL_CMD_REMOVE = 3
CTRL_CMD_ENABLE = 4
CTRL_CMD_DISABLE = 5
CTRL_CMD_STATUSBAR = 6
CTRL_CMD_INFO_MSG = 7
CTRL_CMD_WARN_MSG = 8
CTRL_CMD_ERROR_MSG = 9
CTRL_ARG_DEVICE = 0
CTRL_ARG_KEY_TYPE = 1
CTRL_ARG_KEY_VAL = 2
CTRL_ARG_ADVHOP = 3
CTRL_ARG_HELP = 4
CTRL_ARG_RESTORE = 5
CTRL_ARG_LOG = 6
CTRL_ARG_DEVICE_CLEAR = 7
CTRL_ARG_NONE = 255
CTRL_KEY_TYPE_PASSKEY = 0
CTRL_KEY_TYPE_OOB = 1
CTRL_KEY_TYPE_LEGACY_LTK = 2
CTRL_KEY_TYPE_SC_LTK = 3
CTRL_KEY_TYPE_DH_PRIVATE_KEY = 4
CTRL_KEY_TYPE_IRK = 5
CTRL_KEY_TYPE_ADD_ADDR = 6
CTRL_KEY_TYPE_FOLLOW_ADDR = 7
fn_capture = None
fn_ctrl_in = None
fn_ctrl_out = None
extcap_log_handler = None
extcap_version = None
# Wireshark nRF Sniffer for Bluetooth LE Toolbar will always cache the last used key and adv hop and send
# this when starting a capture. To ensure that the key and adv hop is always shown correctly
# in the Toolbar, even if the user has changed it but not applied it, we send the last used
# key and adv hop back as a default value.
last_used_key_type = CTRL_KEY_TYPE_PASSKEY
last_used_key_val = ""
last_used_advhop = "37,38,39"
zero_addr = "[00,00,00,00,00,00,0]"
# While searching for a selected Device we must not write packets to the pipe until
# the device is found to avoid getting advertising packets from other devices.
write_new_packets = False
# Because there are captured packets in the queue, must use this time to
# check if should write or not.
last_parsed_packet_time = None
# The RSSI capture filter value given from Wireshark.
rssi_filter = 0
# The RSSI filtering is not on when in follow mode.
in_follow_mode = False
# nRF Sniffer for Bluetooth LE interface option to only capture advertising packets
capture_only_advertising = False
capture_only_legacy_advertising = False
capture_scan_response = True
capture_scan_aux_pointer = True
capture_coded = False
def extcap_config(interface):
"""List configuration for the given interface"""
print("arg {number=0}{call=--only-advertising}{display=Only advertising packets}"
"{tooltip=The sniffer will only capture advertising packets from the selected device}{type=boolflag}{save=true}")
print("arg {number=1}{call=--only-legacy-advertising}{display=Only legacy advertising packets}"
"{tooltip=The sniffer will only capture legacy advertising packets from the selected device}{type=boolflag}{save=true}")
print("arg {number=2}{call=--scan-follow-rsp}{display=Find scan response data}"
"{tooltip=The sniffer will follow scan requests and scan responses in scan mode}{type=boolflag}{default=true}{save=true}")
print("arg {number=3}{call=--scan-follow-aux}{display=Find auxiliary pointer data}"
"{tooltip=The sniffer will follow aux pointers in scan mode}{type=boolflag}{default=true}{save=true}")
print("arg {number=3}{call=--coded}{display=Scan and follow devices on LE Coded PHY}"
"{tooltip=Scan for devices and follow advertiser on LE Coded PHY}{type=boolflag}{default=false}{save=true}")
def extcap_dlts(interface):
"""List DLTs for the given interface"""
print("dlt {number=272}{name=NORDIC_BLE}{display=nRF Sniffer for Bluetooth LE}")
def get_baud_rates(interface):
if not hasattr(serial, "__version__") or not serial.__version__.startswith('3.'):
raise RuntimeError("Too old version of python 'serial' Library. Version 3 required.")
return UART.find_sniffer_baudrates(interface)
def get_interfaces():
if not hasattr(serial, "__version__") or not serial.__version__.startswith('3.'):
raise RuntimeError("Too old version of python 'serial' Library. Version 3 required.")
devices = UART.find_sniffer()
return devices
def extcap_interfaces():
"""List available interfaces to capture from"""
print("extcap {version=%s}{display=nRF Sniffer for Bluetooth LE}"
"{help=https://www.nordicsemi.com/Software-and-Tools/Development-Tools/nRF-Sniffer-for-Bluetooth-LE}"
% Sniffer.VERSION_STRING)
for interface_port in get_interfaces():
if sys.platform == 'win32':
print("interface {value=%s-%s}{display=nRF Sniffer for Bluetooth LE %s}" % (
interface_port, extcap_version, interface_port))
else:
print("interface {value=%s-%s}{display=nRF Sniffer for Bluetooth LE}" % (interface_port, extcap_version))
print("control {number=%d}{type=selector}{display=Device}{tooltip=Device list}" % CTRL_ARG_DEVICE)
print("control {number=%d}{type=selector}{display=Key}{tooltip=}" % CTRL_ARG_KEY_TYPE)
print("control {number=%d}{type=string}{display=Value}"
"{tooltip=6 digit passkey or 16 or 32 bytes encryption key in hexadecimal starting with '0x', big endian format."
"If the entered key is shorter than 16 or 32 bytes, it will be zero-padded in front'}"
"{validation=\\b^(([0-9]{6})|(0x[0-9a-fA-F]{1,64})|([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}) (public|random))$\\b}" % CTRL_ARG_KEY_VAL)
print("control {number=%d}{type=string}{display=Adv Hop}"
"{default=37,38,39}"
"{tooltip=Advertising channel hop sequence. "
"Change the order in which the sniffer switches advertising channels. "
"Valid channels are 37, 38 and 39 separated by comma.}"
"{validation=^\s*((37|38|39)\s*,\s*){0,2}(37|38|39){1}\s*$}{required=true}" % CTRL_ARG_ADVHOP)
print(
"control {number=%d}{type=button}{display=Clear}{tooltop=Clear or remove device from Device list}" % CTRL_ARG_DEVICE_CLEAR)
print(
"control {number=%d}{type=button}{role=help}{display=Help}{tooltip=Access user guide (launches browser)}" % CTRL_ARG_HELP)
print(
"control {number=%d}{type=button}{role=restore}{display=Defaults}{tooltip=Resets the user interface and clears the log file}" % CTRL_ARG_RESTORE)
print("control {number=%d}{type=button}{role=logger}{display=Log}{tooltip=Log per interface}" % CTRL_ARG_LOG)
print("value {control=%d}{value= }{display=All advertising devices}{default=true}" % CTRL_ARG_DEVICE)
print("value {control=%d}{value=%s}{display=Follow IRK}" % (CTRL_ARG_DEVICE, zero_addr))
print("value {control=%d}{value=%d}{display=Legacy Passkey}{default=true}" % (
CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_PASSKEY))
print("value {control=%d}{value=%d}{display=Legacy OOB data}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_OOB))
print("value {control=%d}{value=%d}{display=Legacy LTK}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_LEGACY_LTK))
print("value {control=%d}{value=%d}{display=SC LTK}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_SC_LTK))
print("value {control=%d}{value=%d}{display=SC Private Key}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_DH_PRIVATE_KEY))
print("value {control=%d}{value=%d}{display=IRK}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_IRK))
print("value {control=%d}{value=%d}{display=Add LE address}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_ADD_ADDR))
print("value {control=%d}{value=%d}{display=Follow LE address}" % (CTRL_ARG_KEY_TYPE, CTRL_KEY_TYPE_FOLLOW_ADDR))
def string_address(address):
"""Make a string representation of the address"""
if len(address) < 7:
return None
addr_string = ''
for i in range(5):
addr_string += (format(address[i], '02x') + ':')
addr_string += format(address[5], '02x') + ' '
if address[6]:
addr_string += ' random '
else:
addr_string += ' public '
return addr_string
def control_read():
"""Read a message from the control channel"""
header = fn_ctrl_in.read(6)
if not header:
# Ref. https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects:
# > If the end of the file has been reached, f.read() will return an
# > empty string ('')
return None, None, None
_, _, length, arg, typ = struct.unpack('>sBHBB', header)
payload = bytearray()
if length > 2:
payload = fn_ctrl_in.read(length - 2)
return arg, typ, payload
def control_write(arg, typ, message):
"""Write the message to the control channel"""
if not fn_ctrl_out:
# No control out has been opened
return
packet = bytearray()
packet += struct.pack('>BBHBB', ord('T'), 0, len(message) + 2, arg, typ)
packet += message.encode('utf-8')
fn_ctrl_out.write(packet)
def capture_write(message):
"""Write the message to the capture pipe"""
fn_capture.write(message)
fn_capture.flush()
def new_packet(notification):
"""A new Bluetooth LE packet has arrived"""
global last_parsed_packet_time
if write_new_packets:
packet = notification.msg["packet"]
last_parsed_packet_time = packet.time
if rssi_filter == 0 or in_follow_mode is True or packet.RSSI > rssi_filter:
p = bytes([packet.boardId] + packet.getList())
capture_write(Pcap.create_packet(p, packet.time))
# TRACE: 130
def device_added(notification):
"""A device is added or updated
search "DEVICE_ADDED"
"""
device = notification.msg
# Only add devices matching RSSI filter
if rssi_filter == 0 or device.RSSI > rssi_filter:
# Extcap selector uses \0 character to separate value and display value,
# therefore the display value cannot contain the \0 character as this
# would lead to truncation of the display value.
display = (device.name.replace('\0', '\\0') +
(" " + str(device.RSSI) + " dBm " if device.RSSI != 0 else " ") +
string_address(device.address))
message = str(device.address) + '\0' + display
#print(f'added a new device: {message}')
control_write(CTRL_ARG_DEVICE, CTRL_CMD_ADD, message)
def device_removed(notification):
"""A device is removed"""
device = notification.msg
display = device.name + " " + string_address(device.address)
message = ""
message += str(device.address)
control_write(CTRL_ARG_DEVICE, CTRL_CMD_REMOVE, message)
logging.info("Removed: " + display)
def devices_cleared(notification):
"""Devices have been cleared"""
message = ""
control_write(CTRL_ARG_DEVICE, CTRL_CMD_REMOVE, message)
control_write(CTRL_ARG_DEVICE, CTRL_CMD_ADD, " " + '\0' + "All advertising devices")
control_write(CTRL_ARG_DEVICE, CTRL_CMD_ADD, zero_addr + '\0' + "Follow IRK")
control_write(CTRL_ARG_DEVICE, CTRL_CMD_SET, " ")
def handle_control_command(sniffer, arg, typ, payload, auto_test=False, device_address=None):
"""Handle command from control channel"""
global last_used_key_type
print(f'handle_control_command()')
if auto_test:
# Instead of finding the device address, directly get from the user input
device = Devices.Device(address=device_address, name='""', RSSI=0)
print(f'\nfocus on device: {device}')
follow_device(sniffer, device)
else:
if arg == CTRL_ARG_DEVICE:
if payload == b' ':
scan_for_devices(sniffer)
else:
values = payload
values = values.replace(b'[', b'')
values = values.replace(b']', b'')
device_address = values.split(b',')
logging.info('follow_device: {}'.format(device_address))
for i in range(6):
device_address[i] = int(device_address[i])
device_address[6] = 1 if device_address[6] == b' 1' else 0
device = Devices.Device(address=device_address, name='""', RSSI=0)
follow_device(sniffer, device)
elif arg == CTRL_ARG_DEVICE_CLEAR:
clear_devices(sniffer)
elif arg == CTRL_ARG_KEY_TYPE:
last_used_key_type = int(payload.decode('utf-8'))
elif arg == CTRL_ARG_KEY_VAL:
set_key_value(sniffer, payload)
elif arg == CTRL_ARG_ADVHOP:
set_advhop(sniffer, payload)
def control_read_initial_values(sniffer, auto_test=False, device_address=None):
"""Read initial control values"""
print(f'control_read_initial_values(), auto_test: {auto_test}, dev addr: {device_address}')
if auto_test:
handle_control_command(sniffer, None, None, None, auto_test=auto_test, device_address=device_address)
else:
initialized = False
while not initialized:
arg, typ, payload = control_read()
if typ == CTRL_CMD_INIT:
initialized = True
else:
handle_control_command(sniffer, arg, typ, payload)
def control_write_defaults():
"""Write default control values"""
control_write(CTRL_ARG_KEY_TYPE, CTRL_CMD_SET, str(last_used_key_type))
control_write(CTRL_ARG_KEY_VAL, CTRL_CMD_SET, last_used_key_val)
control_write(CTRL_ARG_ADVHOP, CTRL_CMD_SET, last_used_advhop)
def scan_for_devices(sniffer):
"""Start scanning for advertising devices"""
global in_follow_mode
if sniffer.state == 2:
log = "Scanning all advertising devices"
logging.info(log)
sniffer.scan(capture_scan_response, capture_scan_aux_pointer, capture_coded)
in_follow_mode = False
def clear_devices(sniffer):
"""Clear the advertising devices list"""
global in_follow_mode
sniffer.clearDevices()
scan_for_devices(sniffer)
in_follow_mode = False
def follow_device(sniffer, device):
"""Follow the selected device"""
global in_follow_mode
print(f'follow_device()')
sniffer.follow(device, capture_only_advertising, capture_only_legacy_advertising, capture_coded)
time.sleep(.1)
in_follow_mode = True
print("Following " + string_address(device.address))
def set_key_value(sniffer, payload):
"""Send key value to device"""
global last_used_key_val
payload = payload.decode('utf-8')
last_used_key_val = payload
if (last_used_key_type == CTRL_KEY_TYPE_PASSKEY):
if re.match("^[0-9]{6}$", payload):
set_passkey(sniffer, payload)
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_OOB):
if re.match("^0[xX][0-9A-Za-z]{1,32}$", payload):
set_OOB(sniffer, payload[2:])
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_DH_PRIVATE_KEY):
if (re.match("^0[xX][0-9A-Za-z]{1,64}$", payload)):
set_dh_private_key(sniffer, payload[2:])
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_LEGACY_LTK):
if (re.match("^0[xX][0-9A-Za-z]{1,32}$", payload)):
set_legacy_ltk(sniffer, payload[2:])
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_SC_LTK):
if (re.match("^0[xX][0-9A-Za-z]{1,32}$", payload)):
set_sc_ltk(sniffer, payload[2:])
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_IRK):
if (re.match("^0[xX][0-9A-Za-z]{1,32}$", payload)):
set_irk(sniffer, payload[2:])
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_ADD_ADDR):
if (re.match("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}) (public|random)$", payload)):
add_address(sniffer, payload)
else:
logging.info("Invalid key value: " + str(payload))
elif (last_used_key_type == CTRL_KEY_TYPE_FOLLOW_ADDR):
if (re.match("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}) (public|random)$", payload)):
follow_address(sniffer, payload)
else:
logging.info("Invalid key value: " + str(payload))
else:
logging.info("Invalid key type: " + str(last_used_key_type))
def parse_hex(value):
if len(value) % 2 != 0:
value = '0' + value
a = list(value)
return [int(x + y, 16) for x, y in zip(a[::2], a[1::2])]
def set_passkey(sniffer, payload):
"""Send passkey to device"""
passkey = []
logging.info("Setting Passkey: " + payload)
init_payload = int(payload, 10)
if len(payload) >= 6:
passkey = []
passkey += [(init_payload >> 16) & 0xFF]
passkey += [(init_payload >> 8) & 0xFF]
passkey += [(init_payload >> 0) & 0xFF]
sniffer.sendTK(passkey)
def set_OOB(sniffer, payload):
"""Send OOB to device"""
logging.info("Setting OOB data: " + payload)
sniffer.sendTK(parse_hex(payload))
def set_dh_private_key(sniffer, payload):
"""Send Diffie-Hellman private key to device"""
logging.info("Setting DH private key: " + payload)
sniffer.sendPrivateKey(parse_hex(payload))
def set_legacy_ltk(sniffer, payload):
"""Send Legacy Long Term Key (LTK) to device"""
logging.info("Setting Legacy LTK: " + payload)
sniffer.sendLegacyLTK(parse_hex(payload))
def set_sc_ltk(sniffer, payload):
"""Send LE secure connections Long Term Key (LTK) to device"""
logging.info("Setting SC LTK: " + payload)
sniffer.sendSCLTK(parse_hex(payload))
def set_irk(sniffer, payload):
"""Send Identity Resolving Key (IRK) to device"""
logging.info("Setting IRK: " + payload)
sniffer.sendIRK(parse_hex(payload))
def add_address(sniffer, payload):
"""Add LE address to device list"""
logging.info("Adding LE address: " + payload)
(addr, addr_type) = payload.split(' ')
device = [int(a, 16) for a in addr.split(":")]
device.append(1 if addr_type == "random" else 0)
new_device = Devices.Device(address=device, name='""', RSSI=0)
sniffer.addDevice(new_device)
def follow_address(sniffer, payload):
"""Add LE address to device list"""
logging.info("Adding LE address: " + payload)
(addr, addr_type) = payload.split(' ')
device = [int(a, 16) for a in addr.split(":")]
device.append(1 if addr_type == "random" else 0)
new_device = Devices.Device(address=device, name='""', RSSI=0)
sniffer.addDevice(new_device)
control_write(CTRL_ARG_DEVICE, CTRL_CMD_SET, f"{new_device.address}")
follow_device(sniffer, new_device)
def set_advhop(sniffer, payload):
"""Set advertising channel hop sequence"""
global last_used_advhop
payload = payload.decode('utf-8')
last_used_advhop = payload
hops = [int(channel) for channel in payload.split(',')]
sniffer.setAdvHopSequence(hops)
log = "AdvHopSequence: " + str(hops)
logging.info(log)
def control_loop(sniffer):
"""Main loop reading control messages"""
arg_read = CTRL_ARG_NONE
while arg_read is not None:
arg_read, typ, payload = control_read()
handle_control_command(sniffer, arg_read, typ, payload)
def error_interface_not_found(interface, fifo):
log = "nRF Sniffer for Bluetooth LE could not find interface: " + interface
control_write(CTRL_ARG_NONE, CTRL_CMD_ERROR_MSG, log)
extcap_close_fifo(fifo)
sys.exit(ERROR_INTERFACE)
def validate_interface(interface, fifo):
"""Check if interface exists"""
if sys.platform != 'win32' and not os.path.exists(interface):
error_interface_not_found(interface, fifo)
def get_default_baudrate(interface, fifo):
"""Return the baud rate that interface is running at, or exit if the board is not found"""
rates = get_baud_rates(interface)
if rates is None:
error_interface_not_found(interface, fifo)
return rates["default"]
def get_supported_protocol_version(extcap_version):
"""Return the maximum supported Packet Protocol Version"""
if extcap_version == 'None':
return 2
(major, minor) = extcap_version.split('.')
major = int(major)
minor = int(minor)
if major > 3 or (major == 3 and minor >= 4):
return 3
else:
return 2
def setup_extcap_log_handler():
"""Add the a handler that emits log messages through the extcap control out channel"""
global extcap_log_handler
extcap_log_handler = ExtcapLoggerHandler()
Logger.addLogHandler(extcap_log_handler)
control_write(CTRL_ARG_LOG, CTRL_CMD_SET, "")
def teardown_extcap_log_handler():
"""Remove and reset the extcap log handler"""
global extcap_log_handler
if extcap_log_handler:
Logger.removeLogHandler(extcap_log_handler)
extcap_log_handler = None
def sniffer_capture(interface, baudrate, fifo, control_in, control_out, auto_test=False, timeout=120, given_name=None,
target_device=None, target_given_addr=None):
"""Start the sniffer to capture packets"""
global fn_capture, fn_ctrl_in, fn_ctrl_out, write_new_packets, extcap_log_handler
sniffer = None
try:
fn_capture = open(fifo, 'wb', 0)
if control_out is not None:
fn_ctrl_out = open(control_out, 'wb', 0)
setup_extcap_log_handler()
if control_in is not None:
# old version: fn_ctrl_in = open(control_in, 'ab+', 0)
fn_ctrl_in = open(control_in, 'rb', 0)
logging.info("Log started at %s", time.strftime("%c"))
interface, extcap_version = interface.split('-')
logging.info("Extcap version %s", str(extcap_version))
capture_write(Pcap.get_global_header())
validate_interface(interface, fifo)
if baudrate is None:
baudrate = get_default_baudrate(interface, fifo)
sniffer = Sniffer.Sniffer(interface, baudrate, auto_test=auto_test, given_name=given_name)
sniffer.subscribe("NEW_BLE_PACKET", new_packet)
sniffer.subscribe("DEVICE_ADDED", device_added)
sniffer.subscribe("DEVICE_UPDATED", device_added)
sniffer.subscribe("DEVICE_REMOVED", device_removed)
sniffer.subscribe("DEVICES_CLEARED", devices_cleared)
sniffer.setAdvHopSequence([37, 38, 39])
sniffer.setSupportedProtocolVersion(get_supported_protocol_version(extcap_version))
logging.info("Sniffer created")
print("Software version: %s" % sniffer.swversion)
sniffer.getFirmwareVersion()
sniffer.getTimestamp()
print(f"\nstart sniffer, auto_test: {auto_test}")
sniffer.start()
print("\nstart capturing adv")
sniffer.scan(capture_scan_response, capture_scan_aux_pointer, capture_coded)
if fn_ctrl_in is not None and fn_ctrl_out is not None:
# First read initial control values
if auto_test:
# Get the target device address
print(f'\nTry to find the target board0 with address: {target_given_addr}.')
tried = 0
while tried < 15:
target_dev_addr = sniffer.get_dev_addr(target_device, target_given_addr)
if target_dev_addr is not None:
msg = f'\nAfter tried {tried} times, ' \
f'found the target device "{target_device}" address: {target_dev_addr}\n'
print(msg)
logging.info(msg)
break
tried += 1
print(f'Tried {tried} times to find the target device "{target_device}".')
time.sleep(0.2)
if tried >= 15:
msg = f'Failed to find the target device "{target_device}" with given address "{target_given_addr}"'
print(msg)
logging.info(msg)
sniffer.doExit("sniffer_capture(), fn_ctr_in/out")
raise Exception
control_read_initial_values(sniffer, auto_test=auto_test, device_address=target_dev_addr)
else:
control_read_initial_values(sniffer)
# Then write default values
control_write_defaults()
logging.info("defaults written")
# Start receiving packets
logging.info("")
write_new_packets = True
write_new_packet_end_time = time.time() + timeout
# Start the control loop
if not auto_test:
logging.info("control loop")
control_loop(sniffer)
logging.info("exiting control loop")
else:
start_time = time.time()
msg = f'\nStart: {time.ctime(start_time)}\n'
print(msg)
while True:
curr = time.time()
delta_secs = curr - start_time
if delta_secs > timeout:
print(f'\nstart time: {time.ctime(start_time)}')
print(f' curr time: {time.ctime(curr)}')
print(f'delta secs: {delta_secs} > {timeout}\n')
break
time.sleep(1)
else:
logging.info("")
# Start receiving packets
write_new_packets = True
start_time = time.time()
logging.info(f'start time: {time.ctime(start_time)}')
while True:
# Wait for keyboardinterrupt
if auto_test:
curr = time.time()
delta_secs = curr - start_time
if delta_secs > timeout:
logging.info(f'end time: {time.ctime(curr)}, totally {delta_secs:.0f} secs.')
logging.info("")
break
except Exceptions.LockedException as e:
logging.info('{}'.format(e.message))
except OSError:
# We'll get OSError=22 when/if wireshark kills the pipe(s) on capture
# stop.
pass
finally:
# The first thing we should do is to tear down the extcap log handler.
# This might already have triggered an OSError, or we will trigger one
# by attempting to log at this point.
teardown_extcap_log_handler()
# Safe to use logging again.
if sniffer:
sniffer.doExit("sniffer_capture() finally")
if fn_capture is not None and not fn_capture.closed:
fn_capture.close()
if fn_ctrl_in is not None and not fn_ctrl_in.closed:
fn_ctrl_in.close()
if fn_ctrl_out is not None and not fn_ctrl_out.closed:
fn_ctrl_out.close()
fn_capture = None
fn_ctrl_out = None
fn_ctrl_in = None
logging.info("Exiting")
def extcap_close_fifo(fifo):
""""Close extcap fifo"""
if not os.path.exists(fifo):
print("FIFO does not exist!", file=sys.stderr)
return
# This is apparently needed to workaround an issue on Windows/macOS
# where the message cannot be read. (really?)
fh = open(fifo, 'wb', 0)
fh.close()
class ExtcapLoggerHandler(logging.Handler):
"""Handler used to display all logging messages in extcap"""
def emit(self, record):
"""Send log message to extcap"""
message = record.message.replace('\0', '\\0')
log_message = f"{record.levelname}: {message}\n"
control_write(CTRL_ARG_LOG, CTRL_CMD_ADD, log_message)
def parse_capture_filter(capture_filter):
""""Parse given capture filter"""
global rssi_filter
m = re.search("^\s*rssi\s*(>=?)\s*(-?[0-9]+)\s*$", capture_filter, re.IGNORECASE)
if m:
rssi_filter = int(m.group(2))
if rssi_filter > -10 or rssi_filter < -256:
print("Illegal RSSI value, must be between -10 and -256")
# Handle >= by modifying the threshold, since comparisons are always done with
# the > operator
if m.group(1) == '>=':
rssi_filter = rssi_filter - 1
else:
print("Filter syntax: \"RSSI >= -value\"")
import atexit
@atexit.register
def goodbye():
logging.info("Exiting PID {}".format(os.getpid()))
def run_sniffer(params: dict):
"""Run the sniffer with input arguments
Args:
params: the dict from input arguments
Returns:
pcap file name
"""
global capture_coded
print(f'\n<<<<<< nrf_sniffer_ble.py, run_sniffer()\n')
print(f' capture_only_advertising: {capture_only_advertising}')
print(f'capture_only_legacy_advertising: {capture_only_legacy_advertising}')
print(f' capture_scan_response: {capture_scan_response}')
print(f' capture_scan_aux_pointer: {capture_scan_aux_pointer}')
print(f' capture_coded: {capture_coded}')
interface = params["extcap_interface"]
try:
logging.info(f'sniffer capture: {params}')
if params["auto_test"]:
if interface[0] == '/':
name = interface[1:].replace("/", "-")
else:
name = interface.replace("/", "-")
name = name + "_" + "_" \
+ datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".pcap"
# base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
base_dir = os.getcwd()
given_name = os.path.join(base_dir, "output", name)
print(f'\ncaptured file will be saved to: {given_name}\n')
else:
given_name = None
sniffer_capture(interface, params["baudrate"], params["fifo"], params["extcap_control_in"],
params["extcap_control_out"], auto_test=params["auto_test"],
timeout=params["timeout"], given_name=given_name,
target_device=params["device"], target_given_addr=params["dev_addr"])
except KeyboardInterrupt:
pass
except Exception as e:
import traceback
logging.info(traceback.format_exc())
logging.info('internal error: {}'.format(repr(e)))
sys.exit(ERROR_INTERNAL)
if params["auto_test"] and given_name is not None:
print(f'{str(datetime.datetime.now())} - pcap file saved: {given_name}')
logging.info('main exit PID {}'.format(os.getpid()))
return given_name
def parse_args():
"""Parse input arguments
"""
# Capture options
parser = argparse.ArgumentParser(description="Nordic Semiconductor nRF Sniffer for Bluetooth LE extcap plugin")
# Extcap Arguments
parser.add_argument("--capture",
help="Start the capture",
action="store_true")
parser.add_argument("--extcap-interfaces",
help="List available interfaces to capture from",
action="store_true")
parser.add_argument("--extcap-interface",
help="The interface to capture from")
parser.add_argument("--extcap-dlts",
help="List DLTs for the given interface",
action="store_true")
parser.add_argument("--extcap-config",
help="List configurations for the given interface",
action="store_true")
parser.add_argument("--extcap-capture-filter",
help="Used together with capture to provide a capture filter")
parser.add_argument("--fifo",
help="Use together with capture to provide the fifo to dump data to")
parser.add_argument("--extcap-control-in",
help="Used together with capture to get control messages from toolbar")
parser.add_argument("--extcap-control-out",
help="Used together with capture to send control messages to toolbar")
parser.add_argument("--extcap-version",
help="Set extcap supported version")
# Interface Arguments
parser.add_argument("--device", help="Device", default="")
parser.add_argument("--baudrate", type=int, help="The sniffer baud rate")
parser.add_argument("--only-advertising", help="Only advertising packets", action="store_true")
parser.add_argument("--only-legacy-advertising", help="Only legacy advertising packets", action="store_true")
parser.add_argument("--scan-follow-rsp", help="Find scan response data ", action="store_true")
parser.add_argument("--scan-follow-aux", help="Find auxiliary pointer data", action="store_true")
parser.add_argument("--coded", help="Scan and follow on LE Coded PHY", action="store_true")
# Add for automatic test
parser.add_argument("--auto-test", help="automatic test, default False", default=False, action='store_true')
parser.add_argument("--timeout", type=int, help="timeout in secs for automatic test, default 120 secs", default=120)
parser.add_argument("--dev-addr", help="device advertising address")
logging.info("Started PID {}".format(os.getpid()))
try:
args, unknown = parser.parse_known_args()
print(f'args:')
pprint(vars(args))
logging.info(f'args: {args}')
logging.info(f'unknown: {unknown}')
except argparse.ArgumentError as exc:
print("%s" % exc, file=sys.stderr)
fifo_found = False
fifo = ""
for arg in sys.argv:
if arg == "--fifo" or arg == "--extcap-fifo":
fifo_found = True
elif fifo_found:
fifo = arg
break
extcap_close_fifo(fifo)
sys.exit(ERROR_ARG)
if len(sys.argv) <= 1:
parser.exit("No arguments given!")
if args.extcap_version:
extcap_version = args.extcap_version
if args.extcap_capture_filter:
parse_capture_filter(args.extcap_capture_filter)
if args.extcap_interface and len(sys.argv) == 5:
sys.exit(0)
if not args.extcap_interfaces and args.extcap_interface is None:
parser.exit("An interface must be provided or the selection must be displayed")
if args.extcap_interfaces or args.extcap_interface is None:
extcap_interfaces()
sys.exit(0)
if len(unknown) > 0:
print("Sniffer %d unknown arguments given" % len(unknown))
logging.info("Sniffer %d unknown arguments given" % len(unknown))
interface = args.extcap_interface
capture_only_advertising = args.only_advertising
capture_only_legacy_advertising = args.only_legacy_advertising
capture_scan_response = True #args.scan_follow_rsp
capture_scan_aux_pointer = True #args.scan_follow_aux