Book Image

Building Bluetooth Low Energy Systems

By : Muhammad Usama bin Aftab
Book Image

Building Bluetooth Low Energy Systems

By: Muhammad Usama bin Aftab

Overview of this book

Bluetooth Low Energy (BLE) is a Wireless Personal Area network technology aimed at novel applications for smart devices. High-tech BLE profiles and services are being increasingly used by application developers and hardware enthusiasts to allow devices to interact with the surrounding world. This book will focus on a technical introduction to BLE and how it is reshaping small-distance communication. We will start with IoT, where many technologies such as BLE, Zigbee, and IEEE 802.15.4 Mesh will be introduced. The book will present BLE from an engineering perspective, from which the protocol stack, architecture, and layers are discussed. You will learn to implement customized projects for Peripheral/Central communication, BLE Beacons, indoor navigation using triangulation, and the Internet gateway for Bluetooth Low Energy Personal Network, all using various code samples and APIs on Android, iOS, and the Web. Finally, the book will conclude with a glimpse into future technologies destined to be prominent in years to come.
Table of Contents (14 chapters)
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Bluetooth Low Energy


Started by Dr. Nils Rydbeck, Bluetooth was first conceptualized in 1989 and later built by Ericsson in 1994. The name Bluetooth was given after the tenth-century king of Denmark, Herald Bluetooth. The king united Danish tribes and introduced them to Christianity. This name was given to the technology by Jim Kardach in 1997. The name was adopted because the core concept of Bluetooth was to build a system that can connect a phone to the computer. The idea of Bluetooth was supported by Nokia and Intel who were thinking to migrate towards a universally interoperable wireless technology. Later, companies including Ericsson, Intel, Toshiba, Nokia and IBM came together in Lund, Sweden, in 1996 to agree on the foundation of Special Interest Group (SIG). This group is responsible for designing and maintaining the Bluetooth technology. Nowadays, the group is called Bluetooth SIG.

Note

King Herald Blatand was given the nickname Bluetooth because of his habit of eating blueberries.

Bluetooth technology was invented to connect mobile devices to computers over a short distance. It was standardized by IEEE 802.15 working group which describes Wireless Personal Area Network (WPAN) standards. IEEE 802.15.1 defines physical and Media Access Control (MAC) layer specifications for short distance wireless connectivity for Bluetooth. Version 1.0 was developed by the SIG but resulted in interoperability problems which were later fixed in v1.1. The technology was never to be used as a replacement of any wireless Internet technology like Wi-Fi. It was to only use for the limited range and with a limited amount of data. Even though Bluetooth today can transfer a huge amount of data, it is still being used for short distance communication only.

Bluetooth versions

From 1999 till 2009, many versions of Bluetooth were released. Solving many problems from the initial release while increase the speed and the connection quality. It was not until the version 3.0 when Bluetooth could achieve a speed of 24 Mbit/s. During this evolution, a continuous change in the protocol stack can be observed to solve various issues in the technology. For example, in Bluetooth v3.0, Logical Link Control and Adaption Protocol (L2CAP) was introduced to multiplex multiple logical connections between various devices using different protocols. Service Discovery Protocol (SDP) was also introduced to connect to the Bluetooth devices like headsets etc. During this period of time, the member companies of Bluetooth SIG rose to 12,000 and by 2010, it surpassed a total of 13,000 companies.

The next step in the history of Bluetooth was a significant one. The SIG decided to take a step back and rethink the protocol stack being used in Classic Bluetooth. Bluetooth Core Specification 4.0 or simply Bluetooth Low Energy came into being in 2011. It was previously known as Wibree by Nokia which replaced the entire protocol stack of the previous technology and concentrated on the speed and the simple architecture. 2011 was the same year when SIG surpassed 15,000 companies, Apple and Nordic Semiconductor joined SIG Board of Directors, Apple released first two computers with Bluetooth 4.0 support and Microsoft announced Windows 8 phone with Bluetooth 4.0 Core Specifications.

Unlike classic Bluetooth, Bluetooth Low Energy focused on the low power consumption. That was a very important step from the SIG as it was realized that in future, the technology will not be just fast but less power hungry as well:

Bluetooth SIG official Logo

