Skip to content

Implement strict BLE AD-structure parsing and raw-byte inspection #55

Open

Description

@NullSovereignOne

Summary

Please add a defensive, byte-accurate parser and optional human-readable hex/AD-structure inspector for Bluetooth LE advertising data returned to Fieldwatch by Android. Preserve the original bytes while exposing parsed AD structures with their offsets, lengths, types, identifiers, payloads, and any parsing errors.

The feature should distinguish what the advertisement contains, what Android has already interpreted, and what Fieldwatch infers from registries or signatures. Invalid or incomplete data must not crash collection or silently become authoritative manufacturer/product attribution.

This request is an enhancement and validation task, not a confirmed finding that Fieldwatch currently misparses all examples below. Any overlap with existing functionality should be assessed against the latest source.

Problem and field observations

Repeated analysis of Fieldwatch CSV exports exposed limitations of flattened fields such as mfg, uuids, and raw:

  1. Ambiguous manufacturer presentation. Observed mfg values include B5B5, 4648, 5050, and FFFF. These may reflect legitimate two-byte values in a manufacturer-specific AD structure, unassigned/vendor-defined company fields, or incorrectly interpreted bytes; they should not automatically become a claimed product brand. Interpretation requires the original AD type and byte boundaries.
  2. Protocol framing vs manufacturer identity. An iBeacon-format payload commonly uses Manufacturer Specific Data with on-wire company bytes 4C 00 (Bluetooth Company ID 0x004C) followed by an iBeacon type/length sequence 02 15. This indicates Apple-defined iBeacon framing, not necessarily Apple-manufactured hardware.
  3. Duplicate presentations of the same UUID. Logs sometimes show short and Bluetooth-base-UUID-expanded forms of the same service, e.g. FEF1 and 0000FEF1-0000-1000-8000-00805F9B34FB. They must not be scored as independent evidence merely because both string representations appear.
  4. Potentially incomplete raw advertisements. Another analysis found a recurring 80-byte raw boundary. A parser must report malformed or incomplete structures rather than reading past available bytes. Determining the actual source of any truncation belongs to Investigate possible 80-byte BLE raw-advertisement truncation across capture, storage, and CSV export.
  5. Loss of structure in flattened fields. A single string or map may omit field occurrence order, duplicate AD types, precise byte spans, and the distinction between service UUID lists and service-data payloads.

The exact raw packet bytes should remain the authoritative source for forensic review; any decoded or normalized interpretation is derived metadata.

Expected behavior

Given an Android ScanRecord byte array, Fieldwatch should:

  • Preserve the complete raw byte sequence as supplied by Android, without alteration.
  • Parse the ordered Advertising Data (AD) structures using the standard Length | AD Type | AD Data convention.
  • Show the original byte offsets/ranges and length validation for each structure.
  • Distinguish a recognized identifier from an unknown or unassigned value, and an assigned owner from the finished-product brand.
  • Represent incomplete/malformed structures and unavailable metadata explicitly.
  • Continue scanning when malformed or adversarial bytes are encountered.
  • Offer an optional analyst-facing raw hex view and a byte-accurate copy operation.

Proposed implementation

1. Parse the original byte sequence with strict bounds checks

Use ScanRecord.getBytes() when a scan record is available. Traverse the returned byte array in order:

  • Read the AD Length octet as unsigned.
  • Treat a zero length as the end of the significant AD region; preserve remaining zero padding and flag nonzero trailing bytes for investigation rather than silently discarding them.
  • Require the length to contain an AD Type octet (Length >= 1).
  • Verify that the declared length fits in the remaining input before reading the type or data.
  • Retain each occurrence independently, even if multiple structures share the same AD Type.
  • Treat a malformed length or truncated structure as a bounded parse error; preserve the offending bytes and stop or recover according to a documented deterministic policy.
  • Avoid unbounded allocations, recursion, exception loops, and regex-driven parsing of binary data.

A structure record could expose:

{
  "offset": 3,
  "declared_length": 5,
  "available_length": 5,
  "ad_type": "0xFF",
  "ad_type_name": "Manufacturer Specific Data",
  "value_hex": "4C000215",
  "status": "complete",
  "warnings": []
}

This JSON illustrates the shape of parsed metadata, not a complete/valid iBeacon advertisement.

2. Correctly parse manufacturer-specific AD type 0xFF

For AD type 0xFF:

  • Require at least two bytes of AD Data before reading the Bluetooth Company Identifier.
  • Interpret those first two on-wire bytes as a little-endian unsigned 16-bit company ID (4C 00 → 0x004C).
  • Preserve the original two-byte sequence separately from the remainder of manufacturer-specific data.
  • Resolve company ownership only from a documented Assigned Numbers snapshot; report unrecognized or unassigned codes without guessing.
  • Permit multiple manufacturer-specific structures to be represented, rather than overwriting earlier occurrences.
  • Distinguish company-ID owner, packet/protocol framing, and product/brand identification.

A syntactically valid ID does not prove that a device belongs to the assigned company; advertisements can be malformed or spoofed. Even a valid assigned company ID is evidence, not cryptographic authentication.

3. Parse service UUID lists and service data without conflating them

Handle applicable AD structures for:

  • 16-, 32-, and 128-bit service UUID lists (including completeness/incompleteness flags).
  • Service Data with 16-, 32-, or 128-bit UUID namespaces.
  • Local Name (shortened and complete), Flags, TX Power, and other recognized types as feasible.
  • Unknown or future AD types as opaque, length-delimited byte sequences.

Store both:

  • Original on-wire UUID bytes / UUID width / AD Type.
  • Normalized canonical UUID value for matching and display.

Retain the distinction between a UUID listed as a service and a UUID labeling a service-data payload. Do not double count the 16-bit and 128-bit Bluetooth-base representation of one UUID.

UUID canonicalization rules and catalog-wide deduplication should remain coordinated with Canonicalize Bluetooth UUIDs before matching, counting, candidate generation, and export, rather than duplicating a separate matching system in this ticket.

4. Preserve provenance and errors

Provide a structured result that can distinguish:

  • raw_from_android (original scan-record bytes)
  • ad_structure_parse_status (complete, partial, malformed, unavailable)
  • byte offset/length of each structure
  • warnings/errors with reason and offset
  • Android-provided parsed values, when present
  • Fieldwatch-derived registry/signature interpretations, labeled as derived

Do not infer whether a missing structure was absent on-air if Android reported truncated data. Respect collection/completeness metadata from Investigate possible 80-byte BLE raw-advertisement truncation across capture, storage, and CSV export and Expose BLE extended-advertising, PHY, and advertising-set metadata in observations and exports.

5. Add a raw-byte / AD-structure inspector

Add an optional inspection view in BLE observation details with:

  • Full captured hex bytes, original length, and completeness status where known.
  • Offset-based hex rendering (byte offsets; no misleading inferred packet boundaries).
  • Ordered parsed AD structures with Type, Length, Value, and status.
  • Decoded Company ID and official assignment, where available.
  • Service UUID list versus Service Data labels and raw data bytes.
  • Inline parse warnings, including declared length exceeding available bytes.
  • Copy raw hex (exact bytes) and copy parsed summary as distinct actions.

The inspector should remain usable offline. If copied content includes identifying addresses, location, or other sensitive context, use the app's privacy/export policy; copying raw advertisement bytes should never silently append GPS or device histories.

6. Keep exports backward compatible

Existing CSV columns (raw, mfg, uuids, etc.) should retain their established meaning unless an explicitly versioned schema migration is introduced.

Possible nonbreaking additions for structured JSON/JSONL export:

raw_hex
raw_length_bytes
ad_parse_status
ad_structures[]
ad_parse_errors[]
company_id_on_wire
company_id_normalized
android_scan_data_status

For CSV, consider a separate diagnostics/JSONL export or one safely escaped structured field instead of creating a fragile variable-width set of columns. Historical logs must not be silently reinterpreted as if new fields had been collected.

