0% found this document useful (0 votes)
34 views43 pages

Ota Firmware

Uploaded by

hanoi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views43 pages

Ota Firmware

Uploaded by

hanoi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Bachelor’s thesis

Information and Communications Technology, Embedded Software and IoT

2024

Lassi Lahti

Implementing a Firmware Over-


the-Air Update Mechanism for
Embedded Devices
Bachelor’s | Abstract

Turku University of Applied Sciences

Information and Communications Technology, Embedded Software and IoT

2024 | 43 pages

Lassi Lahti

Implementing a Firmware Over-the-Air Update


Mechanism for Embedded Devices
This thesis presents the design and execution of an embedded device firmware
update mechanism, focusing on the development of a bootloader and over-the-
air update functionality. The thesis describes an employer project with the
requirement to implement a bootloader solution and update features to allow
firmware updates via Bluetooth in real-world scenarios.

The theoretical portion describes fundamental concepts surrounding


bootloaders, firmware, and embedded device cybersecurity, along with relevant
legislation within the European Union.

In practice, the thesis outlines the design and implementation of a custom


bootloader solution, enabling over-the-air updates over Bluetooth using an
XMODEM implementation.

In summary, this thesis aims to offer a comprehensive understanding of


bootloader functionality and its role in enabling device updatability.

Keywords:

Bootloader, Firmware, Embedded systems, Over-the-air updates


Opinnäytetyö (AMK) | Tiivistelmä

Turun ammattikorkeakoulu

Tieto- ja viestintätekniikan insiööritutkinto, Sulautetut järjestelmät ja IoT

2024 | 43 sivua

Lassi Lahti

Langattomien ohjelmistopäivitysjärjestelmän
toteuttaminen sulautetuissa laitteissa
Tämä opinnäytetyö käsittelee sulautettujen laitteiden
ohjelmistopäivitysjärjestelmän suunnittelua ja toteutusta, keskittyen
käynnistyksenlataajan ja langattoman päivitystoiminnon kehittämiseen.
Opinnäytetyö kuvailee työnantajan projektia, jossa tavoitteena oli toteuttaa
käynnistyksenlataaja ja päivitysominaisuus mahdollistamaan
ohjelmistopäivitykset Bluetoothin yli.

Teoreettinen osuus kuvailee käynnistyksenlataajien ja ohjelmiston


peruskäsitteitä, sekä sulautettujen laitteiden kyberturvallisuutta yhdessä
olennaisten EU:n lainsäädäntöjen kanssa.

Käytännössä tämä opinnäytetyö esittelee räätälöidyn käynnistyksenlataimen


suunnittelun ja toteutuksen, sekä langattoman päivitystoiminnon toteutuksen
XMODEM-protokollaa käyttäen.

Tämä opinnäytetyö pyrkii tarjoamaan kattavan ymmärryksen


käynnistyksenlataimen toiminnasta ja sen roolista laitteiden päivitettävyyden
mahdollistajana

Asiasanat:

Käynnistyksenlataaja, Ohjelmisto, Sulautetut järjestelmät, Langattomat


päivitykset
Content

List of abbreviations (or) symbols 7

1 Introduction 8

2 Bootloader 9
2.1 Bootloader fundamentals 9
2.2 Types of bootloaders 9
2.2.1 Primary bootloaders 9
2.2.2 Secondary bootloaders 10
2.3 Choosing the right bootloader implementation 10

3 Firmware 12
3.1 The importance of firmware updates 12
3.2 Firmware update methods and requirements 13

4 Cybersecurity 14
4.1 EU Cyber Resilience Act 14
4.2 Bootloader security measures 15
4.3 OTA update security 15

5 Project requirements 17
5.1 Bootloader requirements 17
5.2 Cybersecurity requirements 17

6 ATSAMC21N18A 18

7 ATSAMC21 Bootloader Implementation 20


7.1 Memory management 20
7.2 Firmware verification 22
7.3 Preparing for updatability 24
7.4 Securing the device 25

8 Over-The-Air Update Implementation 27


8.1 Bluetooth 27
8.2 XMODEM protocol 28
8.3 Custom communication protocol 31

9 Testing 32
9.1 Test setup 32
9.2 Bootloader tests 33
9.2.1 Test case 1.1 34
9.2.2 Test case 1.2 37
9.3 OTA update tests 37
9.3.1 Test case 2.1 38
9.3.2 Test case 2.2 40
9.3.3 Test case 3.1 40
9.3.4 Test case 3.2 40

10 Conclusion 41

References 42

Pictures

Picture 1. System architecture for embedded devices. 12


