AT11787: Safe and Secure Firmware Upgrade via...
Transcript of AT11787: Safe and Secure Firmware Upgrade via...
Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
APPLICATION NOTE
AT11787: Safe and Secure Firmware Upgrade via Ethernet
Atmel 32-bit Microcontroller
Introduction
This application note introduces in-field firmware upgrading via Ethernet and
describes various aspects of the implementation of safety and security. This
document also gives a short description of LwIP stack and the cryptographic
algorithm AES-GCM. It will elaborate the software implementation and memory
footprint to help users to make their own application easily according to the real
requirement. The firmware source code and an Android™ application are
provided with this application note.
Figure 1. The Firmware Upgrading Demo Kits
Features
Atmel® SAM4S ARM® Cortext®-M4 MCU
Dual bank Flash firmware upgrade support
LwIP stack support
DHCP mode support
UDP server support
TCP server support
Authenticated encryption AES-GCM mode support
IEEE® 802.3 CRC-32 support
Communication protocol provides error detection, packet sequence, and
acknowledgement
Authentication before firmware update
High speed data transfer by DMA
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 2
2
Table of Contents
Introduction ....................................................................................................................... 1
Features ....................................................................................................................... 1
1 Kits Overview ................................................................................................................. 3
1.2 Ethernet1 Xplained Pro ......................................................................................................................... 3
2 Software Interfaces ....................................................................................................... 4
2.1 LwIP Stack ............................................................................................................................................ 4
2.1.1 LwIP Stack Overview ................................................................................................................ 4
2.1.2 Application Programming Interface ........................................................................................... 4
2.2 Crypto Algorithm.................................................................................................................................... 7
2.2.1 GCM Algorithm Overview ......................................................................................................... 7
2.2.2 Application Programming Interface ........................................................................................... 7
3 In-field Upgrading .......................................................................................................... 8
3.1 Safety ................................................................................................................................................ 8
3.2 Security ................................................................................................................................................ 8
4 Software Implementation .............................................................................................. 9
4.1 Protocol Design ..................................................................................................................................... 9
4.2 Firmware Design ................................................................................................................................. 10
4.2.1 Bring up the Ethernet Interface and Startup the LwIP Stack ................................................... 10
4.2.2 Firmware in-Field Updating ..................................................................................................... 11
4.3 Firmware Updater Application ............................................................................................................. 12
4.4 Quick-Start Setup ................................................................................................................................ 12
5 Footprint ..................................................................................................................... 16
6 Conclusion ................................................................................................................... 17
Appendix A Additional Information .............................................................................. 18
A.1 LwIP Configuration .............................................................................................................................. 18
7 Document Revision History ....................................................................................... 19
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
3
3
1 Kits Overview
The Atmel® SAM4S Xplained Pro evaluation kit is a hardware platform to evaluate the ATSAM4SD32C
microcontroller. Supported by the Atmel Studio integrated development platform, the kit provides easy access
to the features of the Atmel ATSAM4SD32C and explains how to integrate the device in a custom design. The
Xplained Pro MCU series evaluation kits include an on-board Embedded Debugger, and no external tools are
necessary to program or debug the ATSAM4SD32C. The Xplained Pro extension series evaluation kits offer
additional peripherals to extend features of the board and ease the development of custom designs. More
details about the SAM4S Xplained Pro evaluation kit are available here: http://www.atmel.com/tools/ATSAM4S-
XPRO.aspx?tab=overview.
Figure 1-1. SAM4S Xplained Pro Evaluation Kit
1.2 Ethernet1 Xplained Pro
Ethernet1 Xplained Pro is a basic extension board for the Xplained Pro platform. The Ethernet is controlled via
a SPI interface up to 40MHz for high throughput Ethernet applications. Ethernet1 Xplained Pro connects to any
Xplained Pro standard extension header on any Xplained Pro MCU board. More details about Ethernet1
Xplained Pro extension board are available here:
http://www.atmel.com/tools/ETHERNET1_XPRO.aspx?tab=overview.
Figure 1-2. Ethernet1 Xplained Pro Extension Board
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 4
4
2 Software Interfaces
2.1 LwIP Stack
2.1.1 LwIP Stack Overview
The Lightweight TCP/IP stack is designed for embedded systems. The focus of the LwIP TCP/IP
implementation is to reduce resource usage while still having a full scale TCP. LwIP is suitable for using in
embedded systems with tens of kilobytes of free RAM and around 40 kilobytes of code ROM.
LwIP features:
IP (Internet Protocol) including packet forwarding over multiple network interfaces
ICMP (Internet Control Message Protocol) for network maintenance and debugging
IGMP (Internet Group Management Protocol) for multicast traffic management
UDP (User Datagram Protocol) including experimental UDP-lite extensions
TCP (Transmission Control Protocol) with congestion control, RTT estimation, and fast recovery/fast
retransmit
DNS (Domain Name Server)
Specialized raw API for enhanced performance
Optional Berkeley-alike socket API
DHCP (Dynamic Host Configuration Protocol)
PPP (Point-to-Point Protocol)
PPPoE (Point to Point Protocol over Ethernet)
ARP (Address Resolution Protocol) for Ethernet
For more details about the LwIP, refer to LwIP Wiki: http://lwip.wikia.com/wiki/LwIP_Wiki or the Atmel
AT04055: Using the LwIP Network Stack application note.
2.1.2 Application Programming Interface
The main application programming interfaces (APIs) used for the Ethernet part are the LwIP RAW APIs. The
Raw API is a non-blocking, event-driven API designed to be used without an operating system that implements
zero-copy send and receive.
Table 2-1. TCP RAWW APIs User in This Application
API Function Description
Network interface
Management
netif_add Add a network interface to the list of LwIP netifs
TCP connection
setup
tcp_new Create a new connection PCB (Protocol Control Block). A PCB is a structure used
to store connection status.
tcp_bind Bind the pcb to a local IP address and port number
tcp_listen Command a pcb to start listening for incoming connections
tcp_accept Set the callback function to call when a new connection arrives on a listening con-
nection
tcp_connect Connect to a remote TCP host
Sending TCP data tcp_write Queue up data to be sent
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
5
5
tcp_sent Set the callback function that should be called when data has successfully been
sent and acknowledged by the remote host
Receiving TCP
data
tcp_recv Set the callback function that will be called when new data arrives
tcp_recved Informs LwIP core that the application has processed the data
Callback argument tcp_arg Specify the argument that should be passed callback functions
Closing and abort-
ing connections
tcp_close Close a TCP connection with a remote host
tcp_err Set the callback function to call when a connection is aborted because of an error
tcp_abort Abort a TCP connection
Network Interface Management
In LwIP device drivers for physical network hardware are represented by a network interface structure similar
to that in BSD. To create a new network interface, a new space should be allocated for the struct netif and call
netif_add():
struct netif *netif_add(struct netif *netif, struct ip_addr *ipaddr,
struct ip_addr *netmask, struct ip_addr *gw, void *state,
err_t (* init)(struct netif *netif),
err_t (* input)(struct pbuf *p, struct netif *netif))
In this application, DHCP mode is used and the IP address, netmask and default gateway don’t need to be
specified when calling netif_add function. These parameters will be set automatically when DHCP client gets a
leased address from the DHCP server successfully.
The init parameter specifies a driver-initialization function that should be called once the netif structure has
been prepared by netif_add.
The final parameter input is the function that a driver will call when it has received a new packet. TCP
connection setup functions.
TCP Connection Setup
struct tcp_pcb * tcp_new(void)
Creates a new connection control block (PCB). The connection is initially in the "closed" state. If memory
is not available for creating the new PCB, NULL is returned.
err_t tcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
Binds the PCB to a local IP address and port number. The IP address can be specified as
IP_ADDR_ANY in order to bind the connection to all local IP addresses. If the IP address is not given
(i.e., ipaddr == NULL), the IP address of the outgoing network interface is used instead. If the port is
specified as zero, the function selects an available port. The connection must be in the "closed" state.
If another connection is bound to the same port, the function will return ERR_USE, otherwise ERR_OK is
returned.
struct tcp_pcb * tcp_listen (struct tcp_pcb *pcb)
The "pcb" parameter specifies a connection, which must be in the "closed" state and must have been
bound to a local port with the tcp_bind() function. This functions sets up the local port to listen for
incoming connections.
After calling tcp_listen(), tcp_accept() must be called. Until doing so, incoming connections for
this port will be aborted.
tcp_listen() may return NULL if no memory was available for the listening connection.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 6
6
void tcp_accept(struct tcp_pcb *pcb, err_t (* accept)(void *arg, struct
tcp_pcb *newpcb, err_t err))
Commands a PCB to start listening for incoming connections. tcp_listen() must have been
previously called. When a new connection arrives on the local port, the specified function will be called
with the PCB for the new connection.
err_t tcp_connect(struct tcp_pcb * pcb, struct ip_addr * ipaddr, u16_t port,
err_t (* connected)(void * arg, struct tcp_pcb * tpcb, err_t err));
Sets up the PCB to connect to the remote host and sends the initial SYN segment which opens the
connection. If the connection has not already been bound to a local port, a local port is assigned to it.
The tcp_connect() function returns immediately; it does not wait for the connection to be properly
setup. Instead, it will call the function specified as the fourth argument (the "connected" argument)
when the connection is established. If the connection could not be properly established, either because
the other host refused the connection or because the other host didn't answer, the error handling
function will be called with the "err" argument set accordingly.
The tcp_connect() function can return ERR_MEM if no memory is available for enqueueing the SYN
segment. If the SYN indeed was enqueued successfully, the tcp_connect() function returns
ERR_OK.
Sending TCP Data
err_t tcp_write(struct tcp_pcb *pcb, const void *data, u16_t len, u8_t
apiflags)
Enqueues the data pointed to by the argument dataptr. The length of the data is passed as the len
parameter.
The apiflags argument can have either of the following bits:
– TCP_WRITE_FLAG_COPY indicates that LwIP should allocate new memory and copy the data into
it. If not specified, no new memory should be allocated and the data should only be referenced by
pointer.
– TCP_WRITE_FLAG_MORE indicates that the push flag should not be set in the TCP segment.
The tcp_write() function will fail and return ERR_MEM if the length of the data exceeds the current
send buffer size or if the length of the queue of outgoing segment is larger than the upper limit defined in
lwipopts.h (TCP_SND_QUEUELEN). If the function returns ERR_MEM, the application should wait until
some of the currently enqueued data has been successfully received by the other host and try again.
tcp_sent(struct tcp_pcb *pcb, tcp_sent_fn sent)
Used to specify the function that should be called when TCP data has been successfully delivered to the
remote host.
Receiving TCP Data
void tcp_recv(struct tcp_pcb *pcb, err_t (* recv)(void *arg, struct tcp_pcb
*tpcb, struct pbuf *p, err_t err))
TCP data reception is callback based; an application-specified callback function is called when new data
arrives.
Sets the callback function that will be called when new data arrives. If there are no errors and the
callback function returns ERR_OK, then it is responsible for freeing the pbuf. Otherwise, it must not free
the pbuf so that LwIP core code can store it. If the remote host closes the connection, the callback
function will be called with a NULL pbuf to indicate that fact.
Close Connection
tcp_close(struct tcp_pcb *pcb)
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
7
7
Closes the connection. The function may return ERR_MEM if no memory was available for closing the
connection. If the close succeeds, the function returns ERR_OK.
2.2 Crypto Algorithm
The secure part of the in-field firmware upgrading 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. In this provided application following algorithm and libtomcrypt crypto
stack is used.
2.2.1 GCM Algorithm Overview
Galois/Counter Mode (GCM) is a mode of operation for symmetric key cryptographic block ciphers that has
been widely adopted because of its efficiency and performance. It can be implemented in hardware to achieve
high speeds with low cost and low latency. Software implementations can also achieve excellent performance
by using table-driven field operations. GCM is defined for block ciphers with a block size of 128 bits and it is an
authenticated encryption algorithm designed to provide both data authenticity (integrity) and confidentiality.
2.2.2 Application Programming Interface
In this demo, the libtomcrypt crypto stack is used. LibTomCrypt is a portable ISO C cryptographic library meant
to be a tool set for cryptographers who are designing cryptosystems. It supports symmetric ciphers, one-way
hashes, pseudo-random number generators, public key cryptography (via PKCS #1 RSA, DH or ECCDH), and
a plethora of support routines. More details about libtomcrypt stack can be found here: http://www.libtom.net/.
Register Cipher
int register_cipher(const struct _cipher_descriptor *cipher)
Which accepts a pointer to a descriptor and returns the index into the global descriptor table. If an error occurs
such as there is no more room (it can have 32 ciphers at most) it will return -1. If you try to add the same cipher
more than once it will just return the index of the first copy.
Encrypt/Decrypt Message Packet
int gcm_memory(
int cipher,
const unsigned char *key,
unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
This will initialize the GCM state with the given key, IV, and adata value and then proceed to encrypt or
decrypt the message text and store the final message authentication tag to the tag.
The message data (pt or ct) where pt is the plaintext and ct is the ciphertext. The length of both is equal and
stored in ptlen. Depending on the mode, pt is the input and ct is the output (or vice versa).
When direction equals GCM_ ENCRYPT, the plaintext is read, encrypted and stored in the ciphertext buffer.
When direction equals GCM_DECRYPT, the opposite occurs.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 8
8
3 In-field Upgrading
Many 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, and replace the old firmware
of the device.
However, there are several issues associated with in-field firmware upgrading, such as safety and security.
The issues might happen at two points of the upgrading flow: either during the transport of the firmware from
the host to the device or during the download on the target device.
3.1 Safety
It is critical for most devices to have a working firmware embedded in them at all time, since they probably
cannot function properly or even cannot function at all without it. However, the in-field firmware upgrading can
result in the problematic situation, where the new firmware may not be installed properly, compromising the
behavior of the system.
The following problems might happen:
Transmission error:
– Part of the code is corrupted
Transmission failure:
– The application area would then be corrupted and unusable. This issue usually arises while the
device suddenly loses power during the update process or the connection to the host is lost during
the transmission.
Data loss:
– Some data might be lost while transmitting the firmware, which could completely corrupt the code
after the missing part
Programming error:
– The programming error may occur during the code programming which may corrupt the code
Wrong firmware:
– The wrong firmware may be used by the user carelessly and cause the devices can’t run at all
3.2 Security
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 or host has to transfer
the new code image to the devices through various communication protocols, such as Ethernet, CAN, UART,
SPI, and so on. The unauthorized users can intercept the code image easily and patch their devices
themselves. A skilled person could potentially decompile it to retrieve the original code.
In addition, the devices need to know 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-part. 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 on.
Finally, an authorized firmware may be slightly modified during the transport of the firmware or malicious users
may do a replay attack to the devices which may cause the devices behave improperly or even not work.
Possible security issues list:
Use of a firmware on an unauthorized device
Use of an unauthorized firmware
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
9
9
Firmware modification or replay attack
Firmware reverse-engineering
Therefore, some techniques are needed to enforce the in-field firmware upgrading safety and security. In the
following section, the above safe and secure issues will be addressed and the solution will be elaborated in the
software implementation.
4 Software Implementation
4.1 Protocol Design
Authentication Frame
Header
8
Type
2
TAG
16
Tail
1
IV
16
Authentication frame must be sent firstly when starting the firmware update process. The authentication frame
can be used by the device to verify the identity of the remote sender and the random IV value can be used in
follow-up data packet encryption and decryption for this upgrading session. The device will re-compute the
authentication message code with the IV value and the same secret key stored on the device and then
compares the calculated value with the TAG value sent from the sender. If the two values match then the
sender is verified, otherwise the authentication process fails and the upgrading process will terminate
immediately. The type value indicates the frame type.
Data Frame
Header Length Encrypted Data CRCSequence
8 2 2 Up to 1024 4
Tail
1
Type
2
Data frames come after the authentication frame if the authentication passes. The data frame contains the
actual encrypted new firmware data. The encrypted data length must be 1024 bytes and only the data length in
the last data frame can be less than 1024 bytes, but it should be a multiple of 16 bytes. There is a sequence
value in the data frame and this value should be increased in sequence. Any data frame that contains an
invalid or same sequence number will cause the upgrading process to be terminated. This can prevent a
malicious user from doing a replay attack to the device. The CRC value can be used to verify the data frame
integrity. Any data modified or corrupted during the packet transfer can be detected.
Command Frame
Header
8
Type
2
Command
4
Tail
1
Command frame can be used to execute some commands, such as getting the current code version, getting
the CRC value of the new firmware or switching to new firmware.
The getting CRC value command can check whether there is any data modified or corrupt during data
communication or downloading and thus ensure the entire firmware data integrity.
ACK Frame
Header
8
Type
2
ACK
4
Tail
1
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 1
0
10
There is an ACK frame to respond to the each frame from the sender to make sure the upgrading process
correct and reliable.
4.2 Firmware Design
This application runs on SAM4S Xplained Pro board which embeds a dual bank flash microcontroller
ATSAM4SD32C. Thanks to the dual bank Flash. The application doesn’t need a bootloader to do the firmware
update. The firmware upgrading code can be added into the application and the application can update itself.
Dual bank Flash enables Flash writing to another bank while code is running on one bank. Firmware design is
divided into two parts:
Bring up the Ethernet interface and startup the LwIP stack
Firmware in-field updating
4.2.1 Bring up the Ethernet Interface and Startup the LwIP Stack
The function init_ethernet() will bring up the Ethernet interface, such as set parameters for the Ethernet
PHY, initialize MAC, LwIP stack, and so on.
The LwIP stack uses the ethernet_task() function to poll the incoming Ethernet frames. This function
should be called periodically and the interval should be as short as possible. A callback function
server_recv() will be called when there is a upgrading request from the sender. The implementation is
available on src/network/server/server.c. The configuration file for the LwIP stack is src/config/lwipopts.h.
Figure 4-1. Ethernet Task Behavior
ethernet_task
NValid frame received?
IP packet?
ARP packet?
N
N
etharp_arp_input
Y
Y
ip_input
Y
TCP protocol?
Other protocol handlertcp_input
server_recv
Upgrading packet received?
Firmware update
init_ethernet
Y
N
NY
Output data to UART
In this demonstration, the IP address of the device is allocated via the DHCP and the sender can’t know the
device IP address when they connect to the device first time. In order to solve this issue, the device features a
UDP server which can tell the senders the device IP address when it receives a broadcast message that
contains a magic string at the header of the message from the sender. For example, if there is a mobile phone
that connects to the same network as the device, the mobile phone can broadcast a message contained the
magic string through UDP protocol. The device will reply it with a message in the form of “IP address, MAC
address, Description” when it receives the specific message correctly. Then the sender can extract the IP
address from this message and connect it to the device using this IP address.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
11
11
4.2.2 Firmware In-field Updating
The new firmware is divided into different 1024 bytes packets and each packet is encrypted separately
according to the protocol. When one valid data frame is received, the application code should decrypt it firstly
and then write it to the Flash in other bank.
Figure 4-2. The Firmware Updating Process
Upgrade request
(Authentication)
ACK
Frame0 send
ACK
Frame1 send
ACK
Last Frame send
ACK
ACK
Command frame
(Get CRC)
ACK
Command frame
(EXEC)
DeviceSender
After the last frame sent, the sender should send a “Get CRC” command frame to check the entire firmware
integrity. When the device receives the “Get CRC” command, it will read the firmware from the Flash and
calculates the CRC value and then send it to the sender. If the CRC values matches, the remote sender can
send the “EXEC” command to the device to let the device switch to the new firmware. This can ensure the new
firmware in the device exactly matches the firmware that the sender has sent and to avoid any errors during
the data transmission or downloading that may cause the system can’t function properly or even can’t function
at all.
Figure 4-3. In-field Firmware Updating Task
Upgrading packet received
Valid packet?
NY
Authenticated sender?
Decrypt the data
Data frame
Write data into Flash
Drop packet
Decryption Successful?
Send ACK frame
Command frame?
Execute command
(Getting version, Calculating CRC
or Switching to the new firmware)
Anthentication frame?
Verify the identity of
the Sender
Drop packet
Y
Y
Y
Y
Y
N
NN
N
N
The updating task needs to verify the identity of the Sender firstly and then can do firmware update. So the
unauthorized sender can’t update the device firmware. When data frames arrive, the data will be decrypted
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 1
2
12
with the stored key in the device and then be written into Flash if no error occurs. The address in the Flash
where to write is specified by the sequence number and that’s why the data packet should be 1024 bytes and
only the last frame can be less than 1024. The data is written into the other Flash bank, so any accidents such
as power loss cannot harm or crash the system because the current application code can’t be affected by the
firmware updating.
Thanks to the dual bank Flash swapping feature. Two Flash banks can be swapped, but Flash start address is
always mapped to address 0x0, no matter whether the banks are swapped or not. The same application code
can work on both banks without modifying the binary mapping because both banks can be mapped to the boot
program area.
Table 4-1. Boot Code Mapping
GPNVM[1] GPNVM[1] Boot From
Clear Clear/Set ROM
Set Clear Flash Bank 0
Set Set Flash Bank 1
When receives firmware switching command from the remote sender, the device will swap the Flash bank and
then reset itself. Next time, the system will boot from the new bank and the new firmware will be executed.
4.3 Firmware Updater Application
The firmware updater application is used to transmit the firmware from the PC or a mobile phone to the device.
One Android APP is provided for the test purpose. This application ethernetota.apk has been tested on
Android kernel 4.1.2 and the source code is attached with this application note.
Since no information apart from the application code is required, the firmware can simply be transmitted in
binary format and directly written into internal Flash by the application code. Using other formats would mean
adding the unnecessary code on the application code or the firmware updater APP to handle them; this may
not be worth it. This application will use the binary format firmware.
4.4 Quick-Start Setup
Connect boards as per Figure 4-4.
Figure 4-4. Board Setup
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
13
13
Program the firmware from the Atmel Studio project Safe_Secure_Firmware_Update. Build the project, and
then click on the “Start Debugging” button or click “Debug” menu and select “Start Debugging and Break”
to program the firmware. User can also use the device programming tool (Tools -> Device Programming) to
program the firmware without debugging.
Figure 4-5. Device Programming
Note that the DEBUG USB on the board should be connected to PC to use the on-board Embedded Debugger.
Please refer to Figure 4-4.
When the device is programmed successfully, user can generate a new version firmware by simply changing
the MAJOR_VERSION definition from head file src/network/upgrade/upgrade.h. Then copy this new binary file to
the Android Phone. This file will be used to update the board later.
Plug in your wireless router with a power cable, and then connect its WAN or Internet port to the Ethernet jack
if it’s available to you or just left the port unconnected. The router will then create a Wi-Fi network. Connect
SAM4S Xplained board to the router via Ethernet cable and connect your mobile phone to the router through
Wi-Fi. Now Mobile phone and SAM4S Xplained Pro are on same network.
Install the application ethernetota.apk in an Android mobile phone. Open the APP, and then the APP will
search available device in the network automatically and list the devices that have been found in the
homepage.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 1
4
14
Figure 4-6. Searching the Device
Clicking on the device will go to the firmware update page.
Figure 4-7. Open the Device
In this page, user can choose the new binary firmware which is stored in the phone previously to update the
device. User can also use “Running Version” button to get the current firmware version on the device.
The ota file means over the air file which is the binary file used to update the device.
Note that a file browser, such as ES File Explorer, should be installed in the phone if new binary file can’t be
selected when click ‘Click here to choose your ota file’.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
15
15
Figure 4-8. Select the New Firmware
Sometimes people may choose the wrong firmware carelessly to update the device and then may cause the
whole system not to work or even crash the system.
A simple countermeasure has been taken into the code firmware design. A firmware valid flag and version
number has been written into the binary firmware. When the APP selects the new firmware, it will check the
firmware whether it’s valid or not and tell the user the result. If the firmware is valid, the APP will tell the user
the new firmware version. From the file version, user can know whether it’s the updated firmware or not.
Figure 4-9. Updating the Firmware of the Device
Clicking on the “Update” button will start the firmware updating. There is a progress bar to show the progress.
No need to worry about any accidental interruption on the device while updating the firmware. The firmware
update doesn’t corrupt the application code which is currently running on the device. Thanks to the dual bank
Flash.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 1
6
16
5 Footprint
Figure 5-1 and Figure 5-2 illustrate the Flash and RAM spaces that each module consumed in the software of
this demonstration.
Figure 5-1. RAM Footprint [KB]
Figure 5-2. Flash Footprint [KB]
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
17
17
The RAM consumed by the LwIP stack depends on the stack configuration. Different configurations will have
different RAM consumption. Table A-1 lists the configuration of the LwIP stack. GCM-AES crypto stack doesn’t
cost much RAM since the AES table is placed in the internal Flash. In addition, RAM reserved for the heap
space is not shown in the RAM footprint. The rest of the RAM is reserved for the heap space in this application.
6 Conclusion
This document describes several countermeasures that can help to do a secure and safe firmware update on a
dual bank Flash microcontroller. These countermeasures can be taken into the firmware design to improve the
security and safety of the in-field firmware updating. However, this application just uses the low cost software
based solution. The symmetric key is stored in the software. Key storage is one of the most important
determinants of the strength of security in a system. Hardware key storage is much stronger than software-
based solutions because hardware storage methods are much more difficult to be attacked. If high level
security is required, users can consider Atmel CryptoAuthentication crypto element devices with hardware-
based key storage.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 1
8
18
Appendix A Additional Information
A.1 LwIP Configuration
Table A-1 lists the LwIP stack configuration in this application, and these configurations can be modified
according to the real application in the file config/lwipopts.h.
Table A-1. LwIP Options in This Application
Option Value Description
LWIP_TCP 1 Turn on TCP
LWIP_UDP 1 Turn on UDP
LWIP_DHCP 1 Enable DHCP module
MEMP_NUM_TCP_PCB 15 The number of simultaneously active TCP connections
MEMP_NUM_UDP_PCB 3 The number of UDP protocol control blocks
MEMP_NUM_TCP_PCB_LISTEN 1 The number of listening TCP connections
MEMP_NUM_TCP_SEG 10 The number of simultaneously queued TCP segments
MEMP_NUM_PBUF 2 The number of memp struct pbufs
PBUF_POOL_SIZE 5 The number of buffers in the pbuf pool
PBUF_POOL_BUFSIZE 1518 The size of each pbuf in the pbuf pool
TCP_MSS 1460 TCP Maximum segment size
TCP_WND 2 * TCP_MSS The size of a TCP window
TCP_SND_BUF 2 * TCP_MSS TCP sender buffer space
MEM_LIBC_MALLOC 1 Use malloc/free/realloc provided by C-library
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015
19
19
7 Document Revision History
Doc Rev. Date Comments
42492A 07/2015 Initial document release.
AT11787: Safe and Secure Firmware Upgrade via Ethernet [APPLICATION NOTE] Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015 2
0
20
Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 │ www.atmel.com
© 2015 Atmel Corporation. / Rev.: Atmel-42492A-AT11787-Safe-and-Secure-Firmware-Upgrade-via-Ethernet_ApplicationNote_07/2015. Atmel®, Atmel logo and combinations thereof, Enabling Unlimited Possibilities®, and others are registered trademarks or trademarks of Atmel Corporation in U.S. and other countries. ARM®, ARM Connected® logo, and others are the registered trademarks or trademarks of ARM Ltd. Other terms and product names may be trademarks of others. DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, b y estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF S ALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY R ELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT , EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, auto motive applications. Atmel products are not intended,
authorized, or warranted for use as components in applications intended to support or sustain life.
SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in conne ction with any applications where the failure of such products would reasonably be expected to result in significant personal injury or death (“Safety-Critical Applications”) without an Atmel officer's specific written consent. Safety-Critical Applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems. Atmel products are not designed nor intended for use in military or aerospace applications or environments unless specifically desi gnated by Atmel as military-grade. Atmel products are not
designed nor intended for use in automotive applications unless specifically designated by Atmel as automotive -grade.