share

ENGINEERING

15min read

Bluetooth Low Energy Sniffing Guide

Nowadays, Bluetooth Low Energy is one of the most popular protocols designed for low-powered and short-range communication between smart devices. As the Internet of Things is steadily gaining popularity, there are even more reasons to learn how it works from the ground up. At the end of this guide, you will gain the confidence to effortlessly and effectively debug and analyze BLE communication for your project.

Sniffing in the context of this article is basically a way to analyze packets which are sent between master (Peripheral) and slave (Central Manager). This knowledge is essential to debug critical errors, point out performance bottlenecks or reverse engineer protocol of your interest. I assume you have at least some elementary knowledge of how Bluetooth Low Energy works. My plan is to extend it with the following steps:

  • Prepare low-cost Sniffer setup based on very popular nRF51 or nRF52 boards managed from the Wireshark application.
  • Introduce you to the most common BLE commands, which are used in practice with proper links to specification to extend your knowledge if you are curious.
  • Analyze the example output from TI CC2541 Sensor Tag.
  • Automate most tedious tasks with Lua scripts in Wireshark.

Setup

There are a lot of options to choose from if you are looking for Bluetooth Low Energy sniffers. I decided to base this guide on nRF family boards, as they are easy to use, quite popular, low-cost and have good integration with Wireshark. There are nRF51 DK (PCA10028), nRF52840 DK (PCA10056) and Adafruit Bluefruit LE Friend (nRF51822) at my disposal and I have tested this setup with them. Other nRF51/nRF52 boards should work as well.

D2956ECB-CDE2-4AEB-BA09-3ADBDBF050E9

Solve your BLE issues
with our free guide

nRF Sniffer v2

To enable the Sniffing functionality, we have to flash our boards with the latest nRF Sniffer v2 firmware. You can find a detailed user guide both for nFR & Adafruit and follow it if you have any problems with the steps below. I want to include them for reference here:

  1. Download the nRF Sniffer v2 package from Nordic website. In my case, I got the version 2.0.0-1.beta.
  2. Extract the downloaded zip file, go to seggerjlink folder and install the driver for your operating system. All of my below command’s paths assume that `seggerjlink` is the current directory.
  3. Run Jlink.exe (JLink Commander on Windows) or jlinkexe (Linux/MacOS). You should get J-Link> command prompt. Make sure that VTref is around 3.3V (the board is powered on) and then type the following commands based on your hardware version:
  4. PCA10056 (nRF52840 Preview DK) and PCA10040 (nRF52 DK):

    1. erase - erase the device memory
    2. nRF52832_XXAA - select the device type
    3. s - set the SWD target interface
    4. 1000 - set the interface speed in kHz
    5. loadfile ../hex/sniffer_pca10040_51296aa.hex - flash firmware
    6. r - reboot the device
    7. g - run the board firmware
  5. PCA10028 (nRF51 DK) and Adafruit Bluefruit LE Friend (nRF51822):

    1. erase - erase device memory
    2. nRF51422_XXAC - select device type
    3. s - set SWD target interface
    4. 1000 - set interface speed in kHz
    5. loadfile ../hex/sniffer_pca10028_51296aa.hex - flash firmware
    6. r - reboot device
    7. g - run the board firmware

Wireshark

To test our board configuration properly, we must install Wireshark application with the nRF plugin. You can do that with the following steps:

  1. Install Wireshark from the official website. In my case, I got version 2.6.3.
  2. Open the application and select Help > About Wireshark from the menu. On macOS Wireshark > About Wireshark.
  3. Select Folders tab.
  4. Click on Extcap path - this should open extcap folder in your files explorer.
  5. Extract content from the extcap folder from nRF Sniffer v2 package to the opened folder from the previous point.
  6. Make sure that you have installed Python2.
  7. Install a serial module dependency: pip2.7 install pyserial.

Running nrf_sniffer.py or nrf_sniffer.bat from extcap folder should return with following output: No arguments given! That means nRF plugin is correctly installed and all dependencies are downloaded. Now, plug in your board, restart Wireshark and you should see the following screen with an option to select your board to start sniffing:

image2

Double click on nRF Sniffer and select the device, which we would like to analyze, from the top menu. We are ready to go!

Packet analysis

