wireless security

Performing Bluetooth Security Assessment

Assess Bluetooth Low Energy device security by scanning, enumerating GATT services, and detecting vulnerabilities

blebluetoothgattwireless-security
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

This skill covers performing Bluetooth Low Energy (BLE) security assessments using the Python bleak library. BLE devices are ubiquitous in IoT, healthcare, fitness, and smart home applications, and many ship with weak or absent security controls. This assessment identifies unencrypted GATT characteristics, devices broadcasting sensitive data, known vulnerable device fingerprints, and improperly secured pairing configurations.

The agent uses bleak's asyncio API to discover nearby BLE devices, connect to target devices, enumerate all GATT services and characteristics, and analyze security properties of each characteristic. It flags characteristics that allow unauthenticated read/write access to sensitive data and identifies devices matching known vulnerable profiles.

When to Use

  • When conducting security assessments that involve performing bluetooth security assessment
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Python 3.9 or later
  • bleak library (pip install bleak)
  • Bluetooth adapter supporting BLE (Bluetooth 4.0+)
  • Linux: BlueZ 5.43+ with D-Bus permissions
  • Windows: Windows 10 version 1709+ with Bluetooth support
  • macOS: macOS 10.15+ with CoreBluetooth

Steps

  1. Scan for BLE devices: Use BleakScanner to discover all advertising BLE devices within range. Capture device name, address (MAC), RSSI signal strength, and advertised service UUIDs.

  2. Identify target devices: Filter discovered devices by name pattern, address, or minimum signal strength. Flag devices broadcasting default or well-known vulnerable names.

  3. Connect and enumerate GATT services: Use BleakClient to connect to the target device and iterate over all GATT services. For each service, record the UUID, description, and contained characteristics.

  4. Analyze characteristic properties: For each characteristic, examine its properties (read, write, write-without-response, notify, indicate). Flag characteristics that expose read or write access without requiring authentication or encryption.

  5. Check for known vulnerable UUIDs: Compare discovered service and characteristic UUIDs against a database of known vulnerable or sensitive services (Heart Rate, Blood Pressure, Device Information, Battery Level) that should require encryption.

  6. Detect unencrypted data exposure: Attempt to read characteristics that should be protected. Successful unauthenticated reads of sensitive data indicate missing security controls.

  7. Generate security report: Compile all findings into a structured JSON report with severity classifications and remediation recommendations.

Expected Output

{
  "assessment_type": "ble_security_audit",
  "target_device": {
    "name": "SmartBand-XR",
    "address": "AA:BB:CC:DD:EE:FF",
    "rssi": -42
  },
  "services_found": 5,
  "characteristics_found": 18,
  "findings": [
    {
      "severity": "high",
      "finding": "Heart Rate Measurement readable without encryption",
      "uuid": "00002a37-0000-1000-8000-00805f9b34fb",
      "properties": ["read", "notify"],
      "remediation": "Enable encryption requirement on characteristic"
    }
  ],
  "risk_score": 7.5
}
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md2.4 KB

BLE Security Assessment API Reference

Bleak Python Library (v0.21+)

Device Discovery

from bleak import BleakScanner
 
# Scan with advertisement data
devices = await BleakScanner.discover(timeout=10.0, return_adv=True)
# Returns: dict[str, tuple[BLEDevice, AdvertisementData]]
 
# Find specific device
device = await BleakScanner.find_device_by_name("DeviceName", timeout=10.0)
device = await BleakScanner.find_device_by_address("AA:BB:CC:DD:EE:FF", timeout=10.0)

GATT Client Operations

from bleak import BleakClient
 
async with BleakClient(address, timeout=15.0) as client:
    # Enumerate services
    for service in client.services:
        print(service.uuid, service.description)
        for char in service.characteristics:
            print(char.uuid, char.properties, char.descriptors)
 
    # Read characteristic
    value = await client.read_gatt_char("00002a19-0000-1000-8000-00805f9b34fb")
 
    # Write characteristic
    await client.write_gatt_char(char_uuid, bytearray([0x01, 0x02]))
 
    # Subscribe to notifications
    await client.start_notify(char_uuid, callback)
    await client.stop_notify(char_uuid)

Common GATT Service UUIDs