Reproduction and regression fixtures

Use synthetic, sanitized fixtures and tests derived from the following observed patterns. Do not publish real MAC/location histories.

Case Input / condition Expected result
Standard flags 02 01 06 AD Type 0x01, value 06, correct offsets
Valid manufacturer header 05 FF 4C 00 02 15 Company ID 0x004C; remaining data 02 15; no claim of full iBeacon validity
Truncated company field 02 FF 4C Malformed/insufficient manufacturer value; no company attribution
Unknown company 05 FF B5 B5 01 02 Parsed numeric ID 0xB5B5, unknown/unassigned unless current registry says otherwise; no guessed vendor
Additional ambiguous values Complete AD type 0xFF fixtures containing 48 46, 50 50, FF FF Correct little-endian numeric parsing; attribution based only on validated registry and additional evidence
Same UUID, two presentations FEF1 and its Bluetooth-base 128-bit form One canonical identity, retaining original widths and occurrences
Service UUID versus service data UUID list AD plus service-data AD with the same UUID Two distinct AD structures, not two independent product identifiers
Repeated AD types Two manufacturer-specific AD structures Both preserved in original order
Invalid length Declared AD length exceeds remaining buffer Bounded error with offending offset; no out-of-bounds read or crash
Zero terminator/padding 00 followed by zero padding Proper termination; original input preserved
Nonzero data after zero length 00 then nonzero bytes Original input preserved; documented warning/policy
Empty/null raw input No scan record Explicit unavailable status, no crash
Long input 31-, 80-, 100-, 255-byte complete fixtures Exact original bytes preserved; no artificial clipping by parser
Random input fuzzing Arbitrary bytes, malformed UTF-8/names, unknown AD types Deterministic bounded behavior; no crash

Also compare the parser against Android's ScanRecord convenience fields where supported, documenting differences caused by duplicate AD types, malformed input, or OS handling. The comparison must not assume Android always returns independent advertisement-versus-scan-response packet boundaries.

Acceptance criteria

  • Raw bytes available through Android's scan-record API are preserved unchanged and can be copied as exact hex.
  • AD parsing uses correct unsigned length, type, and value boundaries with explicit byte offsets.
  • Invalid/truncated AD structures are reported and cannot crash scanning or export.
  • Duplicate AD structures remain visible in original order.
  • Manufacturer Company ID is only decoded from the proper first two bytes of a complete 0xFF AD Data field using little-endian byte order.
  • Unknown or unassigned company values are shown without fabricated ownership or product identity.
  • Service UUID lists, service-data namespaces, and manufacturer payloads are separate evidence types.
  • Original UUID widths/raw bytes are retained; equivalent Bluetooth-base UUID representations are normalized consistently with Canonicalize Bluetooth UUIDs before matching, counting, candidate generation, and export.
  • Inspector clearly separates observed raw data, Android-parsed fields, and Fieldwatch-derived interpretations.
  • Offsets, lengths, warnings, and completeness are available in an analyst-readable view and an optional structured export.
  • Existing CSV consumers remain compatible or receive a documented versioned migration path.
  • The listed regression cases and fuzzing fixtures pass on supported Android versions; duplicate types and incomplete records are covered.
  • No sensitive real-world addresses or GPS history are required in public test fixtures.

References

Requested outcome

Provide a byte-accurate, defensive representation of the BLE advertisement structures available to Fieldwatch so analysts can distinguish raw evidence, safely decoded protocol fields, authoritative assignments, and uncertain inferences without losing source bytes or accepting silently malformed data.

Activity

  1. OffGridPete commented on Nov 8, 2026

    @OffGridPete
    Owner

    Company ID, service UUID, and service data are already stored as separate fields. An unknown company ID is shown as "Not in the Bluetooth company list," not as a brand name.

    If you have one raw row where those were mixed, or where an unknown company was given a brand name, please paste that row. The address suffix can stay off.

  2. added
    enhancement
    on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions