Chiavi degli AirPods

Gli AirPods trasmettono il loro stato tramite Bluetooth Low Energy (BLE) più volte al secondo. Una parte di ogni trasmissione è pubblica e una parte è cifrata. Senza chiavi, CAPod legge la parte pubblica: batteria in passi del 10%, stato di ricarica, coperchio della custodia e rilevamento nell’orecchio. Due chiavi dei tuoi AirPods sbloccano di più:

Le chiavi restano le stesse indipendentemente dal telefono o dal computer a cui gli AirPods sono associati.

Queste chiavi appartengono ai tuoi AirPods. Non pubblicarle in segnalazioni pubbliche, chat o screenshot.

Recupero automatico

Sui telefoni che supportano la connessione diretta, CAPod chiede entrambe le chiavi agli AirPods quando si connette e le salva nel profilo che ha quegli AirPods come Dispositivo associato. Non devi fare nulla: apri il profilo ed entrambe le chiavi mostrano Configurato.

Estrai le chiavi manualmente se il tuo telefono non supporta la connessione diretta, o se le chiavi restano su Non impostato.

Estrazione manuale

Android non ha modo di mostrarti le chiavi, quindi l’estrazione manuale richiede un computer a cui gli AirPods sono associati.

macOS con uno script

Questo script legge le chiavi di tutti i dispositivi AirPods o Beats associati dal portachiavi di macOS. macOS chiede la tua password prima di consentire l’accesso.

get_airpod_keys.sh
#!/usr/bin/env bash

set -u

SYSTEM_KEYCHAIN="/Library/Keychains/System.keychain"

usage() {
  cat <<'EOF'
Usage:
  ./get_airpod_keys.sh
  ./get_airpod_keys.sh --address AA:BB:CC:DD:EE:FF

Extracts AirPods / Beats MagicAcc keys from the macOS MobileBluetooth
Keychain item for CAPod:
  - MagicAccIRK     -> CAPod Identity key
  - MagicAccEncKey  -> CAPod Encryption key

macOS may show Keychain permission prompts. These keys are sensitive.
EOF
}

normalize_mac() {
  printf '%s\n' "$1" | tr '[:lower:]' '[:upper:]'
}

discover_bluetooth_addresses() {
  system_profiler SPBluetoothDataType -json 2>/dev/null \
    | awk -F '"' '/"device_address"[[:space:]]*:/ { print $4 }' \
    | sort -u
}

lookup_mobilebluetooth_item() {
  local address="$1"

  security find-generic-password \
    -a "$address" \
    -s MobileBluetooth \
    -g "$SYSTEM_KEYCHAIN" 2>&1
}

extract_plist_value() {
  local key="$1"

  # security(1) prints the password plist as an escaped one-line string, so
  # this intentionally parses the <key>...</key><string>...</string> pattern.
  sed -nE "s/.*<key>${key}<\\/key>[^<]*<string>([^<]+)<\\/string>.*/\\1/p"
}

print_keys_for_address() {
  local address="$1"
  local output
  local irk
  local enc_key
  local local_address

  output="$(lookup_mobilebluetooth_item "$address")"

  irk="$(printf '%s\n' "$output" | extract_plist_value "MagicAccIRK")"
  enc_key="$(printf '%s\n' "$output" | extract_plist_value "MagicAccEncKey")"
  local_address="$(printf '%s\n' "$output" | extract_plist_value "LocalAddress")"

  if [[ -z "$irk" || -z "$enc_key" ]]; then
    return 1
  fi

  printf 'Bluetooth address: %s\n' "$address"
  if [[ -n "$local_address" ]]; then
    printf 'Local Mac address: %s\n' "$local_address"
  fi
  printf 'CAPod Identity key / MagicAccIRK:\n%s\n\n' "$irk"
  printf 'CAPod Encryption key / MagicAccEncKey:\n%s\n' "$enc_key"
  printf '%s\n' '---'
  return 0
}