UUID (16-bit) Service Name
0x180D Heart Rate
0x1810 Blood Pressure
0x1808 Glucose
0x180F Battery Service
0x180A Device Information
0x1812 Human Interface Device
0x1811 Alert Notification
0x1802 Immediate Alert
0x1803 Link Loss

BLE Security Modes

Mode Level Description
LE Security Mode 1 Level 1 No security (no auth, no encryption)
LE Security Mode 1 Level 2 Unauthenticated pairing with encryption
LE Security Mode 1 Level 3 Authenticated pairing with encryption
LE Security Mode 1 Level 4 Authenticated LE Secure Connections
LE Security Mode 2 Level 1 Unauthenticated data signing
LE Security Mode 2 Level 2 Authenticated data signing

Linux BlueZ Commands

# Scan for BLE devices
sudo hcitool lescan
 
# Device info
sudo hcitool leinfo AA:BB:CC:DD:EE:FF
 
# Interactive GATT tool
gatttool -b AA:BB:CC:DD:EE:FF -I
> connect
> primary          # List services
> characteristics  # List characteristics
> char-read-hnd 0x000e
 
# btmgmt commands
sudo btmgmt info
sudo btmgmt find -l
sudo btmgmt pair -c 3 -t 0 AA:BB:CC:DD:EE:FF

Scripts 1