The best way is to learn by example! I’ll use the Texas Instruments CC2541 SensorTag and nRF Connect application to capture the traffic between them. The last one will help us scan, connect and send “read/write” requests so that we can have something interactive to analyze. You can find nRF Connect both on Android and iOS stores. In this section, I’ll also point you out to the Bluetooth Core Specification (CS) and Bluetooth Core Specification Supplement (CSS). You definitely should have them to be able to confirm your assumptions and check parts you don’t understand during sniffing. We will start with the Low Energy Controller Link Layer specifciation (CS Vol 6, Part B), which describes the Link Layer protocol. It is used directly for an advertisement, a connection procedure, and a link configuration.

Advertisement

In practice, before any connection takes place, we want to find our device first. For example, your mobile application might want to know if a specific type of BLE-enabled peripheral is in range. Most of them send broadcasts on three channels (37, 38 and 39) periodically, so that they can be detected. The exemplary advertisement packet is defined in the following way:

image12

Wireshark captures Bluetooth Low Energy Link Layer format (btle) as the outermost layer of the packet. It contains Access Address, PDU and CRC calculated based on the PDU content:

  • Access address (AA) - it is a unique address intended for each Link Layer connection between any two devices. Advertisement channel packets have fixed AA which equals 0x8E89BED6 (data is encoded in little-endian for all L2CAP packets).
  • PDU - it can be Advertising Channel PDU (CS Vol 6, Part B, 2.3) or Data Channel PDU (CS Vol 6, Part B, 2.4). Its maximum size can reach from 2 to 257 bytes.
  • CRC - 24-bit CRC, calculated over the PDU (CS Vol 6, Part B, 3.1.1).

Advertisement Channel PDU’ header determines further information (CS Vol 6, Part B, 2.3):

  • 0x00 - it defines PDU type equal to ADV_IND, which means it is connectable and unidirectional advertisement event. The address contained in the payload is public.
  • 0x09 - the length of Advertising Channel PDU’s payload. As this is only one-byte, the maximum size of any PDU’s payload is up to 255 bytes.

Finally, the specific PDU type I sniffed (ADV_IND) defines:

  • Advertising address (AdvA) - in our case it is the public MAC address of TI SensorTag equal to 5c:31:3e:c1:1f:17.
  • Advertisement data - (up to 31 bytes) containing advertisement data fields (described in detail in CSS v7, Part A). Each field starts with one-byte length (0x02), one-byte type (0x01 - flags) and type-specific data (0x05 -BD/EDR Not Supported and LE Limited Discoverable Mode).

Advertisement data is the most important part of the packet. Its content usually contains flags, the short name of a device and the manufacturer-specific data. Fortunately, you don’t have to remember all bit fields and format from the specification to be able to read these. Wireshark has a built-in dissector which does most of the job for you:

image5

In classic profile (selectable on a bottom right side of the Wireshark’s window) view is split into three parts: the list of captured packets, the decoded description of the packet and the hexadecimal form of the packet. Select View > Interface Toolbars > nRF Sniffer to see nRF Sniffer Toolbar at the top if it’s not enabled already. Feel free to check devices which are advertising around you. There are even more PDU types you can see in your sniffer logs:

  • ADV_DIRECT_IND - connectable directed advertising event. It contains both Advertisement Address and Target Address. This packet does not hold any data as it is directed only at Target Address.
  • ADV_NONCONN_IND - non-connectable and non-scannable undirected advertising event. It has the same structure as ADV_IND.
  • ADV_SCAN_IND - scannable undirected advertising event. It has the same structure as ADV_IND.
  • Other Extended Advertising Payload packets (CS Vol 6, Part B, 2.3.4).

The device is connectable when it can accept connections and it is scannable when it can accept scan requests (SCAN_REQ). The last option is very often utilized when information about the device can’t fit in 31 bytes (advertisement data part of ADV_IND) and the additional response ( SCAN_RSP ) is used to send additional 31 bytes:

image9

Scan request contains information about scanner address (random 4b:63:d5:89:14:10) and advertisement address (public 5c:31:3e:c1:1f:17).

image11

