

# Porting the FreeRTOS libraries
<a name="afr-porting"></a>

Before you start porting, follow the instructions at [Setting up your workspace and project for porting](porting-set-up-project.md).

The [FreeRTOS porting flowchart](porting-chart.md) describes the libraries required for porting.

To port FreeRTOS to your device, follow the instructions in the topics below.

1. [Configuring a FreeRTOS kernel port](afr-porting-kernel.md)

1. [Implementing the library logging macros](afr-library-logging-macros.md)

1. [Porting a TCP/IP stack](afr-porting-tcp.md)

1. [Porting the Network Transport Interface](afr-porting-network-transport-interface.md)

1. [Porting the corePKCS11 library](afr-porting-pkcs.md)

1. [Configuring the coreMQTT library](afr-porting-mqtt.md)

1. [Configuring the coreHTTP library](afr-porting-corehttp.md)

1. [Porting the AWS IoT over-the-air (OTA) update library](afr-porting-ota.md)

1. [Porting the Cellular Interface library](freertos-porting-cellular.md)

# FreeRTOS porting flowchart
<a name="porting-chart"></a>

Use the porting flowchart below as a visual aid, as you port FreeRTOS to your board.

![\[Flowchart for Configuring FreeRTOS with TLS Connectivity and MQTT.\]](http://docs.aws.amazon.com/freertos/latest/portingguide/images/afr-porting.png)


# Configuring a FreeRTOS kernel port
<a name="afr-porting-kernel"></a>

This section provides instructions for integrating a port of the FreeRTOS kernel into a FreeRTOS port-testing project. For a list of available kernel ports, see [FreeRTOS kernel ports](https://freertos.org/RTOS_ports.html).

FreeRTOS uses the FreeRTOS kernel for multitasking and intertask communications. For more information, see the [FreeRTOS kernel fundamentals](https://docs.aws.amazon.com/freertos/latest/userguide/dev-guide-freertos-kernel.html) in the *FreeRTOS User Guide* and [FreeRTOS.org](https://freertos.org/index.html). 

**Note**  
Porting the FreeRTOS kernel to a new architecture is not included in this documentation. If you are interested, [contact the FreeRTOS engineering team](https://freertos.org/RTOS-contact-and-support.html).  
For the FreeRTOS Qualification program, only existing FreeRTOS kernel ports are supported. Modifications to these ports are not accepted within the program. Review the [ FreeRTOS kernel port policy](https://freertos.org/differences-between-officially-supported-and-contributed-FreeRTOS-code.html) for more information.

## Prerequisites
<a name="porting-prereqs-kernel"></a>

To set up the FreeRTOS kernel for porting, you need the following:
+ An official FreeRTOS kernel port, or FreeRTOS supported ports for the target platform.
+ An IDE project that includes the correct FreeRTOS kernel port files for the target platform and compiler. For information about setting up a test project, see [Setting up your workspace and project for porting](porting-set-up-project.md).

## Configuring the FreeRTOS kernel
<a name="porting-steps-kernel"></a>

FreeRTOS kernel is customized using a configuration file called `FreeRTOSConfig.h`. This file specifies application-specific configuration settings for the kernel. For a description of each configuration option, see [Customization](https://freertos.org/a00110.html) on FreeRTOS.org.

To configure the FreeRTOS kernel to work with your device, include `FreeRTOSConfig.h`, and modify any additional FreeRTOS configurations.

For a description of each configuration option, see [Customization](https://freertos.org/a00110.html) configurations on FreeRTOS.org.

## Testing
<a name="porting-testing-kernel"></a>
+ Run a simple FreeRTOS task to log a message to serial output console.
+ Verify that the message outputs to console as expected.

# Implementing the library logging macros
<a name="afr-library-logging-macros"></a>

The FreeRTOS libraries use the following logging macros, listed in increasing order of verbosity.
+ `LogError`
+ `LogWarn`
+ `LogInfo`
+ `LogDebug`

A definition for all the macros must be provided. The recommendations are: 
+ Macros should support `C89` style logging.
+ Logging should be thread safe. Log lines from multiple tasks must not interleave with each other.
+ Logging APIs must not block, and must free application tasks from blocking on I/O.

Refer to the [Logging Functionality](https://www.freertos.org/logging.html) on FreeRTOS.org for implementation specifics. You can see an implementation in this [example](https://github.com/FreeRTOS/lab-iot-reference-nxp-rt1060/tree/main/examples/common/logging).

## Testing
<a name="testing-logging"></a>
+ Run a test with multiple tasks to verify logs do not interleave.
+ Run a test to verify that the logging APIs do not block on I/O.
+ Test logging macros with various standards, such as `C89,C99` style logging.
+ Test logging macros by setting different log levels, such as `Debug`, `Info`, `Error`, and `Warning`.

# Porting a TCP/IP stack
<a name="afr-porting-tcp"></a>

This section provides instruction for porting and testing on-board TCP/IP stacks. If your platform offloads TCP/IP and TLS functionality to a separate network processor or module, you can skip this porting section and visit [Porting the Network Transport Interface](afr-porting-network-transport-interface.md).

[FreeRTOS\$1TCP](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/index.html) is a native TCP/IP stack for the FreeRTOS kernel. FreeRTOS\$1TCP is developed and maintained by the FreeRTOS engineering team and is the recommended TCP/IP stack to use with FreeRTOS. For more information, see [Porting FreeRTOS\$1TCP](#porting-freertos-tcp). Alternatively, you can use the third-party TCP/IP stack [lwIP](https://savannah.nongnu.org/projects/lwip/) . The testing instruction provided in this section uses the transport interface tests for TCP plain text, and is not dependent on the specific implemented TCP/IP stack. 

## Porting FreeRTOS\$1TCP
<a name="porting-freertos-tcp"></a>

FreeRTOS\$1TCP is a native TCP/IP stack for the FreeRTOS kernel. For more information, see [FreeRTOS.org](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/).

### Prerequisites
<a name="porting-prereqs-freertos-tcp"></a>

To port the FreeRTOS\$1TCP library, you need the following:
+ An IDE project that includes the vendor-supplied Ethernet or Wi-Fi drivers.

  For information about setting up a test project, see [Setting up your workspace and project for porting](porting-set-up-project.md).
+ A validated configuration of the FreeRTOS kernel.

  For information about configuring the FreeRTOS kernel for your platform, see [Configuring a FreeRTOS kernel port](afr-porting-kernel.md).

### Porting
<a name="porting-steps-freertos-tcp"></a>

Before you start porting the FreeRTOS\$1TCP library, check the [GitHub](https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/tree/main/source/portable/NetworkInterface) directory to see if a port to your board already exists.

If a port does not exist, do the following:

1. Follow the [Porting FreeRTOS\$1TCP to a Different Microcontroller](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Ethernet_Porting.html) instructions on FreeRTOS.org to port FreeRTOS\$1TCP to your device.

1. If necessary, follow the [Porting FreeRTOS\$1TCP to a New Embedded C Compiler](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html) instructions on FreeRTOS.org to port FreeRTOS\$1TCP to a new compiler.

1. Implement a new port that uses the vendor-supplied Ethernet or Wi-Fi drivers in a file called `NetworkInterface.c`. Visit the [GitHub](https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/tree/main/source/portable/NetworkInterface/board_family) repository for a template.

After you create a port, or if a port already exists, create `FreeRTOSIPConfig.h`, and edit the configuration options so they are correct for your platform. For more information about the configuration options, see [FreeRTOS\$1TCP Configuration](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html) on FreeRTOS.org.

## Testing
<a name="testing-tcp"></a>

Whether you use FreeRTOS\$1TCP library or a third party library, follow the steps below for testing:
+ Provide an implementation for `connect/disconnect/send/receive` APIs in transport interface tests.
+ Setup an echo server in plain text TCP connection mode, and run transport interface tests.

**Note**  
To officially qualify a device for FreeRTOS, if your architecture requires to port a TCP/IP software stack, you need to validate the device's ported source code against transport interface tests in plain text TCP connection mode with AWS IoT Device Tester. Follow the instructions in [Using AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* to set up AWS IoT Device Tester for port validation. To test a specific library's port, the correct test group must be enabled in the `device.json` file in the Device Tester `configs` folder.

# Porting the corePKCS11 library
<a name="afr-porting-pkcs"></a>

The Public Key Cryptography Standard \$111 defines a platform-independent API to manage and use cryptographic tokens. [PKCS 11](https://en.wikipedia.org/wiki/PKCS_11) refers to the standard and the APIs defined by it. The PKCS \$111 cryptographic API abstracts key storage, get/set properties for cryptographic objects, and session semantics. It's widely used for manipulating common cryptographic objects. Its functions allow application software to use, create, modify, and delete cryptographic objects, without exposing those objects to the application's memory. 

FreeRTOS libraries and reference integrations use a subset of the PCKS \$111 interface standard, with a focus on the operations involving asymmetric keys, random number generation, and hashing. The below table lists the use cases and required PKCS \$111 APIs to support.


**Use Cases**  

| Use Case | Required PKCS \$111 API Family | 
| --- | --- | 
| All | Initialize, Finalize, Open/Close Session, GetSlotList, Login | 
| Provisioning | GenerateKeyPair, CreateObject, DestroyObject, InitToken, GetTokenInfo | 
| TLS | Random, Sign, FindObject, GetAttributeValue | 
| FreeRTOS\$1TCP | Random, Digest | 
| OTA | Verify, Digest, FindObject, GetAttributeValue | 

## When to implement a complete PKCS \$111 module
<a name="implemeting-pkcs"></a>

Storing private keys in general-purpose flash memory can be convenient in evaluation and rapid prototyping scenarios. We recommend you use dedicated cryptographic hardware to reduce the threats of data theft and device duplication in production scenarios. Cryptographic hardware includes components with features that prevent cryptographic secret keys from being exported. To support this, you will have to implement a subset of PKCS \$111 required to work with FreeRTOS libraries as defined in the above table. 

## When to use FreeRTOS corePKCS11
<a name="using-pkcs"></a>

The corePKCS11 library contains a software-based implementation of the PKCS \$111 interface (API) that uses the cryptographic functionality provided by [Mbed TLS](https://tls.mbed.org/). This is provided for rapid prototyping and evaluation scenarios where the hardware does not have a dedicated cryptographic hardware. In this case, you only have to implement corePKCS11 PAL to make the corePKCS11 software-based implementation to work with your hardware platform. 

## Porting corePKCS11
<a name="porting-core-pkcs"></a>

You will have to have implementations to read and write cryptographic objects to non-volatile memory (NVM), such as on-board flash memory. Cryptographic objects must be stored in a section of NVM that is not initialized and is not erased on device reprogramming. Users of the corePKCS11 library will provision devices with credentials, and then reprogram the device with a new application that accesses these credentials through the corePKCS11 interface. The corePKCS11 PAL ports must provide a location to store: 
+ The device client certificate
+ The device client private key
+ The device client public key
+ A trusted root CA
+ A code-verification public key (or a certificate that contains the code-verification public key) for secure boot-loader and over-the-air (OTA) updates
+ A Just-In-Time provisioning certificate

Include [the header file](https://github.com/FreeRTOS/corePKCS11/blob/main/source/include/core_pkcs11_pal.h) and implement the PAL APIs defined.


**PAL APIs**  

| Function | Description | 
| --- | --- | 
| PKCS11\$1PAL\$1Initialize |  Initializes the PAL layer. Called by the corePKCS11 library at the start of its initialization sequence.  | 
| PKCS11\$1PAL\$1SaveObject |  Writes data to non-volatile storage.  | 
| PKCS11\$1PAL\$1FindObject |  Uses a PKCS \$111 `CKA_LABEL` to search for a corresponding PKCS \$111 object in non-volatile storage, and returns that object’s handle, if it exists.  | 
| PKCS11\$1PAL\$1GetObjectValue |  Retrieves the value of an object, given the handle.  | 
| PKCS11\$1PAL\$1GetObjectValueCleanup |  Cleanup for the `PKCS11_PAL_GetObjectValue` call. Can be used to free memory allocated in a `PKCS11_PAL_GetObjectValue` call.  | 

## Testing
<a name="porting-testing-pkcs"></a>

If you use the FreeRTOS corePKCS11 library or implement the required subset of PKCS11 APIs, you must pass FreeRTOS PKCS11 tests. These test if the required functions for FreeRTOS libraries perform as expected.

This section also describes how you can locally run the FreeRTOS PKCS11 tests with the qualification tests.

### Prerequisites
<a name="porting-testing-prereqs"></a>

To set up the FreeRTOS PKCS11 tests, the following has to be implemented.
+ A supported port of PKCS11 APIs.
+ An implementation of FreeRTOS qualification tests platform functions which include the following:
  + `FRTest_ThreadCreate`
  + `FRTest_ThreadTimedJoin`
  + `FRTest_MemoryAlloc`
  + `FRTest_MemoryFree`

(See the [ README.md](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests/tree/main/src/pkcs11) file for the FreeRTOS Libraries Integration Tests for PKCS \$111 on GitHub.)

### Porting tests
<a name="porting-tests-pkcs11"></a>
+ Add [ FreeRTOS-Libraries-Integration-Tests](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests/tree/main/src/pkcs11) as a submodule into your project. The submodule can be placed in any directory of the project, as long as it can be built.
+ Copy `config_template/test_execution_config_template.h` and `config_template/test_param_config_template.h` to a project location in the build path, and rename them to `test_execution_config.h` and `test_param_config.h`. 
+ Include relevant files into the build system. If using `CMake`, `qualification_test.cmake` and `src/pkcs11_tests.cmake` can be used to include relevant files.
+ Implement `UNITY_OUTPUT_CHAR` so that test output logs and device logs do not interleave.
+ Integrate the MbedTLS, which verifies the cryptoki operation result.
+ Call `RunQualificationTest()` from the application.

### Configuring tests
<a name="configure-pkcs11-tests"></a>

The PKCS11 test suite must be configured according to the PKCS11 implementation. The following table lists the configuration required by PKCS11 tests in the `test_param_config.h` header file.


**PKSC11 test configurations**  

| Configuration | Description | 
| --- | --- | 
| PKCS11\$1TEST\$1RSA\$1KEY\$1SUPPORT |  The porting supports RSA key functions.  | 
| PKCS11\$1TEST\$1EC\$1KEY\$1SUPPORT |  The porting supports EC key functions.  | 
| PKCS11\$1TEST\$1IMPORT\$1PRIVATE\$1KEY\$1SUPPORT |  The porting supports the import of the private key. RSA and EC key import are validated in the test if the supporting key functions are enabled.  | 
| PKCS11\$1TEST\$1GENERATE\$1KEYPAIR\$1SUPPORT |  The porting supports keypair generation. EC keypair generation is validated in the test if the supporting key functions are enabled.  | 
| PKCS11\$1TEST\$1PREPROVISIONED\$1SUPPORT |  The porting has pre-provisioned credentials. `PKCS11_TEST_LABEL_DEVICE_PRIVATE_KEY_FOR_TLS`, `PKCS11_TEST_LABEL_DEVICE_PUBLIC_KEY_FOR_TLS` and `PKCS11_TEST_LABEL_DEVICE_CERTIFICATE_FOR_TLS`, are examples of the credentials.  | 
| PKCS11\$1TEST\$1LABEL\$1DEVICE\$1PRIVATE\$1KEY\$1FOR\$1TLS |  The label of the private key used in the test.  | 
| PKCS11\$1TEST\$1LABEL\$1DEVICE\$1PUBLIC\$1KEY\$1FOR\$1TLS |  The label of the public key used in the test.  | 
| PKCS11\$1TEST\$1LABEL\$1DEVICE\$1CERTIFICATE\$1FOR\$1TLS |  The label of the certificate used in the test.  | 
| PKCS11\$1TEST\$1JITP\$1CODEVERIFY\$1ROOT\$1CERT\$1SUPPORTED |  The porting supports storage for JITP. Set this to 1 to enable the JITP `codeverify` test.  | 
| PKCS11\$1TEST\$1LABEL\$1CODE\$1VERIFICATION\$1KEY |  The label of the code verification key used in JITP `codeverify` test.  | 
| PKCS11\$1TEST\$1LABEL\$1JITP\$1CERTIFICATE |  The label of the JITP certificate used in JITP `codeverify` test.  | 
| PKCS11\$1TEST\$1LABEL\$1ROOT\$1CERTIFICATE |  The label of the root certificate used in JITP `codeverify` test.  | 

FreeRTOS libraries and reference integrations must support a minimum of one key function configuration like RSA or Elliptic curve keys, and one key provisioning mechanism supported by the PKCS11 APIs. The test must enable the following configurations: 
+ At least one of the following key function configurations:
  + PKCS11\$1TEST\$1RSA\$1KEY\$1SUPPORT
  + PKCS11\$1TEST\$1EC\$1KEY\$1SUPPORT
+ At least one of the following key provisioning configurations:
  + PKCS11\$1TEST\$1IMPORT\$1PRIVATE\$1KEY\$1SUPPORT
  + PKCS11\$1TEST\$1GENERATE\$1KEYPAIR\$1SUPPORT
  + PKCS11\$1TEST\$1PREPROVISIONED\$1SUPPORT 

The pre-provisioned device credential test must run under the following conditions:
+ `PKCS11_TEST_PREPROVISIONED_SUPPORT` must be enabled and other provisioning mechanisms disabled.
+ Only one key function, either `PKCS11_TEST_RSA_KEY_SUPPORT` or `PKCS11_TEST_EC_KEY_SUPPORT`, is enabled.
+ Set up the pre-provisioned key labels according to your key function, including `PKCS11_TEST_LABEL_DEVICE_PRIVATE_KEY_FOR_TLS`, `PKCS11_TEST_LABEL_DEVICE_PUBLIC_KEY_FOR_TLS` and `PKCS11_TEST_LABEL_DEVICE_CERTIFICATE_FOR_TLS`. These credentials must exist before running the test.

The test may need to run several times with different configurations, if the implementation supports pre-provisioned credentials and other provisioning mechanisms.

**Note**  
The objects with labels `PKCS11_TEST_LABEL_DEVICE_PRIVATE_KEY_FOR_TLS`, `PKCS11_TEST_LABEL_DEVICE_PUBLIC_KEY_FOR_TLS` and `PKCS11_TEST_LABEL_DEVICE_CERTIFICATE_FOR_TLS` are destroyed during the test if either `PKCS11_TEST_GENERATE_KEYPAIR_SUPPORT` or `PKCS11_TEST_GENERATE_KEYPAIR_SUPPORT` is enabled.

### Running tests
<a name="running-tests"></a>

This section describes how you can locally test the PKCS11 interface with the qualification tests. Alternatively, you can also use IDT to automate the execution. See [AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* for details.

The following instructions describe how to run the tests:
+ Open `test_execution_config.h` and define **CORE\$1PKCS11\$1TEST\$1ENABLED** to 1.
+ Build and flash the application to your device to run. The test result are output to the serial port.

The following is an example of the output test result.

```
TEST(Full_PKCS11_StartFinish, PKCS11_StartFinish_FirstTest) PASS
TEST(Full_PKCS11_StartFinish, PKCS11_GetFunctionList) PASS
TEST(Full_PKCS11_StartFinish, PKCS11_InitializeFinalize) PASS
TEST(Full_PKCS11_StartFinish, PKCS11_GetSlotList) PASS
TEST(Full_PKCS11_StartFinish, PKCS11_OpenSessionCloseSession) PASS
TEST(Full_PKCS11_Capabilities, PKCS11_Capabilities) PASS
TEST(Full_PKCS11_NoObject, PKCS11_Digest) PASS
TEST(Full_PKCS11_NoObject, PKCS11_Digest_ErrorConditions) PASS
TEST(Full_PKCS11_NoObject, PKCS11_GenerateRandom) PASS
TEST(Full_PKCS11_NoObject, PKCS11_GenerateRandomMultiThread) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_CreateObject) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_FindObject) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_GetAttributeValue) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_Sign) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_FindObjectMultiThread) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_GetAttributeValueMultiThread) PASS
TEST(Full_PKCS11_RSA, PKCS11_RSA_DestroyObject) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_GenerateKeyPair) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_CreateObject) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_FindObject) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_GetAttributeValue) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_Sign) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_Verify) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_FindObjectMultiThread) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_GetAttributeValueMultiThread) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_SignVerifyMultiThread) PASS
TEST(Full_PKCS11_EC, PKCS11_EC_DestroyObject) PASS

-----------------------
27 Tests 0 Failures 0 Ignored
OK
```

 Testing is complete when all tests pass.

**Note**  
To officially qualify a device for FreeRTOS, you must validate the device's ported source code with AWS IoT Device Tester. Follow the instructions in [Using AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the FreeRTOS User Guide to set up AWS IoT Device Tester for port validation. To test a specific library's port, the correct test group must be enabled in the `device.json` file in the AWS IoT Device Tester `configs` folder.

# Porting the Network Transport Interface
<a name="afr-porting-network-transport-interface"></a>

## Integrating the TLS library
<a name="afr-porting-tls"></a>

For Transport Layer Security (TLS) authentication, use your preferred TLS stack. We recommend using [Mbed TLS](https://tls.mbed.org/) because it is tested with FreeRTOS libraries. You can find an example of this at this [GitHub](https://github.com/FreeRTOS/FreeRTOS) repository.

Regardless of the TLS implementation used by your device, you must implement the underlying transport hooks for TLS stack with TCP/IP stack. They must support the [TLS cipher suites that are supported by AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/transport-security.html#tls-cipher-suite-support).

## Porting the Network Transport Interface library
<a name="network-intro"></a>

You must implement a network transport interface to use [coreMQTT](https://www.freertos.org/mqtt/index.html) and [coreHTTP](https://www.freertos.org/http/index.html). Network Transport Interface contains function pointers and context data required to send and receive data on a single network connection. See [Transport Interface](https://www.freertos.org/network-interface.html) for more details. FreeRTOS provides a set of built-in network transport interface tests to validate these implementations. The following section guides you how to set up your project to run these tests. 

## Prerequisites
<a name="prereqs"></a>

To port this test, you need the following:
+ A project with a build system that can build FreeRTOS with a validated FreeRTOS kernel port.
+ Working implementation of network drivers.

## Porting
<a name="porting-network-transport-interface"></a>
+ Add [ FreeRTOS-Libraries-Integration-Tests](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests) as a submodule into your project. It doesn’t matter where the submodule is placed in the project, as long as it can be built.
+ Copy `config_template/test_execution_config_template.h` and `config_template/test_param_config_template.h` to a project location in the build path, and rename them to `test_execution_config.h` and `test_param_config.h`.
+ Include relevant files into the build system. If using `CMake`, `qualification_test.cmake` and `src/transport_interface_tests.cmake` are used to include relevant files.
+ Implement the following functions at an appropriate project location:
+ 
  + A `network connect function`: The signature is defined by `NetworkConnectFunc` in `src/common/network_connection.h`. This function takes in a pointer to network context, a pointer to host info, and a pointer to network credentials. It establishes a connection with the server specified in the host info with the provided network credentials.
  + A `network disconnect function`: The signature is defined by `NetworkDisconnectFunc` in `src/common/network_connection.h`. This function takes in a pointer to a network context. It disconnects a previously established connection stored in the network context.
  + `setupTransportInterfaceTestParam()`: This is defined in `src/transport_interface/transport_interface_tests.h`. The implementation must have exactly the same name and signature as defined in `transport_interface_tests.h`. This function takes in a pointer to a *TransportInterfaceTestParam* struct. It will populate the fields in the *TransportInterfaceTestParam* struct that is used by the transport interface test.
+ Implement **UNITY\$1OUTPUT\$1CHAR** so that test output logs do not interleave with device logs.
+ Call `runQualificationTest()`from the application. The device hardware must be properly initialized and the network must be connected before the call.

### Credential management (on-device generated key)
<a name="cred-management-key"></a>

When **FORCE\$1GENERATE\$1NEW\$1KEY\$1PAIR** in `test_param_config.h` is set to 1, the device application generates a new on-device key pair and outputs the public key. The device application uses **ECHO\$1SERVER\$1ROOT\$1CA** and **TRANSPORT\$1CLIENT\$1CERTIFICATE** as the echo server root CA and client certificate when establishing a TLS connection with the echo server. IDT sets these parameters during the qualification run. 

### Credential Management (importing key)
<a name="cred-management-importing-key"></a>

The device application uses **ECHO\$1SERVER\$1ROOT\$1CA**, **TRANSPORT\$1CLIENT\$1CERTIFICATE** and **TRANSPORT\$1CLIENT\$1PRIVATE\$1KEY** in `test_param_config.h` as the echo server root CA, client certificate, and client private key when establishing a TLS connection with the echo server. IDT sets these parameters during the qualification run.

## Testing
<a name="testing-transport-interface"></a>

This section describes how you can locally test the transport interface with the qualification tests. Additional details can be found in the README.md file provided in the [ transport\$1interface](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests/tree/main/src/transport_interface) section of the FreeRTOS-Libraries-Integration-Tests on GitHub.

Alternatively, you can also use IDT to automate the execution. See [AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* for details.

### Enable the test
<a name="enabling-test"></a>

Open `test_execution_config.h` and define **TRANSPORT\$1INTERFACE\$1TEST\$1ENABLED** to 1.

### Set up the echo server for testing
<a name="configuring-echo-server-test"></a>

An echo server accessible from the device running the tests is required for local testing. The echo server must support TLS if the transport interface implementation supports TLS. If you don’t have one already, [ FreeRTOS-Libraries-Integration-Tests](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests/tree/main/tools/echo_server) GitHub repository has an echo server implementation.

### Configuring the project for testing
<a name="configure-project"></a>

In `test_param_config.h`, update **ECHO\$1SERVER\$1ENDPOINT** and **ECHO\$1SERVER\$1PORT** to the endpoint and server setup in the previous step.

### Setup credentials (on-device generated key)
<a name="setup-credentials-device-key"></a>
+ Set **ECHO\$1SERVER\$1ROOT\$1CA** to the server certificate of the echo server.
+ Set **FORCE\$1GENERATE\$1NEW\$1KEY\$1PAIR** to 1 to generate a key pair and get the public key.
+ Set **FORCE\$1GENERATE\$1NEW\$1KEY\$1PAIR** back to 0 after key generation.
+ User the public key and server key and certificate to generate client certificate.
+ Set **TRANSPORT\$1CLIENT\$1CERTIFICATE** to the generated client certificate.

### Setup credentials (importing key)
<a name="setup-credentials-import-key"></a>
+ Set **ECHO\$1SERVER\$1ROOT\$1CA** to the server certificate of the echo server.
+ Set **TRANSPORT\$1CLIENT\$1CERTIFICATE** to the pre-generated client certificate.
+ Set **TRANSPORT\$1CLIENT\$1PRIVATE\$1KEY** to the pre-generated client private key.

### Build and flash the application
<a name="build-flash"></a>

Build and flash the application using the tool-chain of your choice. When `runQualificationTest()` is invoked, the transport interface tests will run. Test results are outputted to the serial port.

**Note**  
To officially qualify a device for FreeRTOS, you must validate the device's ported source code against OTA PAL and OTA E2E test groups with AWS IoT Device Tester. Follow the instructions in [Using AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* to set up AWS IoT Device Tester for port validation. To test a specific library's port, the correct test group must be enabled in the `device.json` file in the AWS IoT Device Tester `configs` folder.

# Configuring the coreMQTT library
<a name="afr-porting-mqtt"></a>

Devices on the edge can use the MQTT protocol to communicate with the AWS Cloud. AWS IoT hosts an MQTT broker that sends and receives messages to and from connected devices at the edge.

The coreMQTT library implements the MQTT protocol for devices running FreeRTOS. The coreMQTT library doesn't need to be ported, but your device's test project must pass all MQTT tests for qualification. For more information, see [coreMQTT Library](https://docs.aws.amazon.com/freertos/latest/userguide/coremqtt.html) in the *FreeRTOS User Guide.*

## Prerequisites
<a name="testing-prereqs-mqtt"></a>

To set up the coreMQTT library tests, you need a network transport interface port. See [Porting the Network Transport Interface](afr-porting-network-transport-interface.md) to learn more.

## Testing
<a name="testing-mqtt"></a>

Run coreMQTT Integration tests:
+ Register your client certificate with MQTT broker.
+ Set the broker endpoint in `config` and run the integration tests.

## Create reference MQTT demo
<a name="reference-mqtt"></a>

We recommend using the coreMQTT agent to handle thread safety for all MQTT operations. The user will also need publish and subscribe tasks, and Device Advisor tests to validate if the application integrates TLS, MQTT and other FreeRTOS libraries effectively. 

To officially qualify a device for FreeRTOS, validate your integration project with AWS IoT Device Tester MQTT test cases. See [AWS IoT Device Advisor workflow](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-console-tutorial.html) for instructions to set up and test. Mandated test cases for TLS and MQTT are listed below:


**TLS Test Cases**  

| Test Case | Test cases | Required tests | 
| --- | --- | --- | 
| TLS | TLS Connect | Yes | 
| TLS | TLS Support AWS IoT Cipher Suites | A recommended [cipher suite](https://docs.aws.amazon.com/iot/latest/developerguide/transport-security.html#tls-cipher-suite-support)  | 
| TLS | TLS Unsecure Server Cert | Yes | 
| TLS | TLS Incorrect Subject Name Servr Cert | Yes | 


**MQTT Test Cases**  

| Test Case | Test cases | Required tests | 
| --- | --- | --- | 
| MQTT | MQTT Connect | Yes | 
| MQTT | MQTT Connect Jitter Retries | Yes without warnings | 
| MQTT | MQTT Subscribe | Yes | 
| MQTT | MQTT Publish | Yes | 
| MQTT | MQTT ClientPuback QoS1 | Yes | 
| MQTT | MQTT No Ack PingResp | Yes | 

# Configuring the coreHTTP library
<a name="afr-porting-corehttp"></a>

Devices on the edge can use the HTTP protocol to communicate with the AWS Cloud. AWS IoT services host an HTTP server that sends and receives messages to and from connected devices at the edge. 

## Testing
<a name="testing-corehttp"></a>

Follow the steps below for testing:
+ Setup the PKI for TLS mutual authentication with AWS or an HTTP server.
+ Run CoreHTTP integration tests.

# Porting the AWS IoT over-the-air (OTA) update library
<a name="afr-porting-ota"></a>

With FreeRTOS over-the-air (OTA) updates, you can do the following:
+ Deploy new firmware images to a single device, a group of devices, or your entire fleet.
+ Deploy firmware to devices as they are added to groups, reset, or re-provisioned.
+ Verify the authenticity and integrity of new firmware after it is deployed to devices.
+ Monitor the progress of a deployment.
+ Debug a failed deployment.
+ Digitally sign firmware using Code Signing for AWS IoT.

For more information, see [FreeRTOS Over-the-Air Updates](https://docs.aws.amazon.com/freertos/latest/userguide/freertos-ota-dev.html) in the *FreeRTOS User Guide* along with the [AWS IoT Over-the-air Update Documentation](https://freertos.org/Documentation/api-ref/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/index.html).

You can use the OTA update library to integrate OTA functionality into your FreeRTOS applications. For more information, see [FreeRTOS OTA update Library](https://docs.aws.amazon.com/freertos/latest/userguide/ota-update-library.html) in the *FreeRTOS User Guide*.

FreeRTOS devices must enforce cryptographic code-signing verification on the OTA firmware images that they receive. We recommend the following algorithms:
+ Elliptic-Curve Digital Signature Algorithm (ECDSA)
+ NIST P256 curve
+ SHA-256 hash

## Prerequisites
<a name="porting-prereqs-ota"></a>
+ Complete the instructions in [Setting up your workspace and project for porting](porting-set-up-project.md).
+ Create a network transport interface port.

  For information, see [Porting the Network Transport Interface](afr-porting-network-transport-interface.md).
+ Integrate coreMQTT library. See [ coreMQTT library](https://docs.aws.amazon.com/freertos/latest/userguide/coremqtt.html) in the FreeRTOS User Guide.
+ Create a bootloader that can support OTA updates.

## Platform porting
<a name="porting-steps-ota"></a>

You must provide an implementation of the OTA portable abstraction layer (PAL) to port the OTA library to a new device. The PAL APIs are defined in the [ ota\$1platform\$1interface.h](https://github.com/aws/ota-for-aws-iot-embedded-sdk/blob/main/source/include/ota_platform_interface.h) file for which implementation specific details must be provided.


| Function name | Description | 
| --- | --- | 
| `otaPal_Abort` | Stops an OTA update. | 
| `otaPal_CreateFileForRx` | Creates a file to store the received data chunks. | 
| `otaPal_CloseFile` | Closes the specified file. This might authenticate the file if you use storage that implements cryptographic protection. | 
| `otaPal_WriteBlock` | Writes a block of data to the specified file at the given offset. On success, the function returns the number of bytes written. Otherwise, the function returns a negative error code. The block size will always be a power of two and will be aligned. For more information, see [ OTA library configuration](https://freertos.org/Documentation/api-ref/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_config.html). | 
| `otaPal_ActivateNewImage` | Activates or launches the new firmware image. For some ports, if the device is programmatically reset synchronously, this function will not return. | 
| `otaPal_SetPlatformImageState` | Does what is required by the platform to accept or reject the most recent OTA firmware image (or bundle). To implement this function, see the documentation for your board (platform) details and architecture. | 
| `otaPal_GetPlatformImageState` | Gets the state of the OTA update image. | 

Implement the functions in this table if your device has built-in support for them.


| Function name | Description | 
| --- | --- | 
| `otaPal_CheckFileSignature` | Verifies the signature of the specified file. | 
| `otaPal_ReadAndAssumeCertificate` | Reads the specified signer certificate from the file system and returns it to the caller. | 
| `otaPal_ResetDevice` | Resets the device. | 

**Note**  
Make sure that you have a bootloader that can support OTA updates. For instructions on creating your AWS IoT device bootloader, see [IoT device bootloader](#afr-bootloader).

## E2E and PAL tests
<a name="porting-steps-testing"></a>

 Run OTA PAL and E2E tests.

### E2E tests
<a name="porting-ota-e2e"></a>

OTA end to end (E2E) test is used to verify a device’s OTA capability and to simulate scenarios from reality. This test will include error handling.

#### Prerequisites
<a name="e2e-prereqs"></a>

To port this test, you need the following:
+ A project with an AWS OTA library integrated in it. Visit the[ OTA Library Porting Guide ](https://www.freertos.org/Documentation/api-ref/ota-for-aws-iot-embedded-sdk/docs/doxygen/output/html/ota_porting.html) for additional information.
+ Port the demo application using the OTA library to interact with AWS IoT Core to do the OTA updates. See [Porting the OTA demo application](#e2e-porting-demo-application).
+ Set up the IDT tool. This runs the OTA E2E host application to build, flash, and monitor the device with different configurations, and validates the OTA library integration.

#### Porting the OTA demo application
<a name="e2e-porting-demo-application"></a>

The OTA E2E test must have an OTA demo application to validate the OTA library integration. The demo application must have the capacity to perform OTA firmware updates. You can find the FreeRTOS OTA demo application at [ FreeRTOS GitHub](https://github.com/FreeRTOS/FreeRTOS/tree/main/FreeRTOS-Plus/Demo/AWS/Ota_Windows_Simulator) repository. We recommend that you use the demo application as a reference, and modify it according to your specifications. 

##### Porting steps
<a name="e2e-port-demo"></a>

1. Initialize the OTA agent.

1. Implement the OTA application callback function.

1. Create the OTA agent event processing task.

1. Start the OTA agent.

1. Monitor the OTA agent statistics.

1. Shut down the OTA agent.

Visit [ FreeRTOS OTA over MQTT - Entry point of the demo ](https://www.freertos.org/ota/ota-mqtt-agent-demo.html#OtaMqttAgentEntryPoint) for detailed instructions.

##### Configuration
<a name="e2e-port-config"></a>

The following configurations are necessary to interact with AWS IoT Core:
+ AWS IoT Core client credentials
  + Set-up **democonfigROOT\$1CA\$1PEM** in `Ota_Over_Mqtt_Demo/demo_config.h` with Amazon Trust Services endpoints. See [AWS server-authentication](https://docs.aws.amazon.com/iot/latest/developerguide/server-authentication.html) for more details.
  + Set-up **democonfigCLIENT\$1CERTIFICATE\$1PEM** and **democonfigCLIENT\$1PRIVATE\$1KEY\$1PEM** in `Ota_Over_Mqtt_Demo/demo_config.h` with your AWS IoT client credentials. See [AWS client-authentication details](https://docs.aws.amazon.com/iot/latest/developerguide/client-authentication.html)to learn about client certificates and private keys.
+ Application version
+ OTA Control Protocol
+ OTA Data Protocol
+ Code Signing credentials
+ Other OTA library configurations

You can find the preceding information in `demo_config.h` and `ota_config.h` in FreeRTOS OTA demo applications. Visit [ FreeRTOS OTA over MQTT - Setting up the device](https://www.freertos.org/ota/ota-mqtt-agent-demo.html#OTABasicDemoClient) for more information.

##### Build verification
<a name="e2e-port-validation"></a>

Run the demo application to run the OTA job. When it completes successfully, you can continue to run the OTA E2E tests.

FreeRTOS [OTA demo](https://www.freertos.org/ota/ota-mqtt-agent-demo.html) provides detailed information about setting up an OTA client and an AWS IoT Core OTA job on the FreeRTOS windows simulator. AWS OTA supports both MQTT and HTTP protocols. Refer to the following examples for more details:
+ [OTA over MQTT Demo on Windows Simulator](https://github.com/FreeRTOS/FreeRTOS/tree/main/FreeRTOS-Plus/Demo/AWS/Ota_Windows_Simulator/Ota_Over_Mqtt_Demo)
+ [OTA over HTTP Demo on Windows Simulator](https://github.com/FreeRTOS/FreeRTOS/tree/main/FreeRTOS-Plus/Demo/AWS/Ota_Windows_Simulator/Ota_Over_Http_Demo)

#### Running tests with the IDT tool
<a name="e2e-idt"></a>

To run the OTA E2E tests, you must use AWS IoT Device Tester (IDT) to automate the execution. See [AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* for more details.

##### E2E test cases
<a name="e2e-test-cases"></a>


| Test case | Description | 
| --- | --- | 
| `OTAE2EGreaterVersion` | Happy path test for regular OTA updates. It creates an update with a newer version, which the device updates successfully. | 
| `OTAE2EBackToBackDownloads` | This test creates 3 consecutive OTA updates. The device is expected to update 3 consecutive times. | 
| `OTAE2ERollbackIfUnableToConnectAfterUpdate` | This test verifies that the device rollbacks to the previous firmware if it cannot connect to network with the new firmware. | 
| `OTAE2ESameVersion` | This test confirms that the device rejects the incoming firmware if the version stays the same. | 
| `OTAE2EUnsignedImage` | This test verifies that the device rejects an update if the image is not signed. | 
| `OTAE2EUntrustedCertificate` | This test verifies that the device rejects an update if the firmware is signed with an untrusted certificate. | 
| `OTAE2EPreviousVersion` | This test verifies that the device rejects an older update version. | 
| `OTAE2EIncorrectSigningAlgorithm` | Different devices support different signing and hashing algorithms. This test verifies that the device fails the OTA update if it's created with a non-supported algorithm. | 
| `OTAE2EDisconnectResume` | This is the happy path test for the suspend and resume feature. This test creates an OTA update and starts the update. It then connects to AWS IoT Core with the same client ID (thing name) and credentials. AWS IoT Core then disconnects the device. The device is expected to detect that it is disconnected from AWS IoT Core, and after a period of time, move itself to a suspended state and try to reconnect to AWS IoT Core and resume the download. | 
| `OTAE2EDisconnectCancelUpdate` | This test checks if the device can recover itself if the OTA job gets canceled while it is in a suspended state. It does the same thing as the `OTAE2EDisconnectResume` test, except that after connecting to AWS IoT Core, which disconnects the device, it cancels the OTA update. A new update is created. The device is expected to reconnect to the AWS IoT Core, abort the current update, go back to waiting state, and accept and finish the next update. | 
| `OTAE2EPresignedUrlExpired` | When an OTA update is created, you can configure the lifetime of the S3 pre-signed url. This test verifies that the device is able to perform an OTA, even if it cannot finish the download when the url expires. The device is expected to request a new job document, which contains a new url to resume the download. | 
| `OTAE2E2UpdatesCancel1st` | This test creates two OTA updates in a row. When the device reports that it is downloading the first update, the test force-cancels the first update. The device is expected to abort the current update and pick up the second update, and complete it. | 
| `OTAE2ECancelThenUpdate` | This test creates two OTA updates in a row. When the device reports that it is downloading the first update, the test force-cancels the first update. The device is expected to abort the current update and pick up the second update, then complete it. | 
| `OTAE2EImageCrashed` | This test checks that the device is able to reject an update when the image crashes. | 

### PAL tests
<a name="porting-ota-pal"></a>

#### Prerequisites
<a name="pal-prereqs"></a>

To port the Network Transport Interface tests, you need the following:
+ A project that can build FreeRTOS with a valid FreeRTOS kernel port.
+ A working implementation of OTA PAL.

#### Porting
<a name="pal-porting"></a>
+ Add [FreeRTOS-Libraries-Integration-Tests](https://github.com/FreeRTOS/FreeRTOS-Libraries-Integration-Tests) as a submodule into your project. The location of the submodule in the project must be where it can be built.
+ Copy `config_template/test_execution_config_template.h` and `config_template/test_param_config_template.h` to a location in the build path, and rename them to `test_execution_config.h` and `test_param_config.h`.
+ Include relevant files in the build system. If using `CMake`, `qualification_test.cmake` and `src/ota_pal_tests.cmake` can be used to include relevant files.
+ Configure the test by implementing the following functions:
  + `SetupOtaPalTestParam()`: defined in `src/ota/ota_pal_test.h`. The implementation must have the same name and signature as defined in `ota_pal_test.h`. Currently, you do not need to configure this function.
+ Implement **UNITY\$1OUTPUT\$1CHAR** so that test output logs do not interleave with device logs.
+ Call `RunQualificationTest()` from the application. The device hardware must be properly initialized, and the network must be connected before the call.

#### Testing
<a name="ota-testing"></a>

This section describes the local testing of the OTA PAL qualification tests.

##### Enable the test
<a name="ota-testing-enabling"></a>

Open `test_execution_config.h` and define **OTA\$1PAL\$1TEST\$1ENABLED** to 1.

In `test_param_config.h`, update the following options:
+ **OTA\$1PAL\$1TEST\$1CERT\$1TYPE**: Select the certificate type used.
+ **OTA\$1PAL\$1CERTIFICATE\$1FILE**: Path to the device certificate, if applicable.
+ **OTA\$1PAL\$1FIRMWARE\$1FILE**: Name of the firmware file, if applicable.
+ **OTA\$1PAL\$1USE\$1FILE\$1SYSTEM**: Set to 1 if the OTA PAL uses file system abstraction.

Build and flash the application using a tool chain of your choice. When the `RunQualificationTest()` is called, the OTA PAL tests will run. The test results are output to the serial port.

### Integrating OTA tasks
<a name="integrating-ota"></a>
+ Add OTA agent to your current MQTT demo.
+ Run OTA End to End (E2E) tests with AWS IoT. This verifies if the integration is working as expected.

**Note**  
To officially qualify a device for FreeRTOS, you must validate the device's ported source code against OTA PAL and OTA E2E test groups with AWS IoT Device Tester. Follow the instructions in [Using AWS IoT Device Tester for FreeRTOS](https://docs.aws.amazon.com/freertos/latest/userguide/device-tester-for-freertos-ug.html) in the *FreeRTOS User Guide* to set up AWS IoT Device Tester for port validation. To test a specific library's port, the correct test group must be enabled in the `device.json` file in the AWS IoT Device Tester `configs` folder.

## IoT device bootloader
<a name="afr-bootloader"></a>

You must provide your own secure bootloader application. Make sure that the design and implementation provide proper mitigation to security threats. Below is the threat modeling for your reference.

### Threat modeling for the IoT device bootloader
<a name="afr-threat-model-for-bootloader"></a>

#### Background
<a name="afr-threat-model-for-bootloader-background"></a>

As a working definition, the embedded AWS IoT devices referenced by this threat model are microcontroller-based products that interact with cloud services. They may be deployed in consumer, commercial, or industrial settings. IoT devices may gather data about a user, a patient, a machine, or an environment, and may control anything from light bulbs and door locks to factory machinery.

Threat modeling is an approach to security from the point of view of a hypothetical adversary. By considering the adversary's goals and methods, a threat list is created. Threats are attacks against a resource or asset performed by an adversary. The list is prioritized and used to identify and create mitigation solutions. When choosing a mitigation solution, the cost of implementing and maintaining it should be balanced with the real security value it provides. There are multiple [threat model methodologies](https://en.wikipedia.org/wiki/Threat_model). Each is capable of supporting the development of a secure and successful AWS IoT product.

FreeRTOS offers OTA (over-the-air) software updates to AWS IoT devices. The update facility combines cloud services with on-device software libraries and a partner-supplied bootloader. This threat model focuses specifically on threats against the bootloader.

**Bootloader use cases**
+ Digitally sign and encrypt firmware before deployment.
+ Deploy new firmware images to a single device, a group of devices, or an entire fleet.
+ Verify the authenticity and integrity of new firmware after it's deployed to devices.
+ Devices only run unmodified software from a trusted source.
+ Devices are resilient to faulty software received through OTA.

**Data Flow Diagram**

![\[Data Flow Diagram for Embedded Device Security that contains Physical Access, Embedded Device, Internet Boundary, and other components.\]](http://docs.aws.amazon.com/freertos/latest/portingguide/images/bootloader-dataflow-diagram.png)


#### Threats
<a name="afr-threat-model-for-bootloader-threats"></a>

Some attacks have multiple mitigation models; for example, a network man-in-the-middle intended to deliver a malicious firmware image is mitigated by verifying trust in both the certificate offered by the TLS server, and the code-signer certificate of the new firmware image. To maximize the security of the bootloader, any non-bootloader mitigation solutions are considered unreliable. The bootloader should have intrinsic mitigation solutions for each attack. Having layered mitigation solutions are known as defense-in-depth.

**Threats:**
+ An attacker hijacks the device's connection to the server to deliver a malicious firmware image.

**Mitigation example**
  + Upon boot, the bootloader verifies the cryptographic signature of the image using a known certificate. If the verification fails, the bootloader rolls back to the previous image.
+ An attacker exploits a buffer overflow to introduce malicious behavior to the existing firmware image stored in flash.

**Mitigation examples**
  + Upon boot, the bootloader verifies, as previously described. When verification fails with no previous image available, the bootloader halts.
  + Upon boot, the bootloader verifies, as previously described. When verification fails with no previous image available, the bootloader enters a fail safe OTA only mode.
+ An attacker boots the device to a previously stored image, which is exploitable.

**Mitigation examples**
  + Flash sectors storing the last image are erased upon successful installation and test of a new image.
  + A fuse is burned with each successful upgrade, and each image refuses to run unless the correct number of fuses have been burned.
+ An OTA update delivers a faulty or malicious image that bricks the device.

**Mitigation example**
  + The bootloader starts a hardware watchdog timer that triggers rollback to the previous image.
+ An attacker patches the bootloader to bypass image verification so the device will accept unsigned images.

**Mitigation examples**
  + The bootloader is in ROM (read-only memory), and cannot be modified.
  + The bootloader is in OTP (one-time-programmable memory), and cannot be modified.
  + The bootloader is in the secure zone of ARM TrustZone, and cannot be modified.
+ An attacker replaces the verification certificate so the device will accept malicious images.

**Mitigation examples**
  + The certificate is in a cryptographic co-processor, and cannot be modified.
  + The certificate is in ROM (or OTP, or secure zone), and cannot be modified.

#### Further threat modeling
<a name="afr-threat-model-for-bootloader-further"></a>

This threat model considers only the bootloader. Further threat modeling could improve overall security. A recommended method is to list the adversary's goals, the assets targeted by those goals, and points of entry to the assets. A list of threats can be made by considering attacks on the points of entry to gain control of the assets. The following are lists of examples of goals, assets, and entry points for an IoT device. These lists are not exhaustive, and are intended to spur further thought.

**Adversary's goals**
+ Extort money 
+ Ruin reputations 
+ Falsify data 
+ Divert resources 
+ Remotely spy on a target 
+ Gain physical access to a site 
+ Wreak havoc
+ Instill terror 

**Key assets**
+ Private keys 
+ Client certificate 
+ CA root certificates 
+ Security credentials and tokens 
+ Customer's personally identifiable information 
+ Implementations of trade secrets 
+ Sensor data 
+ Cloud analytics data store 
+ Cloud infrastructure 

**Entry points**
+ DHCP response 
+ DNS response 
+ MQTT over TLS 
+ HTTPS response 
+ OTA software image 
+ Other, as dictated by application, for example, USB 
+ Physical access to bus 
+ Decapped IC 

# Porting the Cellular Interface library
<a name="freertos-porting-cellular"></a>

FreeRTOS supports the AT commands of a TCP offloaded cellular abstraction layer. For more information, see the [Cellular Interface Library](https://freertos.org/cellular/index.html) and [Porting the Cellular Interface Library](https://freertos.org/cellular-porting-guide.html) on freertos.org.

## Prerequisites
<a name="freertos-porting-cellular-prereqs"></a>

There is no direct dependency for the Cellular Interface library. However, in the FreeRTOS network stack, Ethernet, Wi-Fi and cellular cannot co-exist, so developers must choose one of them to integrate with the [Porting the Network Transport Interface](afr-porting-network-transport-interface.md).

**Note**  
If the cellular module is able to support TLS offload, or does not support AT commands, developers can implement their own cellular abstraction to integrate with the [Porting the Network Transport Interface](afr-porting-network-transport-interface.md).