Picture 2. ATSAMC21N18A block diagram. 19
Picture 3. Memory architecture. 21
Picture 4. XMODEM protocol data flow. 29
Picture 5. Modified binary file inspected in a code editor. 32
Picture 6. Bootloader indicator LED. 34
Picture 7. Firmware indicator LED. 35
Picture 8. NMEA messages with GPS data. 36
Picture 9. Connection established in bootloader. 37
Picture 10. Initial version number. 38
Picture 11. Valid binary file upload. 39
Picture 12. Updated version number. 40
Tables

Table 1. XMODEM packet 28


Table 2. XMODEM symbol definitions 28
Table 3. Testing requirements. 33

Code

Code 1. Snippet from the bootloader linker file. 20


Code 2. Shared memory section memory definition. 21
Code 3. Snippet from the go_to_app function. 22
Code 4. Firmware header verification. 23
Code 5. Bluetooth module configuration. 24
Code 6. Shared data structure and use cases. 25
Code 7. CRC calculation function 30
Code 8. CRC match functionality 30
Code 9. NMEA command loop file upload mode and command 31
List of abbreviations (or) symbols

Abbreviation Explanation of abbreviation (Source)

ROM Read-Only Memory

MCU Micro Controller Unit

IoT Internet of Things

OTA Over-The-Air

EU European Union

CRA Cyber Resilience Act

TPM Trusted Platform Module

CRC Cyclic Redundancy Check

KB Kilobyte

SRAM Static Random Access Memory

USART Universal Synchronous and Asynchronous Receiver-


Transmitter

UART Universal Asynchronous Receiver-Transmitter

MPU Memory Protection Unit

ASCII American Standard Code for Information Interchange

XOR Exclusive OR

NMEA National Marine Electronics Association


8

1 Introduction

This thesis details the design and implementation of an embedded devices


firmware update scheme. The thesis describes the development process of a
bootloader and over-the-air update functionality. Basic understanding of
software development on the part of the reader is assumed.

This thesis was written based on an employer project. The request was to
implement a bootloader and update functionality to enable firmware updates
over Bluetooth in the field.

The theoretical segment of this thesis describes the fundamental concepts


surrounding bootloaders, firmware, and embedded device cybersecurity. It aims
to provide the reader with a basic understanding of the development process of
a bootloader. In addition, it describes cybersecurity legislation related to
embedded devices and the process of developing a device compliant with
regulations set by the European Union.

The practical segment describes the development process of a custom


bootloader implementation designed and developed by the author with the help
of colleagues. The result is a device capable of over-the-air updates using a
Bluetooth XMODEM implementation and custom NMEA command protocol. In
addition, the device is capable of verifying the integrity and validity of a provided
firmware file. Thorough testing is performed to verify the functionality of the
device.

In summary, this thesis aims to provide a comprehensive understanding of


bootloader functionality and device updatability.
9

2 Bootloader

2.1 Bootloader fundamentals

A bootloader, also known as a bootstrap loader or boot manager, is a program


most commonly stored in the first block of a bootable medium and is used to
verify and launch an application or operating system. In embedded devices,
bootloaders are for the most part used to update the firmware of the device.
‘Bootloaders offer a productive way to update the firmware on the device
without the need to remove it from the system or connect it to a programming
tool’ (Gwata, N. 2023).

As embedded devices have evolved, the need for updatability and upgradability
has risen. As a result, bootloaders have become more common even in the
simplest of devices.

2.2 Types of bootloaders

There are two main types of bootloaders in an embedded system, primary and
secondary bootloaders.

2.2.1 Primary bootloaders

Primary bootloaders, also known as first-stage bootloaders, are responsible for


initializing the hardware, configuring the system, and loading the operating
system into memory. They are often stored in ROM or some other fixed location
within the device’s memory. Primary bootloaders, like secondary bootloaders,
are designed to be as compact as possible to minimize memory usage on the
device.
10

2.2.2 Secondary bootloaders

Secondary bootloaders or application bootloaders, expand on the functionality


of a primary bootloader. They are responsible for more advanced tasks such as
loading the main application code and performing additional system
configurations that may require the system to be initialized.

Second-stage bootloaders are often more flexible and customizable compared


to primary bootloaders.

2.3 Choosing the right bootloader implementation

Bootloader implementations vary based on the intended purpose of the device.


The main considerations when selecting a bootloader implementation are
functional requirements, security considerations and resource constraints.

Taking into consideration factors such as the need for updatability,


cybersecurity and MCU selection, the appropriate choice can be made. For
example, devices such as smartphones or other IoT devices that handle
sensitive data or operate in potentially hostile environments require secure
bootloader implementations to safeguard from unauthorized firmware
modifications and ensure that only authorized updates from trusted sources are
installed. In such cases a secure bootloader solution using techniques such as
digital signatures and secure boot protocols are essential to verify the integrity
of firmware images before execution.

Devices with simpler functionality such as embedded sensors or basic control


systems, may choose a simpler approach. A simpler implementation allows for
efficient operation while minimizing memory usage.

Additionally, firmware update requirements and the frequency of updates are


critical factors in bootloader selection. For devices that require frequent
firmware updates and offer support for OTA updates, a bootloader solution with
11

remote update mechanisms and secure update protocols helps streamline the
update process while ensuring security and integrity of the device’s firmware.

Choosing the appropriate bootloader implementation involves a careful


evaluation of project requirements and resource constraints. By considering
these factors, developers are able to select a suitable bootloader ensuring the
device meets the intended requirements and standards.
12

3 Firmware

Firmware or as it is sometimes called “software for hardware”, is installed onto a


hardware device in manufacturing and “provides a low-level control for a device”
(Lutkevich, 2022). In essence, firmware is used to run programs on a hardware
device.

Generally, firmware can be divided into three categories, low-level firmware


often programmed to ROM, high-level firmware allowing for updatability with
greater complexity compared to low-level firmware, and subsystem firmware
often found in embedded devices, comparable to high-level firmware.

Firmware is often considered to be software, however there are certain


distinctions separating the two technologies. The main distinction to be made is
that firmware allows hardware to function and communicate with other software
on the device, while software communicates with hardware via the firmware.

Picture 1. System architecture for embedded devices.

3.1 The importance of firmware updates

During the development of embedded devices, many different versions of the


device’s firmware are developed and tested. These versions expand upon the
functionality of the last versions and in some cases completely rework how the
firmware functions. When the device is tested and approved, the product’s first
version is launched, and the device is sold to customers. This version is often
13

the first time the device has been used for its intended purpose on a large
scale. Due to this, problems often arise as oversights in testing lead to
unforeseen issues in the firmware.

For this purpose, devices developed with the intention of an extended lifetime
are made updatable. These updates allow the developer to fix bugs and
improve the functionality after the launch of the product. In addition, firmware
updates often provide upgrades and critical fixes that improve the products
quality and user friendliness.

3.2 Firmware update methods and requirements

Embedded devices can be updated using multiple different methods, each with
their own advantages and disadvantages. The main methods employed by
embedded devices however are external storage devices and OTA updates. In
rare cases the update process requires the device to be returned to the
manufacturer to be updated by an engineer.

For devices that operate in places where a dedicated team of engineers can
access and manipulate the device, the updates are often provided by the
developers and installed by an engineer using external storage devices or
dedicated update devices. Examples of such devices are industrial automation
devices, where the update process requires an engineer to be present.

On the other hand, devices operating in remote locations that do not require or
have access to a dedicated team of engineers, the developer may opt to use
OTA updates to provide firmware packages to the user. These devices often
require a mobile application, or a similar method provided by the manufacturer.
OTA updates allow more flexibility to the device’s operator, as they can decide
when and where to update the device. While these types of devices provide an
easy and efficient way to update firmware, they carry more risk as providing a
faulty firmware package may cause a device to become inoperable. In such
cases, the device must be sent back to the manufacturer, where it will be reset
and reprogrammed.
14

4 Cybersecurity

Cybersecurity vulnerabilities are common in embedded devices. ‘This is often


because developers lack awareness and understanding of embedded security
and are unsure of which protocols to follow’ (Wilcocks, 2023). This indicates a
lack of information about encryption algorithms and ways of dealing with
personal data. The lack of developer knowledge places embedded devices at
risk of attacks that could be prevented using proper development practices and
regular testing.

4.1 EU Cyber Resilience Act

The EU CRA introduces new requirements and cybersecurity principles for


products with digital elements. Manufacturers are responsible for the
assessment and verification process of these devices, with the exception of
devices determined to belong to a higher category, where third-party
assessment is required.

Devices produced for and sold in EU member states are required to follow
regulations set in the CRA, which details device types and software
requirements as well as risk assessment guidelines that determine the device
type.

At its core, CRA addresses two major problems according to the Council of the
European Union:

1. The low level of cybersecurity of products with digital elements, reflected


by widespread vulnerabilities and the insufficient and inconsistent
provision of security updates to address them.
2. The insufficient understanding and access to information by users,
preventing them from choosing products with adequate cybersecurity
properties or using them in a secure manner.
15