Bluetooth v4.1 came as a software update rather a hardware update. The update focused on the usability and implemented Bluetooth Core Specification Addenda. Previously, the Bluetooth radio and LTE radio didn't coexist and resulted in interference. The issue was causing performance issue and fast battery drainage. Bluetooth 4.1 enabled both these technologies to co-exist in one device with high data rates. BLE v4.1 was the first version which enabled any device to become a server and client. On the other hand, the smart connectivity was introduced which let devices manage their power better by enabling manufacturers to define their own reconnection time intervals. The version of Bluetooth was commercially available in early 2013. In the same year, Google also announced the native BLE support to Android.

With power efficiency and server/client flexibility, Bluetooth Low Energy officially stepped into the Internet of Things.

The evolution in the Bluetooth leads us to Bluetooth v4.2. In December 2014, Bluetooth SIG announced the next version of Bluetooth with some special features supporting IoT. Bluetooth Low Energy v4.2 provided flexible Internet connectivity options to achieve power efficiency. IPv6 support was given to the standard with an ability to make Bluetooth Smart Internet Gateway (GATT) architecture. The concept will be discussed in detail later in the chapter.

In Bluetooth 4.2, LE privacy and LE Secure Connections were also introduced by Bluetooth SIG. Two-factor authentication via BLE was introduced to provide better security. The new version also claimed that it is not 2.5 times faster with 10-fold extension in data length. The over-the-air firmware update was also introduced in this version which provides manufacturers to remotely update the firmware without even touching the device. Bluetooth 4.2 is backward compatible with version 4.0 and 4.1 which were also Bluetooth Low Energy.

Note

iOS, Android, Windows Phone, BlackBerry, OS X, Linux and Windows 8 natively support Bluetooth Low Energy.

Bluetooth Low Energy Key Concepts

Bluetooth Low Energy is a standard with millions of devices running it. Discussing Bluetooth Core Specification in full-length is almost an impossible task as it has many technicalities. So the key concepts that will help you develop the Bluetooth Low Energy applications will be discussed in the book.

The layer stack of Bluetooth Low Energy corresponds to the OSI layer. In this book, we will not discuss the lower level layers (that is, from PHY to L2CAP) as they are out of the scope. The main concepts covered in this book will be Attribute Protocol, Generic Attribute Profile (GATT), Generic Access Profile (GAP) and the top layer Bluetooth Application. The book will give practical examples of how to write the Bluetooth Application based on the GATT server/client architecture.

The protocol stack of the Bluetooth Low Energy can be seen in the following figure:

Bluetooth Layered Model

Attribute Protocol (ATT) and Generic Attribute Profile (GATT)

Bluetooth Low Energy brought two core specifications and every Low Energy profile is supposed to use them. Attribute Protocol and Generic Attribute Profile.

Attribute Protocol is a low-level layer that defines how to transfer data. It identifies the device discovery, reading and writing attributes on a fellow device. On the other hand, Generic Attribute Profile is built on the top of ATT to give high-level services to the manufacturer implementing LE. These services are basically used to manage the data transfer process in a more systematic way. For example, GATT defines if a device's role is going to be Server or Client.

An interesting thing about ATT and GATT is that they are not transport-layer specifications, that means that they can be implemented on BR/EDR or LE. GATT is a mandatory entity in LE and used to discover services and characteristics. The GATT server listens to an ATT requests and confirmations sent by GATT client. GATT server stores, process and transfer the data to the client. Another role of the GATT is that it defines the data arrangement on the server side so that the client can read it accordingly. The data transfer between GATT server and GATT client is called an "Attribute". An attribute is uniquely identified by a Universally Unique Identifier (UUID) which is 128 bits long string ID.

Note

The Bluetooth system consists of four base layers. Radio (Physical layer), Baseband, Link Layer, and L2CAP. More information about the working on these layers can be found in the core specification document: https://www.bluetooth.com/specifications/adopted-specifications.

GATT Server and GATT Client

Any device that wants to transfer data over Bluetooth can adopt a role based on the requirement. A device can act as a GATT Server which welcomes requests from the client, process data accordingly and returns back the value. GATT Server is responsible for processing and making data attribute available to the client.

GATT client, on the other hand, initiates the request to the server and receive the responses. A GATT client needs to perform a service discovery process in order to know the server's attributes. Once it is done identifying the services, it can read or write data attribute.

Universally Unique Identifiers (UUIDs)

A UUID is a unique identifier that is guaranteed to be globally unique all the time. It is a 128-bit identifier out of which some pre-allocated values are used for registration purposes as described by the Bluetooth SIG. One of the very first pre-allocated values for UUID is known as Bluetooth Base UUID and has a value of 00000000-0000-1000-8000- 00805F9B34FB. Pre-allocated values in the UUID often has 16-bits or 32-bits aliases that can be used to generate your own UUIDs. The formula for generating a 128-bits UUID with pre-allocated alias is:

128-bit-UUID = 16-bit-value * 2 ^ 96 + Bluetooth-Base-UUID
128-bit-UUID = 32-bit-value * 2 ^ 96 + Bluetooth-Base-UUID

Bluetooth SIG provides UUIDS for services and profiles and they are made for a specific purpose. If it doesn't specify a particular need, a new UUID can be created. Using the Bluetooth-Base-UUID is recommended by the SIG for this purpose.

GATT-based Bluetooth Profile Hierarchy

Generic Attribute Profile describes the structure following which a profile exchange data from one device to another. The basic elements of a profile are services and characteristics. Typically, a profile is made in order to achieve the desired task. Services and characteristics are the main components of a profile which can be described as the subtasks.

The division of the GATT-based hierarchy is given here:

GATT based profile model with services, characteristics, and descriptors.

Service

A service is a collection of characteristics designed to fulfil a particular task. It can also reference another sub-service which then comprises of characteristics. For example, a profile can have a Heart Rate Monitor service which is to expose heart rate for fitness purposes. This service can have Heart Rate Measurement, Body Sensor Location, and Heart Rate Control Point characteristics which are the subtasks of the Heart Rate Monitor service.

Characteristic

A characteristic contains a value, properties, and configuration information. Characteristic is the combination of characteristic properties, characteristic declaration, characteristic value, and a descriptor. Characteristic properties define the level of access that characteristic grants. For example, if a characteristic is read-only it will be defined in the properties. The characteristic declaration can be seen as a characteristic overview where the name, description, type and the requirements of the characteristic is mentioned. Descriptors are used to define a characteristic value.

The following diagram shows a view of the BLE characteristics:

Heart Rate Measurement characteristic with overview, properties, security and descriptor

The example in the figure is describing a Heart Rate Measurement characteristic. The overview describes the functionality of the characteristics and the requirement level. The requirement tells if it is mandatory or optional for the service. The properties show the access-level of this characteristic. In this particular scenario, the characteristic is only used to notify. The descriptor identifies the value or permits configurations of the GATT server with respect to the characteristic value.

Generic Access Profile (GAP)

Bluetooth Low Energy specifies a generic profile that enables BLE devices to communicate with each other. It can be understood as a base profile which is the same throughout the BLE devices. It defines basic requirements of a Bluetooth device. This generic profile is used to tie all the layers together and identifies all the layers from PHY to L2CAP. It helps to universally maintain all the layers of Bluetooth Low Energy.

Generic Access Profile defines security by implementing cryptographic algorithms that enable devices to securely transfer data attributes. This functionality is achieved by Security Manager which is implemented on the protocol stack. As GAP is universally spread over all the layers, it can maintain and dictate the standard to all the layers. The Advanced Encryption Standard (AES) is used for secure key exchange between the peers to start a communication. GAP sets the procedures for security by giving the trust to the peers to carry sensitive data across the Bluetooth connection.

Generic Access Profile (GAP) also defines the roles used in the Bluetooth Low Energy. These roles are Broadcaster, Observer, Peripheral, and Central. These roles are really important to understand as the foundation of BLE is based on it. Based on the implementation, a BLE device can operate under one role at a time. This multi-role scenario is only possible if the underlying controllers support those roles.

Broadcaster

Broadcaster is a role to the device that wants to periodically or constantly broadcast the information. A Bluetooth beacon is a good example of this when all it needs to do is to broadcast information. Theoretically, the role of broadcasting is given to the transmit-only devices, but practically it can be given to any device that transmits and receives. Another important information about the broadcasters it that the data sent is not a result of any connection. Broadcaster always transmits data irrespective of who is listening. These packets are special advertising packets and should not be confused with the connection data packets from GATT Server and Client.

Observer

The role of Observer is to listen to the packets broadcast from the Broadcaster. Typically, they are meant to be for receive-only applications. The observer is able to read the advertised packets and listen to the data coming out of the Broadcaster. Just like Broadcasters, they do not support incoming connections.

Central

The role of Central can be understood as a role of master in a master-slave architecture. It is capable of making a connection to the peer. A central can connect to multiple peers at the same time. A central can be a smartphone/tablet which can initiate a session by connecting to various BLE peer. A smartphone has the capability to connect to the Bluetooth headphones and Bluetooth smartwatch both at the same time. Central is also the originator of the connection request which means that no other role can start the connection request.

