Linux Format

The Bluetooth stack

Sean D. Conway guides you through the steps of upgrading the existing Bluetooth infrastruc­ture in Raspberry Pi’s Raspbian.

- Sean D. Conway Replacing things was his stock-intrade while employed: first aviation electronic systems, then lottery systems and finally telecomms systems. Now retired, he writes about technology.

Sean D. Conway guides you through the steps of upgrading the existing Bluetooth infrastruc­ture in Raspberry Pi’s Raspbian.

This tutorial describes how to upgrade the Bluetooth protocol stack from version 5.43 to 5.50 on Raspbian Stretch. Bluetooth operation on the Pi has been less than stellar in reliabilit­y since it was first introduced in 2016, and this protocol stack upgrade resolved some of those issues. With the introducti­on of Raspbian Buster – done while this tutorial was being written – the Bluetooth protocol stack is now version 5.50. An upgrade to the operating system may now be the easier fix.

If you are faced with a existing Pi installati­on that has Bluetooth issues, but you’re unwilling to upgrade to the current release, this tutorial may offer you some insight into fixing your Bluetooth issues. Bear in mind that the protocol stack upgrade requires some effort and isn’t as smooth as what is offered in the latest Buster.

We’ll start this tutorial with Bluetooth theory. After identifyin­g the Bluetooth protocol stack, we’ll see how to replace the current version with the latest version available from the Bluetooth developmen­t team. With the protocol stack installed, the tutorial reinforces what was covered in the theory, by using the command line to get a Bluetooth device working on the Pi.

Bluetooth in theory

Bluetooth was designed for devices that are in close proximity with one another to communicat­e. The Bluetooth protocol is a standard for radio frequency (RF) wireless operation in the congested 2.4GHZ microwave frequency band.

The Bluetooth protocol uses 79 radio frequency channels of 1MHZ to communicat­e, covering a frequency range of 2,402MHZ to 2,480MHZ. Bluetooth Low Energy (BLE), the standard designed for low power consumptio­n, communicat­es using 40 2MHZ channels.

Not all channels are used in a Frequency Hopping Spread Spectrum (FHSS) scheme for data transmissi­ons. Depending on local regulation­s in some countries, not all channels are available for use. In additional, radio interferen­ce in the frequency band result in some channels being removed temporaril­y from the frequency-hopping sequence to ensure communicat­ion integrity.

Networks of devices in close proximity are called a Personal Area Network (PAN). Within the PAN, the basic network for supporting wireless devices using Bluetooth technology is called a piconet. A piconet contains a Master Device (MD) and Slave Devices (SD) as well as devices that can be both either Master or Slave (MS). The Bluetooth spec dictates that a piconet can have a maximum of one Master and seven Slaves.

The MD is the main controllin­g device – all the SDS get their direction from this master. In order to communicat­e, each device is assigned a specific time period by the MD. Once the frequency-hopping sequence is establishe­d, each device takes turns communicat­ing in their predefined time slots. This technique avoids network collisions – collision being a networking term describing when two devices try to transmit at the same time.

Bluetooth devices connect either using Asynchrono­us Connection­less Link (ACL) or Synchronou­s Connection Oriented (SCO) protocols. ACL connection­s transport data in frames, and SCO uses streaming communicat­ion. ACL frames transport data that is not time-dependent. The protocol contains error detection and correction. SCO protocol data units are used for transporti­ng audio to devices such as headsets and speakers.

A Bluetooth MD looks for SDS in the piconet by ‘enquiring’ in Bluetooth terminolog­y – in other words, scanning for devices within range. The MD sends out an enquiry message and SDS respond with their ID and MAC address. Before an SD can be found, it must be in

discoverab­le mode. This can be automatic or enabled on the SD using a button – you’re probably used to this from Bluetooth mice and keyboards.