The CRA focuses heavily on cybersecurity of embedded devices and the


requirements related to the manufacture and retail process of these devices.

4.2 Bootloader security measures

Implementing cybersecurity protocols to prevent malicious or unauthorized


modification of firmware is a critical part of the development process of a
bootloader. In addition to firmware verification methods, the bootloader itself
must be secured to prevent modification.

For embedded devices, the ability for the system to autonomously verify
firmware to detect unauthorized modifications is critical in ensuring device
security and integrity. This can be achieved through hardware-based security
methods such as TPMs to establish a hardware-based root of trust for the
device or storing the bootloader in ROM. ‘A programmable hardware-based root
of trust can be continuously updated to contend with an ever-increasing range
of threats’ (Rambus Press, 2023). Another option is software-based security,
where measures such as digital signatures using cryptographic keys, and
runtime integrity checks can be used.

Bootloaders developed in accordance with the CRA are required to include


firmware update capabilities. In cases where the device is determined to belong
to a higher classification the bootloader itself must be updatable through
security updates. The update process must include authentication methods and
include the capability to monitor and record an event log of the update process.

4.3 OTA update security

OTA updatable firmware presents further difficulties concerning the


cybersecurity of a device. Depending on the update method and protocol,
signals can be intercepted, allowing malicious actors to gain access to the
firmware or allow them to inject a modified version of the firmware to the device.
In such cases, communication between the device providing the update and the
16

device receiving the update should be encrypted in accordance with the EU


Cyber Resilience Act Annex 1 section 2(f), ‘products with digital elements are
required to protect the integrity of stored, transmitted or otherwise processed
data, personal or other, commands, programs and configuration against any
manipulation or modification not authorized by the user, and report on
corruptions’ (European Parliament, 2022).
17

5 Project requirements

The subject device of this paper will be implemented with a simple bootloader
and update function. In this project, there is no need for a secure bootloader or
advanced cybersecurity functions. The requirements are for the device to be
updated remotely via an OTA update provided by a mobile application over a
Bluetooth connection using an XMODEM implementation.

Furthermore, the device must be able to communicate with the mobile


application to provide information about the status of the update, such as
possible error codes.

5.1 Bootloader requirements

The bootloader itself will reside in the first 8KB of memory, leaving enough free
memory for future modifications and upgrades. The bootloader must initialize a
Bluetooth module and establish a connection to a mobile device. It must also be
able to verify the integrity of a firmware file and revert to an earlier version in
case of faulty firmware.

5.2 Cybersecurity requirements

Considering the devices relation to the regulations set by the CRA and the
project requirements, the device does not directly relate to a classification
defined in the regulations. Therefore, the implementation will ignore more
advanced features such as bootloader updatability. The regulations set in the
CRA will be followed where applicable, however no verification of accordance
will be performed.

Firmware verification methods such as file headers with digital signatures will be
used, and the device calculates a CRC for the provided file to verify its integrity.
18

6 ATSAMC21N18A

The ATSAMC21N18A, more commonly known as C21 is a 5V Cortex M0+


series MCU, it will be the main MCU used for this project. Notable features
include a maximum clock speed of 48MHz when using an external oscillator,
32KB of SRAM, USART, I2C up to 3.4MHz and a Watchdog timer.

For the bootloader implementation, the most important feature is the Watchdog
timer. The timer allows for boot and update process interruptions in case of
faults.
19

Picture 2. ATSAMC21N18A block diagram.


20

7 ATSAMC21 Bootloader Implementation

In accordance with the project requirements the bootloader reads a portion of


the external flash memory to determine if a firmware update is available. If a
firmware update is not available, the bootloader attempts to run the existing
firmware. In case the firmware is corrupted or does not exist, the bootloader
configures the Bluetooth module, and a firmware update can be initiated. In
case a firmware update is available, the bootloader verifies the header portion
of the existing firmware matches the expected outcome and initiates the
copying process to write the new firmware to the device.

7.1 Memory management

As defined in the project requirements for the bootloader, the bootloader resides
in the first 8 KB of memory on the device. Since the bootloader is compact and
does not require the entire 8KB of memory, it leaves a significant portion of the
reserved space free for future expansion.

Code 1. Snippet from the bootloader linker file.

/* Memory Spaces Definitions */