Scan response data has the same fields as advertisement data except flags data type (CCS Part A, 1.0). I received following values from my TI SensorTag:

  • SRP (#1) - complete local name (0x09): “SensorTag”
  • SRP (#2) - connection interval range (0x12): 100ms (0x50 * 1.25ms) - 1000ms (0x0320 * 1.25ms).
  • SRP (#3) - tx power level (0x0A) - 0 dB.

With the data gathered from advertisement packets seen above, the Central Manager can filter and finally recognize device with which it can establish a connection. It’s worth to note that the selected data types of advertisement are visible and can be processed by applications on iOS phones only. Therefore, the MAC address is not available. What’s important, the distinguishing information such as manufacturer’s company and product id are usually provided in manufacturer data type (0xFF).

Connection establishment

image8

Open nRF Connect application and press side button on TI SensorTag. Then when the device is visible on your list click “CONNECT” to establish a link. Make sure to have opened Wireshark application with the applied device filter to only capture TI’s packets - you can set it in the top nRF Sniffer Toolbar.

Don’t be surprised if you don’t see anything for the first time. Both nRF51 and nRF52 boards are limited to listen to one channel simultaneously. It may happen that a connection request event occurred in the different channel than the one which the device was listening to. In that case, just disconnect and retry the whole procedure.

A lot of events will appear after connection, so make sure to pause sniffing to analyze carefully what really happened. First one of them should be a connection request which is the last, not mentioned, type of PDU of Advertisement Channel PDUs. It is responsible for creating a connection, which will continue on a different channel. It has the following structure:

image1

There are a lot of fields to cover so start slowly, one by one:

  • Initiator’s device address (InitA) - It’s a MAC address of a device, which is trying to connect to TI SensorTag. In this case, based on the header and this field’s value, we know that it has the following random address: 50:ab:a9:13:95:85.

  • Advertiser’s device address (AdvA) - It’s a MAC address of a device, to which we are connecting. It’s TI SensorTag address.

  • Access address (CS Vol 6, Part B, 2.2) - This is an address specific to the newly established Link Layer connection. Every successive packet will use this address in the header until the connection terminates.

  • CRC initialization value (CS Vol 6, Part B, 3.1.1) - this is an initialization value for linear feedback shift register used to implement 24-bit CRC polynomial.

  • Transmit window size (CS Vol 6, Part B, 4.5.3, 0x03 * 1.25ms = 3.75ms) - after CONNECT_IND is sent, a master can specify a duration of the time window when the slave should receive the first message. This first message, called anchor point defines when connection event starts.

  • Transmit window offset (CS Vol 6, Part B, 4.5.3, 0x09 * 1.25ms = 11.25ms) - transmit window start is defined by an offset plus delay (1.25ms for CONNECT_IND). Therefore, this payload declares that the first transmit window will start 12.5ms from CONNECT_IND message and be closed 16,25ms from CONNECT_IND (based on above transmit window size). A slave must respond to the message in 1 out of 6 transmission windows, which are started once again every connection interval.

  • Connection interval (CS Vol 6, Part B, 4.5.1, 0x0018 * 1.25ms = 30ms) - the time between each connection event. Connection event is a time window when both slave and master can exchange packets. When this procedure is done, both devices have to wait till the next connection event occurs. Higher connection interval value decreases the power consumption but increases the connection latency.

  • Connection slave latency (CS Vol 6, Part B, 4.5.1, 0x0000) - allows a slave to skip the specified number of connection events. In this case, TI Sensor Tag must listen to every connection event.

  • Connection supervision timeout (CS Vol 6, Part B, 4.5.2, 0x0048 * 10ms = 720ms) - it defines the maximum time between two Data Packet PDUs before the connection is considered lost. Before the connection is established, this value is equal to 6 times connection interval value.

  • Channel map field (ChM, CS Vol 6, Part B, 1.4.1, 0xFFFFFFFF1F) - the map indicating the used (bit set to 1) and the unused (bit set to 0) data channels during connection. This connection uses all channels except 37, 38, 39 which are equal to RF channels: 0,12, 39 and are reserved for advertisement purposes.

  • Hop increment & Master’s sleep clock accuracy (CS Vol 6, Part B, 4.5.8.2 & 4.2.2, 0x30 = 001 10000b = 1 SCA & 16 Hop) - hop increment defined in the first 5 bits is an additional field which is used to calculate next channel index in use based on the current channel index. New channel in our case is calculated using following formula: newChannelIndex = (currentChannelIndex + hopIncrement) % 37, which results in 16, 32, 11 and so on. You can read about algorithm variants and various edge cases in the Core Specification. Master’s sleep clock is defined in the last 3 bits and specified as PPM value. In this payload value of 1 means 151 to 250 ppm accuracy. It is used to calculate time delta relative to window start and end when the receiver should start and end listening.

Timing parameters like window size, window offset, connection interval, and connection slave latency might be hard to grasp without an example. The following graph shows the beginning of connection establishment with all relevant timings marked and annotated:

image4

After CONNECT_IND message, the first packet should appear inside a green area called transmit window. If that message won’t appear, a successive green window can be used to retry connection procedure. In our case, as the first packet arrived in time, it is not used. Master’s packets are blue rectangles and slave’s packets are red rectangles. Horizontal size should mark timings, but to make actual packets visible they are larger than expected. For example, the first connection event lasted 128μs (LL_VERSION_IND) + 150μs (T_IFS) + 80μs (EMPTY_PDU) = 358μs which is only ~1,2% of available time in the first connection event. Once a Data Channel packet is received from the peer device (~14ms mark in our case), the connection is considered established.

Control packets

Data Channel PDUs are split into Link Layer Data PDUs and Link Layer Control PDUs. The last one can be used both by master and slave after successful connection establishment to change Link Layer connection parameters, ask for supported features, change maximum PDU size, terminate connection etc. My TI SensorTag exchanged 1 packet of that type with the mobile application just after CONNECT_IND. It was sent in both directions to determine the supported version of the Bluetooth specification:

image7

Data Channel PDU can be only transmitted over physical channels which are not used for advertisement data. That’s why the Data Channel Header can be completely different than the one previously discussed in Advertisement Data PDUs. It has the following fields:

  1. LLID (2bits: 0b11, CS Vol 6, Part B, 2.4) - this value defines the type of the Data Channel PDU:

    1. 10 - the start of LL Data PDU, which contains the whole L2CAP message or first fragment of it (explained in next section).
    2. 01 - the continuation of LL Data PDU or Empty PDU (length set to zero). The remaining fragments of L2CAP messages are sent by this packet if Empty PDU is not specified.
    3. 11 - LL Control PDU.
  2. NESN (1bit: 0b00: , CS Vol 6, Part B, 4.5.9) - the next sequence number expected. It is used by the slave device to acknowledge the received packet or request resending the last Data Channel PDU sent. If SN doesn’t match NESN packet, it is ignored by slave.

  3. SN (1bit: 0b00, CS Vol 6, Part B, 4.5.9) - Sequence number. It is used to identify packets sent by a master. If SN matches NESN, the previous packet is retransmitted by master.

  4. MD (1bit: 0b00, CS Vol 6, Part B, 4.5.6) - More data flag, which can be set both by slave and a master. If the master sets this value to 0, the connection event is closed and no more packets are exchanged.

  5. Length (1 byte: 0x06) - the length of a payload (excluding header).

The first byte of LL Control Payload (CS Vol 6, Part B, 2.4.2) is an opcode, which defines both type and length of the remaining part. In my captured trace 0x0C defines LL_VERSION_IND. The master notified that it supports Bluetooth LE version 5.0 (0x09) and uses Broadcom (0x0F) controller with 0x420E version. The slave notified that it supports Bluetooth LE version 4.0 (0x06) and uses Texas Instruments (0x0D) controller with 0x0140 version. All the available Link Layer Controls PDUs are described in CS Vol 6, Part B, 2.4.2.

Summary

Today, we’ve learned how the low-level packets specific to Low Energy host controller are structured. We know how to recognize and analyze the advertisement procedure as well as the connection establishment. We’ve learned how to manage the link layer configuration. Additionally, you can start to sniff packets with Wireshark application by yourself. In the upcoming second part, we will learn about L2CAP and some other higher level protocols which work on top of ED/BDR as well. We will cover the discovery procedure and the characteristic operations by example.

share


PrzemekStaff Software Engineer

LEARN MORE

Contact us if you have any questions regarding the article or just want to chat about technology, our services, job offers and more!

POLIDEA NEWSLETTER

Sign in and expect sharp insights, recommendations, ebooks and fascinating project stories delivered to your inbox

The controller of the personal data that you are about to provide in the above form will be Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: 0048 795 536 436, email: hello@polidea.com (“Polidea”). We will process your personal data based on our legitimate interest and/or your consent. Providing your personal data is not obligatory, but necessary for Polidea to respond to you in relation to your question and/or request. If you gave us consent to call you on the telephone, you may revoke the consent at any time by contacting Polidea via telephone or email. You can find detailed information about the processing of your personal data in relation to the above contact form, including your rights relating to the processing, HERE.

Data controller:

The controller of your personal data is Polidea sp. z o.o. with its registered office in Warsaw at ul. Przeskok 2, 00-032 Warsaw, KRS number: 0000330954, tel.: [0048795536436], email: [hello@polidea.com] (“Polidea”)

Purpose and legal bases for processing:

 

Used abbreviations:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

ARES – Polish Act on Rendering Electronic Services dated 18 July 2002

TL – Polish Telecommunications Law dated 16 July 2004

1)        sending to the given email address a newsletter including information on Polidea’s new projects, products, services, organised events and/or general insights from the mobile app business world |art. 6.1 a) GDPR, art. 10.2 ARES and art. 172.1 TL (upon your consent)

Personal data:name, email address

2)       statistical, analytical and reporting purposes |art. 6. 1 f) GDPR (based on legitimate interests pursued by Polidea, consisting in analysing the way our services are used and adjusting them to our clients’ needs, as well as developing new services)