agent.py7.7 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""BLE security assessment using bleak for device scanning and GATT enumeration."""

import argparse
import asyncio
import json
import sys
import time

from bleak import BleakClient, BleakScanner


SENSITIVE_SERVICE_UUIDS = {
    "0000180d-0000-1000-8000-00805f9b34fb": "Heart Rate",
    "00001810-0000-1000-8000-00805f9b34fb": "Blood Pressure",
    "00001808-0000-1000-8000-00805f9b34fb": "Glucose",
    "00001809-0000-1000-8000-00805f9b34fb": "Health Thermometer",
    "0000180f-0000-1000-8000-00805f9b34fb": "Battery Service",
    "0000180a-0000-1000-8000-00805f9b34fb": "Device Information",
    "00001812-0000-1000-8000-00805f9b34fb": "Human Interface Device",
    "00001802-0000-1000-8000-00805f9b34fb": "Immediate Alert",
}

SENSITIVE_CHAR_UUIDS = {
    "00002a37-0000-1000-8000-00805f9b34fb": "Heart Rate Measurement",
    "00002a35-0000-1000-8000-00805f9b34fb": "Blood Pressure Measurement",
    "00002a18-0000-1000-8000-00805f9b34fb": "Glucose Measurement",
    "00002a1c-0000-1000-8000-00805f9b34fb": "Temperature Measurement",
    "00002a19-0000-1000-8000-00805f9b34fb": "Battery Level",
    "00002a29-0000-1000-8000-00805f9b34fb": "Manufacturer Name",
    "00002a26-0000-1000-8000-00805f9b34fb": "Firmware Revision",
    "00002a28-0000-1000-8000-00805f9b34fb": "Software Revision",
    "00002a25-0000-1000-8000-00805f9b34fb": "Serial Number",
}

VULNERABLE_DEVICE_PATTERNS = [
    "ITAG", "SmartLock", "BLE_Door", "FitBand", "iTag",
    "CC2541", "HM-10", "JDY-08", "AT-09", "MLT-BT05",
]


async def scan_devices(scan_time: float) -> list:
    devices = await BleakScanner.discover(timeout=scan_time, return_adv=True)
    results = []
    for addr, (device, adv_data) in devices.items():
        name = adv_data.local_name or device.name or "Unknown"
        vuln_match = None
        for pattern in VULNERABLE_DEVICE_PATTERNS:
            if pattern.lower() in name.lower():
                vuln_match = pattern
                break
        results.append({
            "address": str(addr),
            "name": name,
            "rssi": adv_data.rssi,
            "service_uuids": [str(u) for u in (adv_data.service_uuids or [])],
            "manufacturer_data": {str(k): v.hex() for k, v in (adv_data.manufacturer_data or {}).items()},
            "known_vulnerable_pattern": vuln_match,
        })
    results.sort(key=lambda d: d["rssi"], reverse=True)
    return results


async def enumerate_gatt(device_address: str) -> dict:
    findings = []
    services_info = []
    total_chars = 0
    async with BleakClient(device_address, timeout=15.0) as client:
        if not client.is_connected:
            return {"error": f"Failed to connect to {device_address}"}
        for service in client.services:
            svc_uuid = str(service.uuid)
            svc_name = SENSITIVE_SERVICE_UUIDS.get(svc_uuid, service.description or "Unknown")
            is_sensitive_svc = svc_uuid in SENSITIVE_SERVICE_UUIDS
            chars_info = []
            for char in service.characteristics:
                total_chars += 1
                char_uuid = str(char.uuid)
                props = char.properties
                char_name = SENSITIVE_CHAR_UUIDS.get(char_uuid, char.description or "Unknown")
                is_sensitive_char = char_uuid in SENSITIVE_CHAR_UUIDS
                char_entry = {
                    "uuid": char_uuid,
                    "name": char_name,
                    "properties": list(props),
                    "handle": char.handle,
                }
                if is_sensitive_char and ("read" in props):
                    findings.append({
                        "severity": "high",
                        "finding": f"{char_name} readable without encryption",
                        "uuid": char_uuid,
                        "service": svc_name,
                        "properties": list(props),
                        "remediation": "Enable encryption requirement on characteristic",
                    })
                if "write-without-response" in props and is_sensitive_svc:
                    findings.append({
                        "severity": "critical",
                        "finding": f"{char_name} writable without response in sensitive service",
                        "uuid": char_uuid,
                        "service": svc_name,
                        "properties": list(props),
                        "remediation": "Remove write-without-response or require authenticated pairing",
                    })
                if "write" in props and not is_sensitive_svc:
                    findings.append({
                        "severity": "medium",
                        "finding": f"{char_name} writable without known authentication",
                        "uuid": char_uuid,
                        "service": svc_name,
                        "properties": list(props),
                        "remediation": "Verify write access requires bonded connection",
                    })
                chars_info.append(char_entry)
            services_info.append({
                "uuid": svc_uuid,
                "name": svc_name,
                "sensitive": is_sensitive_svc,
                "characteristics": chars_info,
            })
    severity_weights = {"critical": 10, "high": 7, "medium": 4, "low": 1}
    risk_total = sum(severity_weights.get(f["severity"], 0) for f in findings)
    risk_score = min(10.0, round(risk_total / max(len(findings), 1), 1))
    return {
        "services_found": len(services_info),
        "characteristics_found": total_chars,
        "services": services_info,
        "findings": findings,
        "risk_score": risk_score,
    }


async def run_audit(device_address: str, scan_time: float) -> dict:
    scan_results = await scan_devices(scan_time)
    target = None
    for dev in scan_results:
        if dev["address"].upper() == device_address.upper():
            target = dev
            break
    if not target:
        return {"error": f"Device {device_address} not found in scan", "scanned_devices": len(scan_results)}
    gatt_result = await enumerate_gatt(device_address)
    return {
        "assessment_type": "ble_security_audit",
        "target_device": target,
        **gatt_result,
    }


def main():
    parser = argparse.ArgumentParser(description="BLE Security Assessment Tool")
    parser.add_argument("--action", choices=["scan", "enumerate", "audit"],
                        required=True, help="Action to perform")
    parser.add_argument("--scan-time", type=float, default=10.0,
                        help="BLE scan duration in seconds")
    parser.add_argument("--device-address", type=str, default=None,
                        help="Target BLE device address (MAC or UUID)")
    parser.add_argument("--output", type=str, default=None,
                        help="Output JSON file path")
    args = parser.parse_args()

    if args.action in ("enumerate", "audit") and not args.device_address:
        print(json.dumps({"error": "Device address required for enumerate/audit"}))
        sys.exit(1)

    start = time.time()
    if args.action == "scan":
        result = asyncio.run(scan_devices(args.scan_time))
        output = {"action": "scan", "devices_found": len(result), "devices": result}
    elif args.action == "enumerate":
        result = asyncio.run(enumerate_gatt(args.device_address))
        output = {"action": "enumerate", "target": args.device_address, **result}
    elif args.action == "audit":
        output = asyncio.run(run_audit(args.device_address, args.scan_time))

    output["elapsed_seconds"] = round(time.time() - start, 2)
    report = json.dumps(output, indent=2)
    if args.output:
        with open(args.output, "w") as f:
            f.write(report)
    print(report)


if __name__ == "__main__":
    main()
Keep exploring