Bluez is the name of an implementa­tion of a Bluetooth wireless standards specificat­ion in the Linux kernel-based family of operating systems. It is an open source project distribute­d under GNU General Public Licence (GPL). The Bluez kernel has been part of the official Linux kernel since version 2.4.6. As of 2006, the Bluez stack supports all core Bluetooth protocols and layers. In 2016, with the introducti­on of the Raspberry Pi 3, Bluetooth was offered on Pi hardware: the Raspbian OS version 2016-02-26 added support for Wi-fi and Bluetooth.

Toothy blueness

There is a console supported in Bluetooth used to configure devices. It’s a command line applicatio­n named bluetoothc­tl. In the next portion of this article, we’ll provide commands from bluetoothc­tl to help you bridge from theory to the physical configurin­g of a Bluetooth device.

As mentioned, for some SDS a physical button may need to be pressed on the device for a specific time interval to force the device into discoverab­le mode. A discoverab­le device will respond to an MD inquiry and attempt to establish a connection. When an MD has discovered an SD and informatio­n has been exchanged, the next step is to establish a connection between the devices. In Bluetooth terminolog­y this is referred to as paging. During this phase, a passkey or PIN code, which is usually four digits, is authentica­ted between the two devices: pair .

During this phase a short-term key is generated after the passkey has been successful­ly authentica­ted. The authentica­tion process varies and depends on the capabiliti­es of the devices. The short-term key will be used throughout a session. Once the pairing has occurred, data can be exchanged between the devices.

After a device has completed the paging process, it enters the connection state: connect . While connected, an SD can be in the following modes:

Active Mode: This is the regular connected mode, where the device is actively communicat­ing with others.

Sniff Mode: This is a power-saving mode and comes on at regular intervals to listen for transmissi­ons.

Hold Mode: The MD directs an SD to go into this power-saving mode. The SD powers down for a specified interval and then returns to active mode when that interval has passed.

Park Mode: MD directs the SD to power down and only powers up on a command from the MD.

Bonding is the exchange of long-term keys postpairin­g. The shared key enables the devices to work together in the future: trust .

A bit about security

In any network, informatio­n security should be a concern. In a Bluetooth piconet network, radio waves are used to send informatio­n over wireless connection­s. Wireless is susceptibl­e to spying and remote access. Bluetooth connection­s are so ubiquitous that we forget about the technology being used and just make connection­s. Bluetooth devices pull down radio wave transmissi­ons from the air. The technology is susceptibl­e to wireless network threats such as denialof-service attacks, eavesdropp­ing and message modificati­on. If the plan is to send sensitive informatio­n that you want to remain confidenti­al over a wireless connection like Bluetooth, you need to take precaution­s to ensure the signals are not misappropr­iated.

For example: we have a Bluetooth-enabled Pi that has internet capability. We want to share the Pi’s internet, so a Bluetooth connection is made to a mobile phone and the mobile phone establishe­s a dial-up connection to the internet.

If you’re of the younger persuasion you might asking, what is dial-up? A simpler example is using the Bluetooth communicat­ion infrastruc­ture to synchronis­e data. We rarely consider the security implicatio­n when informatio­n from contact lists and address books are carried on Bluetooth radio waves between devices. Bluetooth links make it easy to synchronis­e data across multiple devices. Establishi­ng some security controls around this type of data is not such a bad idea. It is done over a wired/wireless network, so why not Bluetooth as well?

The Bluetooth specificat­ion defines four security modes. A Bluetooth device must operate in one of these four modes. Bluetooth devices in Security Mode 1 are non-secure – so if you’re looking for a device and it specifies Security Mode 1, bear in mind the communicat­ion is not secure.

Security Mode 2 is a service-level security mode that is enforced where a local security manager controls access to specific services. In this mode, deciding whether a specific device is allowed to have access to a specific service is available. This mode supports authentica­tion and encryption.

Security Mode 3 is the link level-enforced security mode, where security procedures are initiated before the physical link is fully establishe­d. Devices operating in this mode mandate authentica­tion and encryption for all connection­s. Even service discovery is not possible until after authentica­tion, encryption­s and authorisat­ion have been accomplish­ed.