Personal data:name, email address

Withdrawal of consent:

You may withdraw your consent to process your personal data at any time.

Withdrawal of the consent is possible solely in the scope of processing performed based on the consent. Polidea is authorised to process your personal data after you withdraw your consent if it has another legal basis for the processing, for the purposes covered by that legal basis.

Categories of recipients:

Your personal data may be shared with:

1)       authorised employees and/or contractors of Polidea

2)       persons or entities providing particular services to Polidea (accounting, legal, IT, marketing and advertising services) – in the scope required for those persons or entities to provide those services to Polidea

 

Retention period:

1)       For the purpose of sending newsletter to the given email address – for as long as the relevant consent is not withdrawn

2)       For statistical, analytical and reporting purposes – for as long as the relevant consent is not withdrawn

Your rights:

 

Used abbreviation:

GDPR – Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016
on the protection of natural persons with regard to the processing of personal data and on the free movement
of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)

According to GDPR, you have the following rights relating to the processing of your personal data, exercised by contacting Polidea via [e-mail, phone].

1)       to access to your personal data (art. 15 GDPR) by requesting sharing and/or sending a copy of all your personal data processed by Polidea

2)       to request rectification of inaccurate personal data
(art. 16 GDPR) by indicating the data requiring rectification

3)       to request erasure of your persona data (art. 17 GDPR); Polidea has the rights to refuse erasing the personal data in specific circumstances provided by law

