The Bluetooth stack
Sean D. Conway guides you through the steps of upgrading the existing Bluetooth infrastructure in Raspberry Pi’s Raspbian.
Sean D. Conway guides you through the steps of upgrading the existing Bluetooth infrastructure 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 reliability since it was first introduced in 2016, and this protocol stack upgrade resolved some of those issues. With the introduction 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 installation 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 identifying the Bluetooth protocol stack, we’ll see how to replace the current version with the latest version available from the Bluetooth development 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 communicate. 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 communicate, covering a frequency range of 2,402MHZ to 2,480MHZ. Bluetooth Low Energy (BLE), the standard designed for low power consumption, communicates using 40 2MHZ channels.
Not all channels are used in a Frequency Hopping Spread Spectrum (FHSS) scheme for data transmissions. Depending on local regulations in some countries, not all channels are available for use. In additional, radio interference in the frequency band result in some channels being removed temporarily from the frequency-hopping sequence to ensure communication 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 controlling device – all the SDS get their direction from this master. In order to communicate, each device is assigned a specific time period by the MD. Once the frequency-hopping sequence is established, each device takes turns communicating 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 Asynchronous Connectionless Link (ACL) or Synchronous Connection Oriented (SCO) protocols. ACL connections transport data in frames, and SCO uses streaming communication. ACL frames transport data that is not time-dependent. The protocol contains error detection and correction. SCO protocol data units are used for transporting audio to devices such as headsets and speakers.
A Bluetooth MD looks for SDS in the piconet by ‘enquiring’ in Bluetooth terminology – 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
discoverable 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 implementation of a Bluetooth wireless standards specification in the Linux kernel-based family of operating systems. It is an open source project distributed 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 introduction 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 application named bluetoothctl. In the next portion of this article, we’ll provide commands from bluetoothctl to help you bridge from theory to the physical configuring 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 discoverable mode. A discoverable device will respond to an MD inquiry and attempt to establish a connection. When an MD has discovered an SD and information has been exchanged, the next step is to establish a connection between the devices. In Bluetooth terminology this is referred to as paging. During this phase, a passkey or PIN code, which is usually four digits, is authenticated between the two devices: pair
During this phase a short-term key is generated after the passkey has been successfully authenticated. The authentication process varies and depends on the capabilities 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
Active Mode: This is the regular connected mode, where the device is actively communicating with others.
Sniff Mode: This is a power-saving mode and comes on at regular intervals to listen for transmissions.
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 postpairing. The shared key enables the devices to work together in the future: trust
A bit about security
In any network, information security should be a concern. In a Bluetooth piconet network, radio waves are used to send information over wireless connections. Wireless is susceptible to spying and remote access. Bluetooth connections are so ubiquitous that we forget about the technology being used and just make connections. Bluetooth devices pull down radio wave transmissions from the air. The technology is susceptible to wireless network threats such as denialof-service attacks, eavesdropping and message modification. If the plan is to send sensitive information that you want to remain confidential over a wireless connection like Bluetooth, you need to take precautions to ensure the signals are not misappropriated.
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 establishes 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 communication infrastructure to synchronise data. We rarely consider the security implication when information from contact lists and address books are carried on Bluetooth radio waves between devices. Bluetooth links make it easy to synchronise data across multiple devices. Establishing 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 specification 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 communication 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 authentication and encryption.
Security Mode 3 is the link level-enforced security mode, where security procedures are initiated before the physical link is fully established. Devices operating in this mode mandate authentication and encryption for all connections. Even service discovery is not possible until after authentication, encryptions and authorisation have been accomplished.
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 authentication abuse – that is, a device being able to authenticate without your knowledge. Typically, Bluetooth service discovery can be performed prior to any security challenges (authentication, encryption and/or authorisation). Establishing 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 requirements for services protected by Security Mode 4 must be classified as one of the following: authenticated link key required, unauthenticated link key required, or no security required. Mode 4 is mandatory for communication between Bluetooth v2.1 devices, but can fall back to lower security modes for compatibility when communicating 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 requirements such as audit, integrity and nonrepudiation. These requirements would need to be provided through additional means.
The components and features that provide Bluetooth security such as pairing and authentication 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 , bluetoothctl -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 repositories 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 dependencies are met for the replacement Bluetooth protocol stack software installation:
sudo apt install -y libdbus-1-dev libglib2.0-dev libudevdev libical-dev libreadline-dev
To install/upgrade the replacement 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 replacement 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 --localstatedir=/var --enable
experimental make -j4 sudo make install
There is a problem with the operating system groups and permissions 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 configuration file in order to take advantage of the group and permission changes. Make a copy of the configuration 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 configuration 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 infrastructure of the Pi. Advanced Linux Sound Architecture (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 replacement Bluetooth protocol stack. If you want to see the changes that were just implemented, you can use the commands sudo systemctl status Bluetooth and sudo systemctl status bluealsa to return information 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:
raspberrypi 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 development 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 bluetoothctl is the command-line application that provides a console for configuring Linux Bluetooth devices. You might recognise that the command bluetoothctl -v can be used to determine the version of the Bluetooth protocol stack. To enter the Bluetooth device setup console, enter bluetoothctl 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
bluetoothctl console is shown in the screenshot above. The commands are highlighted by the green ellipses. The red ellipsis indicate the MAC address of the device that was provided by the SD during discoverable 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 replacement protocol stack in place we used the Bluetooth console line to establish a Bluetooth device.
If you remember, we experienced a few problems during the replacement exercise. In order to complete the task we implemented some quick fixes.
Raspbian’s implementation of Bluetooth pre-buster was not the most current version. During this replacement 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!