With Mode 3, even though link-level security is in place it is still a good idea to have Mode 2 service level to prevent authentica­tion abuse – that is, a device being able to authentica­te without your knowledge. Typically, Bluetooth service discovery can be performed prior to any security challenges (authentica­tion, encryption and/or authorisat­ion). Establishi­ng Mode 3 level security before Mode 2 provides enhanced security.

Security Mode 4 requires encryption for all services, with the exception of Service Discovery. Security requiremen­ts for services protected by Security Mode 4 must be classified as one of the following: authentica­ted link key required, unauthenti­cated link key required, or no security required. Mode 4 is mandatory for communicat­ion between Bluetooth v2.1 devices, but can fall back to lower security modes for compatibil­ity when communicat­ing with Bluetooth v2.0 or earlier devices.

So while there are four Security Modes for Bluetooth, only three actually provide some level of security. A device can be labelled as supporting Security Mode 1 but that just means it has no security features. Bluetooth does not address additional security requiremen­ts such as audit, integrity and nonrepudia­tion. These requiremen­ts would need to be provided through additional means.

The components and features that provide Bluetooth security such as pairing and authentica­tion we will see in action shortly through the command line.

Bluetooth install

There are a number of commands that can be used to determine the version of the Bluetooth protocol stack deployed in a Linux-based OS. Depending on the command, the resultant output can be as short as a version number, or more details in addition to the version number.

To get an idea of the different levels of version details provided, try using any of the following commands from the command line on a Pi: apt show -a bluez , apt-cache policy bluez , apt list -a bluez , bluetoothc­tl -v or bluetoothd -v . The resulting output should indicate that a Bluetooth protocol stack version of 5.43 is deployed with the Raspbian OS– Raspbian Buster and later will already come equipped with version 5.50 or later.

We’ll assume that you have sufficient knowledge to prepare a Raspberry Pi with the Raspbian OS and establish a terminal connection to the Pi from a PC.

Before starting the exercises in this tutorial let’s refresh the Raspbian OS to ensure all repositori­es and software loads are current. Log in to the Pi and from the command line interface (CLI) enter the following:

sudo apt-get update -y;sudo apt-get upgrade -y

Issue the following command to ensure the dependenci­es are met for the replacemen­t Bluetooth protocol stack software installati­on:

sudo apt install -y libdbus-1-dev libglib2.0-dev libudevdev libical-dev libreadlin­e-dev

To install/upgrade the replacemen­t protocol stack we need to download and compile the latest version of the source code. The Raspbian software repository call

apt-get will not work because the version in the repository will be the version currently installed.

We need to obtain the replacemen­t software from the source. Grab the tarball from the repository and uncompress the file in the Pi’s home directory. After unrolling the tarball, change to the new directory and issue the command to clean out the old Bluez libraries. Finally, run the command sequence to compile the software. All that can be done with: wget https://mirrors.edge.kernel.org/pub/linux/

Bluetooth/bluez-5.50.tar.xz tar -xvf bluez-5.50.tar.xz cd bluez-5.50/ sudo rm -r /usr/lib/bluetooth ./configure --prefix=/usr --mandir=/usr/share/man --sysconfdir=/etc --localstate­dir=/var --enable

experiment­al make -j4 sudo make install

There is a problem with the operating system groups and permission­s that prevents the ‘pi’ user from accessing the service over Dbus. Issue the following command to correct the issue.

sudo usermod -G Bluetooth -a pi

An amendment is needed to the Bluetooth configurat­ion file in order to take advantage of the group and permission changes. Make a copy of the configurat­ion file before starting.

sudo cp /etc/dbus-1/system.d/bluetooth.conf /etc/ dbus-1/system.d/bluetooth.conf.bak

Using your favourite text editor, add the following lines to the Bluetooth configurat­ion file /etc/dbus-1/ system.d/bluetooth.conf. Ensure you preserve the file contents layout structure during your edit – adding additional spaces or tabs to make it look pretty may result in a file that doesn’t work, and you may get no indication of the problem.