4)       to request restriction of processing of your personal data (art. 18 GDPR) by indicating the data which should be restricted

5)       to move your personal data (art. 20 GDPR) by requesting preparation and transfer by Polidea of the personal data that you provided to Polidea to you or another controller in a structured, commonly used machine-readable format

6)       to object to processing your personal data conducted based on art. 6.1 e) or f) GDPR, on grounds relating to your particular situation (art. 21 GDPR)

7)       to lodge a complaint with a supervisory authority,
in particular in the EU member state of your habitual residence, place of work or place of the alleged infringement if you consider that the processing
of personal data relating to you infringes the GDPR
(art. 77.1 GDPR)

No obligation to provide data:

Providing your personal data is not obligatory, but necessary for Polidea to provide you the newsletter service

Refusal to provide the above data will result in inability to receive the newsletter service.

Profiling

In the process of providing the newsletter service, we make decisions in an automated way, including profiling, based on the data you provide.

 

“Profiling” means automated processing of personal data consisting of the use of your personal data to evaluate certain personal aspects relating to you, in particular to analyze or predict aspects concerning your personal preferences and interests.

 

The automated decisions are taken based on the analysis of clicked and viewed content. They affect the targeting of specific newsletter content to selected users registered to receive the newsletter service, based on the anticipated interests of the recipient.