main() {
  local addresses=()
  local found=0

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --address|-a)
        if [[ $# -lt 2 ]]; then
          usage >&2
          exit 2
        fi
        addresses+=("$(normalize_mac "$2")")
        shift 2
        ;;
      --help|-h)
        usage
        exit 0
        ;;
      *)
        printf 'Unknown argument: %s\n\n' "$1" >&2
        usage >&2
        exit 2
        ;;
    esac
  done

  if [[ ${#addresses[@]} -eq 0 ]]; then
    while IFS= read -r address; do
      [[ -n "$address" ]] && addresses+=("$(normalize_mac "$address")")
    done < <(discover_bluetooth_addresses)
  fi

  if [[ ${#addresses[@]} -eq 0 ]]; then
    printf 'No Bluetooth device addresses found. Try --address AA:BB:CC:DD:EE:FF\n' >&2
    exit 1
  fi

  for address in "${addresses[@]}"; do
    if print_keys_for_address "$address"; then
      found=1
    fi
  done

  if [[ "$found" -eq 0 ]]; then
    printf 'No MobileBluetooth entries with MagicAccIRK/MagicAccEncKey were found.\n' >&2
    printf 'Make sure the AirPods are paired with this Mac, then try again.\n' >&2
    exit 1
  fi
}

main "$@"

Contributo di @akshaynexus in #597.

macOS con uno script più breve

Questa alternativa più breve funziona con il semplice sh e richiede python3. Legge le chiavi del primo dispositivo AirPods o Beats connesso, quindi collegali prima al Mac. Esegui lo script con sh airpod_key_retrieval_posix.sh. Se i campi delle chiavi risultano vuoti, macOS ha negato l’accesso al portachiavi oppure gli AirPods non sono associati a questo Mac.

airpod_key_retrieval_posix.sh
ADDR="$(
  system_profiler SPBluetoothDataType -json 2>/dev/null |
  python3 -c '
import json, sys, re

data = json.load(sys.stdin)

for controller in data.get("SPBluetoothDataType", []):
    for item in controller.get("device_connected", []):
        for name, info in item.items():
            if re.search(r"AirPods|Beats", name, re.I):
                print(info.get("device_address", ""))
                raise SystemExit
'
)"

if [ -z "$ADDR" ]; then
  echo "No connected AirPods or Beats device found."
  exit 1
fi

OUT="$(security find-generic-password \
  -a "$ADDR" \
  -s MobileBluetooth \
  -g /Library/Keychains/System.keychain 2>&1)"

IRK="$(printf '%s\n' "$OUT" |
  sed -nE 's/.*<key>MagicAccIRK<\/key>[^<]*<string>([^<]+)<\/string>.*/\1/p')"

ENC="$(printf '%s\n' "$OUT" |
  sed -nE 's/.*<key>MagicAccEncKey<\/key>[^<]*<string>([^<]+)<\/string>.*/\1/p')"

LOCAL="$(printf '%s\n' "$OUT" |
  sed -nE 's/.*<key>LocalAddress<\/key>[^<]*<string>([^<]+)<\/string>.*/\1/p')"

printf '\nAirPods Keys\n'
printf '%s\n' '--------------------------------------------'
printf 'AirPods Address : %s\n' "$ADDR"
printf 'Mac Address     : %s\n' "$LOCAL"
printf 'Identity Key    : %s\n' "$IRK"
printf 'Encryption Key  : %s\n' "$ENC"
printf '%s\n' '--------------------------------------------'

Contributo di @ikcv in #597.

macOS con Accesso Portachiavi

Funziona senza script, ma non su tutte le versioni di macOS.

  1. Associa gli AirPods al Mac.
  2. Tieni premuto Option e fai clic sull’icona Bluetooth nella barra dei menu. Annota l’indirizzo dei tuoi AirPods, per esempio 9C:FC:….
  3. Apri Accesso Portachiavi e cerca MobileBluetooth. Potrebbero esserci più voci. Apri quella il cui Account è l’indirizzo del passaggio 2.
  4. Seleziona Mostra password e inserisci la tua password quando richiesto. macOS potrebbe chiederla più di una volta.
  5. Copia il testo dal campo della password. È un breve documento XML. MagicAccIRK è la chiave di identità e MagicAccEncKey è la chiave di crittografia:
<key>MagicAccEncKey</key>
<string>3A-9C-81-57-E6-44-7F-F2-FB-8E-07-63-6C-99-E1-29</string>
<key>MagicAccIRK</key>
<string>71-44-65-1E-E2-CA-D1-26-F2-4E-20-EE-3E-CC-DE-77</string>

Linux

Questo script Python si connette agli AirPods associati e chiede loro le chiavi. Passa l’indirizzo Bluetooth degli AirPods come argomento.

airpod_key_retrieval.py
import sys
import socket

PROXIMITY_KEY_TYPES = {
    0x01: "IRK",
    0x04: "ENC_KEY",
}

def parse_proximity_keys_response(data):
    if len(data) < 7 or data[4] != 0x31:
        return None
    key_count = data[6]
    keys = []
    offset = 7
    for _ in range(key_count):
        if offset + 3 >= len(data):
            break
        key_type = data[offset]
        key_length = data[offset + 2]
        offset += 4
        if offset + key_length > len(data):
            break
        key_bytes = data[offset:offset + key_length]
        keys.append((PROXIMITY_KEY_TYPES.get(key_type, f"TYPE_{key_type:02X}"), key_bytes))
        offset += key_length
    return keys

def hexdump(data):
    return " ".join(f"{b:02X}" for b in data)

def main():
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} <MAC>")
        sys.exit(1)

    bdaddr = sys.argv[1]
    PSM = 0x1001

    handshake = bytes.fromhex("00 00 04 00 01 00 02 00 00 00 00 00 00 00 00 00")
    key_req = bytes.fromhex("04 00 04 00 30 00 05 00")

    sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)
    sock.connect((bdaddr, PSM))
    sock.send(handshake)
    sock.send(key_req)

    try:
        while True:
            pkt = sock.recv(1024)
            keys = parse_proximity_keys_response(pkt)
            if keys is not None:
                print("Proximity Keys:")
                for name, key_bytes in keys:
                    print(f"  {name}: {hexdump(key_bytes)}")
                break
    finally:
        sock.close()

if __name__ == "__main__":
    main()

Contributo di @kavishdevar in #290.

Windows

Non è ancora confermato che funzioni con gli AirPods. La guida Private BLE Device di Home Assistant mostra come leggere la chiave di identità di un dispositivo dal registro di Windows.

Segnalato in #757.

Qualsiasi computer con una macchina virtuale

La guida di @2Elvin esegue macOS in una macchina virtuale per estrarre le chiavi su qualsiasi piattaforma.

Inserisci le chiavi in CAPod

  1. Apri Impostazioni, Dispositivi e tocca il tuo profilo.
  2. Tocca Chiave di identità e incolla la chiave di identità (MagicAccIRK, oppure IRK dallo script Linux).
  3. Tocca Chiave di crittografia e incolla la chiave di crittografia (MagicAccEncKey, oppure ENC_KEY).
  4. Salva il profilo.

CAPod accetta le chiavi con trattini, spazi o senza separatori, per esempio 71-44-65-1E-…. Quando entrambe le chiavi funzionano, la dashboard mostra le percentuali esatte della batteria dei tuoi AirPods.