From bd9db07f28a03c6b466f8465beb225f44d3678ec Mon Sep 17 00:00:00 2001 From: Oscar Michael Abrina Date: Fri, 2 Oct 2020 20:26:02 -0700 Subject: [PATCH] Add submodules for coreMQTT, coreJSON, and Device Shadow along with platform dependencies (#311) This adds coreMQTT, coreJSON, and Device Shadow as submodules to the following directories: coreMQTT: FreeRTOS-Plus/Source/Application-Protocols/coreMQTT coreJSON: FreeRTOS-Plus/Source/coreJSON Device Shadow: FreeRTOS/FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk Platform sources and includes that are utilized by these libraries are also moved from lts-development branch to master: FreeRTOS-Plus/Source/FreeRTOS-IoT-Libraries-LTS-Beta2/c_sdk/platform (lts-development) -> FreeRTOS-Plus/Source/Application-Protocols/platform (master) Co-authored-by: abhidixi11 <44424462+abhidixi11@users.noreply.github.com> Co-authored-by: leegeth <51681119+leegeth@users.noreply.github.com> Co-authored-by: Muneeb Ahmed <54290492+muneebahmed10@users.noreply.github.com> Co-authored-by: Carl Lundin <53273776+lundinc2@users.noreply.github.com> --- .gitmodules | 9 + .../device-shadow-for-aws-iot-embedded-sdk | 1 + .../Source/Application-Protocols/coreMQTT | 1 + .../freertos/mbedtls/mbedtls_freertos_port.c | 286 ++++++ .../platform/freertos/mbedtls/threading_alt.h | 54 + .../retry_utils/retry_utils_freertos.c | 101 ++ .../include/freertos_sockets_wrapper.h | 85 ++ .../transport/include/plaintext_freertos.h | 127 +++ .../freertos/transport/include/tls_freertos.h | 202 ++++ .../transport/include/tls_freertos_pkcs11.h | 213 ++++ .../transport/src/freertos_sockets_wrapper.c | 168 +++ .../transport/src/plaintext_freertos.c | 122 +++ .../freertos/transport/src/tls_freertos.c | 625 ++++++++++++ .../transport/src/tls_freertos_pkcs11.c | 956 ++++++++++++++++++ .../platform/include/retry_utils.h | 245 +++++ .../platform/include/transport_interface.h | 72 ++ FreeRTOS-Plus/Source/coreJSON | 1 + 17 files changed, 3268 insertions(+) create mode 160000 FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk create mode 160000 FreeRTOS-Plus/Source/Application-Protocols/coreMQTT create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/mbedtls_freertos_port.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/threading_alt.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/retry_utils/retry_utils_freertos.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/freertos_sockets_wrapper.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/plaintext_freertos.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos_pkcs11.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/freertos_sockets_wrapper.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/plaintext_freertos.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos_pkcs11.c create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/include/retry_utils.h create mode 100644 FreeRTOS-Plus/Source/Application-Protocols/platform/include/transport_interface.h create mode 160000 FreeRTOS-Plus/Source/coreJSON diff --git a/.gitmodules b/.gitmodules index 56038c1026..2baf0c4c6a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,12 @@ [submodule "FreeRTOS/Test/CMock/CMock"] path = FreeRTOS/Test/CMock/CMock url = https://github.com/ThrowTheSwitch/CMock.git +[submodule "FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk"] + path = FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk + url = https://github.com/aws/device-shadow-for-aws-iot-embedded-sdk +[submodule "FreeRTOS-Plus/Source/Application-Protocols/coreMQTT"] + path = FreeRTOS-Plus/Source/Application-Protocols/coreMQTT + url = https://github.com/FreeRTOS/coreMQTT +[submodule "FreeRTOS-Plus/Source/coreJSON"] + path = FreeRTOS-Plus/Source/coreJSON + url = https://github.com/FreeRTOS/coreJSON diff --git a/FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk b/FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk new file mode 160000 index 0000000000..664d4e75cc --- /dev/null +++ b/FreeRTOS-Plus/Source/AWS/device-shadow-for-aws-iot-embedded-sdk @@ -0,0 +1 @@ +Subproject commit 664d4e75cc4b643a033570afc48ffb93af1c5864 diff --git a/FreeRTOS-Plus/Source/Application-Protocols/coreMQTT b/FreeRTOS-Plus/Source/Application-Protocols/coreMQTT new file mode 160000 index 0000000000..eaa612145e --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/coreMQTT @@ -0,0 +1 @@ +Subproject commit eaa612145ec7a6554a4ea07324e2783ae0ab0a96 diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/mbedtls_freertos_port.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/mbedtls_freertos_port.c new file mode 100644 index 0000000000..7516c16506 --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/mbedtls_freertos_port.c @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * @file mbedtls_freertos_port.c + * @brief Implements mbed TLS platform functions for FreeRTOS. + */ + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "FreeRTOS_Sockets.h" + +/* mbed TLS includes. */ +#include "mbedtls_config.h" +#include "threading_alt.h" +#include "mbedtls/entropy.h" + +/*-----------------------------------------------------------*/ + +/** + * @brief Allocates memory for an array of members. + * + * @param[in] nmemb Number of members that need to be allocated. + * @param[in] size Size of each member. + * + * @return Pointer to the beginning of newly allocated memory. + */ +void * mbedtls_platform_calloc( size_t nmemb, + size_t size ) +{ + size_t totalSize = nmemb * size; + void * pBuffer = NULL; + + /* Check that neither nmemb nor size were 0. */ + if( totalSize > 0 ) + { + /* Overflow check. */ + if( totalSize / size == nmemb ) + { + pBuffer = pvPortMalloc( totalSize ); + + if( pBuffer != NULL ) + { + ( void ) memset( pBuffer, 0x00, totalSize ); + } + } + } + + return pBuffer; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Frees the space previously allocated by calloc. + * + * @param[in] ptr Pointer to the memory to be freed. + */ +void mbedtls_platform_free( void * ptr ) +{ + vPortFree( ptr ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Sends data over FreeRTOS+TCP sockets. + * + * @param[in] ctx The network context containing the socket handle. + * @param[in] buf Buffer containing the bytes to send. + * @param[in] len Number of bytes to send from the buffer. + * + * @return Number of bytes sent on success; else a negative value. + */ +int mbedtls_platform_send( void * ctx, + const unsigned char * buf, + size_t len ) +{ + Socket_t socket; + + configASSERT( ctx != NULL ); + configASSERT( buf != NULL ); + + socket = ( Socket_t ) ctx; + + return ( int ) FreeRTOS_send( socket, buf, len, 0 ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Receives data from FreeRTOS+TCP socket. + * + * @param[in] ctx The network context containing the socket handle. + * @param[out] buf Buffer to receive bytes into. + * @param[in] len Number of bytes to receive from the network. + * + * @return Number of bytes received if successful; Negative value on error. + */ +int mbedtls_platform_recv( void * ctx, + unsigned char * buf, + size_t len ) +{ + Socket_t socket; + + configASSERT( ctx != NULL ); + configASSERT( buf != NULL ); + + socket = ( Socket_t ) ctx; + + return ( int ) FreeRTOS_recv( socket, buf, len, 0 ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Creates a mutex. + * + * @param[in, out] pMutex mbedtls mutex handle. + */ +void mbedtls_platform_mutex_init( mbedtls_threading_mutex_t * pMutex ) +{ + configASSERT( pMutex != NULL ); + + /* Create a statically-allocated FreeRTOS mutex. This should never fail as + * storage is provided. */ + pMutex->mutexHandle = xSemaphoreCreateMutexStatic( &( pMutex->mutexStorage ) ); + configASSERT( pMutex->mutexHandle != NULL ); +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Frees a mutex. + * + * @param[in] pMutex mbedtls mutex handle. + * + * @note This function is an empty stub as nothing needs to be done to free + * a statically allocated FreeRTOS mutex. + */ +void mbedtls_platform_mutex_free( mbedtls_threading_mutex_t * pMutex ) +{ + /* Nothing needs to be done to free a statically-allocated FreeRTOS mutex. */ + ( void ) pMutex; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Function to lock a mutex. + * + * @param[in] pMutex mbedtls mutex handle. + * + * @return 0 (success) is always returned as any other failure is asserted. + */ +int mbedtls_platform_mutex_lock( mbedtls_threading_mutex_t * pMutex ) +{ + BaseType_t mutexStatus = 0; + + configASSERT( pMutex != NULL ); + + /* mutexStatus is not used if asserts are disabled. */ + ( void ) mutexStatus; + + /* This function should never fail if the mutex is initialized. */ + mutexStatus = xSemaphoreTake( pMutex->mutexHandle, portMAX_DELAY ); + configASSERT( mutexStatus == pdTRUE ); + + return 0; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Function to unlock a mutex. + * + * @param[in] pMutex mbedtls mutex handle. + * + * @return 0 is always returned as any other failure is asserted. + */ +int mbedtls_platform_mutex_unlock( mbedtls_threading_mutex_t * pMutex ) +{ + BaseType_t mutexStatus = 0; + + configASSERT( pMutex != NULL ); + /* mutexStatus is not used if asserts are disabled. */ + ( void ) mutexStatus; + + /* This function should never fail if the mutex is initialized. */ + mutexStatus = xSemaphoreGive( pMutex->mutexHandle ); + configASSERT( mutexStatus == pdTRUE ); + + return 0; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Function to generate a random number. + * + * @param[in] data Callback context. + * @param[out] output The address of the buffer that receives the random number. + * @param[in] len Maximum size of the random number to be generated. + * @param[out] olen The size, in bytes, of the #output buffer. + * + * @return 0 if no critical failures occurred, + * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise. + */ +int mbedtls_platform_entropy_poll( void * data, + unsigned char * output, + size_t len, + size_t * olen ) +{ + int status = 0; + NTSTATUS rngStatus = 0; + + configASSERT( output != NULL ); + configASSERT( olen != NULL ); + + /* Context is not used by this function. */ + ( void ) data; + + /* TLS requires a secure random number generator; use the RNG provided + * by Windows. This function MUST be re-implemented for other platforms. */ + rngStatus = + BCryptGenRandom( NULL, output, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG ); + + if( rngStatus == 0 ) + { + /* All random bytes generated. */ + *olen = len; + } + else + { + /* RNG failure. */ + *olen = 0; + status = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED; + } + + return status; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Function to generate a random number based on a hardware poll. + * + * For this FreeRTOS Windows port, this function is redirected by calling + * #mbedtls_platform_entropy_poll. + * + * @param[in] data Callback context. + * @param[out] output The address of the buffer that receives the random number. + * @param[in] len Maximum size of the random number to be generated. + * @param[out] olen The size, in bytes, of the #output buffer. + * + * @return 0 if no critical failures occurred, + * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise. + */ +int mbedtls_hardware_poll( void * data, + unsigned char * output, + size_t len, + size_t * olen ) +{ + return mbedtls_platform_entropy_poll( data, output, len, olen ); +} + +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/threading_alt.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/threading_alt.h new file mode 100644 index 0000000000..799ca5f5c3 --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/mbedtls/threading_alt.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file threading_alt.h + * @brief mbed TLS threading functions implemented for FreeRTOS. + */ + + +#ifndef MBEDTLS_THREADING_ALT_H_ +#define MBEDTLS_THREADING_ALT_H_ + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "semphr.h" + +/** + * @brief mbed TLS mutex type. + * + * mbed TLS requires platform specific definition for the mutext type. Defining the type for + * FreeRTOS with FreeRTOS semaphore + * handle and semaphore storage as members. + */ +typedef struct mbedtls_threading_mutex +{ + SemaphoreHandle_t mutexHandle; + StaticSemaphore_t mutexStorage; +} mbedtls_threading_mutex_t; + +/* mbed TLS mutex functions. */ +void mbedtls_platform_mutex_init( mbedtls_threading_mutex_t * pMutex ); +void mbedtls_platform_mutex_free( mbedtls_threading_mutex_t * pMutex ); +int mbedtls_platform_mutex_lock( mbedtls_threading_mutex_t * pMutex ); +int mbedtls_platform_mutex_unlock( mbedtls_threading_mutex_t * pMutex ); + +#endif /* ifndef MBEDTLS_THREADING_ALT_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/retry_utils/retry_utils_freertos.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/retry_utils/retry_utils_freertos.c new file mode 100644 index 0000000000..39c58cfd2f --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/retry_utils/retry_utils_freertos.c @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file retry_utils_freertos.c + * @brief Utility implementation of backoff logic, used for attempting retries of failed processes. + */ + +/* Standard includes. */ +#include + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" + +#include "retry_utils.h" + +#define _MILLISECONDS_PER_SECOND ( 1000U ) /**< @brief Milliseconds per second. */ + +extern UBaseType_t uxRand( void ); + +/*-----------------------------------------------------------*/ + +RetryUtilsStatus_t RetryUtils_BackoffAndSleep( RetryUtilsParams_t * pRetryParams ) +{ + RetryUtilsStatus_t status = RetryUtilsRetriesExhausted; + int32_t backOffDelayMs = 0; + + /* If pRetryParams->maxRetryAttempts is set to 0, try forever. */ + if( ( pRetryParams->attemptsDone < pRetryParams->maxRetryAttempts ) || + ( 0 == pRetryParams->maxRetryAttempts ) ) + { + /* Choose a random value for back-off time between 0 and the max jitter value. */ + backOffDelayMs = uxRand() % pRetryParams->nextJitterMax; + + /* Wait for backoff time to expire for the next retry. */ + vTaskDelay( pdMS_TO_TICKS( backOffDelayMs * _MILLISECONDS_PER_SECOND ) ); + + /* Increment backoff counts. */ + pRetryParams->attemptsDone++; + + /* Double the max jitter value for the next retry attempt, only + * if the new value will be less than the max backoff time value. */ + if( pRetryParams->nextJitterMax < ( MAX_RETRY_BACKOFF_SECONDS / 2U ) ) + { + pRetryParams->nextJitterMax += pRetryParams->nextJitterMax; + } + else + { + pRetryParams->nextJitterMax = MAX_RETRY_BACKOFF_SECONDS; + } + + status = RetryUtilsSuccess; + } + else + { + /* When max retry attempts are exhausted, let application know by + * returning RetryUtilsRetriesExhausted. Application may choose to + * restart the retry process after calling RetryUtils_ParamsReset(). */ + status = RetryUtilsRetriesExhausted; + RetryUtils_ParamsReset( pRetryParams ); + } + + return status; +} + +/*-----------------------------------------------------------*/ + +void RetryUtils_ParamsReset( RetryUtilsParams_t * pRetryParams ) +{ + uint32_t jitter = 0; + + /* Reset attempts done to zero so that the next retry cycle can start. */ + pRetryParams->attemptsDone = 0; + + /* Calculate jitter value using picking a random number. */ + jitter = ( uxRand() % MAX_JITTER_VALUE_SECONDS ); + + /* Reset the backoff value to the initial time out value plus jitter. */ + pRetryParams->nextJitterMax = INITIAL_RETRY_BACKOFF_SECONDS + jitter; +} + +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/freertos_sockets_wrapper.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/freertos_sockets_wrapper.h new file mode 100644 index 0000000000..445349862a --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/freertos_sockets_wrapper.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file freertos_sockets_wrapper.h + * @brief FreeRTOS Sockets connect and disconnect function wrapper. + */ + +#ifndef FREERTOS_SOCKETS_WRAPPER_H_ +#define FREERTOS_SOCKETS_WRAPPER_H_ + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Logging related header files are required to be included in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. + * 3. Include the header file "logging_stack.h". + */ + +/* Include header that defines log levels. */ +#include "logging_levels.h" + +/* Logging configuration for the Sockets. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "Sockets" +#endif +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#include "logging_stack.h" + +/************ End of logging configuration ****************/ + +/** + * @brief Establish a connection to server. + * + * @param[out] pTcpSocket The output parameter to return the created socket descriptor. + * @param[in] pHostName Server hostname to connect to. + * @param[in] pServerInfo Server port to connect to. + * @param[in] receiveTimeoutMs Timeout (in milliseconds) for transport receive. + * @param[in] sendTimeoutMs Timeout (in milliseconds) for transport send. + * + * @note A timeout of 0 means infinite timeout. + * + * @return Non-zero value on error, 0 on success. + */ +BaseType_t Sockets_Connect( Socket_t * pTcpSocket, + const char * pHostName, + uint16_t port, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ); + +/** + * @brief End connection to server. + * + * @param[in] tcpSocket The socket descriptor. + */ +void Sockets_Disconnect( Socket_t tcpSocket ); + +#endif /* ifndef FREERTOS_SOCKETS_WRAPPER_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/plaintext_freertos.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/plaintext_freertos.h new file mode 100644 index 0000000000..c109aa578d --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/plaintext_freertos.h @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef TRANSPORT_INTERFACE_FREERTOS_H_ +#define TRANSPORT_INTERFACE_FREERTOS_H_ + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Logging related header files are required to be included in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. + * 3. Include the header file "logging_stack.h". + */ + +/* Include header that defines log levels. */ +#include "logging_levels.h" + +/* Logging configuration for the Sockets. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "PlaintextTransport" +#endif +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#include "logging_stack.h" + +/************ End of logging configuration ****************/ + +/* Transport interface include. */ +#include "transport_interface.h" + +/** + * @brief Network context definition for FreeRTOS sockets. + */ +struct NetworkContext +{ + Socket_t tcpSocket; +}; + +/** + * @brief Plain text transport Connect / Disconnect return status. + */ +typedef enum PlaintextTransportStatus +{ + PLAINTEXT_TRANSPORT_SUCCESS = 1, /**< Function successfully completed. */ + PLAINTEXT_TRANSPORT_INVALID_PARAMETER = 2, /**< At least one parameter was invalid. */ + PLAINTEXT_TRANSPORT_CONNECT_FAILURE = 3 /**< Initial connection to the server failed. */ +} PlaintextTransportStatus_t; + +/** + * @brief Create a TCP connection with FreeRTOS sockets. + * + * @param[out] pNetworkContext Pointer to a network context to contain the + * initialized socket handle. + * @param[in] pHostName The hostname of the remote endpoint. + * @param[in] port The destination port. + * @param[in] receiveTimeoutMs Receive socket timeout. + * + * @return #PLAINTEXT_TRANSPORT_SUCCESS, #PLAINTEXT_TRANSPORT_INVALID_PARAMETER, + * or #PLAINTEXT_TRANSPORT_CONNECT_FAILURE. + */ +PlaintextTransportStatus_t Plaintext_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ); + +/** + * @brief Gracefully disconnect an established TCP connection. + * + * @param[in] pNetworkContext Network context containing the TCP socket handle. + * + * @return #PLAINTEXT_TRANSPORT_SUCCESS, or #PLAINTEXT_TRANSPORT_INVALID_PARAMETER. + */ +PlaintextTransportStatus_t Plaintext_FreeRTOS_Disconnect( const NetworkContext_t * pNetworkContext ); + +/** + * @brief Receives data from an established TCP connection. + * + * @param[in] pNetworkContext The network context containing the TCP socket + * handle. + * @param[out] pBuffer Buffer to receive bytes into. + * @param[in] bytesToRecv Number of bytes to receive from the network. + * + * @return Number of bytes received if successful; 0 if the socket times out; + * Negative value on error. + */ +int32_t Plaintext_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ); + +/** + * @brief Sends data over an established TCP connection. + * + * @param[in] pNetworkContext The network context containing the TCP socket + * handle. + * @param[in] pBuffer Buffer containing the bytes to send. + * @param[in] bytesToSend Number of bytes to send from the buffer. + * + * @return Number of bytes sent on success; else a negative value. + */ +int32_t Plaintext_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ); + +#endif /* ifndef TRANSPORT_INTERFACE_FREERTOS_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos.h new file mode 100644 index 0000000000..f6355bea0c --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos.h @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file tls_freertos.h + * @brief TLS transport interface header. + */ + +#ifndef TLS_FREERTOS_H_ +#define TLS_FREERTOS_H_ + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Logging related header files are required to be included in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. + * 3. Include the header file "logging_stack.h". + */ + +/* Include header that defines log levels. */ +#include "logging_levels.h" + +/* Logging configuration for the Sockets. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "TlsTransport" +#endif +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#include "logging_stack.h" + +/************ End of logging configuration ****************/ + +/* FreeRTOS+TCP include. */ +#include "FreeRTOS_Sockets.h" + +/* Transport interface include. */ +#include "transport_interface.h" + +/* mbed TLS includes. */ +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ssl.h" +#include "mbedtls/threading.h" +#include "mbedtls/x509.h" + +/** + * @brief Secured connection context. + */ +typedef struct SSLContext +{ + mbedtls_ssl_config config; /**< @brief SSL connection configuration. */ + mbedtls_ssl_context context; /**< @brief SSL connection context */ + mbedtls_x509_crt_profile certProfile; /**< @brief Certificate security profile for this connection. */ + mbedtls_x509_crt rootCa; /**< @brief Root CA certificate context. */ + mbedtls_x509_crt clientCert; /**< @brief Client certificate context. */ + mbedtls_pk_context privKey; /**< @brief Client private key context. */ +} SSLContext_t; + +/** + * @brief Definition of the network context for the transport interface + * implementation that uses mbedTLS and FreeRTOS+TLS sockets. + */ +struct NetworkContext +{ + Socket_t tcpSocket; + SSLContext_t sslContext; +}; + +/** + * @brief Contains the credentials necessary for tls connection setup. + */ +typedef struct NetworkCredentials +{ + /** + * @brief Set this to a non-NULL value to use ALPN. + * + * This string must be NULL-terminated. + * + * See [this link] + * (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/) + * for more information. + */ + const char * pAlpnProtos; + + /** + * @brief Disable server name indication (SNI) for a TLS session. + */ + BaseType_t disableSni; + + const unsigned char * pRootCa; /**< @brief String representing a trusted server root certificate. */ + size_t rootCaSize; /**< @brief Size associated with #IotNetworkCredentials.pRootCa. */ + const unsigned char * pClientCert; /**< @brief String representing the client certificate. */ + size_t clientCertSize; /**< @brief Size associated with #IotNetworkCredentials.pClientCert. */ + const unsigned char * pPrivateKey; /**< @brief String representing the client certificate's private key. */ + size_t privateKeySize; /**< @brief Size associated with #IotNetworkCredentials.pPrivateKey. */ + const unsigned char * pUserName; /**< @brief String representing the username for MQTT. */ + size_t userNameSize; /**< @brief Size associated with #IotNetworkCredentials.pUserName. */ + const unsigned char * pPassword; /**< @brief String representing the password for MQTT. */ + size_t passwordSize; /**< @brief Size associated with #IotNetworkCredentials.pPassword. */ +} NetworkCredentials_t; + +/** + * @brief TLS Connect / Disconnect return status. + */ +typedef enum TlsTransportStatus +{ + TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */ + TLS_TRANSPORT_INVALID_PARAMETER, /**< At least one parameter was invalid. */ + TLS_TRANSPORT_INSUFFICIENT_MEMORY, /**< Insufficient memory required to establish connection. */ + TLS_TRANSPORT_INVALID_CREDENTIALS, /**< Provided credentials were invalid. */ + TLS_TRANSPORT_HANDSHAKE_FAILED, /**< Performing TLS handshake with server failed. */ + TLS_TRANSPORT_INTERNAL_ERROR, /**< A call to a system API resulted in an internal error. */ + TLS_TRANSPORT_CONNECT_FAILURE /**< Initial connection to the server failed. */ +} TlsTransportStatus_t; + +/** + * @brief Create a TLS connection with FreeRTOS sockets. + * + * @param[out] pNetworkContext Pointer to a network context to contain the + * initialized socket handle. + * @param[in] pHostName The hostname of the remote endpoint. + * @param[in] port The destination port. + * @param[in] pNetworkCredentials Credentials for the TLS connection. + * @param[in] receiveTimeoutMs Receive socket timeout. + * @param[in] sendTimeoutMs Send socket timeout. + * + * @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS, + * #TLS_TRANSPORT_HANDSHAKE_FAILED, #TLS_TRANSPORT_INTERNAL_ERROR, or #TLS_TRANSPORT_CONNECT_FAILURE. + */ +TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + const NetworkCredentials_t * pNetworkCredentials, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ); + +/** + * @brief Gracefully disconnect an established TLS connection. + * + * @param[in] pNetworkContext Network context. + */ +void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext ); + +/** + * @brief Receives data from an established TLS connection. + * + * This is the TLS version of the transport interface's + * #TransportRecv_t function. + * + * @param[in] pNetworkContext The Network context. + * @param[out] pBuffer Buffer to receive bytes into. + * @param[in] bytesToRecv Number of bytes to receive from the network. + * + * @return Number of bytes (> 0) received if successful; + * 0 if the socket times out without reading any bytes; + * negative value on error. + */ +int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ); + +/** + * @brief Sends data over an established TLS connection. + * + * This is the TLS version of the transport interface's + * #TransportSend_t function. + * + * @param[in] pNetworkContext The network context. + * @param[in] pBuffer Buffer containing the bytes to send. + * @param[in] bytesToSend Number of bytes to send from the buffer. + * + * @return Number of bytes (> 0) sent on success; + * 0 if the socket times out without sending any bytes; + * else a negative value to represent error. + */ +int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ); + +#endif /* ifndef TLS_FREERTOS_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos_pkcs11.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos_pkcs11.h new file mode 100644 index 0000000000..f95e1c712f --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/include/tls_freertos_pkcs11.h @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file tls_freertos_pkcs11.h + * @brief TLS transport interface header. + * @note This file is derived from the tls_freertos.h header file found in the mqtt + * section of IoT Libraries source code. The file has been modified to support using + * PKCS #11 when using TLS. + */ + +#ifndef TLS_FREERTOS_H_ +#define TLS_FREERTOS_H_ + +/**************************************************/ +/******* DO NOT CHANGE the following order ********/ +/**************************************************/ + +/* Logging related header files are required to be included in the following order: + * 1. Include the header file "logging_levels.h". + * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. + * 3. Include the header file "logging_stack.h". + */ + +/* Include header that defines log levels. */ +#include "logging_levels.h" + +/* Logging configuration for the Sockets. */ +#ifndef LIBRARY_LOG_NAME + #define LIBRARY_LOG_NAME "PkcsTlsTransport" +#endif +#ifndef LIBRARY_LOG_LEVEL + #define LIBRARY_LOG_LEVEL LOG_ERROR +#endif + +#include "logging_stack.h" + +/************ End of logging configuration ****************/ + +/* FreeRTOS+TCP include. */ +#include "FreeRTOS_Sockets.h" + +/* Transport interface include. */ +#include "transport_interface.h" + +/* mbed TLS includes. */ +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ssl.h" +#include "mbedtls/threading.h" +#include "mbedtls/x509.h" +#include "mbedtls/pk.h" +#include "mbedtls/pk_internal.h" + +/* PKCS #11 includes. */ +#include "iot_pkcs11.h" + +/** + * @brief Secured connection context. + */ +typedef struct SSLContext +{ + mbedtls_ssl_config config; /**< @brief SSL connection configuration. */ + mbedtls_ssl_context context; /**< @brief SSL connection context */ + mbedtls_x509_crt_profile certProfile; /**< @brief Certificate security profile for this connection. */ + mbedtls_x509_crt rootCa; /**< @brief Root CA certificate context. */ + mbedtls_x509_crt clientCert; /**< @brief Client certificate context. */ + mbedtls_pk_context privKey; /**< @brief Client private key context. */ + mbedtls_pk_info_t privKeyInfo; /**< @brief Client private key info. */ + + /* PKCS#11. */ + CK_FUNCTION_LIST_PTR pxP11FunctionList; + CK_SESSION_HANDLE xP11Session; + CK_OBJECT_HANDLE xP11PrivateKey; + CK_KEY_TYPE xKeyType; +} SSLContext_t; + +/** + * @brief Definition of the network context for the transport interface + * implementation that uses mbedTLS and FreeRTOS+TLS sockets. + */ +struct NetworkContext +{ + Socket_t tcpSocket; + SSLContext_t sslContext; +}; + +/** + * @brief Contains the credentials necessary for tls connection setup. + */ +typedef struct NetworkCredentials +{ + /** + * @brief Set this to a non-NULL value to use ALPN. + * + * This string must be NULL-terminated. + * + * See [this link] + * (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/) + * for more information. + */ + const char * pAlpnProtos; + + /** + * @brief Disable server name indication (SNI) for a TLS session. + */ + BaseType_t disableSni; + + const unsigned char * pRootCa; /**< @brief String representing a trusted server root certificate. */ + size_t rootCaSize; /**< @brief Size associated with #IotNetworkCredentials.pRootCa. */ + const unsigned char * pUserName; /**< @brief String representing the username for MQTT. */ + size_t userNameSize; /**< @brief Size associated with #IotNetworkCredentials.pUserName. */ + const unsigned char * pPassword; /**< @brief String representing the password for MQTT. */ + size_t passwordSize; /**< @brief Size associated with #IotNetworkCredentials.pPassword. */ +} NetworkCredentials_t; + +/** + * @brief TLS Connect / Disconnect return status. + */ +typedef enum TlsTransportStatus +{ + TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */ + TLS_TRANSPORT_INVALID_PARAMETER, /**< At least one parameter was invalid. */ + TLS_TRANSPORT_INSUFFICIENT_MEMORY, /**< Insufficient memory required to establish connection. */ + TLS_TRANSPORT_INVALID_CREDENTIALS, /**< Provided credentials were invalid. */ + TLS_TRANSPORT_HANDSHAKE_FAILED, /**< Performing TLS handshake with server failed. */ + TLS_TRANSPORT_INTERNAL_ERROR, /**< A call to a system API resulted in an internal error. */ + TLS_TRANSPORT_CONNECT_FAILURE /**< Initial connection to the server failed. */ +} TlsTransportStatus_t; + +/** + * @brief Create a TLS connection with FreeRTOS sockets. + * + * @param[out] pNetworkContext Pointer to a network context to contain the + * initialized socket handle. + * @param[in] pHostName The hostname of the remote endpoint. + * @param[in] port The destination port. + * @param[in] pNetworkCredentials Credentials for the TLS connection. + * @param[in] receiveTimeoutMs Receive socket timeout. + * @param[in] sendTimeoutMs Send socket timeout. + * + * @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS, + * #TLS_TRANSPORT_HANDSHAKE_FAILED, #TLS_TRANSPORT_INTERNAL_ERROR, or #TLS_TRANSPORT_CONNECT_FAILURE. + */ +TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + const NetworkCredentials_t * pNetworkCredentials, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ); + +/** + * @brief Gracefully disconnect an established TLS connection. + * + * @param[in] pNetworkContext Network context. + */ +void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext ); + +/** + * @brief Receives data from an established TLS connection. + * + * This is the TLS version of the transport interface's + * #TransportRecv_t function. + * + * @param[in] pNetworkContext The Network context. + * @param[out] pBuffer Buffer to receive bytes into. + * @param[in] bytesToRecv Number of bytes to receive from the network. + * + * @return Number of bytes (> 0) received if successful; + * 0 if the socket times out without reading any bytes; + * negative value on error. + */ +int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ); + +/** + * @brief Sends data over an established TLS connection. + * + * This is the TLS version of the transport interface's + * #TransportSend_t function. + * + * @param[in] pNetworkContext The network context. + * @param[in] pBuffer Buffer containing the bytes to send. + * @param[in] bytesToSend Number of bytes to send from the buffer. + * + * @return Number of bytes (> 0) sent on success; + * 0 if the socket times out without sending any bytes; + * else a negative value to represent error. + */ +int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ); + +#endif /* ifndef TLS_FREERTOS_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/freertos_sockets_wrapper.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/freertos_sockets_wrapper.c new file mode 100644 index 0000000000..fc30c9ec7a --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/freertos_sockets_wrapper.c @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file freertos_sockets_wrapper.c + * @brief FreeRTOS Sockets connect and disconnect wrapper implementation. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" + +#include "freertos_sockets_wrapper.h" + +/*-----------------------------------------------------------*/ + +/* Maximum number of times to call FreeRTOS_recv when initiating a graceful shutdown. */ +#ifndef FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS + #define FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS ( 3 ) +#endif + +/* A negative error code indicating a network failure. */ +#define FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR ( -1 ) + +/*-----------------------------------------------------------*/ + +BaseType_t Sockets_Connect( Socket_t * pTcpSocket, + const char * pHostName, + uint16_t port, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ) +{ + Socket_t tcpSocket = FREERTOS_INVALID_SOCKET; + BaseType_t socketStatus = 0; + struct freertos_sockaddr serverAddress = { 0 }; + TickType_t transportTimeout = 0; + + /* Create a new TCP socket. */ + tcpSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM, FREERTOS_IPPROTO_TCP ); + + if( tcpSocket == FREERTOS_INVALID_SOCKET ) + { + LogError( ( "Failed to create new socket." ) ); + socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR; + } + else + { + LogDebug( ( "Created new TCP socket." ) ); + + /* Connection parameters. */ + serverAddress.sin_family = FREERTOS_AF_INET; + serverAddress.sin_port = FreeRTOS_htons( port ); + serverAddress.sin_addr = FreeRTOS_gethostbyname( pHostName ); + serverAddress.sin_len = ( uint8_t ) sizeof( serverAddress ); + + /* Check for errors from DNS lookup. */ + if( serverAddress.sin_addr == 0 ) + { + LogError( ( "Failed to connect to server: DNS resolution failed: Hostname=%s.", + pHostName ) ); + socketStatus = FREERTOS_SOCKETS_WRAPPER_NETWORK_ERROR; + } + } + + if( socketStatus == 0 ) + { + /* Establish connection. */ + LogDebug( ( "Creating TCP Connection to %s.", pHostName ) ); + socketStatus = FreeRTOS_connect( tcpSocket, &serverAddress, sizeof( serverAddress ) ); + + if( socketStatus != 0 ) + { + LogError( ( "Failed to connect to server: FreeRTOS_Connect failed: ReturnCode=%d," + " Hostname=%s, Port=%u.", + socketStatus, + pHostName, + port ) ); + } + } + + if( socketStatus == 0 ) + { + /* Set socket receive timeout. */ + transportTimeout = pdMS_TO_TICKS( receiveTimeoutMs ); + /* Setting the receive block time cannot fail. */ + ( void ) FreeRTOS_setsockopt( tcpSocket, + 0, + FREERTOS_SO_RCVTIMEO, + &transportTimeout, + sizeof( TickType_t ) ); + + /* Set socket send timeout. */ + transportTimeout = pdMS_TO_TICKS( sendTimeoutMs ); + /* Setting the send block time cannot fail. */ + ( void ) FreeRTOS_setsockopt( tcpSocket, + 0, + FREERTOS_SO_SNDTIMEO, + &transportTimeout, + sizeof( TickType_t ) ); + } + + /* Clean up on failure. */ + if( socketStatus != 0 ) + { + if( tcpSocket != FREERTOS_INVALID_SOCKET ) + { + FreeRTOS_closesocket( tcpSocket ); + } + } + else + { + /* Set the socket. */ + *pTcpSocket = tcpSocket; + LogInfo( ( "Established TCP connection with %s.", pHostName ) ); + } + + return socketStatus; +} + +/*-----------------------------------------------------------*/ + +void Sockets_Disconnect( Socket_t tcpSocket ) +{ + BaseType_t waitForShutdownLoopCount = 0; + uint8_t pDummyBuffer[ 2 ]; + + if( tcpSocket != FREERTOS_INVALID_SOCKET ) + { + /* Initiate graceful shutdown. */ + ( void ) FreeRTOS_shutdown( tcpSocket, FREERTOS_SHUT_RDWR ); + + /* Wait for the socket to disconnect gracefully (indicated by FreeRTOS_recv() + * returning a FREERTOS_EINVAL error) before closing the socket. */ + while( FreeRTOS_recv( tcpSocket, pDummyBuffer, sizeof( pDummyBuffer ), 0 ) >= 0 ) + { + /* We don't need to delay since FreeRTOS_recv should already have a timeout. */ + + if( ++waitForShutdownLoopCount >= FREERTOS_SOCKETS_WRAPPER_SHUTDOWN_LOOPS ) + { + break; + } + } + + ( void ) FreeRTOS_closesocket( tcpSocket ); + } +} + +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/plaintext_freertos.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/plaintext_freertos.c new file mode 100644 index 0000000000..189a8b5b3d --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/plaintext_freertos.c @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "atomic.h" +#include "semphr.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" + +/* FreeRTOS Socket wrapper include. */ +#include "freertos_sockets_wrapper.h" + +/* Transport interface include. */ +#include "plaintext_freertos.h" + +PlaintextTransportStatus_t Plaintext_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ) +{ + PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS; + BaseType_t socketStatus = 0; + + if( ( pNetworkContext == NULL ) || ( pHostName == NULL ) ) + { + LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, " + "pHostName=%p.", + pNetworkContext, + pHostName ) ); + plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER; + } + else + { + /* Establish a TCP connection with the server. */ + socketStatus = Sockets_Connect( &( pNetworkContext->tcpSocket ), + pHostName, + port, + receiveTimeoutMs, + sendTimeoutMs ); + + /* A non zero status is an error. */ + if( socketStatus != 0 ) + { + LogError( ( "Failed to connect to %s with error %d.", + pHostName, + socketStatus ) ); + plaintextStatus = PLAINTEXT_TRANSPORT_CONNECT_FAILURE; + } + } + + return plaintextStatus; +} + +PlaintextTransportStatus_t Plaintext_FreeRTOS_Disconnect( const NetworkContext_t * pNetworkContext ) +{ + PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS; + + if( pNetworkContext == NULL ) + { + LogError( ( "pNetworkContext cannot be NULL." ) ); + plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER; + } + else if( pNetworkContext->tcpSocket == FREERTOS_INVALID_SOCKET ) + { + LogError( ( "pNetworkContext->tcpSocket cannot be an invalid socket." ) ); + plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER; + } + else + { + /* Call socket disconnect function to close connection. */ + Sockets_Disconnect( pNetworkContext->tcpSocket ); + } + + return plaintextStatus; +} + +int32_t Plaintext_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ) +{ + int32_t socketStatus = 0; + + socketStatus = FreeRTOS_recv( pNetworkContext->tcpSocket, pBuffer, bytesToRecv, 0 ); + + return socketStatus; +} + +int32_t Plaintext_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ) +{ + int32_t socketStatus = 0; + + socketStatus = FreeRTOS_send( pNetworkContext->tcpSocket, pBuffer, bytesToSend, 0 ); + + return socketStatus; +} diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos.c new file mode 100644 index 0000000000..4e3fece8e8 --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos.c @@ -0,0 +1,625 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file tls_freertos.c + * @brief TLS transport interface implementations. This implementation uses + * mbedTLS. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" + +/* TLS transport header. */ +#include "tls_freertos.h" + +/* FreeRTOS Socket wrapper include. */ +#include "freertos_sockets_wrapper.h" + +/* mbedTLS util includes. */ +#include "mbedtls_error.h" + +/*-----------------------------------------------------------*/ + +/** + * @brief Represents string to be logged when mbedTLS returned error + * does not contain a high-level code. + */ +static const char * pNoHighLevelMbedTlsCodeStr = ""; + +/** + * @brief Represents string to be logged when mbedTLS returned error + * does not contain a low-level code. + */ +static const char * pNoLowLevelMbedTlsCodeStr = ""; + +/** + * @brief Utility for converting the high-level code in an mbedTLS error to string, + * if the code-contains a high-level code; otherwise, using a default string. + */ +#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \ + ( mbedtls_strerror_highlevel( mbedTlsCode ) != NULL ) ? \ + mbedtls_strerror_highlevel( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr + +/** + * @brief Utility for converting the level-level code in an mbedTLS error to string, + * if the code-contains a level-level code; otherwise, using a default string. + */ +#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \ + ( mbedtls_strerror_lowlevel( mbedTlsCode ) != NULL ) ? \ + mbedtls_strerror_lowlevel( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr + +/*-----------------------------------------------------------*/ + +/** + * @brief mbed TLS entropy context for generation of random numbers. + */ +static mbedtls_entropy_context entropyContext; + +/** + * @brief mbed TLS CTR DRBG context for generation of random numbers. + */ +static mbedtls_ctr_drbg_context ctrDrgbContext; + +/*-----------------------------------------------------------*/ + +/** + * @brief Initialize the mbed TLS structures in a network connection. + * + * @param[in] pSslContext The SSL context to initialize. + */ +static void sslContextInit( SSLContext_t * pSslContext ); + +/** + * @brief Free the mbed TLS structures in a network connection. + * + * @param[in] pSslContext The SSL context to free. + */ +static void sslContextFree( SSLContext_t * pSslContext ); + +/** + * @brief Set up TLS on a TCP connection. + * + * @param[in] pNetworkContext Network context. + * @param[in] pHostName Remote host name, used for server name indication. + * @param[in] pNetworkCredentials TLS setup parameters. + * + * @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS, + * #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR. + */ +static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext, + const char * pHostName, + const NetworkCredentials_t * pNetworkCredentials ); + +/** + * @brief Initialize mbedTLS. + * + * @return #TLS_TRANSPORT_SUCCESS, or #TLS_TRANSPORT_INTERNAL_ERROR. + */ +static TlsTransportStatus_t initMbedtls( void ); + +/*-----------------------------------------------------------*/ + +static void sslContextInit( SSLContext_t * pSslContext ) +{ + configASSERT( pSslContext != NULL ); + + mbedtls_ssl_config_init( &( pSslContext->config ) ); + mbedtls_x509_crt_init( &( pSslContext->rootCa ) ); + mbedtls_pk_init( &( pSslContext->privKey ) ); + mbedtls_x509_crt_init( &( pSslContext->clientCert ) ); + mbedtls_ssl_init( &( pSslContext->context ) ); +} +/*-----------------------------------------------------------*/ + +static void sslContextFree( SSLContext_t * pSslContext ) +{ + configASSERT( pSslContext != NULL ); + + mbedtls_ssl_free( &( pSslContext->context ) ); + mbedtls_x509_crt_free( &( pSslContext->rootCa ) ); + mbedtls_x509_crt_free( &( pSslContext->clientCert ) ); + mbedtls_pk_free( &( pSslContext->privKey ) ); + mbedtls_ssl_config_free( &( pSslContext->config ) ); +} + +/*-----------------------------------------------------------*/ + +static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext, + const char * pHostName, + const NetworkCredentials_t * pNetworkCredentials ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + int mbedtlsError = 0; + + configASSERT( pNetworkContext != NULL ); + configASSERT( pHostName != NULL ); + configASSERT( pNetworkCredentials != NULL ); + configASSERT( pNetworkCredentials->pRootCa != NULL ); + + /* Initialize the mbed TLS context structures. */ + sslContextInit( &( pNetworkContext->sslContext ) ); + + mbedtlsError = mbedtls_ssl_config_defaults( &( pNetworkContext->sslContext.config ), + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set default SSL configuration: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + /* Per mbed TLS docs, mbedtls_ssl_config_defaults only fails on memory allocation. */ + returnStatus = TLS_TRANSPORT_INSUFFICIENT_MEMORY; + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Set up the certificate security profile, starting from the default value. */ + pNetworkContext->sslContext.certProfile = mbedtls_x509_crt_profile_default; + + /* test.mosquitto.org only provides a 1024-bit RSA certificate, which is + * not acceptable by the default mbed TLS certificate security profile. + * For the purposes of this demo, allow the use of 1024-bit RSA certificates. + * This block should be removed otherwise. */ + if( strncmp( pHostName, "test.mosquitto.org", strlen( pHostName ) ) == 0 ) + { + pNetworkContext->sslContext.certProfile.rsa_min_bitlen = 1024; + } + + /* Set SSL authmode and the RNG context. */ + mbedtls_ssl_conf_authmode( &( pNetworkContext->sslContext.config ), + MBEDTLS_SSL_VERIFY_REQUIRED ); + mbedtls_ssl_conf_rng( &( pNetworkContext->sslContext.config ), + mbedtls_ctr_drbg_random, + &ctrDrgbContext ); + mbedtls_ssl_conf_cert_profile( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.certProfile ) ); + + /* Parse the server root CA certificate into the SSL context. */ + mbedtlsError = mbedtls_x509_crt_parse( &( pNetworkContext->sslContext.rootCa ), + pNetworkCredentials->pRootCa, + pNetworkCredentials->rootCaSize ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + mbedtls_ssl_conf_ca_chain( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.rootCa ), + NULL ); + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + if( ( pNetworkCredentials->pPrivateKey != NULL ) && ( pNetworkCredentials->pClientCert != NULL ) ) + { + /* Setup the client private key. */ + mbedtlsError = mbedtls_pk_parse_key( &( pNetworkContext->sslContext.privKey ), + pNetworkCredentials->pPrivateKey, + pNetworkCredentials->privateKeySize, + 0, + 0 ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to parse client certificate: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + /* Setup the client certificate. */ + mbedtlsError = mbedtls_x509_crt_parse( &( pNetworkContext->sslContext.clientCert ), + pNetworkCredentials->pClientCert, + pNetworkCredentials->clientCertSize ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to parse the client private key: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + mbedtls_ssl_conf_own_cert( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.clientCert ), + &( pNetworkContext->sslContext.privKey ) ); + } + } + } + } + + if( ( returnStatus == TLS_TRANSPORT_SUCCESS ) && ( pNetworkCredentials->pAlpnProtos != NULL ) ) + { + /* Include an application protocol list in the TLS ClientHello + * message. */ + mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pNetworkContext->sslContext.config ), + ( const char ** ) &( pNetworkCredentials->pAlpnProtos ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Initialize the mbed TLS secured connection context. */ + mbedtlsError = mbedtls_ssl_setup( &( pNetworkContext->sslContext.context ), + &( pNetworkContext->sslContext.config ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set up mbed TLS SSL context: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + else + { + /* Set the underlying IO for the TLS connection. */ + mbedtls_ssl_set_bio( &( pNetworkContext->sslContext.context ), + pNetworkContext->tcpSocket, + mbedtls_platform_send, + mbedtls_platform_recv, + NULL ); + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Enable SNI if requested. */ + if( pNetworkCredentials->disableSni == pdFALSE ) + { + mbedtlsError = mbedtls_ssl_set_hostname( &( pNetworkContext->sslContext.context ), + pHostName ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set server name: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Perform the TLS handshake. */ + do + { + mbedtlsError = mbedtls_ssl_handshake( &( pNetworkContext->sslContext.context ) ); + } while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) || + ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED; + } + } + + if( returnStatus != TLS_TRANSPORT_SUCCESS ) + { + sslContextFree( &( pNetworkContext->sslContext ) ); + } + else + { + LogInfo( ( "(Network connection %p) TLS handshake successful.", + pNetworkContext ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +static TlsTransportStatus_t initMbedtls( void ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + int mbedtlsError = 0; + + /* Set the mutex functions for mbed TLS thread safety. */ + mbedtls_threading_set_alt( mbedtls_platform_mutex_init, + mbedtls_platform_mutex_free, + mbedtls_platform_mutex_lock, + mbedtls_platform_mutex_unlock ); + + /* Initialize contexts for random number generation. */ + mbedtls_entropy_init( &entropyContext ); + mbedtls_ctr_drbg_init( &ctrDrgbContext ); + + /* Add a strong entropy source. At least one is required. */ + mbedtlsError = mbedtls_entropy_add_source( &entropyContext, + mbedtls_platform_entropy_poll, + NULL, + 32, + MBEDTLS_ENTROPY_SOURCE_STRONG ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to add entropy source: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Seed the random number generator. */ + mbedtlsError = mbedtls_ctr_drbg_seed( &ctrDrgbContext, + mbedtls_entropy_func, + &entropyContext, + NULL, + 0 ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to seed PRNG: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + LogDebug( ( "Successfully initialized mbedTLS." ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + const NetworkCredentials_t * pNetworkCredentials, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + BaseType_t socketStatus = 0; + + if( ( pNetworkContext == NULL ) || + ( pHostName == NULL ) || + ( pNetworkCredentials == NULL ) ) + { + LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, " + "pHostName=%p, pNetworkCredentials=%p.", + pNetworkContext, + pHostName, + pNetworkCredentials ) ); + returnStatus = TLS_TRANSPORT_INVALID_PARAMETER; + } + else if( ( pNetworkCredentials->pRootCa == NULL ) ) + { + LogError( ( "pRootCa cannot be NULL." ) ); + returnStatus = TLS_TRANSPORT_INVALID_PARAMETER; + } + + /* Establish a TCP connection with the server. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + socketStatus = Sockets_Connect( &( pNetworkContext->tcpSocket ), + pHostName, + port, + receiveTimeoutMs, + sendTimeoutMs ); + + if( socketStatus != 0 ) + { + LogError( ( "Failed to connect to %s with error %d.", + pHostName, + socketStatus ) ); + returnStatus = TLS_TRANSPORT_CONNECT_FAILURE; + } + } + + /* Initialize mbedtls. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + returnStatus = initMbedtls(); + } + + /* Perform TLS handshake. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials ); + } + + /* Clean up on failure. */ + if( returnStatus != TLS_TRANSPORT_SUCCESS ) + { + if( pNetworkContext->tcpSocket != FREERTOS_INVALID_SOCKET ) + { + FreeRTOS_closesocket( pNetworkContext->tcpSocket ); + } + } + else + { + LogInfo( ( "(Network connection %p) Connection to %s established.", + pNetworkContext, + pHostName ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext ) +{ + BaseType_t tlsStatus = 0; + + /* Attempting to terminate TLS connection. */ + tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pNetworkContext->sslContext.context ) ); + + /* Ignore the WANT_READ and WANT_WRITE return values. */ + if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) && + ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + if( tlsStatus == 0 ) + { + LogInfo( ( "(Network connection %p) TLS close-notify sent.", + pNetworkContext ) ); + } + else + { + LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.", + pNetworkContext, + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + } + else + { + /* WANT_READ and WANT_WRITE can be ignored. Logging for debugging purposes. */ + LogInfo( ( "(Network connection %p) TLS close-notify sent; ", + "received %s as the TLS status can be ignored for close-notify." + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ? "WANT_READ" : "WANT_WRITE", + pNetworkContext ) ); + } + + /* Call socket shutdown function to close connection. */ + Sockets_Disconnect( pNetworkContext->tcpSocket ); + + /* Free mbed TLS contexts. */ + sslContextFree( &( pNetworkContext->sslContext ) ); + + /* Free the contexts for random number generation. */ + mbedtls_ctr_drbg_free( &ctrDrgbContext ); + mbedtls_entropy_free( &entropyContext ); + + /* Clear the mutex functions for mbed TLS thread safety. */ + mbedtls_threading_free_alt(); +} + +/*-----------------------------------------------------------*/ + +int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ) +{ + int32_t tlsStatus = 0; + + tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pNetworkContext->sslContext.context ), + pBuffer, + bytesToRecv ); + + if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + LogDebug( ( "Failed to read data. However, a read can be retried on this error. " + "mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + + /* Mark these set of errors as a timeout. The libraries may retry read + * on these errors. */ + tlsStatus = 0; + } + else if( tlsStatus < 0 ) + { + LogError( ( "Failed to read data: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + else + { + /* Empty else marker. */ + } + + return tlsStatus; +} + +/*-----------------------------------------------------------*/ + +int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ) +{ + int32_t tlsStatus = 0; + + tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pNetworkContext->sslContext.context ), + pBuffer, + bytesToSend ); + + if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + LogDebug( ( "Failed to send data. However, send can be retried on this error. " + "mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + + /* Mark these set of errors as a timeout. The libraries may retry send + * on these errors. */ + tlsStatus = 0; + } + else if( tlsStatus < 0 ) + { + LogError( ( "Failed to send data: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + else + { + /* Empty else marker. */ + } + + return tlsStatus; +} +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos_pkcs11.c b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos_pkcs11.c new file mode 100644 index 0000000000..4b244980ac --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/freertos/transport/src/tls_freertos_pkcs11.c @@ -0,0 +1,956 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file tls_freertos_pkcs11.c + * @brief TLS transport interface implementations. This implementation uses + * mbedTLS. + * @note This file is derived from the tls_freertos.c source file found in the mqtt + * section of IoT Libraries source code. The file has been modified to support using + * PKCS #11 when using TLS. + */ + +/* Standard includes. */ +#include + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" + +/* FreeRTOS+TCP includes. */ +#include "FreeRTOS_IP.h" +#include "FreeRTOS_Sockets.h" + +/* TLS transport header. */ +#include "tls_freertos_pkcs11.h" + +/* FreeRTOS Socket wrapper include. */ +#include "freertos_sockets_wrapper.h" + +/* mbedTLS util includes. */ +#include "mbedtls_error.h" + +/* PKCS #11 includes. */ +#include "iot_pkcs11_config.h" +#include "iot_pkcs11.h" +#include "pkcs11.h" +#include "iot_pki_utils.h" + +/*-----------------------------------------------------------*/ + +/** + * @brief Represents string to be logged when mbedTLS returned error + * does not contain a high-level code. + */ +static const char * pNoHighLevelMbedTlsCodeStr = ""; + +/** + * @brief Represents string to be logged when mbedTLS returned error + * does not contain a low-level code. + */ +static const char * pNoLowLevelMbedTlsCodeStr = ""; + +/** + * @brief Utility for converting the high-level code in an mbedTLS error to string, + * if the code-contains a high-level code; otherwise, using a default string. + */ +#define mbedtlsHighLevelCodeOrDefault( mbedTlsCode ) \ + ( mbedtls_strerror_highlevel( mbedTlsCode ) != NULL ) ? \ + mbedtls_strerror_highlevel( mbedTlsCode ) : pNoHighLevelMbedTlsCodeStr + +/** + * @brief Utility for converting the level-level code in an mbedTLS error to string, + * if the code-contains a level-level code; otherwise, using a default string. + */ +#define mbedtlsLowLevelCodeOrDefault( mbedTlsCode ) \ + ( mbedtls_strerror_lowlevel( mbedTlsCode ) != NULL ) ? \ + mbedtls_strerror_lowlevel( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr + +/*-----------------------------------------------------------*/ + +/** + * @brief mbed TLS entropy context for generation of random numbers. + */ +static mbedtls_entropy_context entropyContext; + +/** + * @brief mbed TLS CTR DRBG context for generation of random numbers. + */ +static mbedtls_ctr_drbg_context ctrDrgbContext; + +/*-----------------------------------------------------------*/ + +/** + * @brief Initialize the mbed TLS structures in a network connection. + * + * @param[in] pSslContext The SSL context to initialize. + */ +static void sslContextInit( SSLContext_t * pSslContext ); + +/** + * @brief Free the mbed TLS structures in a network connection. + * + * @param[in] pSslContext The SSL context to free. + */ +static void sslContextFree( SSLContext_t * pSslContext ); + +/** + * @brief Set up TLS on a TCP connection. + * + * @param[in] pNetworkContext Network context. + * @param[in] pHostName Remote host name, used for server name indication. + * @param[in] pNetworkCredentials TLS setup parameters. + * + * @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, #TLS_TRANSPORT_INVALID_CREDENTIALS, + * #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR. + */ +static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext, + const char * pHostName, + const NetworkCredentials_t * pNetworkCredentials ); + +/** + * @brief Initialize mbedTLS. + * + * @return #TLS_TRANSPORT_SUCCESS, or #TLS_TRANSPORT_INTERNAL_ERROR. + */ +static TlsTransportStatus_t initMbedtls( void ); + +/*-----------------------------------------------------------*/ + +/** + * @brief Callback that wraps PKCS#11 for pseudo-random number generation. + * + * @param[in] pvCtx Caller context. + * @param[in] pucRandom Byte array to fill with random data. + * @param[in] xRandomLength Length of byte array. + * + * @return Zero on success. + */ +static int generateRandomBytes( void * pvCtx, + unsigned char * pucRandom, + size_t xRandomLength ); + +/** + * @brief Helper for reading the specified certificate object, if present, + * out of storage, into RAM, and then into an mbedTLS certificate context + * object. + * + * @param[in] pSslContext Caller TLS context. + * @param[in] pcLabelName PKCS #11 certificate object label. + * @param[in] xClass PKCS #11 certificate object class. + * @param[out] pxCertificateContext Certificate context. + * + * @return Zero on success. + */ +static CK_RV readCertificateIntoContext( SSLContext_t * pSslContext, + char * pcLabelName, + CK_OBJECT_CLASS xClass, + mbedtls_x509_crt * pxCertificateContext ); + +/** + * @brief Helper for setting up potentially hardware-based cryptographic context. + * + * @param Caller context. + * + * @return Zero on success. + */ +static CK_RV initializeClientKeys( SSLContext_t * pxCtx ); + +/** + * @brief Sign a cryptographic hash with the private key. + * + * @param[in] pvContext Crypto context. + * @param[in] xMdAlg Unused. + * @param[in] pucHash Length in bytes of hash to be signed. + * @param[in] uiHashLen Byte array of hash to be signed. + * @param[out] pucSig RSA signature bytes. + * @param[in] pxSigLen Length in bytes of signature buffer. + * @param[in] piRng Unused. + * @param[in] pvRng Unused. + * + * @return Zero on success. + */ +static int privateKeySigningCallback( void * pvContext, + mbedtls_md_type_t xMdAlg, + const unsigned char * pucHash, + size_t xHashLen, + unsigned char * pucSig, + size_t * pxSigLen, + int ( * piRng )( void *, + unsigned char *, + size_t ), + void * pvRng ); + + +/*-----------------------------------------------------------*/ + +static void sslContextInit( SSLContext_t * pSslContext ) +{ + configASSERT( pSslContext != NULL ); + + mbedtls_ssl_config_init( &( pSslContext->config ) ); + mbedtls_x509_crt_init( &( pSslContext->rootCa ) ); + mbedtls_x509_crt_init( &( pSslContext->clientCert ) ); + mbedtls_ssl_init( &( pSslContext->context ) ); + + xInitializePkcs11Session( &( pSslContext->xP11Session ) ); + C_GetFunctionList( &( pSslContext->pxP11FunctionList ) ); +} +/*-----------------------------------------------------------*/ + +static void sslContextFree( SSLContext_t * pSslContext ) +{ + configASSERT( pSslContext != NULL ); + + mbedtls_ssl_free( &( pSslContext->context ) ); + mbedtls_x509_crt_free( &( pSslContext->rootCa ) ); + mbedtls_x509_crt_free( &( pSslContext->clientCert ) ); + mbedtls_ssl_config_free( &( pSslContext->config ) ); + + pSslContext->pxP11FunctionList->C_CloseSession( pSslContext->xP11Session ); +} + +/*-----------------------------------------------------------*/ + +static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext, + const char * pHostName, + const NetworkCredentials_t * pNetworkCredentials ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + int mbedtlsError = 0; + CK_RV xResult = CKR_OK; + + configASSERT( pNetworkContext != NULL ); + configASSERT( pHostName != NULL ); + configASSERT( pNetworkCredentials != NULL ); + configASSERT( pNetworkCredentials->pRootCa != NULL ); + + /* Initialize the mbed TLS context structures. */ + sslContextInit( &( pNetworkContext->sslContext ) ); + + mbedtlsError = mbedtls_ssl_config_defaults( &( pNetworkContext->sslContext.config ), + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set default SSL configuration: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + /* Per mbed TLS docs, mbedtls_ssl_config_defaults only fails on memory allocation. */ + returnStatus = TLS_TRANSPORT_INSUFFICIENT_MEMORY; + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Set up the certificate security profile, starting from the default value. */ + pNetworkContext->sslContext.certProfile = mbedtls_x509_crt_profile_default; + + /* test.mosquitto.org only provides a 1024-bit RSA certificate, which is + * not acceptable by the default mbed TLS certificate security profile. + * For the purposes of this demo, allow the use of 1024-bit RSA certificates. + * This block should be removed otherwise. */ + if( strncmp( pHostName, "test.mosquitto.org", strlen( pHostName ) ) == 0 ) + { + pNetworkContext->sslContext.certProfile.rsa_min_bitlen = 1024; + } + + /* Set SSL authmode and the RNG context. */ + mbedtls_ssl_conf_authmode( &( pNetworkContext->sslContext.config ), + MBEDTLS_SSL_VERIFY_REQUIRED ); + mbedtls_ssl_conf_rng( &( pNetworkContext->sslContext.config ), + generateRandomBytes, + &pNetworkContext->sslContext ); + mbedtls_ssl_conf_cert_profile( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.certProfile ) ); + + /* Parse the server root CA certificate into the SSL context. */ + mbedtlsError = mbedtls_x509_crt_parse( &( pNetworkContext->sslContext.rootCa ), + pNetworkCredentials->pRootCa, + pNetworkCredentials->rootCaSize ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + mbedtls_ssl_conf_ca_chain( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.rootCa ), + NULL ); + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Setup the client private key. */ + xResult = initializeClientKeys( &( pNetworkContext->sslContext ) ); + + if( xResult != CKR_OK ) + { + LogError( ( "Failed to setup key handling by PKCS #11." ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + /* Setup the client certificate. */ + xResult = readCertificateIntoContext( &( pNetworkContext->sslContext ), + pkcs11configLABEL_DEVICE_CERTIFICATE_FOR_TLS, + CKO_CERTIFICATE, + &( pNetworkContext->sslContext.clientCert ) ); + + if( xResult != CKR_OK ) + { + LogError( ( "Failed to get certificate from PKCS #11 module." ) ); + + returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS; + } + else + { + mbedtls_ssl_conf_own_cert( &( pNetworkContext->sslContext.config ), + &( pNetworkContext->sslContext.clientCert ), + &( pNetworkContext->sslContext.privKey ) ); + } + } + } + + if( ( returnStatus == TLS_TRANSPORT_SUCCESS ) && ( pNetworkCredentials->pAlpnProtos != NULL ) ) + { + /* Include an application protocol list in the TLS ClientHello + * message. */ + mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pNetworkContext->sslContext.config ), + ( const char ** ) &( pNetworkCredentials->pAlpnProtos ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Initialize the mbed TLS secured connection context. */ + mbedtlsError = mbedtls_ssl_setup( &( pNetworkContext->sslContext.context ), + &( pNetworkContext->sslContext.config ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set up mbed TLS SSL context: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + else + { + /* Set the underlying IO for the TLS connection. */ + mbedtls_ssl_set_bio( &( pNetworkContext->sslContext.context ), + pNetworkContext->tcpSocket, + mbedtls_platform_send, + mbedtls_platform_recv, + NULL ); + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Enable SNI if requested. */ + if( pNetworkCredentials->disableSni == pdFALSE ) + { + mbedtlsError = mbedtls_ssl_set_hostname( &( pNetworkContext->sslContext.context ), + pHostName ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to set server name: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_INTERNAL_ERROR; + } + } + } + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + /* Perform the TLS handshake. */ + do + { + mbedtlsError = mbedtls_ssl_handshake( &( pNetworkContext->sslContext.context ) ); + } while( ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_READ ) || + ( mbedtlsError == MBEDTLS_ERR_SSL_WANT_WRITE ) ); + + if( mbedtlsError != 0 ) + { + LogError( ( "Failed to perform TLS handshake: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( mbedtlsError ), + mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) ); + + returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED; + } + } + + if( returnStatus != TLS_TRANSPORT_SUCCESS ) + { + sslContextFree( &( pNetworkContext->sslContext ) ); + } + else + { + LogInfo( ( "(Network connection %p) TLS handshake successful.", + pNetworkContext ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +static TlsTransportStatus_t initMbedtls( void ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + + /* Set the mutex functions for mbed TLS thread safety. */ + mbedtls_threading_set_alt( mbedtls_platform_mutex_init, + mbedtls_platform_mutex_free, + mbedtls_platform_mutex_lock, + mbedtls_platform_mutex_unlock ); + + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + LogDebug( ( "Successfully initialized mbedTLS." ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +static int generateRandomBytes( void * pvCtx, + unsigned char * pucRandom, + size_t xRandomLength ) +{ + /* Must cast from void pointer to conform to mbed TLS API. */ + SSLContext_t * pxCtx = ( SSLContext_t * ) pvCtx; + CK_RV xResult; + + xResult = pxCtx->pxP11FunctionList->C_GenerateRandom( pxCtx->xP11Session, pucRandom, xRandomLength ); + + if( xResult != CKR_OK ) + { + LogError( ( "Failed to generate random bytes from the PKCS #11 module." ) ); + } + + return xResult; +} + +/*-----------------------------------------------------------*/ + +static CK_RV readCertificateIntoContext( SSLContext_t * pSslContext, + char * pcLabelName, + CK_OBJECT_CLASS xClass, + mbedtls_x509_crt * pxCertificateContext ) +{ + CK_RV xResult = CKR_OK; + CK_ATTRIBUTE xTemplate = { 0 }; + CK_OBJECT_HANDLE xCertObj = 0; + + /* Get the handle of the certificate. */ + xResult = xFindObjectWithLabelAndClass( pSslContext->xP11Session, + pcLabelName, + xClass, + &xCertObj ); + + if( ( CKR_OK == xResult ) && ( xCertObj == CK_INVALID_HANDLE ) ) + { + xResult = CKR_OBJECT_HANDLE_INVALID; + } + + /* Query the certificate size. */ + if( CKR_OK == xResult ) + { + xTemplate.type = CKA_VALUE; + xTemplate.ulValueLen = 0; + xTemplate.pValue = NULL; + xResult = pSslContext->pxP11FunctionList->C_GetAttributeValue( pSslContext->xP11Session, + xCertObj, + &xTemplate, + 1 ); + } + + /* Create a buffer for the certificate. */ + if( CKR_OK == xResult ) + { + xTemplate.pValue = pvPortMalloc( xTemplate.ulValueLen ); + + if( NULL == xTemplate.pValue ) + { + xResult = CKR_HOST_MEMORY; + } + } + + /* Export the certificate. */ + if( CKR_OK == xResult ) + { + xResult = pSslContext->pxP11FunctionList->C_GetAttributeValue( pSslContext->xP11Session, + xCertObj, + &xTemplate, + 1 ); + } + + /* Decode the certificate. */ + if( CKR_OK == xResult ) + { + xResult = mbedtls_x509_crt_parse( pxCertificateContext, + ( const unsigned char * ) xTemplate.pValue, + xTemplate.ulValueLen ); + } + + /* Free memory. */ + vPortFree( xTemplate.pValue ); + + return xResult; +} + +/*-----------------------------------------------------------*/ + +/** + * @brief Helper for setting up potentially hardware-based cryptographic context + * for the client TLS certificate and private key. + * + * @param Caller context. + * + * @return Zero on success. + */ +static CK_RV initializeClientKeys( SSLContext_t * pxCtx ) +{ + CK_RV xResult = CKR_OK; + CK_SLOT_ID * pxSlotIds = NULL; + CK_ULONG xCount = 0; + CK_ATTRIBUTE xTemplate[ 2 ]; + mbedtls_pk_type_t xKeyAlgo = ( mbedtls_pk_type_t ) ~0; + + /* Get the PKCS #11 module/token slot count. */ + if( CKR_OK == xResult ) + { + xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE, + NULL, + &xCount ); + } + + /* Allocate memory to store the token slots. */ + if( CKR_OK == xResult ) + { + pxSlotIds = ( CK_SLOT_ID * ) pvPortMalloc( sizeof( CK_SLOT_ID ) * xCount ); + + if( NULL == pxSlotIds ) + { + xResult = CKR_HOST_MEMORY; + } + } + + /* Get all of the available private key slot identities. */ + if( CKR_OK == xResult ) + { + xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_GetSlotList( CK_TRUE, + pxSlotIds, + &xCount ); + } + + /* Put the module in authenticated mode. */ + if( CKR_OK == xResult ) + { + xResult = ( BaseType_t ) pxCtx->pxP11FunctionList->C_Login( pxCtx->xP11Session, + CKU_USER, + ( CK_UTF8CHAR_PTR ) configPKCS11_DEFAULT_USER_PIN, + sizeof( configPKCS11_DEFAULT_USER_PIN ) - 1 ); + } + + if( CKR_OK == xResult ) + { + /* Get the handle of the device private key. */ + xResult = xFindObjectWithLabelAndClass( pxCtx->xP11Session, + pkcs11configLABEL_DEVICE_PRIVATE_KEY_FOR_TLS, + CKO_PRIVATE_KEY, + &pxCtx->xP11PrivateKey ); + } + + if( ( CKR_OK == xResult ) && ( pxCtx->xP11PrivateKey == CK_INVALID_HANDLE ) ) + { + xResult = CK_INVALID_HANDLE; + LogError( ( "Could not find private key." ) ); + } + + /* Query the device private key type. */ + if( xResult == CKR_OK ) + { + xTemplate[ 0 ].type = CKA_KEY_TYPE; + xTemplate[ 0 ].pValue = &pxCtx->xKeyType; + xTemplate[ 0 ].ulValueLen = sizeof( CK_KEY_TYPE ); + xResult = pxCtx->pxP11FunctionList->C_GetAttributeValue( pxCtx->xP11Session, + pxCtx->xP11PrivateKey, + xTemplate, + 1 ); + } + + /* Map the PKCS #11 key type to an mbedTLS algorithm. */ + if( xResult == CKR_OK ) + { + switch( pxCtx->xKeyType ) + { + case CKK_RSA: + xKeyAlgo = MBEDTLS_PK_RSA; + break; + + case CKK_EC: + xKeyAlgo = MBEDTLS_PK_ECKEY; + break; + + default: + xResult = CKR_ATTRIBUTE_VALUE_INVALID; + break; + } + } + + /* Map the mbedTLS algorithm to its internal metadata. */ + if( xResult == CKR_OK ) + { + memcpy( &pxCtx->privKeyInfo, mbedtls_pk_info_from_type( xKeyAlgo ), sizeof( mbedtls_pk_info_t ) ); + + pxCtx->privKeyInfo.sign_func = privateKeySigningCallback; + pxCtx->privKey.pk_info = &pxCtx->privKeyInfo; + pxCtx->privKey.pk_ctx = pxCtx; + } + + /* Free memory. */ + vPortFree( pxSlotIds ); + + return xResult; +} + +/*-----------------------------------------------------------*/ + +static int privateKeySigningCallback( void * pvContext, + mbedtls_md_type_t xMdAlg, + const unsigned char * pucHash, + size_t xHashLen, + unsigned char * pucSig, + size_t * pxSigLen, + int ( * piRng )( void *, + unsigned char *, + size_t ), + void * pvRng ) +{ + CK_RV xResult = CKR_OK; + int lFinalResult = 0; + SSLContext_t * pxTLSContext = ( SSLContext_t * ) pvContext; + CK_MECHANISM xMech = { 0 }; + CK_BYTE xToBeSigned[ 256 ]; + CK_ULONG xToBeSignedLen = sizeof( xToBeSigned ); + + /* Unreferenced parameters. */ + ( void ) ( piRng ); + ( void ) ( pvRng ); + ( void ) ( xMdAlg ); + + /* Sanity check buffer length. */ + if( xHashLen > sizeof( xToBeSigned ) ) + { + xResult = CKR_ARGUMENTS_BAD; + } + + /* Format the hash data to be signed. */ + if( CKK_RSA == pxTLSContext->xKeyType ) + { + xMech.mechanism = CKM_RSA_PKCS; + + /* mbedTLS expects hashed data without padding, but PKCS #11 C_Sign function performs a hash + * & sign if hash algorithm is specified. This helper function applies padding + * indicating data was hashed with SHA-256 while still allowing pre-hashed data to + * be provided. */ + xResult = vAppendSHA256AlgorithmIdentifierSequence( ( uint8_t * ) pucHash, xToBeSigned ); + xToBeSignedLen = pkcs11RSA_SIGNATURE_INPUT_LENGTH; + } + else if( CKK_EC == pxTLSContext->xKeyType ) + { + xMech.mechanism = CKM_ECDSA; + memcpy( xToBeSigned, pucHash, xHashLen ); + xToBeSignedLen = xHashLen; + } + else + { + xResult = CKR_ARGUMENTS_BAD; + } + + if( CKR_OK == xResult ) + { + /* Use the PKCS#11 module to sign. */ + xResult = pxTLSContext->pxP11FunctionList->C_SignInit( pxTLSContext->xP11Session, + &xMech, + pxTLSContext->xP11PrivateKey ); + } + + if( CKR_OK == xResult ) + { + *pxSigLen = sizeof( xToBeSigned ); + xResult = pxTLSContext->pxP11FunctionList->C_Sign( ( CK_SESSION_HANDLE ) pxTLSContext->xP11Session, + xToBeSigned, + xToBeSignedLen, + pucSig, + ( CK_ULONG_PTR ) pxSigLen ); + } + + if( ( xResult == CKR_OK ) && ( CKK_EC == pxTLSContext->xKeyType ) ) + { + /* PKCS #11 for P256 returns a 64-byte signature with 32 bytes for R and 32 bytes for S. + * This must be converted to an ASN.1 encoded array. */ + if( *pxSigLen != pkcs11ECDSA_P256_SIGNATURE_LENGTH ) + { + xResult = CKR_FUNCTION_FAILED; + } + + if( xResult == CKR_OK ) + { + PKI_pkcs11SignatureTombedTLSSignature( pucSig, pxSigLen ); + } + } + + if( xResult != CKR_OK ) + { + LogError( ( "Failed to sign message using PKCS #11 with error code %02X.", xResult ) ); + } + + return lFinalResult; +} + +/*-----------------------------------------------------------*/ + +TlsTransportStatus_t TLS_FreeRTOS_Connect( NetworkContext_t * pNetworkContext, + const char * pHostName, + uint16_t port, + const NetworkCredentials_t * pNetworkCredentials, + uint32_t receiveTimeoutMs, + uint32_t sendTimeoutMs ) +{ + TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS; + BaseType_t socketStatus = 0; + + if( ( pNetworkContext == NULL ) || + ( pHostName == NULL ) || + ( pNetworkCredentials == NULL ) ) + { + LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, " + "pHostName=%p, pNetworkCredentials=%p.", + pNetworkContext, + pHostName, + pNetworkCredentials ) ); + returnStatus = TLS_TRANSPORT_INVALID_PARAMETER; + } + else if( ( pNetworkCredentials->pRootCa == NULL ) ) + { + LogError( ( "pRootCa cannot be NULL." ) ); + returnStatus = TLS_TRANSPORT_INVALID_PARAMETER; + } + + /* Establish a TCP connection with the server. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + socketStatus = Sockets_Connect( &( pNetworkContext->tcpSocket ), + pHostName, + port, + receiveTimeoutMs, + sendTimeoutMs ); + + if( socketStatus != 0 ) + { + LogError( ( "Failed to connect to %s with error %d.", + pHostName, + socketStatus ) ); + returnStatus = TLS_TRANSPORT_CONNECT_FAILURE; + } + } + + /* Initialize mbedtls. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + returnStatus = initMbedtls(); + } + + /* Perform TLS handshake. */ + if( returnStatus == TLS_TRANSPORT_SUCCESS ) + { + returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials ); + } + + /* Clean up on failure. */ + if( returnStatus != TLS_TRANSPORT_SUCCESS ) + { + if( pNetworkContext->tcpSocket != FREERTOS_INVALID_SOCKET ) + { + FreeRTOS_closesocket( pNetworkContext->tcpSocket ); + } + } + else + { + LogInfo( ( "(Network connection %p) Connection to %s established.", + pNetworkContext, + pHostName ) ); + } + + return returnStatus; +} + +/*-----------------------------------------------------------*/ + +void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext ) +{ + BaseType_t tlsStatus = 0; + + /* Attempting to terminate TLS connection. */ + tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pNetworkContext->sslContext.context ) ); + + /* Ignore the WANT_READ and WANT_WRITE return values. */ + if( ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_READ ) && + ( tlsStatus != ( BaseType_t ) MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + if( tlsStatus == 0 ) + { + LogInfo( ( "(Network connection %p) TLS close-notify sent.", + pNetworkContext ) ); + } + else + { + LogError( ( "(Network connection %p) Failed to send TLS close-notify: mbedTLSError= %s : %s.", + pNetworkContext, + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + } + else + { + /* WANT_READ and WANT_WRITE can be ignored. Logging for debugging purposes. */ + LogInfo( ( "(Network connection %p) TLS close-notify sent; ", + "received %s as the TLS status can be ignored for close-notify." + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) ? "WANT_READ" : "WANT_WRITE", + pNetworkContext ) ); + } + + /* Call socket shutdown function to close connection. */ + Sockets_Disconnect( pNetworkContext->tcpSocket ); + + /* Free mbed TLS contexts. */ + sslContextFree( &( pNetworkContext->sslContext ) ); + + /* Free the contexts for random number generation. */ + mbedtls_ctr_drbg_free( &ctrDrgbContext ); + mbedtls_entropy_free( &entropyContext ); + + /* Clear the mutex functions for mbed TLS thread safety. */ + mbedtls_threading_free_alt(); +} + +/*-----------------------------------------------------------*/ + +int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ) +{ + int32_t tlsStatus = 0; + + tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pNetworkContext->sslContext.context ), + pBuffer, + bytesToRecv ); + + if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + LogDebug( ( "Failed to read data. However, a read can be retried on this error. " + "mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + + /* Mark these set of errors as a timeout. The libraries may retry read + * on these errors. */ + tlsStatus = 0; + } + else if( tlsStatus < 0 ) + { + LogError( ( "Failed to read data: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + else + { + /* Empty else marker. */ + } + + return tlsStatus; +} + +/*-----------------------------------------------------------*/ + +int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ) +{ + int32_t tlsStatus = 0; + + tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pNetworkContext->sslContext.context ), + pBuffer, + bytesToSend ); + + if( ( tlsStatus == MBEDTLS_ERR_SSL_TIMEOUT ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_READ ) || + ( tlsStatus == MBEDTLS_ERR_SSL_WANT_WRITE ) ) + { + LogDebug( ( "Failed to send data. However, send can be retried on this error. " + "mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + + /* Mark these set of errors as a timeout. The libraries may retry send + * on these errors. */ + tlsStatus = 0; + } + else if( tlsStatus < 0 ) + { + LogError( ( "Failed to send data: mbedTLSError= %s : %s.", + mbedtlsHighLevelCodeOrDefault( tlsStatus ), + mbedtlsLowLevelCodeOrDefault( tlsStatus ) ) ); + } + else + { + /* Empty else marker. */ + } + + return tlsStatus; +} +/*-----------------------------------------------------------*/ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/include/retry_utils.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/include/retry_utils.h new file mode 100644 index 0000000000..57f328403d --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/include/retry_utils.h @@ -0,0 +1,245 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * @file retry_utils.h + * @brief Declaration of the exponential backoff retry logic utility functions + * and constants. + */ + +#ifndef RETRY_UTILS_H_ +#define RETRY_UTILS_H_ + +/* Standard include. */ +#include + +/** + * @page retryutils_page Retry Utilities + * @brief An abstraction of utilities for retrying with exponential back off and + * jitter. + * + * @section retryutils_overview Overview + * The retry utilities are a set of APIs that aid in retrying with exponential + * backoff and jitter. Exponential backoff with jitter is strongly recommended + * for retrying failed actions over the network with servers. Please see + * https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ for + * more information about the benefits with AWS. + * + * Exponential backoff with jitter is typically used when retrying a failed + * connection to the server. In an environment with poor connectivity, a client + * can get disconnected at any time. A backoff strategy helps the client to + * conserve battery by not repeatedly attempting reconnections when they are + * unlikely to succeed. + * + * Before retrying the failed communication to the server there is a quiet period. + * In this quiet period, the task that is retrying must sleep for some random + * amount of seconds between 0 and the lesser of a base value and a predefined + * maximum. The base is doubled with each retry attempt until the maximum is + * reached.
+ * + * > sleep_seconds = random_between( 0, min( 2attempts_count * base_seconds, maximum_seconds ) ) + * + * @section retryutils_implementation Implementing Retry Utils + * + * The functions that must be implemented are:
+ * - @ref RetryUtils_ParamsReset + * - @ref RetryUtils_BackoffAndSleep + * + * The functions are used as shown in the diagram below. This is the exponential + * backoff with jitter loop: + * + * @image html retry_utils_flow.png width=25% + * + * The following steps give guidance on implementing the Retry Utils. An example + * implementation of the Retry Utils for a POSIX platform can be found in file + * @ref retry_utils_posix.c. + * + * -# Implementing @ref RetryUtils_ParamsReset + * @snippet this define_retryutils_paramsreset + *
+ * This function initializes @ref RetryUtilsParams_t. It is expected to set + * @ref RetryUtilsParams_t.attemptsDone to zero. It is also expected to set + * @ref RetryUtilsParams_t.nextJitterMax to @ref INITIAL_RETRY_BACKOFF_SECONDS + * plus some random amount of seconds, jitter. This jitter is a random number + * between 0 and @ref MAX_JITTER_VALUE_SECONDS. This function must be called + * before entering the exponential backoff with jitter loop using + * @ref RetryUtils_BackoffAndSleep.

+ * Please follow the example below to implement your own @ref RetryUtils_ParamsReset. + * The lines with FIXME comments should be updated. + * @code{c} + * void RetryUtils_ParamsReset( RetryUtilsParams_t * pRetryParams ) + * { + * uint32_t jitter = 0; + * + * // Reset attempts done to zero so that the next retry cycle can start. + * pRetryParams->attemptsDone = 0; + * + * // Seed pseudo random number generator with the current time. FIXME: Your + * // system may have another method to retrieve the current time to seed the + * // pseudo random number generator. + * srand( time( NULL ) ); + * + * // Calculate jitter value using picking a random number. + * jitter = ( rand() % MAX_JITTER_VALUE_SECONDS ); + * + * // Reset the backoff value to the initial time out value plus jitter. + * pRetryParams->nextJitterMax = INITIAL_RETRY_BACKOFF_SECONDS + jitter; + * } + * @endcode
+ * + * -# Implementing @ref RetryUtils_BackoffAndSleep + * @snippet this define_retryutils_backoffandsleep + *
+ * When this function is invoked, the calling task is expected to sleep a random + * number of seconds between 0 and @ref RetryUtilsParams_t.nextJitterMax. After + * sleeping this function must double @ref RetryUtilsParams_t.nextJitterMax, but + * not exceeding @ref MAX_RETRY_BACKOFF_SECONDS. When @ref RetryUtilsParams_t.maxRetryAttempts + * are reached this function should return @ref RetryUtilsRetriesExhausted, unless + * @ref RetryUtilsParams_t.maxRetryAttempts is set to zero. + * When @ref RetryUtilsRetriesExhausted is returned the calling application can + * stop trying with a failure, or it can call @ref RetryUtils_ParamsReset again + * and restart the exponential back off with jitter loop.

+ * Please follow the example below to implement your own @ref RetryUtils_BackoffAndSleep. + * The lines with FIXME comments should be updated. + * @code{c} + * RetryUtilsStatus_t RetryUtils_BackoffAndSleep( RetryUtilsParams_t * pRetryParams ) + * { + * RetryUtilsStatus_t status = RetryUtilsRetriesExhausted; + * // The quiet period delay in seconds. + * int backOffDelay = 0; + * + * // If pRetryParams->maxRetryAttempts is set to 0, try forever. + * if( ( pRetryParams->attemptsDone < pRetryParams->maxRetryAttempts ) || + * ( 0 == pRetryParams->maxRetryAttempts ) ) + * { + * // Choose a random value for back-off time between 0 and the max jitter value. + * backOffDelay = rand() % pRetryParams->nextJitterMax; + * + * // Wait for backoff time to expire for the next retry. + * ( void ) myThreadSleepFunction( backOffDelay ); // FIXME: Replace with your system's thread sleep function. + * + * // Increment backoff counts. + * pRetryParams->attemptsDone++; + * + * // Double the max jitter value for the next retry attempt, only + * // if the new value will be less than the max backoff time value. + * if( pRetryParams->nextJitterMax < ( MAX_RETRY_BACKOFF_SECONDS / 2U ) ) + * { + * pRetryParams->nextJitterMax += pRetryParams->nextJitterMax; + * } + * else + * { + * pRetryParams->nextJitterMax = MAX_RETRY_BACKOFF_SECONDS; + * } + * + * status = RetryUtilsSuccess; + * } + * else + * { + * // When max retry attempts are exhausted, let application know by + * // returning RetryUtilsRetriesExhausted. Application may choose to + * // restart the retry process after calling RetryUtils_ParamsReset(). + * status = RetryUtilsRetriesExhausted; + * RetryUtils_ParamsReset( pRetryParams ); + * } + * + * return status; + * } + * @endcode + */ + +/** + * @brief Max number of retry attempts. Set this value to 0 if the client must + * retry forever. + */ +#define MAX_RETRY_ATTEMPTS 4U + +/** + * @brief Initial fixed backoff value in seconds between two successive + * retries. A random jitter value is added to every backoff value. + */ +#define INITIAL_RETRY_BACKOFF_SECONDS 1U + +/** + * @brief Max backoff value in seconds. + */ +#define MAX_RETRY_BACKOFF_SECONDS 128U + +/** + * @brief Max jitter value in seconds. + */ +#define MAX_JITTER_VALUE_SECONDS 5U + +/** + * @brief Status for @ref RetryUtils_BackoffAndSleep. + */ +typedef enum RetryUtilsStatus +{ + RetryUtilsSuccess = 0, /**< @brief The function returned successfully after sleeping. */ + RetryUtilsRetriesExhausted /**< @brief The function exhausted all retry attempts. */ +} RetryUtilsStatus_t; + +/** + * @brief Represents parameters required for retry logic. + */ +typedef struct RetryUtilsParams +{ + /** + * @brief Max number of retry attempts. Set this value to 0 if the client must + * retry forever. + */ + uint32_t maxRetryAttempts; + + /** + * @brief The cumulative count of backoff delay cycles completed + * for retries. + */ + uint32_t attemptsDone; + + /** + * @brief The max jitter value for backoff time in retry attempt. + */ + uint32_t nextJitterMax; +} RetryUtilsParams_t; + + +/** + * @brief Resets the retry timeout value and number of attempts. + * This function must be called by the application before a new retry attempt. + * + * @param[in, out] pRetryParams Structure containing attempts done and timeout + * value. + */ +void RetryUtils_ParamsReset( RetryUtilsParams_t * pRetryParams ); + +/** + * @brief Simple platform specific exponential backoff function. The application + * must use this function between retry failures to add exponential delay. + * This function will block the calling task for the current timeout value. + * + * @param[in, out] pRetryParams Structure containing retry parameters. + * + * @return #RetryUtilsSuccess after a successful sleep, #RetryUtilsRetriesExhausted + * when all attempts are exhausted. + */ +RetryUtilsStatus_t RetryUtils_BackoffAndSleep( RetryUtilsParams_t * pRetryParams ); + +#endif /* ifndef RETRY_UTILS_H_ */ diff --git a/FreeRTOS-Plus/Source/Application-Protocols/platform/include/transport_interface.h b/FreeRTOS-Plus/Source/Application-Protocols/platform/include/transport_interface.h new file mode 100644 index 0000000000..3980221402 --- /dev/null +++ b/FreeRTOS-Plus/Source/Application-Protocols/platform/include/transport_interface.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef TRANSPORT_INTERFACE_H_ +#define TRANSPORT_INTERFACE_H_ + +#include +#include + +/** + * @brief The NetworkContext is an incomplete type. An implementation of this + * interface must define NetworkContext as per the requirements. This context + * is passed into the network interface functions. + */ +struct NetworkContext; +typedef struct NetworkContext NetworkContext_t; + +/** + * @brief Transport interface for receiving data on the network. + * + * @param[in] pNetworkContext Implementation-defined network context. + * @param[in] pBuffer Buffer to receive the data into. + * @param[in] bytesToRecv Number of bytes requested from the network. + * + * @return The number of bytes received or a negative error code. + */ +typedef int32_t ( * TransportRecv_t )( NetworkContext_t * pNetworkContext, + void * pBuffer, + size_t bytesToRecv ); + +/** + * @brief Transport interface for sending data over the network. + * + * @param[in] pNetworkContext Implementation-defined network context. + * @param[in] pBuffer Buffer containing the bytes to send over the network stack. + * @param[in] bytesToSend Number of bytes to send over the network. + * + * @return The number of bytes sent or a negative error code. + */ +typedef int32_t ( * TransportSend_t )( NetworkContext_t * pNetworkContext, + const void * pBuffer, + size_t bytesToSend ); + +/** + * @brief The transport layer interface. + */ +typedef struct TransportInterface +{ + TransportRecv_t recv; /**< Transport receive interface. */ + TransportSend_t send; /**< Transport send interface. */ + NetworkContext_t * pNetworkContext; /**< Implementation-defined network context. */ +} TransportInterface_t; + +#endif /* ifndef TRANSPORT_INTERFACE_H_ */ diff --git a/FreeRTOS-Plus/Source/coreJSON b/FreeRTOS-Plus/Source/coreJSON new file mode 160000 index 0000000000..7e09e8fdbe --- /dev/null +++ b/FreeRTOS-Plus/Source/coreJSON @@ -0,0 +1 @@ +Subproject commit 7e09e8fdbef5f2cf5e39d4c9171c6130e46365b5