Peripheral

Peripheral, on the other hand, resembles a slave in a master-slave architecture. It broadcasts advertisement packets for the central so that it can find it and then accepts the connection request. Even though it advertises the data, it is power and processing efficient.

Note

Bluetooth Low Energy works on 40 channels with 2MHz spacing where the discovery is done by advertising. BLE supports a maximum data rate of about 1Mbps and provides AES-CCM encryption for confidentiality. 50-100 meters is the practical range of BLE with 10mW maximum power output.

Bluetooth Low Energy Security

Bluetooth Low Energy provides five features for its security including pairing, bonding, encryption, authentication and message integrity. These satisfy three pillars of security which are Authentication, Confidentiality, and Authorization. Attacks against improperly secured Bluetooth implementation can provide hackers with unauthorized access to the sensitive information and unauthorized use of the Bluetooth device. The main security features in Bluetooth Low Energy are:

  • Pairing is the process of generating shared keys (on both ends) known as Short Term Key (STK)
  • Bonding is the subsequent process of pairing where they store the STK in order to form a trusted pair
  • Device authentication is when two devices identify if they have same keys
  • Encryption is for message confidentiality
  • Message integrity is to avoid attackers to forge the data

Key Generation

Key generation is a process done while a device wants to pair with another device. The process is independent of any other LE device. The reason to generate a key and pair the device with another device are:

  • Securing device identity
  • Authentication of the unencrypted data.
  • Confidentiality

For key generation purposes the devices exchange required information and then the Short Term Key (STK) is calculated. The link is then encrypted used AES-CCM cryptography. While the key generation is not performed on the controller, the actual encryption is performed on the controller.

Association Models in Pairing

These models describe the negotiations between the device to generate Short Term Key (STK). BLE provides four association models:

  • Numeric Comparison
  • Just Works
  • Out of Bands (OOB)
  • Passkey Entry
Numeric Comparison

This model is defined when both BLE devices are designed with a display. This display is used to show a six-digit number and both are capable to verifies those numbers with a simple yes or no. For example, a user is shown a six-digit number 453145 on both screens and then asked if the numbers appeared on both ends are same. If the user answer yes, the pairing is successful. This model provides security from man-in-the-middle attacks and also serves the purpose if the user is connected to the right device.

Just Works

This model is defined for the scenarios where one or more devices do not have a display to show any pin or any digit. In this model, the user is not shown any digits, rather, a numeric comparison happens and then the user is asked to accept the connection. This model is not secure from man-in-the-middle (MITM) attack , where a person is listening to the channel constantly.

An example of this model is when a cellular phone tries to connect to a headset. At the headset end, there is no display to show the digits. Hence, the numeric comparison happens and the user is just asked to accept the connection.

Out of Band (OOB)

This model is applicable in the scenarios where devices are capable of using another technology like NFC. It is called Out of Band mechanism to discover both devices as well as to exchange cryptographic numbers. The model provides security from MITM attacks. The practical example of this model is NFC-based connection between a cellular phone and a Bluetooth headphone. The user needs to touch the headset in order to pair it with the phone.

Passkey Entry

This model is for the scenarios where one device has input functionality but not the display functionality and other devices have only display functionality. The user is shown a six-digit number 456654 on the device with a display and then asked to enter the number on the other device. If the number entered in the other device is correct, the connection is paired.

Note

According to Bluetooth SIG, Just Works and Passkey Entry do not provide any passive eavesdropping protection. This is because Secure Simple Pairing uses Elliptic Curve Diffie-Hellman and LE legacy pairing does not.

Signing the Data

Signing the data is a very important concept in terms of message integrity. If the encryption is not available, BLE has the ability to send authenticated data over an unencrypted link between two devices. This is done by signing a data using a Connection Signature Resolving Key (CSRK). This signature is placed after the Packet Data Unit (PDU). The receiving device verifies the signature and considers it coming from a trusted source. The signature is made by a Message Authentication Code (MAC) which can sometime use Hash Functions. This MAC is made upon counter value which protects the replay attack.

Privacy

Bluetooth Low Energy provides a unique feature that diminishes the ability to track an LE device by changing the Bluetooth device address frequently. This is an important privacy feature as it allows an advertiser to hide. These Bluetooth device addresses are temporary and are randomly generated that can only be recognized by bonded device. Whenever a device is bonded to another device for the first time, an identity key (IRK) is generated which is later used to generate a private address. This address must be resolvable by the other devices in order to keep the privacy.