MEMORY
{
rom (rx) : ORIGIN = 0x00000000, LENGTH = 0x00004000
ram (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

In addition to the space reserved for the bootloader, the device utilizes a shared
memory section in external flash memory. The shared memory section includes
utilities such as a reset counter and flag to force the device into bootloader
mode in case too many reboots without successful boot are detected.
21

Code 2. Shared memory section memory definition.

#define APP_ADDRESS 0x00004000

uint32_t shared_data_address = APP_ADDRESS - sizeof(struct


shared_data_stuct);

The bootloader also contains the address where the firmware’s reset vector is
located. The reset vector is a 4-byte address located at the beginning of the
firmware memory section and points to the initial address of the code to be
executed after a reset.

Picture 3. Memory architecture.

The bootloader executes code to jump to the memory address of the reset
vector.
22

Code 3. Snippet from the go_to_app function.

void go_to_app(void) {
uint32_t jump_address;
start_app jump_to_app;

if(((*(uint32_t*)APP_ADDRESS) & 0x2FFE0000) == 0x20000000){


jump_address = *(uint32_t*)(APP_ADDRESS + 4);
jump_to_app = (start_app) jump_address;

__set_MSP(*(uint32_t*)APP_ADDRESS);
jump_to_app();
}
else {
led_set_pin_level(LED_IO_ORANGE, 0);
}
}

7.2 Firmware verification

All valid firmware packages for the device include a header portion in the first
512-byte section of the file. The bootloader verifies the existence of the header
portion and performs checks to determine the validity of the header. It checks
the firmware version and a hard-coded identification number. After the checks
have been performed, the bootloader executes a function to jump to the
application address.
23

Code 4. Firmware header verification.

struct __attribute__((packed)) header_t {


uint8_t header_id[2]; // Always {0x12, 0x69}
uint8_t header_version;

uint8_t version_str[5];
uint8_t hw_version_compatability[6];
uint32_t bin_length;
uint32_t crc32;
uint32_t app_offset; // From binary header = header size
};

-------------------------------------SNIP---------------------------

// Read header from external flash


struct header_t file_header;
memset(&file_header, 0, sizeof(struct header_t));
read_file_header(&file_header);

-------------------------------------SNIP-------------------------

uint8_t check_for_update = memcmp(&header_update, &file_header,


sizeof(struct header_t));

// Checks if file header and command header is not the same or header
has 0xFF in it or there is no header
if ((check_for_update || file_header.header_version == 0xFF ||
(file_header.header_id[0] != xxx && file_header.header_id[1] != xxx))
&& !get_force_bootloader_flag()) {
go_to_app();
}

-------------------------------------SNIP---------------------------
24

7.3 Preparing for updatability

According to the project requirements, the device must be capable of updating


itself when receiving a valid firmware package from a mobile device. The
updatability of the device is taken into consideration when designing the
bootloader. This includes the previously mentioned verification methods, as well
as a Bluetooth module configuration inside the bootloader code. When
functioning correctly, the device will be updated from inside the application and
not the bootloader. However, as a failsafe to prevent the device from losing
access to valid firmware, the Bluetooth module is configured inside the
bootloader.

Code 5. Bluetooth module configuration.

usart_async_register_callback(&USART_BT, USART_ASYNC_RXC_CB, NULL);


usart_async_register_callback(&USART_BT, USART_ASYNC_RXC_CB,
xmodem_rx_callback);
usart_async_get_io_descriptor(&USART_BT, &bt_uart_io);
usart_async_enable(&USART_BT);

In addition to the Bluetooth configuration, a shared memory section is created.


The shared memory section includes a reboot counter and flag to force the
device to remain in bootloader in case of a failed boot sequence.
25

Code 6. Shared data structure and use cases.

struct shared_data_struct {
uint8_t reboot_counter;
uint8_t copy_counter;
uint8_t force_bootloader_flag;
};

-------------------------------------SNIP---------------------------

int main(void) {
atmel_start_init();
increment_reboot_counter();

get_shared_data(&shared_data);
if(shared_data.reboot_counter >= 3) {
if(shared_data.copy_counter == 0) {

-------------------------------------SNIP---------------------------
}
else {
// Force bootloader
set_force_bootloader();

reset_reboot_counter();
reset_copy_counter();

-------------------------------------SNIP---------------------------

7.4 Securing the device

The firmware verification process prevents unauthorized or invalid firmware


packages from being uploaded to the device. This prevents malicious code
injection and prevents users from accidentally uploading an older version of the
firmware.
26

To secure the bootloader and prevent tampering, the bootloader memory region
will be defined as a write protected region using the MPU included in the
ATSAMC21N18A. As of the current version this feature is not enabled.
27

8 Over-The-Air Update Implementation

The OTA protocol according to project requirements uses an XMODEM file


transfer protocol over Bluetooth. When a verified firmware file is received, the
device writes it to external flash memory. After a complete firmware image is
received, the device reboots, and the bootloader confirms the existence of a
valid firmware image. If digital signatures match the firmware is copied from
external flash to the device.

The update functionality is intended to be used when the device has booted into
the application. However, as a failsafe feature, the update can also be
performed while in the bootloader.

In case the firmware does not function as expected, the Watchdog timer is
initialized and will revert to the bootloader.

8.1 Bluetooth

The communication between the user and the device will be handled over
Bluetooth, including the file upload and custom communication protocol related
to the update functionality.

Bluetooth communication was chosen over other methods as the device will be
used in areas where a wireless network may not be available. In addition, the
application firmware requirements define the need for Bluetooth communication
with a mobile device for normal operation. Therefore, the basis for Bluetooth
communication already exists and does not require significant changes to be
able to transfer files over Bluetooth.
28

8.2 XMODEM protocol

XMODEM is a file transfer protocol developed by Ward Christensen in 1977. It


is a simple to implement file transfer protocol that sends data packets
associated with checksums and waits for acknowledgement from the recipient.

A typical XMODEM packet consists of 133 bytes, of which one byte is reserved
for a defined protocol symbol such as SOH or EOT to determine the type of
packet being sent. Bytes two and three are reserved for packet numbers, with
byte three being a negated version of byte twos packet number. Bytes 4-131
include the data contained in the packet, while the remaining two bytes contain
the calculated checksum of the packet.

Table 1. XMODEM packet

Byte 1 Byte 2 Byte 3 Bytes 4-131 Bytes 132-133


SOH Packet number Negated packet Packet data 16-bit CRC
number

Valid XMODEM packets include data packets starting with a start of header
symbol, end of transmission symbol, or cancel symbol.

Table 2. XMODEM symbol definitions

Symbol Description Value


SOH Start of header 0x01
EOT End of transmission 0x04
ACK Acknowledge 0x06
NAK Not acknowledge 0x15
CAN Cancel (Force receiver to send C’s) 0x17
C ASCII “C” 0x43
29

The protocol works by receiver initiation when device A sends the ASCII
character ‘C’. Device B constructs a packet and passes it to device A. Device A
handles the received packet appropriately and in response, sends an ACK
message back to device B signaling a completed transfer. The packet exchange
continues until device B sends an EOT packet to device A, to which device A
responds once more with an ACK message, finalizing the file transfer.

Picture 4. XMODEM protocol data flow.

The chosen implementation includes a CRC calculation to generate the


checksum of packets and perform the final calculation to verify the integrity of
the entire firmware packet once uploaded. The CRC is calculated when the
entire firmware packet has been received and copied to external flash memory.

The CRC is calculated by using a predetermined lookup table containing


polynomial values and iterating over each byte of the input data. The algorithm
30

combines the current CRC value with the data using a bitwise XOR operation. It
then looks up the result in the polynomial table to determine the next CRC value
and applies a bitwise shift right to process each byte, continuing until all bytes in
the buffer have been processed.

Code 7. CRC calculation function

// CRC calculation for copying packets to external flash

uint32_t calc_crc32(const uint8_t *data, uint32_t length, uint32_t


crc) {
/* For standard CRC32B results, set crc = 0xffffffffu */
/* loop over the buffer data */
for (int i = 0; i < length; i++) {
crc = crc_32_tab[(crc ^ data[i]) & 0xFFu] ^ (crc >> 8);
}
return crc;
}

After a CRC calculation is completed, the calculated value is compared to the


CRC included in the header of the received firmware. If the CRCs match, the
device will be rebooted, and the update process will continue inside the
bootloader.

Code 8. CRC match functionality

// Send ACK
reply = ACK;
io_write(bt_uart_io, (uint8_t *)&reply, 1);
delay_ms(1);
// Cleanup
external_flash_buffer_write_ptr = external_flash_buffer;
external_flash_buffer_overflow_counter = 0;
xmodem_status = X_DONE;
// Reset mcu so bootloader can update app
_reset_mcu();
31

8.3 Custom communication protocol

The firmware upload requires the device to switch to a separate firmware


upload mode, where all other communication between the devices is disabled.
This is achieved by creating a custom communication protocol using NMEA
messages the system uses to communicate with the mobile device in normal
operation.

In normal operation the mobile device receives GPS data from the system in
NMEA format. The mobile device is able to send custom commands to the
system, which responds accordingly. When the mobile device sends the
command “$FWUPLOAD”, the system stops forwarding GPS data to the mobile
device and initiates the file transfer by repeatedly sending the ASCII character
‘C’ until it receives a valid XMODEM packet or a cancel command.

Code 9. NMEA command loop file upload mode and command

static const uint8_t NMEA_FILE_UPLOAD_MODE[10] = "$FWUPLOAD";

else if (!memcmp(nmea_command, NMEA_FILE_UPLOAD_MODE,


sizeof(NMEA_FILE_UPLOAD_MODE)-1)) {
// PUT INTO FILE UPLOAD MODE
xmodem_init();

change_module_mode_variable(FILE_UPLOAD);

delay_ms(1);
}
32

9 Testing

This chapter describes the testing process, starting with the bootloader, and
finally testing the update capability.

9.1 Test setup

Preparations for testing include flashing the device with a functioning bootloader
and building the necessary binaries, one valid version and one invalid modified
version. The invalid binary has been modified by assigning random values to 6
bytes of the binary file, picture 5.

Picture 5. Modified binary file inspected in a code editor.

The hardware used for testing is a custom PCB with an ATSAMC21N18A and a
BM70 Bluetooth module.

The software used in testing includes Microchip studio version 7.0.2594 and a
Serial Bluetooth Terminal application version 1.47.

To evaluate the implementation, requirements for test outcomes must be


determined. These requirements are listed in table 3. All components of the
system must be tested individually. Test cases where GPS data transmission is
verified, a Serial Bluetooth Terminal mobile application is used to receive the
data transmitted by the device.
33

Table 3. Testing requirements.

Test case Description Expected Outcome


1.1 Attempt to boot into valid The device boots and begins
verified firmware flashed to the transmitting GPS data over
device Bluetooth
1.2 Attempt to boot into invalid The device remains in
firmware flashed to the device bootloader and an orange
indicator LED is lit
2.1 Attempt to update valid verified The device boots and begins
firmware from application transmitting GPS data over
Bluetooth, compared firmware
versions differ
2.2 Attempt to update invalid The device remains in
firmware from application bootloader and an orange
indicator LED is lit
3.1 Attempt to update valid verified The device boots and begins
firmware from bootloader transmitting GPS data over
Bluetooth
3.2 Attempt to update invalid The device remains in
verified firmware from bootloader and an orange
bootloader indicator LED is lit

9.2 Bootloader tests

This test is performed by programming the device with a functioning bootloader


implementation. Verifying the bootloader functionality is done by observing
indicator LEDs. Next, a firmware file is programmed to the device. The firmware
is placed to the appropriate memory address ensuring the bootloader is not
overwritten.
34

Picture 6. Bootloader indicator LED.

9.2.1 Test case 1.1

As seen from picture 6, when the bootloader is programmed to the device, an


orange indicator LED is lit, indicating the lack of existing firmware. When
programming the firmware file to the device, the device reboots and a green
indicator LED is lit, indicating a successful boot.
35

Picture 7. Firmware indicator LED.

A successful boot is then verified by connecting to the device using the mobile
application, where multiple NMEA messages containing GPS data are received.
36

Picture 8. NMEA messages with GPS data.


37

9.2.2 Test case 1.2

Replicating test case 1.1, the device lights an orange indicator LED to indicate
the lack of existing firmware. When programming the invalid firmware file to the
device, the device reboots and reverts to the bootloader indicated again by the
orange LED. The lack of firmware can be verified by connecting to the device
using the mobile application. As seen in picture 8, there are no NMEA
messages containing GPS data, and the device sends the ASCII character ‘C’
indicating the device is in bootloader mode and is attempting to initiate an
update.

Picture 9. Connection established in bootloader.

9.3 OTA update tests

Test cases 2.1 and 2.2 are performed using the same valid firmware file used in
test case 1.1. A “$FWUPLOAD” command is sent to the device from the mobile
application and the ASCII character ‘C’ is sent to the application by the device.
Once a valid binary file is selected, the mobile application begins sending
XMODEM packets to the device. Once finished, the device reboots and begins
transmitting GPS data. The firmware version can be verified by sending a
“$GETVER” command, prompting the device to send the version number to the
mobile application over Bluetooth.
38

Picture 10. Initial version number.

Test cases 3.1 and 3.2 are performed by programming the bootloader to the
device with no valid firmware file. Bluetooth connection is then established, and
firmware binary file is transmitted to the device. Successful updates are verified
by a green indicator LED and GPS data transmission. Failed updates are
indicated by an orange indicator LED, indicating the device remains in
bootloader.

9.3.1 Test case 2.1

The device is programmed with a functioning bootloader and a valid firmware


file and Bluetooth connection is established. The version number is verified by
sending the “$GETVER” command. The file upload is then initiated by sending
the “$FWUPLOAD” command to the device. A valid binary is then selected to
be transmitted to the device, picture 11.
39

Picture 11. Valid binary file upload.

Once the upload is complete and Bluetooth connection is re-established, the


“$GETVER” command is sent to the device and the version number is
compared to the initial version number in picture 9.
40

Picture 12. Updated version number.

9.3.2 Test case 2.2

The same steps as in test case 2.1 are repeated, but a modified binary file is
sent to the device. Upon reboot of the device, the “$GETVER” command is sent
to the device and the version number returned to the application has not
changed.

9.3.3 Test case 3.1

The device is programmed with a functioning bootloader without a firmware file


and Bluetooth connection is established. The device begins sending the ASCII
character ‘C’ automatically when connection is established (Picture 9). A valid
firmware file is selected for transmission and the application begins sending
packets to the device. When the upload process is complete, the device reboots
and a green indicator LED begins blinking, indicating the existence of valid
firmware.

9.3.4 Test case 3.2

Test case 3.1 is repeated, but a modified binary file is uploaded to the device.
After the upload is complete, the device reboots and an orange indicator LED
can be observed, indicating the device remained in the bootloader and the
update was not successful.
41

10 Conclusion

In conclusion, this thesis includes a comprehensive description of the


development process of a bootloader with over-the-air update functionality.
Through a thorough examination of theoretical concepts and practical
implementation, several key findings and contributions have emerged.

Firstly, this thesis included a comprehensive theoretical segment, describing the


fundamental aspects of embedded development. By providing the reader with
the necessary understanding of bootloader functionality and firmware
management, this thesis provided a foundation for the subsequent practical
segment.

In the practical segment, a complete bootloader implementation was developed


based on requirements set in the first phase of development. The system was
designed to meet current industry standards and thoroughly tested to ensure
functionality.

Future research will focus on the regulations set by the European Union’s Cyber
Resilience Act. Continuous development is required to provide security updates
and patches mandated by the legislation.

In closing, this thesis underscores the importance of over-the-air update


capabilities in embedded devices and ensuring the security and functionality of
embedded systems. Combining a theoretical basis with a practical solution, this
research contributes to the advancement of embedded systems.
42

References

1 Amos, Z. (2024). How secure are Over-the-Air updates for IoT devices?
Available at: https://www.iotinsider.com/iot-insights/how-secure-are-over-
the-air-updates-for-iot-devices/ [Accessed 2 April 2024]

2 Baldassari, F. (2019). From Zero to main(): How to Write a Bootlaoder


from Scratch. Available at: https://interrupt.memfault.com/blog/how-to-
write-a-bootloader-from-scratch [Accessed 29 March 2024]

3 Catsoulis, J. (2005). Designing Embedded Hardware, 2nd ed. [e-book]


O’Reilly Media, Inc. Available at:
https://www.oreilly.com/library/view/designing-embedded-
hardware/0596007558/ch01.html [Accessed 3 April 2024]

4 Cyber Resilience Act (2022). European Parliament [Official reference:


COM(2022)0454] Available at:
https://www.europarl.europa.eu/doceo/document/TA-9-2024-
0130_EN.html

5 Gwata, N. (2023). Bootloaders in embedded systems. Available at:


https://medium.com/@ngonidzashegwt/bootloaders-in-embedded-
systems-9f9513132177 [Accessed 26 March 2024]

6 Lutkevich, B. (2022). Firmware. Available at:


https://www.techtarget.com/whatis/definition/firmware [Accessed 29
March 2024]

7 Rambus Press (2023). Hardware root of trust: Everything you need to


know. Available at: https://www.rambus.com/blogs/hardware-root-of-
trust/#whatis [Accessed 10 April 2024]

8 Ruddock, D. (2024). OTA updates: What are Over-The-Air Updates?


Available at: https://www.esper.io/blog/the-evolution-of-android-ota-
updates [Accessed 2 April 2024]

9 Vilcocq, G. (2023). What does the EU Cyber Resilience Act (CRA) mean
for connected device manufacturers? Available at:
https://eshard.com/posts/CRA-connected-device-manufacturers
[Accessed 25 March 2024]
43

10 Wilcocks, R. (2023) The importance of cybersecurity in embedded


software design. Available at: https://www.redlinegroup.com/insight-
details/the-importance-of-cybersecurity-in-embedded-software-design/
[Accessed 29 March 2024]

You might also like