Atmel 42141 SAM AT02333 Safe and Secure Bootloader Implementation For SAM3 4 Application Note
Atmel 42141 SAM AT02333 Safe and Secure Bootloader Implementation For SAM3 4 Application Note
Atmel 42141 SAM AT02333 Safe and Secure Bootloader Implementation For SAM3 4 Application Note
Description
This document introduces in-field firmware upgrading and describes various aspects
of the implementation of a safe & secure bootloader. It discusses several design
considerations in developing this kind of software, which readers can refer to when
consulting this document.
Correct bootloader implementation poses several challenges, such as correctly
remapping the chip memory with the new-loaded program. Those issues will be
described and solved in the following sections, with focus on Atmel ARM Cortex-M
based microcontroller. Simple bootloader software is also provided along with this
application note as example.
42141ASAM06/2013
Table of Contents
1. Introduction ........................................................................................ 4
2. In-field Upgrading ............................................................................... 5
2.1
2.2
2.3
2.4
2.5
2.6
The Bootloader.................................................................................................. 5
Issues 6
2.2.1
Safety 7
2.2.2
Security ............................................................................................... 7
Possible Solutions ............................................................................................. 8
Safety Solutions ................................................................................................ 8
2.4.1
Communication Protocol Stack ........................................................... 8
2.4.1.1
Error Detection/Correction ................................................ 9
2.4.1.2
Block Numbering............................................................... 9
2.4.1.3
Packet Acknowledgement ............................................... 10
2.4.1.4
Existing Protocols ........................................................... 10
2.4.2
Memory Partitioning .......................................................................... 11
2.4.2.1
Memory & Memory Banking ............................................ 11
2.4.2.2
Single Banked Partitioning .............................................. 12
2.4.2.3
Dual Banked Partitioning ................................................ 12
2.4.3
Summary .......................................................................................... 13
Security Solutions ........................................................................................... 13
2.5.1
Integrity ............................................................................................. 13
2.5.1.1
Hash Function ................................................................. 14
2.5.1.2
Digital Signature.............................................................. 14
2.5.1.3
Message Authentication Codes ...................................... 15
2.5.2
Authentication ................................................................................... 15
2.5.2.1
Digital Signature.............................................................. 15
2.5.2.2
Message Authentication Code ........................................ 16
2.5.3
Privacy 16
2.5.4
Target Device Authentication ............................................................ 16
2.5.5
Summary .......................................................................................... 17
Design Considerations .................................................................................... 18
2.6.1
Transmission Media .......................................................................... 18
2.6.2
Cryptographic Algorithms.................................................................. 18
2.6.2.1
Symmetric Ciphers .......................................................... 19
2.6.2.2
Hash Functions ............................................................... 20
2.6.2.3
Message Authentication Codes ...................................... 21
2.6.2.4
Digital Signature Algorithms ............................................ 21
2.6.2.5
Pseudorandom Number Generators (PRNG) ................. 22
2.6.2.6
Available Libraries........................................................... 22
2.6.2.7
Performances on an SAM3X8 Chip ................................ 22
2.6.3
Error Detection Codes ...................................................................... 23
2.6.4
Firmware File Format ........................................................................ 23
2.6.5
Target Chips ..................................................................................... 23
3.2
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
3.2.5
3.2.4.1
Single Banked Code Linking ........................................... 34
3.2.4.2
Dual Banked Code Linking.............................................. 35
Boot Region Locking ......................................................................... 35
4.2
4.3
4.4
Bootloader....................................................................................................... 36
4.1.1
Features............................................................................................ 36
4.1.2
Configurability ................................................................................... 36
4.1.3
Code Location................................................................................... 37
4.1.3.1
Main Bootloader Algorithm .............................................. 37
4.1.3.2
Vector Table Relocating & Application Execute .............. 37
4.1.3.3
Flash Programming......................................................... 37
4.1.3.4
Linking Code ................................................................... 37
Dual Banked Bootloader ................................................................................. 37
Firmware Updater ........................................................................................... 38
Firmware Packager ......................................................................................... 38
5. Related Documents.......................................................................... 40
6. Revision History ............................................................................... 40
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
1.
Introduction
Microcontrollers are used increasingly in a variety of electronic products. The devices are becoming more flexible,
thanks to the reprogrammable memory (typically flash) often used to store the firmware of the product. This means that
a device which has been sold can still be upgraded in-field, e.g., to correct bugs or add new functionalities.
Figure 1-1 illustrates this concept.
Figure 1-1. In-field Upgrading
1.
2.
3.
4.
5.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
2.
In-field Upgrading
2.1
The Bootloader
Many modern microcontrollers use Flash memory to store their application code. The main advantage of Flash is that
the memory can be modified by the software itself. This is the key to in-field programming: a small piece of code is
added to the main application to provide the ability to download updates, replacing the old firmware of the device. This
code is often called a bootloader, as its role is to load a new program at boot.
A bootloader always resides in memory to make it possible for the device to be upgraded at anytime. Therefore, it must
be as small as possible. Since one does not want to waste a large amount of memory on a piece of code which does
not add any direct functionality for the user.
Figure 2-1. Memory Organization with a Bootloader
To download a new firmware onto the device, there must be a way to tell the bootloader to prepare for the transfer.
There are two types of trigger conditions: hardware and software. A hardware condition might be a pressed button
during a reset, whereas a software condition could be the lack of a valid application in the system. When the system
starts, the bootloader checks the predefined conditions. If one of them is true, it will try to connect to a host and wait for
a new firmware. This host can theoretically be any device; however, a standard PC with the appropriate software is
most often used. The transmission of the firmware can be done via any media supported by the target, i.e., RS232,
USB, CAN and so forth.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
1.
2.
3.
4.
5.
6.
7.
Once the transfer is finished, the bootloader replaces the old firmware with the new version. This new application is then
loaded.
There are several other ways of carrying out in-field programming of a product. For example, the main application might
do the upgrade itself: for a device using external memory storage, the new firmware could be written on it as a file. The
main advantage of using a bootloader is that you do not have to design your application in a different way. Therefore,
while modifying your application to include an upgrade mechanism can be tedious, a bootloader can always be used
without additional programming (providing the bootloader is readily available, of course).
2.2
Issues
There are several issues associated with using such a simple bootloader. The issues might happen at two points of the
upgrading flow: either during the transport of the firmware from the manufacturer to the customer or during the
download on the target device. Figure 2-3 is a diagram showing several issues which will be discussed in the following
sections.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
2.2.1
Safety
It is critical for most devices to have a working firmware embedded in them at all times, since they probably cannot
function properly or even cannot function at all without it. However, the use of a bootloader can result in the problematic
situation, where the new firmware has not been installed properly, compromising the behavior of the system. The
following problems (in Figure 2-3) might happen:
Issue #2, Transmission failure: As a result, the application area would then be corrupted and unusable. This issue
arises:
If the device suddenly loses power during the update process.
If the connection to the host is lost during the transmission.
2.2.2
Issue #3, Information loss: some data might be lost while transmitting the firmware, which would completely corrupt
the code after the missing part.
Security
Securing a system means enforcing several features: privacy, integrity and authenticity.
Privacy means that a piece of data cannot be read by unauthorized users or devices. A major concern of firmware
developers is to ensure that the application they have designed cannot be leaked by competitors. They thus want their
code to be private, the target devices being the only authorized users.
Microcontrollers typically provide a mechanism making it impossible for malicious users to read the program code
written in the device. However, for in-field firmware upgrading, the manufacturer has to give the new code image to
customers so they can patch their devices themselves.
This means that a skilled person could potentially decompile it to retrieve the original code (issue #7 in Figure 2-3).
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
Authenticity makes it possible to verify that the firmware is from the manufacturer itself, not anybody else. Indeed,
another problem of reprogrammability is that a device could be given a firmware which is not designed by the original
manufacturer, but by a third-party (issue #5 in Figure 2-3). This may be especially problematic if that firmware is
developed for malicious use, i.e., to bypass security protections, to illegally use critical functions of the device, and so
forth.
A genuine firmware could also be used on a different device other than the one that it is intended for (issue #4 in Figure
2-3). This could be an unauthorized hardware copy of the product, or a device designed for hacking purpose. This is
again an authenticity concern, this time regarding the target device.
Finally, integrity is required to detect a modification of the data. For example, an authorized firmware may be slightly
modified (issue #6 in Figure 2-3). It would appear as genuine, but attacks that are similar to those described in the
previous paragraph could be achieved in this way.
Possible security issues list:
Without any kind of security feature, a firmware will be subject to all attacks regarding privacy, integrity and authenticity.
Therefore, some techniques are needed to enforce those three aspects.
2.3
Possible Solutions
The following two sections offer a practical solution to the issues identified in previous sections. However, most of the
techniques to circumvent those problems present a trade-off between the level of security and safety and the size and
speed of the system. As such, the safest and most secure solution is also probably the biggest and slowest one. This
means that one must first carefully analyze what is needed in terms of security and safety in a system, to implement
only the required functionalities.
Several techniques for enforcing safety and security are presented in the following sections. Please note that no
software solution can give perfect security. Indeed, there are many hardware-based attacks (like micro-probing, power
analysis, timing analysis, etc.) which enable a malicious user to break software protections. These attacks are best
solved by using a dedicated secure chip. However, using soft protection is not inappropriate, as they make it more
costly (both in time and money) to attack your system.
2.4
Safety Solutions
The following techniques are ways to prevent safety-related errors from happening. However, it is interesting to note
that, since the bootloader should never be compromised (as it cannot be updated), the user can simply try upgrading
his device again if there is a failure. Naturally, this may not always be a desirable alternative, which is why the following
solutions are presented.
2.4.1
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
Transport reliability is usually obtained by using several techniques: error detection/correction code, block numbering
and packet acknowledgement. They are presented below. Existing protocols for the media available on Atmel ARM
Thumb-2 based AT91SAM microcontrollers are then described in Section 2.4.1.4.
However, there are limitations to error detection/correction codes. Depending on how they are mathematically
constructed, they will have a maximum number of detectable/correctable errors. As such, a thorough analysis of the
system must be carried out prior to selecting the method to use, to avoid choosing an inappropriate code.
Finally, error correction is not really necessary in this particular case. It is most suited when it is unpractical to resend
the erroneous data, which is not a concern here. Since error correction codes typically incur a bigger overhead than
error detection ones, they should be implemented with good reasons.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
No other data is sent by the emitter while it is waiting for an acknowledgement. Therefore, packets cannot be received
out of order since only one is sent at a time.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
10
TCP/IP is the most widely used protocol stack on top of Ethernet. The Transport Control Protocol (TCP) implements
reliability by using a packet sequence number as well as a checksum (a simple error detection code). It also uses a
variant of packet acknowledgment. But since several packets can be sent at once, they can arrive out of order (thus
block numbering is still needed).
Figure 2-7. TCP Frame Structure
The USB protocol uses a Cyclic Redundancy Check (CRC) for error detection. There is no sequence number on the
packets, but a receiver acknowledges each block of data. This is the same for the CAN bus.
Figure 2-8. CAN Frame Structure
Lastly, there are several file-oriented communication protocols for the RS-232 interface. One of them is X-MODEM,
which was developed in the 1970s. It features a simple single byte checksum, block numbering and packet
acknowledgment.
Figure 2-9. X-Modem Frame Structure
2.4.2
Memory Partitioning
The main idea of memory partitioning is to have, at all times, a copy of a working firmware somewhere in memory.
Achieving this means that even if anything goes wrong during an update, it is still possible to revert back to that
firmware.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
11
The following sections will describe solutions based on single banked or dual banked memory.
Region B is used as a buffer. The new firmware is downloaded to this region and verified. If firmware downloaded on
this region is verified OK, it is programmed to region A, so that downloading errors will not affect the working firmware
on region A. This method ensures that there is always a working firmware on a device after an upgrade, whether it was
successful or not.
For more details on single banked partitioning consideration and implementation, please refer to Section 3.1.3.1.
Firmware region in bank 1 is used as upgrade buffer zone, which accepts the newly downloaded firmware (v2).
After downloading firmware (v2) to bank 1 and verifying it OK, the boot bank is changed to bank 1, that is, bank 1
is mapped to boot area for the next system boot.
Now, memory bank 1 is boot bank and firmware (v2) on it will run on start-up.
When system restarts, it runs firmware (v2) on bank1. This time firmware region on bank 0 is used as upgrade
buffer zone, to receive new firmware (the old firmware is not deleted, and the new downloaded firmware will then
overwrite it in this zone).
The advantage of this method is that there are maximum two workable firmware versions in memory, and there is no
need to perform additional programming (simply changing the boot mapping instead of copying firmware from region to
region), but in each bank there must be a bootloader so that the available application memory is a bit smaller than
single banked solution.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
12
For more details on dual banked partitioning consideration and implementation, please refer to Section 3.1.3.2.
Figure 2-11. Dual Banked Memory Organization with Partitioning
2.4.3
Summary
Error detection and correction (Section 2.4.1.1)
Pros
Detects transmission errors
Cons
Code must be chosen wisely
Slightly increased code size
Slightly reduced speed (during upgrade only)
Pros
Solves all safety-related issues
Cons
The required memory size is doubled
Slightly increased code size
Reduced execution speed (during upgrade only, for dual banked memory, it is not a problem since code need
not be copied)
2.5
Security Solutions
Several security-related techniques to solve the afore-mentioned issues (see Section 2.2.2) are presented in this
section. See Section 2.6.2 for in-depth information about security considerations.
2.5.1
Integrity
Verifying integrity means checking the following:
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
13
Accidental modification is a safety problem. It is typically solved by using error detection codes (see Section 2.4.1.1).
There are several ways to verify that a firmware has not been voluntarily modified by a mischievous user. They are
presented in the following paragraphs, and make it possible to solve issue #6 described in Figure 2-3.
Since the output length is fixed (regardless of the input), it is not possible to generate a different digest for every piece
of data imaginable. However, hash functions ensure that it is almost impossible to find two different messages which will
have the same digest. This achieves almost the same result as uniqueness, at least in practice.
The downside of simply hashing the firmware is that anybody can do it. This means that an attacker could modify the
file and re-compute the hash. The bootloader would thus not be able to tell that an alteration was made.
However, a hash function alone can still be used to verify the firmware integrity at runtime, to avoid running a damaged
application.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
14
Since only the private key can encrypt data, nobody except the manufacturer can produce the signature. Thus, a
malicious user would not be able to perform the attack described in the previous section. But anybody can verify the
signature using the public key of the manufacturer.
Private Key encryption relies on only one secret key, which is shared between the manufacturer and the devices. This
has several implications, compared to a digital signature:
If the private key inside the device gets exposed, then the security of the system is completely compromised.
The first point is not a concern in practice; as a device will not use its private key to produce MACs, only to verify them.
The second implication means that if an attacker manages to retrieve the key from the bootloader (which is supposed to
be locked using security bits), then he will be able to modify a firmware and still have it accepted as unmodified by a
target. Depending on your requirements, this may or may not be an issue.
It should be noted that since private-key cryptography is much faster than public-key, a MAC will be computed and
verified faster than a digital signature. But since only one MAC/signature is required for the firmware, it would probably
not make a big difference in practice.
2.5.2
Authentication
Authentication is about verifying the identity of the sender and the receiver of a message. In the case of the bootloader,
this means verifying that the firmware has been issued by the manufacturer, and that the target is a genuine one. It
solves issue #4 and #5 described in Figure 2-3.
It happens that the methods which provide authentication also provide integrity: digital signatures and MACs. Since
they are described from the integrity point of view (see Section 2.5.1), this section only discusses their authentication
properties.
This section only discusses firmware authentication; authentication of the target device will be treated further.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
15
However, since the signature is freely decipherable by anyone possessing the public key (which is not supposed to be
secret), the computed hash of the firmware can be obtained by anyone. This means that an attacker could find a
collision in the hash function which is used, e.g., two different texts giving the same hash. The signature would also
authenticate this data as produced by the original sender.
This may not be a problem in practice however, as a collision is extremely hard to find and it is unlikely that it would
result in a valid program. It would only enable a malicious user to create a fake firmware which would render the device
unusable.
2.5.3
Privacy
Data privacy is enforced using encryption: the data is processed using a cryptographic algorithm along with an
encryption key, generating a cipher text which is different from the (plain) original one. Without the required decryption
key, the data will look like complete nonsense, preventing anyone unauthorized from reading it. This takes care of issue
#7, as described in Figure 2-3.
In practice, a private-key algorithm is used to generate the encrypted firmware. It is obvious that a public-key system
cannot be used, as the firmware would then be decipherable by anyone. The encryption and decryption keys are thus
identical and shared between the bootloader and the manufacturer.
Note that code encryption does not solve every security issue all by itself. For example, the firmware might still be
modified, even if it is quite difficult. An attacker could manage to pinpoint the location in the code of an important
variable and tweak it until he gets the desired result.
Code encryption also combines itself well with a message authentication code. Since they both use a symmetric
encryption algorithm, they can use the same one to save code size. There are also secure modes to combine both a
block cipher and a MAC while using the same key (see Section 2.6.2.1).
2.5.4
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
16
In this particular case, encrypting the firmware will also authenticate the device. Indeed, it will need the private key to
decrypt the firmware. As only genuine device shave them embedded in their bootloader, an unauthorized target will not
be able to recover the original code and run the application.
This is especially applicable as target authentication cannot be achieved without encrypting the code anyway; otherwise,
it could be simply downloaded to the device.
An active authentication method would involve adding an authentication technique for the target. Since the device
identity would be verified during the upgrade process by the host, a message authentication code cannot be used.
Indeed, since it would require the host to have the private key, an attacker could easily retrieve it.
Adding such a mechanism would also incur a significant overhead, both in terms of bootloader size (for storing the
additional key and the digital signature encryption algorithm) and upgrade speed (because of the transactions needed
to identify the device). In addition, the host upgrading program could be modified to get rid of that additional mechanism
anyway.
2.5.5
Summary
Hash function (Section 2.5.1.1)
Pros
Detects accidental and voluntary changes
Can be used to check firmware integrity at runtime
Cons
Can be recomputed by a malicious user
Slightly increased code size
Slightly reduced execution speed
Pros
Detects third-party and modified firmware
If the key inside the bootloader is compromised, the system remains safe
Cons
Slower than a MAC
Requires a large key length
Increased code size
Reduced execution speed (during upgrade only)
Pros
Detects third-party and modified firmware
Faster than a digital signature
Cons
If the key inside the bootloader is compromised, the system is broken
Increased code size
Slightly reduced execution speed (during upgrade only)
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
17
Pros
Prevents reverse-engineering
Authenticates the target
Cons
If the key inside the bootloader is compromised, the system is broken
Increased code size
Reduced execution speed (during upgrade only)
2.6
Design Considerations
There are several choices and problems which arise when designing a bootloader such as the one described in this
application note. This section gives an overview of the major topics.
2.6.1
Transmission Media
SAM microcontrollers provide a wide variety of peripherals to communicate with an external host, such as:
USB
CAN
RS232
Ethernet
Choices should be made on the implementation priority (and relevance) of each method. Given the simplest one to
implement is probably RS232; it could be used to get the system ready. Other interfaces could then be added in an
easier way.
It should be noted that there is a USB device class geared toward firmware upgrading. This class, referred to as Device
Firmware Upgrade (DFU), may be used to implement the bootloader functionality. However, please note that since it is
not supported by Microsoft Windows, it may not be easy to do so.
Finally, media such as CAN or Ethernet have the potential to allow for batch programming, i.e., programming several
devices at once. The host could broadcast all the messages it sends, enabling every connected device to receive them
and upgrade their firmware.
2.6.2
Cryptographic Algorithms
The secure part of the bootloader relies on different types of cryptographic primitives (hash functions, MACs, digital
signature algorithms, block ciphers, etc.). But for every type of primitive, there are many different algorithms to choose
from.
This section tries to give a brief overview of the choices available for the following: symmetric block ciphers, hash
functions, message authentication codes, digital signature algorithms and pseudorandom number generators (PRNG).
While the latter has not been introduced before because it is not a security method itself, it is critical to the design of a
secure system.
For further recommendations, you may also look at those made by committees such as CRYP-TREC or NESSIE, which
carefully analyze existing and new algorithms.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
18
Key length in bits: The larger it is, the more difficult it is to perform a brute force attack. A reasonable length
seems to be128 bits at the moment, as it is the one key length selected for the Advanced Encryption Standard
(AES) cipher.
Block length in bits: is needed to avoid a codebook attack. Most block ciphers will use at least 64 bits, with
modern ciphers using at least 128 bits.
Size & speed: depend on the techniques they use. Since embedded system has limits in resources, more suitable
encryption should be chosen.
Table 2-1 gives an overview of several popular ciphers. Note that if the target platform has hardware acceleration
available, the resulting code size will be much smaller and the system will be much faster.
Table 2-1. Symmetric Encryption Algorithms
Algorithm
Key Length
Block Length
Security
AES
128 bits
Secure
Blowfish
32 to 448 bits
64 bits
Secure
DES
56 bits
64 bits
Broken
Slow
Triple-DES
168 bits
64 bits
Secure
Very Slow
RC6
128 bits
Secure
Serpent
128 bits
Secure
Twofish
128 bits
Secure
Note that block ciphers can also be used (with modifications) as hash functions and message authentication codes.
This can be useful to save code size when several primitives are needed (by reusing the same algorithm more than
once).
Figure 2-16. Block Cipher as Hash Function
Electronic codebook (ECB): The basic mode of operation, each block of plain text is encrypted using the key and
the chosen algorithm, resulting in a block of cipher text. However, this mode is very insecure, as it does not hide
patterns.
Cipher block chaining (CBC, CFB, OFB, CTR ...): Encryption is not only done with the current block of plain text,
but also with the last encrypted block. Make everything interdependent.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
19
Authenticated encryptions (EAX, CCM, OCB ...): are used to provide privacy, integrity and authentication at once.
They are basically the combination of a MAC algorithm and a symmetric block cipher. They are useful when the
three components are needed, as using a mode such as EAX will be faster and has less overhead than applying a
MAC and a symmetric cipher separately.
The first block is encrypted using a random Initialization Vector (IV). While this vector can be transmitted in clear text,
the same vector shall never be used more than once with the same key. It is likely that a manufacturer will produce
more than one firmware upgrade for a product in its lifetime. This means that the IV cannot be stored in the chip in the
same way the key is. Therefore, it will have to be transmitted by the host.
Output length: needs to be large enough to make it almost impossible to find collisions.
Security: is much more critical than the length of its output. Indeed, MD5 (which only has a 128-bit output) would
still be secure if it did not have serious design flaws in it.
Size & speed: the stronger algorithms are often the slowest ones (which are not true for block ciphers), so there
will be a security/speed trade-off
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
20
Block Length
Security
MD5
128 bits
Broken
Fast
RIPEMD-160
160 bits
Secure
Slow
SHA-1
160 bits
Broken
Slow
SHA-256
256 bits
Secure
Slow
WHIRLPOOL
512 bits
Secure
Very Slow
Tiger
192 bits
Secure
Fast
HAVAL
Broken
Moderately fast
Note that UMAC might not be usable in practice, as it requires many different hash algorithms. The incurred size
overhead would thus be far too important for a bootloader
The Digital Signature Standard (DSS): specifically designed for digital signatures. It is based on a public-key
algorithm known as the ElGamal scheme. The key length required to have a strong enough security is at least
1024 bits.
A system based on the Rivest-Shamir-Adleman (RSA) public-key algorithm: the most popular method, used with a
padding scheme (to append data to the message to encrypt). There are three commonly used schemes:
Full-domain hashing: involves using a hash function that has an output size equal to the RSA key length.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
21
Optimal Asymmetric Encryption Padding (OEAP): adding a quantity of random data to convert RSA into a
probabilistic encryption scheme.
Probabilistic Signature Scheme (PSS): adding a quantity of random data to convert RSA into a probabilistic
encryption scheme.
This means that in practice, there is neither real speed nor size constraint on the PRNG algorithm. Only its security
matters.
PRNGs work by using a starting seed to generate successive random values. Initializing that seed is a core problem,
which is referred to as gathering entropy. Consider the case where the current date & time are used to seed the PRNG.
An attacker could obtain that information and thus reconstruct every random number generated using that seed: private
keys, nonce, etc.
Operating systems usually provide a mechanism to provide entropy, e.g., /dev/random on UNIX systems. They use, for
example, the response time of devices such as hard disks to gather the required entropy.
Most PRNGs then rely on another cryptographic primitive (such as a block cipher or a hash function) to generate
pseudo-random outputs. Here is a list of several secure PRNGs:
Yarrow
Fortuna
libTomCrypt (http://libtom.org)
Crypto++ (http://www.cryptopp.com)
Libmcrypt (http://mcrypt.hellug.gr/#_libmcrypt)
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
22
The AES cipher has been tested using different implementations. The first one uses the libTomCrypt library, freely
available from http://libtom.org. The second one is based on a standard implementation provided by Paulo Baretto and
Vincent Rijmen.
Table 2-3. Performance of AES (128-bit key and 128-bit blocks)
Encryption
Mode
ECB
CBC
CTR
Implementation
Source
Size Overhead
(bytes)
libTomCrypt
8576
680.0
Reference
implement
2632
libTomCrypt
8660
734.7
Reference
implement
2708
libTomCrypt
8820
752.7
Reference
implement
2096
2.6.3
Encryption
Mode
Implementation
Source
Size Overhead
(bytes)
ECB
libTomCrypt
4742
2006.9
CBC
libTomCrypt
4862
2065.3
CTR
libTomCrypt
5022
2085.3
2.6.4
2.6.5
Target Chips
Some of the chips in the SAM family have different IPs, such as the Flash controller. This means that they are
programmed differently; therefore, several versions of the code must be written to accommodate all the microcontrollers.
Thus, the bootloader will be developed for a particular chip first, but in a modular way. This means that functions which
are chip-dependent are wrapped in an abstraction layer. Porting the software to another chip is easy: only the
necessary low-level functions have to be coded, without touching the bootloader core.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
23
The following implementation example will use SAM3X8 as candidate, since it has no cryptographic accelerators, a
software solution with libTomCrypt or Reference design is used to encrypt.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
24
3.
Bootloader Implementation
This section details several issues that one may encounter while implementing a safe & secure bootloader, along with
some insight on how to approach them. Example code from a working implementation is given in the following sections
to illustrate the solutions.
3.1
Bootloader Flow
3.1.1
Boot Sequence
The startup sequence of the bootloader is as follows:
Initialization
The following is a simple bootloader example that supports only Firmware upgrade:
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
25
3.1.2
Upgrade Sequence
The basic upgrade flow starts with the host sending the firmware to the target, which then programs it in memory. Once
the programming is done, the new application is loaded.
While, in theory, the downloading and programming steps are different, this is not the case in practice. Indeed, SAM
microcontrollers usually have much more Flash memory than RAM. Thus, they cannot store the whole firmware in RAM
before writing it permanently to the Flash.
This means that the code must be written to the memory while it is received, but not after. Since a Flash write operation
takes approximately 6 ms (with a page erase), a communication protocol is needed to halt the transfer when the
memory is being written and resume it afterwards.
Note also that the Flash memory is split up into fixed-size blocks called pages. A memory write operation can upgrade
one page (or less) at a time; thus it seems logical to send packets containing one full page.
Finally, there are several optional post-processing features to take into account. If code encryption is activated, then
each page must be decrypted before being written. If a digital signature or a message authentication code is present, it
must be verified once the download is completed.
Figure 3-2. Basic Firmware Upgrading Process Example
3.1.3
Memory Partitioning
As described in Section 2.4.2, using memory partitioning makes it possible to have at least one working version of the
firmware in the device at anytime. This is useful to avoid firmware corruption if a problem occurs during an upgrade,
such as a power loss or a connection loss.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
26
The following sections will describe the implements for single and dual banked memory.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
27
Choice #1, manage the whole memory as a single space, and accesses to different memory banks are translated to
continuous memory address. In this way, the whole memory is looked as a single banked memory to partition. For
more details, please refer to Section 3.1.3.1 and Section 3.2.1.
Choice #2, as described in Section 2.4.2.3, manages the Flash by banks, and each bank has its bootloader and
firmware region. Here the two banks have different physical addresses, but they are mapped to the same boot
program address on boot time, so binary should use a link file that links to boot program address space. When the
boot memory layout is changed, different firmware version is chosen.
The first choice can apply if the two memory banks should be in a continuous address (such as SAM3X, SAM3SD8,
SAM4SD16 and SAM4SD32, the Flash address of two banks are continuous), or the banks are able to be mapped to a
continuous address (such as SAM3U, the Flash address of two banks are not continuous, but the bank in Flash area is
mapped to reserved space to access, see Figure 3-5).
The link file should use this continuous address to generate the application firmware. For more information about Flash
banks, please refer to datasheet for SAM3/4 chips.
Figure 3-5. Map Two Memory Banks to a Continuous Address
Then the second choice: since Flash memory has two banks, the two firmware regions A & B are placed at the same
offset of these banks; they are remarked as boot region and buffer region. Both of them are located right above the
bootloader, on its location bank and contain the firmware code. The boot region A is loaded by bootloader on that bank
when system starts up. The buffer region, B, is a buffer on upgrading: the code is downloaded to that region and verified.
Finally, the roles of these regions can switch, by selecting different boot bank. That is, when booting from bank 0, the
firmware region on it acts as boot region (A) and the firmware region on bank 1 acts as buffer region (B); when booting
from bank 1, the firmware region on bank 0 acts as buffer region (B) and the firmware region on bank 1 acts as boot
region (A).
In this case, when performing upgrade, the firmware is always loaded to buffer region (B) and after downloaded data in
buffer region (B) is verified OK, the boot bank is switched and new firmware will be loaded when system restarts. As a
result, the old firmware is still kept in buffer region but not used, so the two regions both contain workable firmware and
the latest downloaded one is to be loaded.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
28
Note that in SAM3SD8, SAM4SD16 and SAM4SD32, there is a slight difference when changing boot banks. It swaps
the physical banks! E.g., before swap, the old firmware is in address area 0 and the new firmware is in address area 1,
while after swap, the new firmware will be in address area 0 and the old firmware in address area 1. This feature keeps
the boot firmware in the same physical address, whether Flash banks have been swapped or not.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
29
Figure 3-8. Dual Banked Memory Content during Upgrade Process for SAM3SD8, SAM4SD16, SAM4SD32
3.2
The Enhanced Embedded Flash Controller (EEFC): Used by most of SAM3 and SAM4 chips
The FLASHCALW: Used by SAM4L
Here we take EEFC as example to show how internal flash of SAM3/4 chips are programmed. For operations that using
FLASHCALW, please refer to SAM4L documents (can be found here).
3.2.1
Flash Programming
Usually the Flash of the SAM3 chip is organized in one or two planes (banks) that are made of pages of 256 bytes.
SAM4 chip has the same organization while the page size is 512 bytes. The EEFC is used to manage the Flash access.
The Fast Flash Programming Interface (FFPI) is used to program the device. Depending on the device, there might be
one or two Flash Controllers, and the physical address of two Flashes (banks) can be continuous or not. Table 3-1
gathers the rough information. For more detailed information, please refer to chips data sheet.
Note:
The Flash memory of SAM microcontrollers cannot be read and written at the same time for one single bank case.
For SAM3 the programming command can perform erase and program automatically.
For SAM4, before writing the Flash memory, an erase operation must be performed,
If flash erase block size are bigger than write block size (this is a usual situation for flash devices, e.g., in SAM4
writing bases on one page but minimum erasing size is eight pages), the partition must be aligned with erase block
size so that the unexpected area will not be erased.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
30
Flash
Organization
Number of Flash
Controllers
Flash (bank)
Address is continuous
SAM3U2/1
Single Bank
SAM3U4
Dual Bank
No
SAM3S4/2/1
Single Bank
SAM3N Series
Single Bank
SAM3X(A) Series
Dual Bank
Yes
SAM3S8
Single Bank
SAM3SD8
Dual Bank
Yes
SAM4S16/8
Single Bank
SAM4SA16
Single Bank
SAM4SD32/16
Dual Bank
Yes
SAM4E Series
Single Bank
SAM4L4/2
Single Bank
Flash
Controller
EEFC
FLASHCALW
Put function codes in bank 0 to perform writing in bank 1 and vice versa. When writing to a Flash bank, judge which
function to use by the writing address.
Use RAM functions, the same as single banked Flash programming in Section 3.2.1.1.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
31
3.2.2
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
32
);
3.2.3
GPNVM[2]
Boot From
Clear
Clear/Set
ROM
Set
Clear
Flash Bank0
Set
Set
Flash Bank1
Figure 3-9. Memory Organization Before and After Boot Code Selection
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
33
Note that for SAM3SD8 and SAM4SD32/16, setting GPNVM bit 2 will swap the two Flash banks, so the memory
mapping change is as follows:
Figure 3-10. Memory Organization Before and After Boot Code Selection SAM3SD8, SAM4SD32/16
3.2.4
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
34
...
Code segments are then defined between __region_ROM_start__ and __region_ROM_end__.
Note that when single banked Flash is selected to boot, the whole Flash is mapped to address 0x0, so its also possible
to arrange bootloader and application based on this mirrored address. It also works for a dual banked Flash with
continuous bank addresses. But when a dual banked Flash without continuous bank addresses is used (as choice #1
described in Section 3.1.3.2), the linking map must be based on the virtual continuous Flash start address (see Figure
3-5) but not on this boot mirror, since the boot mirror might only include the single bank that is used for boot.
3.2.5
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
35
4.
Example Implementation
This section describes a sample implementation of the safe & secure bootloader presented in this document. It is made
up of three programs: the bootloader itself and two program tools. One program tool is used to transfer the firmware
between a PC and the bootloader. The other one is necessary to encrypt the firmware before sending it. The three
pieces of software are detailed below.
4.1
Bootloader
Its general implementation for device with single banked Flash or dual banked Flash.
4.1.1
Features
The following features have been implemented:
Memory partitioning
The software has been developed for IAR Embedded Workbench 5.50.
4.1.2
Configurability
The bootloader has been designed in a way which makes it easy to add new components to it, like a new media or a
new communication protocol.
The /inc/config.h file controls the configuration of both mandatory components (such as which media to use) and
optional ones (security, safety). A particular component can be selected by defining the following constant:
#define USE_COMPONENTNAME
The COMPONENTNAME is the name of the components (e.g., USART0, UART, and BUTTONS for SAM3/4). Note that
only one component can be selected for each mandatory category, which are:
Communication protocol
XON/XOFF (USE_XON_XOFF)
Media layer
USART (USE_USART0)
Debug
DBGU (USE_DBGU)
UART (USE_UART)
Memory type
Flash (USE_Flash)
Trigger condition
Dummy (USE_DUMMY)
Switches (USE_SWITCHES)
Button (USE_BUTTONS)
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
36
Timing measurement
Timer0 (USE_TIMER0)
Both the debug and timing categories are not truly mandatory. If no debug driver is defined, for example, then the
bootloader does not output debug messages. The timing module can be used to perform benchmarks on several
features.
The following optional parameters are available:
4.1.3
Code Location
4.2
bootloader_sam3x8_flash_0.icf: startup and linker file for the bootloader without boot code remap (based on Flash
beginning address)
bootloader_sam3x8_flash_remap.icf: startup and linker file for the bootloader with boot code remap (based on
address 0x0, the mapped address of Flash)
firmware_sam3x8_flash_0.icf: startup and linker file for a firmware without remapped boot code (based on Flash
beginning address)
firmware_sam3x8_flash_remap.icf: startup and linker file for a firmware with remapped boot code (based on
address 0x0, the mapped address of Flash)
It allows customers to implement the FW upgrade in application without bootloader: let application run in one bank
and buffer FW upgrade data in another bank.
It adds the advantage to let the same code work on both banks without modifying the binary mapping, since both
banks can be mapped to boot program area.
It allows 2 firmware versions in 2 banks and selection of boot firmware version.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
37
This simple example adds implementation of dual banked bootloader as described in Section 3.1.3.2. Its added as an
alternative partitioning method. The following constant should be defined to enable it:
#define PARTITION_DUAL_BANK
When using this option, the two firmware region size (for region A & B, defined as REGION_SIZE) should also be
decreased, because the bootloader code is duplicated.
4.3
Firmware Updater
This program is used to transmit the firmware from the host PC to the bootloader. Since an RS232 (through a PC COM
port) link is implemented at the moment, a standard terminal application (like HyperTerminal) could be used to perform
the same operation. However, it will be necessary to develop a program if another media or communication protocol is
implemented and not supported by standard programs.
Figure 4-1. Firmware Updater Main Window
The main window of the application enables the user to perform the following operations:
Launch an upgrade
Note that you must select the same parameters in the Firmware Updater as the ones which have been selected for the
bootloader. For example, if the bootloader is configured to connect using a USART configured at 115200 bps, no parity
and 1 stop bit, select those parameters in the Firmware Updater.
4.4
Firmware Packager
The Firmware Packager is used to prepare the firmware prior to sending it to customers, including encrypting it,
generating a signature or MAC tag, etc.
Note that when the bootloader enables code encryption (USE_ENCRYPTION), the Firmware Packager must be used,
with the same encryption settings, to generate encrypted firmware for Firmware Updater to download.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
38
Note that you must select the same parameters in the Firmware Packager as the ones selected for the bootloader. For
example, if the bootloader is configured to accept a firmware encryption in AES-CBC with a particular key and IV, enter
the same parameters in the Firmware packager.
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
39
5.
Related Documents
[1] Atmel Corp., 2006, Safe and Secure Firmware Upgrade for AT91SAM Microcontrollers, literature no. 6253.
[2] Atmel Corp., 2006, Safe and Secure Bootloader Implementation, literature no. 6282.
6.
Revision History
Doc. Rev.
Date
Comments
42141A
06/2013
Initial revision
Atmel AT02333: Safe and Secure Bootloader Implementation for SAM3/4 [APPLICATION NOTE]
42141ASAM06/2013
40
Atmel Corporation
Business Campus
Parkring 4
1-6-4 Osaki
USA
GERMANY
JAPAN
HONG KONG
www.atmel.com