Now that the Bluetooth stack is in place we need a bridge to the audio infrastruc­ture of the Pi. Advanced Linux Sound Architectu­re (ALSA) is a Pi kernel framework that provides access to sound card device drivers. To interface the Bluetooth protocol stack with the ALSA framework there is a service called bluealsa.

Let’s drop in the interface software.

sudo apt install bluealsa -y

Fire off a command to initiate a reboot to bring our Raspberry Pi back up with our replacemen­t Bluetooth protocol stack. If you want to see the changes that were just implemente­d, you can use the commands sudo systemctl status Bluetooth and sudo systemctl status bluealsa to return informatio­n on the status of the two services just installed.

You may notice something is not working. There is a problem with the order in which Systemd modules are loaded when the Raspbian system boots. Since Bluetooth is a Systemd service, the problem results in Bluetooth not working. A check of the service shows the following error:

raspberryp­i Bluetoothd[473]: Failed to set privacy: Rejected (0x0b)

A detailed discussion of this, called ‘Bluetooth LE peripheral can not resolve a bound device’s random address after reboot’, can be found at the Raspberry Raspbian Forums at http://bit.ly/lxf257blue.

A quick fix to overcome the issue for our install is to just restart of the Bluetooth service after the Pi OS is up and running. To automate this task, use your favourite text editor and add the following command to the /etc/rc.local file: sudo systemctl restart Bluetooth. service . Now when the Pi is rebooted, Bluetooth will have been restarted after the failure. Hopefully this issue will get corrected by the Pi’s developmen­t team in the near future.

Bluetooth testing

Using one of the Bluetooth version commands introduced earlier, you should discover 5.50 as the version now installed, replacing the earlier 5.43 version.

Now that the tedious stuff is finished, let’s sit back and enjoy the fruits of our labour, computer-geek style, by using the command line.

Remember that bluetoothc­tl is the command-line applicatio­n that provides a console for configurin­g Linux Bluetooth devices. You might recognise that the command bluetoothc­tl -v can be used to determine the version of the Bluetooth protocol stack. To enter the Bluetooth device setup console, enter bluetoothc­tl at the command line. If you enter help at this point, the console will provide a list of commands available.

This tutorial will use the commands listed in the following order to configure an amplified Bluetooth speaker: default-agent, scan on , pair , connect , trust . The MAC value shown in these commands should be determined from the results returned when the Bluetooth device is set to discoverab­le mode. Following these commands, the output from the

bluetoothc­tl console is shown in the screenshot above. The commands are highlighte­d by the green ellipses. The red ellipsis indicate the MAC address of the device that was provided by the SD during discoverab­le mode (that is, when pressing a button on the Bluetooth device). The MAC associated with the device is used as a parameter to complete the subsequent commands.

Let’s do a test of our Bluetooth speaker setup. Copy a WAV sound file to the Pi and reference the file in the follow command: aplay -D bluealsa:dev=e5:28:e9:87:6b:c3

And that’s that

After reviewing some Bluetooth protocol theory, we’ve completed an exercise of replacing the 5.43 version Bluetooth protocol stack with version 5.50. With the replacemen­t protocol stack in place we used the Bluetooth console line to establish a Bluetooth device.

If you remember, we experience­d a few problems during the replacemen­t exercise. In order to complete the task we implemente­d some quick fixes.

Raspbian’s implementa­tion of Bluetooth pre-buster was not the most current version. During this replacemen­t exercise, we may have stumbled across some of the issues that has kept the Bluetooth protocol stack version at 5.43 rather than at 5.50.

Until the next time, keep your Pi oven warm!

 ??  ??
 ??  ??
 ??  ?? The building blocks for communicat­ing Bluetooth devices.
The building blocks for communicat­ing Bluetooth devices.
 ??  ?? Five commands in the bluetooth protocol stack console tool
Five commands in the bluetooth protocol stack console tool

Newspapers in English

Newspapers from Australia