-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathirk_extractor.py
More file actions
1651 lines (1393 loc) · 68.2 KB
/
Copy pathirk_extractor.py
File metadata and controls
1651 lines (1393 loc) · 68.2 KB
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
"""
irk_extractor.py - Extract BLE Identity Resolving Keys from BlueZ for Bermuda.
Usage:
sudo python3 irk_extractor.py list
sudo python3 irk_extractor.py monitor --discoverable
sudo python3 irk_extractor.py monitor --le-only # headless/dual-mode adapters
python3 irk_extractor.py pair AA:BB:CC:DD:EE:FF
python3 irk_extractor.py verify --irk <hex> --rpa AA:BB:CC:DD:EE:FF
BlueZ stores IRKs little-endian. Bermuda/Private BLE Device expects them
big-endian (reversed). `list` and `monitor` output the Bermuda format.
Requires Python 3.8+. `list` and `monitor` use only stdlib.
`verify` needs `cryptography` (pip install cryptography).
`pair` needs `pexpect` (pip install pexpect).
"""
from __future__ import annotations
import argparse
import configparser
import ctypes
import os
import pathlib
import select
import socket
import struct
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
try:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
CRYPTO_OK = True
except ImportError:
CRYPTO_OK = False
BLUEZ_DIR = pathlib.Path("/var/lib/bluetooth")
# MGMT socket constants (kernel API, stable across BlueZ versions)
_MGMT_HDR = struct.Struct("<HHH") # opcode/event, hci_index, param_len
_MGMT_EV_IRK = 0x0018 # MGMT_EV_NEW_IDENTITY_RESOLVING_KEY
_NEW_IRK_FMT = struct.Struct("<B6s6sB16s") # store_hint, rpa, identity, type, irk
# Payload layout verified against BlueZ monitor/packet.c mgmt_new_identity_resolving_key_evt:
# [0] store_hint uint8
# [1:7] RPA 6-byte little-endian bdaddr_t (always random type)
# [7:13] identity addr 6-byte little-endian bdaddr_t
# [13] identity type uint8 (0=public, 1=random)
# [14:30] IRK 16-byte little-endian
# MGMT event codes
_MGMT_EV_USER_CONFIRM_REQUEST = 0x000F
# MGMT write opcodes
_MGMT_OP_SET_POWERED = 0x0005 # power off required before toggling BR/EDR
_MGMT_OP_SET_DISCOVERABLE = 0x0006
_MGMT_OP_SET_CONNECTABLE = 0x0007
_MGMT_OP_SET_BONDABLE = 0x0009
_MGMT_OP_SET_LE = 0x000D
_MGMT_OP_SET_ADVERTISING = 0x0029 # kernel-managed LE advertising (no bluetoothd)
_MGMT_OP_SET_IO_CAPABILITY = 0x0018 # was incorrectly 0x0024 (STOP_DISCOVERY)
_MGMT_OP_SET_BREDR = 0x002A # disable to force LE-only mode
_MGMT_OP_SET_SECURE_CONN = 0x002D # uint8: 0=off 1=on; disable for iOS legacy-pairing compat
_MGMT_OP_USER_CONFIRM_REPLY = 0x001C
_MGMT_OP_PAIR_DEVICE = 0x0019 # 6B addr + uint8 addr_type + uint8 io_cap
_MGMT_OP_ADD_ADVERTISING = 0x003E # add LE advertising instance with custom AD data
_MGMT_OP_LOAD_LINK_KEYS = 0x0012 # uint8 debug + uint16 num_keys; 0 keys = flush RAM cache
_MGMT_OP_LOAD_LONG_TERM_KEYS = 0x0013 # uint16 num_keys; 0 keys = flush RAM cache
_MGMT_OP_LOAD_IRKS = 0x0030 # uint16 num_keys; 0 keys = flush RAM cache
_MGMT_OP_SET_PRIVACY = 0x002F # uint8 mode + 16B IRK; mode=1 enables LE privacy
_MGMT_OP_UNPAIR_DEVICE = 0x001B # 6B addr + uint8 type + uint8 disconnect
@dataclass
class Device:
adapter: str
address: str
name: str
irk_le: str | None # little-endian hex as stored by BlueZ
# ---------------------------------------------------------------------------
# Core helpers
# ---------------------------------------------------------------------------
def irk_le_to_be(le_hex: str) -> str:
"""Reverse byte order: BlueZ little-endian → big-endian (Bermuda format)."""
return bytes.fromhex(le_hex)[::-1].hex()
def resolve_rpa(irk_bytes: bytes, rpa_mac: str) -> bool:
"""
Return True if irk_bytes (BlueZ little-endian order) resolves rpa_mac.
Implements BLE spec Vol 6 Part B §1.3.2.1 ah(), matching kernel smp.c:
r' = 13 zero bytes || prand
hash = AES(irk, r')[13:16] reversed
"""
mac = bytes(int(x, 16) for x in rpa_mac.split(":"))
r_prime = bytes(13) + mac[0:3] # prand = upper 3 bytes of MAC string
cipher = Cipher(algorithms.AES(irk_bytes), modes.ECB(), backend=default_backend())
enc = cipher.encryptor()
result = enc.update(r_prime) + enc.finalize()
return result[15] == mac[5] and result[14] == mac[4] and result[13] == mac[3]
def _bdaddr(raw: bytes) -> str:
"""6-byte little-endian bdaddr_t → 'AA:BB:CC:DD:EE:FF'."""
return ":".join(f"{b:02X}" for b in reversed(raw))
def get_adapter_addresses() -> list[str]:
"""
Return all Bluetooth adapter addresses found on this machine.
Reads from sysfs (no external tool needed); falls back to hciconfig.
"""
addrs = []
sys_bt = pathlib.Path("/sys/class/bluetooth")
if sys_bt.exists():
for addr_file in sorted(sys_bt.glob("hci*/address")):
addr = addr_file.read_text().strip().upper()
if addr:
addrs.append(addr)
if not addrs:
try:
out = subprocess.check_output(
["hciconfig"], text=True, stderr=subprocess.DEVNULL
)
for line in out.splitlines():
if "BD Address" in line:
addrs.append(line.split()[2].upper())
except Exception:
pass
return addrs
def read_devices(adapter_addr: str) -> list[Device]:
"""Read all bonded devices from BlueZ database for one adapter."""
adapter_dir = BLUEZ_DIR / adapter_addr
if not adapter_dir.exists():
return []
devices = []
for device_dir in sorted(adapter_dir.iterdir()):
if not device_dir.is_dir():
continue
info_file = device_dir / "info"
if not info_file.exists():
continue
cfg = configparser.ConfigParser()
cfg.read(str(info_file))
name = cfg.get("General", "Name", fallback=device_dir.name)
irk_le = None
if cfg.has_section("IdentityResolvingKey"):
irk_le = cfg.get("IdentityResolvingKey", "Key", fallback=None)
devices.append(Device(adapter_addr, device_dir.name, name, irk_le))
return devices
def print_device(dev: Device, show_raw: bool = False) -> None:
if dev.irk_le is None:
print(f" # {dev.name} ({dev.address}) — no IRK (classic BT or no LE Privacy)")
return
print(f' - irk: "{irk_le_to_be(dev.irk_le)}" # {dev.name} ({dev.address})')
if show_raw:
print(f" # bluez (little-endian): {dev.irk_le}")
def require_root(cmd: str) -> None:
if os.geteuid() != 0:
print(f"Error: '{cmd}' requires root to read /var/lib/bluetooth/")
print(f"Run: sudo python3 {sys.argv[0]} {cmd}")
sys.exit(1)
def _open_mgmt_socket() -> socket.socket:
"""
Open a BlueZ MGMT socket (AF_BLUETOOTH / HCI_CHANNEL_CONTROL).
Works for users in the 'bluetooth' group; sudo always works.
Uses ctypes only for bind() — Python's socket API does not expose hci_channel.
"""
class _SockaddrHci(ctypes.Structure):
_fields_ = [
("hci_family", ctypes.c_uint16),
("hci_dev", ctypes.c_uint16), # 0xFFFF = HCI_DEV_NONE (all adapters)
("hci_channel", ctypes.c_uint16), # 3 = HCI_CHANNEL_CONTROL
]
sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI)
addr = _SockaddrHci(hci_family=socket.AF_BLUETOOTH, hci_dev=0xFFFF, hci_channel=3)
libc = ctypes.CDLL(None, use_errno=True)
ret = libc.bind(sock.fileno(), ctypes.byref(addr), ctypes.sizeof(addr))
if ret < 0:
err = ctypes.get_errno()
sock.close()
raise OSError(err, os.strerror(err))
return sock
# MGMT status codes
_MGMT_STATUS = {
0x00: "Success", 0x01: "Unknown command", 0x02: "Not connected",
0x03: "Failed", 0x04: "Connect failed", 0x05: "Auth failed",
0x06: "Not paired", 0x07: "No resources", 0x08: "Timeout",
0x09: "Already connected", 0x0A: "Busy", 0x0B: "Rejected",
0x0C: "Not supported", 0x0D: "Invalid params", 0x0E: "Disconnected",
0x0F: "Not powered", 0x10: "Cancelled", 0x11: "Invalid index",
0x12: "RFKilled", 0x13: "Already paired", 0x14: "Permission denied",
}
_MGMT_EV_CMD_COMPLETE = 0x0001
# MGMT read opcodes (read-only — to probe what the socket can do)
_MGMT_OP_READ_INDEX_LIST = 0x0003 # params: none, hci_index=0xFFFF
_MGMT_OP_READ_INFO = 0x0004 # params: none, hci_index=<adapter>
# MGMT write opcodes (adapter configuration)
_MGMT_OP_SET_DISCOVERABLE = 0x0006 # params: uint8 val, uint16 timeout
_MGMT_OP_SET_CONNECTABLE = 0x0007 # params: uint8 val
_MGMT_OP_SET_BONDABLE = 0x0009 # params: uint8 val
_MGMT_OP_SET_IO_CAPABILITY = 0x0024 # params: uint8 capability
_MGMT_EV_CMD_STATUS = 0x0002
def _mgmt_cmd(sock: socket.socket, hci_index: int, opcode: int,
params: bytes = b'', timeout: float = 2.0,
verbose: bool = False) -> tuple[int, bytes]:
"""
Send a MGMT command and wait for CMD_COMPLETE or CMD_STATUS for that opcode.
Returns (status_code, response_params). status=0 means success.
status=-1 means timeout (no response received at all).
CMD_STATUS with non-zero status means immediate rejection (no pending async op).
"""
pkt = _MGMT_HDR.pack(opcode, hci_index, len(params)) + params
if verbose:
print(f" [mgmt send] opcode=0x{opcode:04x} idx={hci_index} "
f"params={params.hex() or '(none)'} raw={pkt.hex()}")
sock.send(pkt)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
rem = deadline - time.monotonic()
if not select.select([sock], [], [], rem)[0]:
break
data = sock.recv(4096)
if len(data) < _MGMT_HDR.size:
continue
ev, idx, plen = _MGMT_HDR.unpack_from(data)
ev_params = data[_MGMT_HDR.size:]
if verbose:
print(f" [mgmt recv] event=0x{ev:04x} idx={idx} "
f"plen={plen} {ev_params.hex()}")
if ev in (_MGMT_EV_CMD_COMPLETE, _MGMT_EV_CMD_STATUS) and len(ev_params) >= 3:
resp_op = struct.unpack_from('<H', ev_params)[0]
if resp_op == opcode:
status = ev_params[2]
# CMD_STATUS with non-zero = immediate rejection; return it.
# CMD_STATUS with zero = command accepted, async result pending
# (we treat pending as success for fire-and-forget commands).
return status, ev_params[3:]
return -1, b''
def _get_hci_index(adapter_addr: str) -> int:
"""Return the integer index of the hciN adapter with the given address."""
for p in pathlib.Path("/sys/class/bluetooth").glob("hci*"):
try:
if (p / "address").read_text().strip().upper() == adapter_addr.upper():
return int(p.name[3:])
except (OSError, ValueError):
pass
return 0
def _mgmt_read_info(sock: socket.socket, hci_index: int,
verbose: bool = False) -> dict:
"""
Read adapter state via MGMT (read-only, no side effects).
Returns a dict with keys: addr, powered, le, bredr, discoverable, bondable, connectable.
"""
st, data = _mgmt_cmd(sock, 0xFFFF, _MGMT_OP_READ_INDEX_LIST, verbose=verbose)
if verbose:
if st == 0:
n = struct.unpack_from('<H', data)[0] if len(data) >= 2 else 0
indices = [struct.unpack_from('<H', data, 2 + i*2)[0]
for i in range(n) if 2 + i*2 + 2 <= len(data)]
print(f" [mgmt] read_index_list: OK — adapters: {indices}")
else:
print(f" [mgmt] read_index_list: {_MGMT_STATUS.get(st, f'0x{st:02x}')}")
st, data = _mgmt_cmd(sock, hci_index, _MGMT_OP_READ_INFO, verbose=verbose)
if st != 0 or len(data) < 17:
if verbose:
print(f" [mgmt] read_info: {_MGMT_STATUS.get(st, f'0x{st:02x}')}")
return {}
addr = ":".join(f"{b:02X}" for b in reversed(data[0:6]))
cur = struct.unpack_from('<I', data, 13)[0]
info = {
"addr": addr,
"powered": bool(cur & 0x0001),
"connectable": bool(cur & 0x0002),
"discoverable":bool(cur & 0x0008),
"bondable": bool(cur & 0x0010),
"ssp": bool(cur & 0x0040),
"bredr": bool(cur & 0x0080),
"le": bool(cur & 0x0200),
"secure_conn": bool(cur & 0x0800),
}
if verbose:
flags = " ".join(k for k, v in info.items() if v and k != "addr")
print(f" [mgmt] read_info: OK — {addr} [{flags}]")
return info
def _adapter_name(sock: socket.socket, hci_index: int, fallback: str) -> str:
"""Friendly adapter name from MGMT READ_INFO (the hostname BlueZ advertises)."""
st, data = _mgmt_cmd(sock, hci_index, _MGMT_OP_READ_INFO)
if st == 0 and len(data) >= 21:
nm = data[20:20 + 249].split(b'\x00', 1)[0].decode("utf-8", "replace").strip()
if nm:
return nm
return fallback
def _mgmt_setup_pairing(sock: socket.socket, hci_index: int,
verbose: bool = False) -> dict[str, bool]:
"""
Configure adapter for LE pairing via MGMT socket.
Attempts to disable BR/EDR to force LE-only (prevents phone from choosing BR/EDR).
Returns a dict of command → success so caller can decide on fallback.
"""
results: dict[str, bool] = {}
def _try(name: str, opcode: int, params: bytes) -> bool:
st, _ = _mgmt_cmd(sock, hci_index, opcode, params, verbose=verbose)
ok = (st == 0)
results[name] = ok
if verbose:
desc = "OK" if ok else _MGMT_STATUS.get(st, f"0x{st:02x}")
print(f" [mgmt] {name}: {desc}")
return ok
# Disable BR/EDR — forces phone to connect via LE only.
# Kernel auto-clears discoverable when BR/EDR is turned off.
# May fail if adapter is BR/EDR-only or if kernel rejects it;
# caller will note whether it worked.
_try("set_bredr_off", _MGMT_OP_SET_BREDR, struct.pack('<B', 0))
_try("set_connectable", _MGMT_OP_SET_CONNECTABLE, struct.pack('<B', 1))
_try("set_bondable", _MGMT_OP_SET_BONDABLE, struct.pack('<B', 1))
_try("set_sc_off", _MGMT_OP_SET_SECURE_CONN, struct.pack('<B', 0))
_try("set_privacy", _MGMT_OP_SET_PRIVACY, struct.pack('<B', 1) + os.urandom(16))
# timeout=0 → stay discoverable indefinitely
_try("set_discoverable", _MGMT_OP_SET_DISCOVERABLE, struct.pack('<BH', 1, 0))
# Flush stale bond keys from kernel RAM to force fresh SMP on next connect.
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LINK_KEYS, struct.pack('<BH', 0, 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LONG_TERM_KEYS, struct.pack('<H', 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_IRKS, struct.pack('<H', 0), verbose=verbose)
# Add LE advertising only when we have MGMT control (BR/EDR is off).
# When set_bredr_off failed we are in the bluetoothctl-fallback path: the
# agent ("agent NoInputNoOutput") must be registered *before* advertising
# starts so the kernel has the right IO capability in place. Advertising
# too early lets phones connect before the agent is ready and causes the
# wrong pairing method (Passkey Entry instead of Just Works) to be chosen.
# In that path, bluetoothctl's own "advertise on" handles LE advertising
# after the agent is set up.
if results.get("set_bredr_off"):
_ad = bytes([0x03, 0x03, 0x0D, 0x18, # Complete 16-bit UUIDs: Heart Rate (0x180D)
0x03, 0x19, 0x40, 0x03]) # Appearance: Heart Rate Sensor (0x0340)
if not _try("add_advertising", _MGMT_OP_ADD_ADVERTISING,
struct.pack('<BIHHBB', 1, 0x48, 0, 0, len(_ad), 0) + _ad):
_try("set_advertising", _MGMT_OP_SET_ADVERTISING, struct.pack('<B', 1))
return results
def _mgmt_teardown_pairing(sock: socket.socket, hci_index: int,
re_enable_bredr: bool = False) -> None:
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_ADVERTISING, struct.pack('<B', 0))
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_DISCOVERABLE, struct.pack('<BH', 0, 0))
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_BONDABLE, struct.pack('<B', 0))
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_SECURE_CONN, struct.pack('<B', 1))
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_PRIVACY, struct.pack('<B', 0) + bytes(16))
if re_enable_bredr:
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_BREDR, struct.pack('<B', 1))
# ---------------------------------------------------------------------------
# LE-only path (headless appliances: stop bluetoothd, drive controller via MGMT)
# ---------------------------------------------------------------------------
def _bluetoothd_active() -> bool:
"""True if the bluetooth systemd service is currently active."""
try:
r = subprocess.run(["systemctl", "is-active", "--quiet", "bluetooth"],
capture_output=True)
return r.returncode == 0
except FileNotFoundError:
return False
def _stop_bluetoothd(verbose: bool = False) -> bool:
"""
Stop bluetoothd so it can't keep the controller in dual (BR/EDR+LE) mode.
Returns True if we stopped it (so the caller restarts it on exit).
No-op (returns False) if it isn't running or systemctl is unavailable.
"""
if not _bluetoothd_active():
return False
if verbose:
print("[svc] Stopping bluetooth service so it can't re-enable BR/EDR ...")
subprocess.run(["systemctl", "stop", "bluetooth"], capture_output=True)
time.sleep(0.5) # let bluetoothd release the controller
return True
def _start_bluetoothd(verbose: bool = False) -> None:
if verbose:
print("[svc] Restarting bluetooth service ...")
subprocess.run(["systemctl", "start", "bluetooth"], capture_output=True)
def _mgmt_force_le_only(sock: socket.socket, hci_index: int,
verbose: bool = False) -> dict[str, bool]:
"""
Force the adapter into LE-only mode via a power cycle, then make it a
connectable/bondable/discoverable LE peripheral with NoInputNoOutput IO.
The kernel only accepts SET_BREDR while the controller is powered off, and
the change only sticks if bluetoothd isn't around to re-power it in dual
mode — so the caller must stop bluetoothd first.
Sequence: power off → bredr off → le on → bondable + io cap → power on →
connectable → discoverable → advertising.
"""
results: dict[str, bool] = {}
def _try(name: str, opcode: int, params: bytes) -> bool:
st, _ = _mgmt_cmd(sock, hci_index, opcode, params, verbose=verbose)
ok = (st == 0)
results[name] = ok
if verbose:
desc = "OK" if ok else _MGMT_STATUS.get(st, f"0x{st:02x}")
print(f" [mgmt] {name}: {desc}")
return ok
# Powered-off phase: mode changes the kernel rejects while powered.
_try("power_off", _MGMT_OP_SET_POWERED, struct.pack('<B', 0))
# Flush stale bond keys NOW while the controller is off. Some kernels reject
# LOAD_LONG_TERM_KEYS while powered on (returns INVALID_PARAMS); calling it
# here clears the in-memory LTK list before the controller re-initialises,
# preventing the phone from reconnecting with its cached LTK.
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LINK_KEYS, struct.pack('<BH', 0, 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LONG_TERM_KEYS, struct.pack('<H', 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_IRKS, struct.pack('<H', 0), verbose=verbose)
_try("set_bredr_off", _MGMT_OP_SET_BREDR, struct.pack('<B', 0))
_try("set_le_on", _MGMT_OP_SET_LE, struct.pack('<B', 1))
_try("set_bondable", _MGMT_OP_SET_BONDABLE, struct.pack('<B', 1))
# Disable Secure Connections so iOS falls back to legacy Just Works pairing,
# which reliably distributes the IRK. SC mid-handshake failures are the most
# common reason iOS shows "Pairing failed" with no IRK event emitted.
_try("set_sc_off", _MGMT_OP_SET_SECURE_CONN, struct.pack('<B', 0))
# Enable LE privacy with a fresh random IRK. Without HCI_PRIVACY set, the
# kernel only negotiates ENC_KEY in SMP — it never adds ID_KEY (the IRK) to
# the key distribution bitmask, so the peer's IRK is never sent to us.
_try("set_privacy", _MGMT_OP_SET_PRIVACY, struct.pack('<B', 1) + os.urandom(16))
# We don't set IO capability: this controller's kernel rejects
# SET_IO_CAPABILITY (status 0x0b) regardless of power state, and the default
# is fine — the phone drives a USER_CONFIRM_REQUEST that we auto-accept below.
# Powered-on phase: connectable/discoverable/advertising need the controller up.
_try("power_on", _MGMT_OP_SET_POWERED, struct.pack('<B', 1))
_try("set_connectable", _MGMT_OP_SET_CONNECTABLE, struct.pack('<B', 1))
_try("set_discoverable", _MGMT_OP_SET_DISCOVERABLE, struct.pack('<BH', 1, 0))
# LE advertising payload for iOS compatibility:
# Heart Rate UUID (0x180D) — iOS recognises this and shows the device in
# Settings → Bluetooth as something to pair with
# Appearance: Heart Rate Sensor (0x0340) — proper device category
# MGMT flags: bit3=Add Flags AD type (kernel sets LE_DISC|BREDR_UNSUP),
# bit6=Add Local Name in scan response (device hostname)
_ad = bytes([0x03, 0x03, 0x0D, 0x18, # Complete 16-bit UUIDs: Heart Rate (0x180D)
0x03, 0x19, 0x40, 0x03]) # Appearance: Heart Rate Sensor (0x0340)
if not _try("add_advertising", _MGMT_OP_ADD_ADVERTISING,
struct.pack('<BIHHBB', 1, 0x48, 0, 0, len(_ad), 0) + _ad):
_try("set_advertising", _MGMT_OP_SET_ADVERTISING, struct.pack('<B', 1))
# Realtek (and some other) adapters silently re-enable BR/EDR when advertising
# starts. Disable it again now that advertising is up.
_try("set_bredr_off_retry", _MGMT_OP_SET_BREDR, struct.pack('<B', 0))
return results
def _mgmt_teardown_le_only(sock: socket.socket, hci_index: int,
verbose: bool = False) -> None:
"""Undo _mgmt_force_le_only: stop advertising/discoverable, restore BR/EDR."""
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_ADVERTISING, struct.pack('<B', 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_DISCOVERABLE, struct.pack('<BH', 0, 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_BONDABLE, struct.pack('<B', 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_PRIVACY, struct.pack('<B', 0) + bytes(16), verbose=verbose)
# Re-enable BR/EDR (requires powered off), then power back on so the
# controller is left in the dual mode bluetoothd expects on restart.
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_POWERED, struct.pack('<B', 0), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_BREDR, struct.pack('<B', 1), verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_SET_POWERED, struct.pack('<B', 1), verbose=verbose)
def _ctl(*args: str) -> None:
"""Run a bluetoothctl command non-interactively, ignore errors."""
subprocess.run(["bluetoothctl", *args], capture_output=True)
def _ctl_setup_pairing() -> subprocess.Popen:
"""
Make adapter discoverable and start a persistent bluetoothctl process as a
NoInputNoOutput pairing agent. The process must stay alive for the duration
of monitoring so incoming pairing confirmations are auto-accepted.
Returns the agent process so the caller can clean it up.
"""
_ctl("discoverable-timeout", "0")
_ctl("pairable", "on")
_ctl("discoverable", "on")
proc = subprocess.Popen(
["bluetoothctl"],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
# Register agent, then explicitly start LE advertising so phones can find
# this adapter via BLE scan (SET_DISCOVERABLE alone only enables BR/EDR inquiry
# on some adapters — ADVERTISING flag stays unset without an explicit advertise cmd).
proc.stdin.write(b"agent NoInputNoOutput\ndefault-agent\nadvertise on\n")
proc.stdin.flush()
return proc
def _ctl_teardown_pairing(agent_proc: subprocess.Popen | None = None) -> None:
_ctl("pairable", "off")
_ctl("discoverable", "off")
if agent_proc is not None:
try:
agent_proc.stdin.write(b"quit\n")
agent_proc.stdin.flush()
agent_proc.wait(timeout=2)
except Exception:
agent_proc.kill()
def _load_dbus():
try:
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GLib
except ImportError as e:
print(f"Error: the experimental GATT mode needs python dbus/gi: {e}")
print("On Debian/Raspberry Pi OS install: sudo apt install python3-dbus python3-gi")
sys.exit(1)
return dbus, GLib
def _dbus_get_adapter(bus, adapter_addr: str | None = None):
dbus, _ = _load_dbus()
obj = bus.get_object("org.bluez", "/")
mgr = dbus.Interface(obj, "org.freedesktop.DBus.ObjectManager")
objects = mgr.GetManagedObjects()
want = adapter_addr.upper() if adapter_addr else None
for path, ifaces in objects.items():
props = ifaces.get("org.bluez.Adapter1")
if not props:
continue
if want is None or str(props.get("Address", "")).upper() == want:
return path
raise RuntimeError(f"Bluetooth adapter not found: {adapter_addr or 'auto'}")
def _dbus_props(value):
dbus, _ = _load_dbus()
if isinstance(value, bool):
return dbus.Boolean(value)
if isinstance(value, int):
return dbus.UInt16(value)
if isinstance(value, list):
return dbus.Array(value, signature="s")
return value
def _mgmt_prepare_bluez_gatt(sock: socket.socket, hci_index: int,
verbose: bool = False,
invasive: bool = False) -> dict[str, bool]:
results: dict[str, bool] = {}
def _try(name: str, opcode: int, params: bytes) -> bool:
st, _ = _mgmt_cmd(sock, hci_index, opcode, params, verbose=verbose)
ok = (st == 0)
results[name] = ok
if verbose:
print(f" [mgmt] {name}: {_MGMT_STATUS.get(st, f'0x{st:02x}') if st >= 0 else 'timeout'}")
return ok
if not invasive:
if verbose:
print("[mgmt] GATT mode: leaving power/advertising control to bluetoothd")
return results
if verbose:
print("[mgmt] Preparing adapter for BlueZ GATT capture (invasive) ...")
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LINK_KEYS, struct.pack('<BH', 0, 0),
verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_LONG_TERM_KEYS, struct.pack('<H', 0),
verbose=verbose)
_mgmt_cmd(sock, hci_index, _MGMT_OP_LOAD_IRKS, struct.pack('<H', 0),
verbose=verbose)
_try("set_bredr_off", _MGMT_OP_SET_BREDR, struct.pack('<B', 0))
_try("set_le_on", _MGMT_OP_SET_LE, struct.pack('<B', 1))
_try("set_bondable", _MGMT_OP_SET_BONDABLE, struct.pack('<B', 1))
_try("set_sc_off", _MGMT_OP_SET_SECURE_CONN, struct.pack('<B', 0))
_try("set_privacy", _MGMT_OP_SET_PRIVACY, struct.pack('<B', 1) + os.urandom(16))
return results
def _mgmt_irk_monitor(sock: socket.socket, stop: threading.Event,
hci_index: int, raw: bool = False,
verbose: bool = False) -> None:
seen_irks: set[str] = set()
while not stop.is_set():
if not select.select([sock], [], [], 0.5)[0]:
continue
data = sock.recv(512)
if len(data) < _MGMT_HDR.size:
continue
event_code, ev_hci_index, param_len = _MGMT_HDR.unpack_from(data)
params = data[_MGMT_HDR.size:]
if verbose:
ev_name = {
0x0001: "CMD_COMPLETE",
0x0002: "CMD_STATUS",
0x0006: "NEW_SETTINGS",
0x000B: "DEVICE_CONNECTED",
0x000C: "DEVICE_DISCONNECTED",
0x0018: "NEW_IRK",
}.get(event_code, f"0x{event_code:04x}")
print(f"[mgmt] {ev_name} idx={ev_hci_index} plen={param_len} {params.hex()}")
if event_code == 0x0006 and len(params) >= 4:
if struct.unpack_from('<I', params)[0] & 0x0080:
sock.send(_MGMT_HDR.pack(_MGMT_OP_SET_BREDR, hci_index, 1) + b'\x00')
if verbose:
print("[gatt] BR/EDR re-enabled by firmware/bluetoothd - disabling again")
continue
if event_code != _MGMT_EV_IRK or len(params) < _NEW_IRK_FMT.size:
continue
store_hint, rpa_le, identity_le, _, irk_raw = _NEW_IRK_FMT.unpack_from(params)
irk_le = irk_raw.hex()
if irk_le in seen_irks:
continue
seen_irks.add(irk_le)
identity = _bdaddr(identity_le)
rpa = _bdaddr(rpa_le)
label = identity if identity_le != bytes(6) else rpa
print(f"\n=== IRK captured for {label} ===")
print("known_irks:")
print(f' - irk: "{irk_le_to_be(irk_le)}" # {label}')
if raw:
print(f" # bluez (little-endian): {irk_le}")
print(f" # RPA: {rpa} store_hint: {bool(store_hint)}")
print()
class _BlueZGattObject:
PATH_BASE = "/com/phil/irk_extractor"
def _make_bluez_gatt_classes():
dbus, _ = _load_dbus()
class Application(dbus.service.Object):
def __init__(self, bus):
self.path = _BlueZGattObject.PATH_BASE
self.services = []
super().__init__(bus, self.path)
def add_service(self, service):
self.services.append(service)
@dbus.service.method("org.freedesktop.DBus.ObjectManager",
out_signature="a{oa{sa{sv}}}")
def GetManagedObjects(self):
response = {}
for service in self.services:
response[service.path] = service.get_properties()
for char in service.characteristics:
response[char.path] = char.get_properties()
return response
class Service(dbus.service.Object):
def __init__(self, bus, index: int, uuid: str, primary: bool = True):
self.path = f"{_BlueZGattObject.PATH_BASE}/service{index}"
self.bus = bus
self.uuid = uuid
self.primary = primary
self.characteristics = []
super().__init__(bus, self.path)
def add_characteristic(self, characteristic):
self.characteristics.append(characteristic)
def get_properties(self):
return {
"org.bluez.GattService1": {
"UUID": self.uuid,
"Primary": dbus.Boolean(self.primary),
"Characteristics": dbus.Array(
[dbus.ObjectPath(c.path) for c in self.characteristics],
signature="o",
),
}
}
@dbus.service.method("org.freedesktop.DBus.Properties",
in_signature="s", out_signature="a{sv}")
def GetAll(self, interface):
return self.get_properties().get(interface, {})
class Characteristic(dbus.service.Object):
def __init__(self, bus, service: Service, index: int, uuid: str,
flags: list[str], value: bytes):
self.path = f"{service.path}/char{index}"
self.bus = bus
self.service = service
self.uuid = uuid
self.flags = flags
self.value = value
self.notifying = False
super().__init__(bus, self.path)
def get_properties(self):
return {
"org.bluez.GattCharacteristic1": {
"Service": dbus.ObjectPath(self.service.path),
"UUID": self.uuid,
"Flags": dbus.Array(self.flags, signature="s"),
}
}
@dbus.service.method("org.freedesktop.DBus.Properties",
in_signature="s", out_signature="a{sv}")
def GetAll(self, interface):
return self.get_properties().get(interface, {})
@dbus.service.method("org.bluez.GattCharacteristic1",
in_signature="a{sv}", out_signature="ay")
def ReadValue(self, options):
return dbus.Array([dbus.Byte(b) for b in self.value], signature="y")
@dbus.service.method("org.bluez.GattCharacteristic1")
def StartNotify(self):
self.notifying = True
@dbus.service.method("org.bluez.GattCharacteristic1")
def StopNotify(self):
self.notifying = False
class Advertisement(dbus.service.Object):
PATH = f"{_BlueZGattObject.PATH_BASE}/advertisement0"
def __init__(self, bus, local_name: str, service_uuid: str, appearance: int):
self.path = self.PATH
self.local_name = local_name
self.service_uuid = service_uuid
self.appearance = appearance
super().__init__(bus, self.path)
def get_properties(self):
return {
"org.bluez.LEAdvertisement1": {
"Type": "peripheral",
"ServiceUUIDs": dbus.Array([self.service_uuid], signature="s"),
"LocalName": self.local_name,
"Appearance": dbus.UInt16(self.appearance),
"Includes": dbus.Array(["tx-power"], signature="s"),
}
}
@dbus.service.method("org.freedesktop.DBus.Properties",
in_signature="s", out_signature="a{sv}")
def GetAll(self, interface):
return self.get_properties().get(interface, {})
@dbus.service.method("org.bluez.LEAdvertisement1")
def Release(self):
print("[gatt] Advertisement released")
class Agent(dbus.service.Object):
PATH = f"{_BlueZGattObject.PATH_BASE}/agent"
def __init__(self, bus):
super().__init__(bus, self.PATH)
@dbus.service.method("org.bluez.Agent1", in_signature="", out_signature="")
def Release(self):
pass
@dbus.service.method("org.bluez.Agent1", in_signature="os", out_signature="")
def AuthorizeService(self, device, uuid):
return
@dbus.service.method("org.bluez.Agent1", in_signature="ou", out_signature="")
def RequestConfirmation(self, device, passkey):
print(f"[gatt] Auto-confirming Just Works pairing for {device}")
return
@dbus.service.method("org.bluez.Agent1", in_signature="o", out_signature="")
def RequestAuthorization(self, device):
return
@dbus.service.method("org.bluez.Agent1", in_signature="", out_signature="")
def Cancel(self):
pass
return Application, Service, Characteristic, Advertisement, Agent
def _build_heart_rate_app(bus):
Application, Service, Characteristic, _, _ = _make_bluez_gatt_classes()
app = Application(bus)
hr = Service(bus, 0, "0000180d-0000-1000-8000-00805f9b34fb")
hr.add_characteristic(Characteristic(
bus, hr, 0, "00002a37-0000-1000-8000-00805f9b34fb",
["read", "encrypt-read", "notify"], bytes([0x00, 72])))
app.add_service(hr)
devinfo = Service(bus, 1, "0000180a-0000-1000-8000-00805f9b34fb")
devinfo.add_characteristic(Characteristic(
bus, devinfo, 0, "00002a29-0000-1000-8000-00805f9b34fb",
["read", "encrypt-read"], b"Linux"))
devinfo.add_characteristic(Characteristic(
bus, devinfo, 1, "00002a24-0000-1000-8000-00805f9b34fb",
["read", "encrypt-read"], b"IRK Capture"))
app.add_service(devinfo)
batt = Service(bus, 2, "0000180f-0000-1000-8000-00805f9b34fb")
batt.add_characteristic(Characteristic(
bus, batt, 0, "00002a19-0000-1000-8000-00805f9b34fb",
["read", "notify"], bytes([95])))
app.add_service(batt)
protected = Service(bus, 3, "12345678-90ab-cdef-fedc-ba0987654321")
protected.add_characteristic(Characteristic(
bus, protected, 0, "21436587-09ba-dcfe-efcd-ab9078563412",
["read", "encrypt-read"], b"Protected Info"))
app.add_service(protected)
return app
def _build_keyboard_app(bus):
Application, Service, Characteristic, _, _ = _make_bluez_gatt_classes()
app = Application(bus)
hid = Service(bus, 0, "00001812-0000-1000-8000-00805f9b34fb")
hid.add_characteristic(Characteristic(
bus, hid, 0, "00002a4e-0000-1000-8000-00805f9b34fb",
["read"], b"\x01"))
app.add_service(hid)
devinfo = Service(bus, 1, "0000180a-0000-1000-8000-00805f9b34fb")
devinfo.add_characteristic(Characteristic(
bus, devinfo, 0, "00002a29-0000-1000-8000-00805f9b34fb",
["read", "encrypt-read"], b"Linux"))
devinfo.add_characteristic(Characteristic(
bus, devinfo, 1, "00002a24-0000-1000-8000-00805f9b34fb",
["read", "encrypt-read"], b"IRK Capture"))
app.add_service(devinfo)
batt = Service(bus, 2, "0000180f-0000-1000-8000-00805f9b34fb")
batt.add_characteristic(Characteristic(
bus, batt, 0, "00002a19-0000-1000-8000-00805f9b34fb",
["read", "notify"], bytes([95])))
app.add_service(batt)
protected = Service(bus, 3, "12345678-90ab-cdef-fedc-ba0987654321")
protected.add_characteristic(Characteristic(
bus, protected, 0, "21436587-09ba-dcfe-efcd-ab9078563412",
["read", "encrypt-read"], b"Protected Info"))
app.add_service(protected)
return app
def _print_bluez_power_recovery() -> None:
print(" BlueZ cannot power the adapter right now.")
print(" Recovery:")
print(" sudo systemctl restart bluetooth")
print(" sudo bluetoothctl power on")
print(" If that still fails after the earlier MGMT power cycle:")
print(" sudo modprobe -r btusb btrtl")
print(" sudo modprobe btusb")
print(" sudo systemctl restart bluetooth")
def _build_gatt_profile(bus, profile: str):
if profile == "keyboard":
return _build_keyboard_app(bus), "00001812-0000-1000-8000-00805f9b34fb", 0x03C1
return _build_heart_rate_app(bus), "0000180d-0000-1000-8000-00805f9b34fb", 0x0340
# ---------------------------------------------------------------------------
# Subcommand: list
# ---------------------------------------------------------------------------
def cmd_list(args) -> None:
require_root("list")
adapters = [args.adapter] if args.adapter else get_adapter_addresses()
if not adapters:
print("Error: no Bluetooth adapters found. Use --adapter XX:XX:XX:XX:XX:XX")
sys.exit(1)
all_devices = []
for adapter in adapters:
all_devices.extend(read_devices(adapter))
if not all_devices:
print(f"No bonded devices found in {BLUEZ_DIR}")
return
irk_devices = [d for d in all_devices if d.irk_le]
no_irk = [d for d in all_devices if not d.irk_le]
if irk_devices:
print("# Paste into Home Assistant configuration.yaml:")
print()
print("known_irks:")
for dev in irk_devices:
print_device(dev, show_raw=args.raw)
else:
print("No IRKs found. Pair a BLE device that uses LE Privacy (e.g. a phone).")
if no_irk:
print()
print("# Devices without IRK (classic BT or no LE Privacy):")
for dev in no_irk:
print(f"# {dev.name} ({dev.address})")
# ---------------------------------------------------------------------------
# Subcommand: verify
# ---------------------------------------------------------------------------
def cmd_verify(args) -> None:
if not CRYPTO_OK:
print("Error: install 'cryptography': pip install cryptography")
sys.exit(1)
irk_hex = args.irk.strip().lower().replace(" ", "").replace(":", "")
rpa = args.rpa.strip().upper()
if len(irk_hex) != 32:
print(f"Error: IRK must be 32 hex chars (16 bytes), got {len(irk_hex)}")
sys.exit(1)
parts = rpa.split(":")
if len(parts) != 6 or not all(len(p) == 2 for p in parts):
print(f"Error: RPA must be in AA:BB:CC:DD:EE:FF format, got: {rpa}")
sys.exit(1)
first_byte = int(parts[0], 16)
if (first_byte & 0xC0) != 0x40:
print(f"Warning: {rpa} may not be an RPA "
f"(bits 47-46 should be 01, got {first_byte >> 6:02b})")
print(" Only addresses in range 40:xx–7F:xx are RPAs.")
print()
irk_bytes = bytes.fromhex(irk_hex)
reversed_hex = irk_le_to_be(irk_hex)
if resolve_rpa(irk_bytes, rpa):
print(f"MATCH — paste this into Bermuda:")
print(f' irk: "{irk_hex}"')
print(f" (reversed would be: {reversed_hex})")
return
if resolve_rpa(irk_bytes[::-1], rpa):
print(f"MATCH — paste this into Bermuda:")
print(f' irk: "{reversed_hex}"')
print(f" (your input {irk_hex} is the reversed form — don't use that)")