Add cellular library submodule path and demo (#695)

* [Cellular] Add cellulr lib submodule and demo app

* [Cellular] Fix memory violation in transport layer and add using LoggingPrintf

* Update FreeRTOS Cellular Interface

* Change the mbedtls usage in FreeRTOS-Plus

* [Cellular] Fix missing spell

* [Cellular] Add manifest.yml

* Fix missing spell

* Update manifest.yml

* [Cellular] Add integration test

* Modify the demo log level to LOG_INFO

* Update cellular interface

* The modification of the folder structure for cellular library

* Rename the naming of demo

* Adjust the location of using_mbedtls and socket_wrapper

* Adjust project setting for relocating using_mbedtls and socket_wrapper

* Turn off PSM mode

* Add start marker for CI validation.

* The modification for mbedtls platform send/recv function for cellular

* Change the project file due to the changes of mbedtls platform send/recv function for cellular

* Fix missing newline and remove unused file

* Add missing configuration.

* Make cellular and freertos tcp plus use the same transport implementation

* Add comment for the macro MBEDTLS_SSL_SEND and MBEDTLS_SSL_RECV

* Make changes from the github comment.
This commit is contained in:
andysun2015 2021-11-10 11:38:44 +08:00 committed by GitHub
parent 223d2d0e21
commit 957fb26dbe
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
142 changed files with 45928 additions and 14758 deletions

View file

@ -0,0 +1,851 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/**
* @file tls_freertos.c
* @brief TLS transport interface implementations. This implementation uses
* mbedTLS.
*/
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
/* TLS transport header. */
#include "using_mbedtls.h"
/* FreeRTOS Socket wrapper include. */
#include "sockets_wrapper.h"
/*-----------------------------------------------------------*/
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer as seen below whenever the header file
* of this transport implementation is included to your project.
*
* @note When using multiple transports in the same compilation unit,
* define this pointer as void *.
*/
struct NetworkContext
{
TlsTransportParams_t * pParams;
};
/*-----------------------------------------------------------*/
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a high-level code.
*/
static const char * pNoHighLevelMbedTlsCodeStr = "<No-High-Level-Code>";
/**
* @brief Represents string to be logged when mbedTLS returned error
* does not contain a low-level code.
*/
static const char * pNoLowLevelMbedTlsCodeStr = "<No-Low-Level-Code>";
/**
* @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_high_level_strerr( mbedTlsCode ) != NULL ) ? \
mbedtls_high_level_strerr( 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_low_level_strerr( mbedTlsCode ) != NULL ) ? \
mbedtls_low_level_strerr( mbedTlsCode ) : pNoLowLevelMbedTlsCodeStr
/*-----------------------------------------------------------*/
/**
* @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 Add X509 certificate to the trusted list of root certificates.
*
* OpenSSL does not provide a single function for reading and loading certificates
* from files into stores, so the file API must be called. Start with the
* root certificate.
*
* @param[out] pSslContext SSL context to which the trusted server root CA is to be added.
* @param[in] pRootCa PEM-encoded string of the trusted server root CA.
* @param[in] rootCaSize Size of the trusted server root CA.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setRootCa( SSLContext_t * pSslContext,
const uint8_t * pRootCa,
size_t rootCaSize );
/**
* @brief Set X509 certificate as client certificate for the server to authenticate.
*
* @param[out] pSslContext SSL context to which the client certificate is to be set.
* @param[in] pClientCert PEM-encoded string of the client certificate.
* @param[in] clientCertSize Size of the client certificate.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setClientCertificate( SSLContext_t * pSslContext,
const uint8_t * pClientCert,
size_t clientCertSize );
/**
* @brief Set private key for the client's certificate.
*
* @param[out] pSslContext SSL context to which the private key is to be set.
* @param[in] pPrivateKey PEM-encoded string of the client private key.
* @param[in] privateKeySize Size of the client private key.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setPrivateKey( SSLContext_t * pSslContext,
const uint8_t * pPrivateKey,
size_t privateKeySize );
/**
* @brief Passes TLS credentials to the OpenSSL library.
*
* Provides the root CA certificate, client certificate, and private key to the
* OpenSSL library. If the client certificate or private key is not NULL, mutual
* authentication is used when performing the TLS handshake.
*
* @param[out] pSslContext SSL context to which the credentials are to be imported.
* @param[in] pNetworkCredentials TLS credentials to be imported.
*
* @return 0 on success; otherwise, failure;
*/
static int32_t setCredentials( SSLContext_t * pSslContext,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Set optional configurations for the TLS connection.
*
* This function is used to set SNI and ALPN protocols.
*
* @param[in] pSslContext SSL context to which the optional configurations are to be set.
* @param[in] pHostName Remote host name, used for server name indication.
* @param[in] pNetworkCredentials TLS setup parameters.
*/
static void setOptionalConfigurations( SSLContext_t * pSslContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Setup TLS by initializing contexts and setting configurations.
*
* @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,
* or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Perform the TLS handshake on a TCP connection.
*
* @param[in] pNetworkContext Network context.
* @param[in] pNetworkCredentials TLS setup parameters.
*
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_HANDSHAKE_FAILED, or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
const NetworkCredentials_t * pNetworkCredentials );
/**
* @brief Initialize mbedTLS.
*
* @param[out] entropyContext mbed TLS entropy context for generation of random numbers.
* @param[out] ctrDrgbContext mbed TLS CTR DRBG context for generation of random numbers.
*
* @return #TLS_TRANSPORT_SUCCESS, or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
mbedtls_ctr_drbg_context * pCtrDrgbContext );
/*-----------------------------------------------------------*/
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_entropy_free( &( pSslContext->entropyContext ) );
mbedtls_ctr_drbg_free( &( pSslContext->ctrDrgbContext ) );
mbedtls_ssl_config_free( &( pSslContext->config ) );
}
/*-----------------------------------------------------------*/
static int32_t setRootCa( SSLContext_t * pSslContext,
const uint8_t * pRootCa,
size_t rootCaSize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pRootCa != NULL );
/* Parse the server root CA certificate into the SSL context. */
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->rootCa ),
pRootCa,
rootCaSize );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse server root CA certificate: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
else
{
mbedtls_ssl_conf_ca_chain( &( pSslContext->config ),
&( pSslContext->rootCa ),
NULL );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setClientCertificate( SSLContext_t * pSslContext,
const uint8_t * pClientCert,
size_t clientCertSize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pClientCert != NULL );
/* Setup the client certificate. */
mbedtlsError = mbedtls_x509_crt_parse( &( pSslContext->clientCert ),
pClientCert,
clientCertSize );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse the client certificate: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setPrivateKey( SSLContext_t * pSslContext,
const uint8_t * pPrivateKey,
size_t privateKeySize )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pPrivateKey != NULL );
/* Setup the client private key. */
mbedtlsError = mbedtls_pk_parse_key( &( pSslContext->privKey ),
pPrivateKey,
privateKeySize,
NULL,
0 );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to parse the client key: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static int32_t setCredentials( SSLContext_t * pSslContext,
const NetworkCredentials_t * pNetworkCredentials )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pNetworkCredentials != NULL );
/* Set up the certificate security profile, starting from the default value. */
pSslContext->certProfile = mbedtls_x509_crt_profile_default;
/* Set SSL authmode and the RNG context. */
mbedtls_ssl_conf_authmode( &( pSslContext->config ),
MBEDTLS_SSL_VERIFY_REQUIRED );
mbedtls_ssl_conf_rng( &( pSslContext->config ),
mbedtls_ctr_drbg_random,
&( pSslContext->ctrDrgbContext ) );
mbedtls_ssl_conf_cert_profile( &( pSslContext->config ),
&( pSslContext->certProfile ) );
mbedtlsError = setRootCa( pSslContext,
pNetworkCredentials->pRootCa,
pNetworkCredentials->rootCaSize );
if( ( pNetworkCredentials->pClientCert != NULL ) &&
( pNetworkCredentials->pPrivateKey != NULL ) )
{
if( mbedtlsError == 0 )
{
mbedtlsError = setClientCertificate( pSslContext,
pNetworkCredentials->pClientCert,
pNetworkCredentials->clientCertSize );
}
if( mbedtlsError == 0 )
{
mbedtlsError = setPrivateKey( pSslContext,
pNetworkCredentials->pPrivateKey,
pNetworkCredentials->privateKeySize );
}
if( mbedtlsError == 0 )
{
mbedtlsError = mbedtls_ssl_conf_own_cert( &( pSslContext->config ),
&( pSslContext->clientCert ),
&( pSslContext->privKey ) );
}
}
return mbedtlsError;
}
/*-----------------------------------------------------------*/
static void setOptionalConfigurations( SSLContext_t * pSslContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials )
{
int32_t mbedtlsError = -1;
configASSERT( pSslContext != NULL );
configASSERT( pHostName != NULL );
configASSERT( pNetworkCredentials != NULL );
if( pNetworkCredentials->pAlpnProtos != NULL )
{
/* Include an application protocol list in the TLS ClientHello
* message. */
mbedtlsError = mbedtls_ssl_conf_alpn_protocols( &( pSslContext->config ),
pNetworkCredentials->pAlpnProtos );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to configure ALPN protocol in mbed TLS: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
}
/* Enable SNI if requested. */
if( pNetworkCredentials->disableSni == pdFALSE )
{
mbedtlsError = mbedtls_ssl_set_hostname( &( pSslContext->context ),
pHostName );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to set server name: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
}
/* Set Maximum Fragment Length if enabled. */
#ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
/* Enable the max fragment extension. 4096 bytes is currently the largest fragment size permitted.
* See RFC 8449 https://tools.ietf.org/html/rfc8449 for more information.
*
* Smaller values can be found in "mbedtls/include/ssl.h".
*/
mbedtlsError = mbedtls_ssl_conf_max_frag_len( &( pSslContext->config ), MBEDTLS_SSL_MAX_FRAG_LEN_4096 );
if( mbedtlsError != 0 )
{
LogError( ( "Failed to maximum fragment length extension: mbedTLSError= %s : %s.",
mbedtlsHighLevelCodeOrDefault( mbedtlsError ),
mbedtlsLowLevelCodeOrDefault( mbedtlsError ) ) );
}
#endif /* ifdef MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetworkContext,
const char * pHostName,
const NetworkCredentials_t * pNetworkCredentials )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t mbedtlsError = 0;
configASSERT( pNetworkContext != NULL );
configASSERT( pNetworkContext->pParams != NULL );
configASSERT( pHostName != NULL );
configASSERT( pNetworkCredentials != NULL );
configASSERT( pNetworkCredentials->pRootCa != NULL );
pTlsTransportParams = pNetworkContext->pParams;
/* Initialize the mbed TLS context structures. */
sslContextInit( &( pTlsTransportParams->sslContext ) );
mbedtlsError = mbedtls_ssl_config_defaults( &( pTlsTransportParams->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 )
{
mbedtlsError = setCredentials( &( pTlsTransportParams->sslContext ),
pNetworkCredentials );
if( mbedtlsError != 0 )
{
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
else
{
/* Optionally set SNI and ALPN protocols. */
setOptionalConfigurations( &( pTlsTransportParams->sslContext ),
pHostName,
pNetworkCredentials );
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t tlsHandshake( NetworkContext_t * pNetworkContext,
const NetworkCredentials_t * pNetworkCredentials )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t mbedtlsError = 0;
configASSERT( pNetworkContext != NULL );
configASSERT( pNetworkContext->pParams != NULL );
configASSERT( pNetworkCredentials != NULL );
pTlsTransportParams = pNetworkContext->pParams;
/* Initialize the mbed TLS secured connection context. */
mbedtlsError = mbedtls_ssl_setup( &( pTlsTransportParams->sslContext.context ),
&( pTlsTransportParams->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. */
/* MISRA Rule 11.2 flags the following line for casting the second
* parameter to void *. This rule is suppressed because
* #mbedtls_ssl_set_bio requires the second parameter as void *.
*/
/* coverity[misra_c_2012_rule_11_2_violation] */
/* These two macros MBEDTLS_SSL_SEND and MBEDTLS_SSL_RECV need to be
* defined in mbedtls_config.h according to which implementation you use.
*/
mbedtls_ssl_set_bio( &( pTlsTransportParams->sslContext.context ),
( void * ) pTlsTransportParams->tcpSocket,
MBEDTLS_SSL_SEND,
MBEDTLS_SSL_RECV,
NULL );
}
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
/* Perform the TLS handshake. */
do
{
mbedtlsError = mbedtls_ssl_handshake( &( pTlsTransportParams->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;
}
else
{
LogInfo( ( "(Network connection %p) TLS handshake successful.",
pNetworkContext ) );
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t initMbedtls( mbedtls_entropy_context * pEntropyContext,
mbedtls_ctr_drbg_context * pCtrDrgbContext )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
int32_t 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( pEntropyContext );
mbedtls_ctr_drbg_init( pCtrDrgbContext );
/* Add a strong entropy source. At least one is required. */
mbedtlsError = mbedtls_entropy_add_source( pEntropyContext,
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( pCtrDrgbContext,
mbedtls_entropy_func,
pEntropyContext,
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 )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
BaseType_t socketStatus = 0;
if( ( pNetworkContext == NULL ) ||
( pNetworkContext->pParams == 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;
}
else
{
/* Empty else for MISRA 15.7 compliance. */
}
/* Establish a TCP connection with the server. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
pTlsTransportParams = pNetworkContext->pParams;
socketStatus = Sockets_Connect( &( pTlsTransportParams->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( &( pTlsTransportParams->sslContext.entropyContext ),
&( pTlsTransportParams->sslContext.ctrDrgbContext ) );
}
/* Initialize TLS contexts and set credentials. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = tlsSetup( pNetworkContext, pHostName, pNetworkCredentials );
}
/* Perform TLS handshake. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = tlsHandshake( pNetworkContext, pNetworkCredentials );
}
/* Clean up on failure. */
if( returnStatus != TLS_TRANSPORT_SUCCESS )
{
if( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) )
{
sslContextFree( &( pTlsTransportParams->sslContext ) );
if( pTlsTransportParams->tcpSocket != FREERTOS_INVALID_SOCKET )
{
( void ) FreeRTOS_closesocket( pTlsTransportParams->tcpSocket );
}
}
}
else
{
LogInfo( ( "(Network connection %p) Connection to %s established.",
pNetworkContext,
pHostName ) );
}
return returnStatus;
}
/*-----------------------------------------------------------*/
void TLS_FreeRTOS_Disconnect( NetworkContext_t * pNetworkContext )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
BaseType_t tlsStatus = 0;
if( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) )
{
pTlsTransportParams = pNetworkContext->pParams;
/* Attempting to terminate TLS connection. */
tlsStatus = ( BaseType_t ) mbedtls_ssl_close_notify( &( pTlsTransportParams->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( pTlsTransportParams->tcpSocket );
/* Free mbed TLS contexts. */
sslContextFree( &( pTlsTransportParams->sslContext ) );
}
/* 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 )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
int32_t tlsStatus = 0;
configASSERT( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) );
pTlsTransportParams = pNetworkContext->pParams;
tlsStatus = ( int32_t ) mbedtls_ssl_read( &( pTlsTransportParams->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 )
{
TlsTransportParams_t * pTlsTransportParams = NULL;
int32_t tlsStatus = 0;
configASSERT( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) );
pTlsTransportParams = pNetworkContext->pParams;
tlsStatus = ( int32_t ) mbedtls_ssl_write( &( pTlsTransportParams->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;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,218 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/**
* @file tls_freertos.h
* @brief TLS transport interface header.
*/
#ifndef USING_MBEDTLS
#define USING_MBEDTLS
/**************************************************/
/******* 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
/* Prototype for the function used to print to console on Windows simulator
* of FreeRTOS.
* The function prints to the console before the network is connected;
* then a UDP port after the network has connected. */
extern void vLoggingPrintf( const char * pcFormatString,
... );
/* Map the SdkLog macro to the logging function to enable logging
* on Windows simulator. */
#ifndef SdkLog
#define SdkLog( message ) vLoggingPrintf message
#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/error.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_entropy_context entropyContext; /**< @brief Entropy context for random number generation. */
mbedtls_ctr_drbg_context ctrDrgbContext; /**< @brief CTR DRBG context for random number generation. */
} SSLContext_t;
/**
* @brief Parameters for the network context of the transport interface
* implementation that uses mbedTLS and FreeRTOS+TCP sockets.
*/
typedef struct TlsTransportParams
{
Socket_t tcpSocket;
SSLContext_t sslContext;
} TlsTransportParams_t;
/**
* @brief Contains the credentials necessary for tls connection setup.
*/
typedef struct NetworkCredentials
{
/**
* @brief To use ALPN, set this to a NULL-terminated list of supported
* protocols in decreasing order of preference.
*
* 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 uint8_t * pRootCa; /**< @brief String representing a trusted server root certificate. */
size_t rootCaSize; /**< @brief Size associated with #NetworkCredentials.pRootCa. */
const uint8_t * pClientCert; /**< @brief String representing the client certificate. */
size_t clientCertSize; /**< @brief Size associated with #NetworkCredentials.pClientCert. */
const uint8_t * pPrivateKey; /**< @brief String representing the client certificate's private key. */
size_t privateKeySize; /**< @brief Size associated with #NetworkCredentials.pPrivateKey. */
} 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 USING_MBEDTLS */

View file

@ -0,0 +1,231 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/**
* @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 USING_MBEDTLS_PKCS11
#define USING_MBEDTLS_PKCS11
/**************************************************/
/******* 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
/* Prototype for the function used to print to console on Windows simulator
* of FreeRTOS.
* The function prints to the console before the network is connected;
* then a UDP port after the network has connected. */
extern void vLoggingPrintf( const char * pcFormatString,
... );
/* Map the SdkLog macro to the logging function to enable logging
* on Windows simulator. */
#ifndef SdkLog
#define SdkLog( message ) vLoggingPrintf message
#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"
#include "mbedtls/error.h"
/* PKCS #11 includes. */
#include "core_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.
*/
typedef struct TlsTransportParams
{
Socket_t tcpSocket;
SSLContext_t sslContext;
} TlsTransportParams_t;
/**
* @brief Contains the credentials necessary for tls connection setup.
*/
typedef struct NetworkCredentials
{
/**
* @brief To use ALPN, set this to a NULL-terminated list of supported
* protocols in decreasing order of preference.
*
* 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 #NetworkCredentials.pRootCa. */
const unsigned char * pUserName; /**< @brief String representing the username for MQTT. */
size_t userNameSize; /**< @brief Size associated with #NetworkCredentials.pUserName. */
const unsigned char * pPassword; /**< @brief String representing the password for MQTT. */
size_t passwordSize; /**< @brief Size associated with #NetworkCredentials.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 USING_MBEDTLS_PKCS11 */

View file

@ -0,0 +1,199 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#if ( configUSE_PREEMPTION == 0 )
#include "task.h"
#endif
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
/* FreeRTOS Socket wrapper include. */
#include "sockets_wrapper.h"
/* Transport interface include. */
#include "using_plaintext.h"
/*-----------------------------------------------------------*/
/**
* @brief Each compilation unit that consumes the NetworkContext must define it.
* It should contain a single pointer as seen below whenever the header file
* of this transport implementation is included to your project.
*
* @note When using multiple transports in the same compilation unit,
* define this pointer as void *.
*/
struct NetworkContext
{
PlaintextTransportParams_t * pParams;
};
/*-----------------------------------------------------------*/
PlaintextTransportStatus_t Plaintext_FreeRTOS_Connect( NetworkContext_t * pNetworkContext,
const char * pHostName,
uint16_t port,
uint32_t receiveTimeoutMs,
uint32_t sendTimeoutMs )
{
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS;
BaseType_t socketStatus = 0;
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) || ( pHostName == NULL ) )
{
LogError( ( "Invalid input parameter(s): Arguments cannot be NULL. pNetworkContext=%p, "
"pHostName=%p.",
pNetworkContext,
pHostName ) );
plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER;
}
else
{
pPlaintextTransportParams = pNetworkContext->pParams;
/* Establish a TCP connection with the server. */
socketStatus = Sockets_Connect( &( pPlaintextTransportParams->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 )
{
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
PlaintextTransportStatus_t plaintextStatus = PLAINTEXT_TRANSPORT_SUCCESS;
if( ( pNetworkContext == NULL ) || ( pNetworkContext->pParams == NULL ) )
{
LogError( ( "pNetworkContext cannot be NULL." ) );
plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER;
}
else if( pNetworkContext->pParams->tcpSocket == FREERTOS_INVALID_SOCKET )
{
LogError( ( "pPlaintextTransportParams->tcpSocket cannot be an invalid socket." ) );
plaintextStatus = PLAINTEXT_TRANSPORT_INVALID_PARAMETER;
}
else
{
pPlaintextTransportParams = pNetworkContext->pParams;
/* Call socket disconnect function to close connection. */
Sockets_Disconnect( pPlaintextTransportParams->tcpSocket );
}
return plaintextStatus;
}
int32_t Plaintext_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
void * pBuffer,
size_t bytesToRecv )
{
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
int32_t socketStatus = 1;
configASSERT( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) );
pPlaintextTransportParams = pNetworkContext->pParams;
/* The TCP socket may have a receive block time. If bytesToRecv is greater
* than 1 then a frame is likely already part way through reception and
* blocking to wait for the desired number of bytes to be available is the
* most efficient thing to do. If bytesToRecv is 1 then this may be a
* speculative call to read to find the start of a new frame, in which case
* blocking is not desirable as it could block an entire protocol agent
* task for the duration of the read block time and therefore negatively
* impact performance. So if bytesToRecv is 1 then don't call recv unless
* it is known that bytes are already available. */
if( bytesToRecv == 1 )
{
socketStatus = ( int32_t ) FreeRTOS_recvcount( pPlaintextTransportParams->tcpSocket );
}
if( socketStatus > 0 )
{
socketStatus = FreeRTOS_recv( pPlaintextTransportParams->tcpSocket,
pBuffer,
bytesToRecv,
0 );
}
return socketStatus;
}
int32_t Plaintext_FreeRTOS_send( NetworkContext_t * pNetworkContext,
const void * pBuffer,
size_t bytesToSend )
{
PlaintextTransportParams_t * pPlaintextTransportParams = NULL;
int32_t socketStatus = 0;
configASSERT( ( pNetworkContext != NULL ) && ( pNetworkContext->pParams != NULL ) );
pPlaintextTransportParams = pNetworkContext->pParams;
socketStatus = FreeRTOS_send( pPlaintextTransportParams->tcpSocket,
pBuffer,
bytesToSend,
0 );
if( socketStatus == -pdFREERTOS_ERRNO_ENOSPC )
{
/* The TCP buffers could not accept any more bytes so zero bytes were sent.
* This is not necessarily an error that should cause a disconnect
* unless it persists. */
socketStatus = 0;
}
#if ( configUSE_PREEMPTION == 0 )
{
/* FreeRTOS_send adds the packet to be sent to the IP task's queue for later processing.
* The packet is sent later by the IP task. When FreeRTOS is used in collaborative
* mode (i.e. configUSE_PREEMPTION is 0), call taskYIELD to give IP task a chance to run
* so that the packet is actually sent before this function returns. */
taskYIELD();
}
#endif
return socketStatus;
}

View file

@ -0,0 +1,152 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
#ifndef USING_PLAINTEXT_H
#define USING_PLAINTEXT_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
/* Prototype for the function used to print to console on Windows simulator
* of FreeRTOS.
* The function prints to the console before the network is connected;
* then a UDP port after the network has connected. */
extern void vLoggingPrintf( const char * pcFormatString,
... );
/* Map the SdkLog macro to the logging function to enable logging
* on Windows simulator. */
#ifndef SdkLog
#define SdkLog( message ) vLoggingPrintf message
#endif
#include "logging_stack.h"
/************ End of logging configuration ****************/
/* FreeRTOS+TCP include. */
#include "FreeRTOS_Sockets.h"
/* Transport interface include. */
#include "transport_interface.h"
/**
* @brief Parameters for the network context that uses FreeRTOS+TCP sockets.
*/
typedef struct PlaintextTransportParams
{
Socket_t tcpSocket;
} PlaintextTransportParams_t;
/**
* @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.
*
* @note When the number of bytes requested is 1, the TCP socket's Rx stream
* is checked for available bytes to read. If there are none, this function
* immediately returns 0 without blocking.
*
* @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 USING_PLAINTEXT_H */

View file

@ -0,0 +1,536 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/**
* @file using_wolfSSL.c
* @brief TLS transport interface implementations. This implementation uses
* wolfSSL.
*/
/* Standard includes. */
#include <string.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
/* TLS transport header. */
#include "using_wolfSSL.h"
/* FreeRTOS Socket wrapper include. */
#include "sockets_wrapper.h"
/* wolfSSL user settings header */
#include "user_settings.h"
/* Demo Specific configs. */
#include "demo_config.h"
/**
* @brief Initialize the TLS structures in a network connection.
*
* @param[in] pSslContext The SSL context to initialize.
*/
static void sslContextInit( SSLContext_t * pSslContext );
/**
* @brief Free the 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 TLS component.
*
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INSUFFICIENT_MEMORY, or #TLS_TRANSPORT_INTERNAL_ERROR.
*/
static TlsTransportStatus_t initTLS( void );
/*
* @brief Receive date from the socket passed as the context
*
* @param[in] ssl WOLFSSL object.
* @param[in] buf Buffer for received data
* @param[in] sz Size to receive
* @param[in] context Socket to be received from
*
* @return received size( > 0 ), #WOLFSSL_CBIO_ERR_CONN_CLOSE, #WOLFSSL_CBIO_ERR_WANT_READ.
*/
static int wolfSSL_IORecvGlue( WOLFSSL * ssl,
char * buf,
int sz,
void * context );
/*
* @brief Send date to the socket passed as the context
*
* @param[in] ssl WOLFSSL object.
* @param[in] buf Buffer for data to be sent
* @param[in] sz Size to send
* @param[in] context Socket to be sent to
*
* @return received size( > 0 ), #WOLFSSL_CBIO_ERR_CONN_CLOSE, #WOLFSSL_CBIO_ERR_WANT_WRITE.
*/
static int wolfSSL_IOSendGlue( WOLFSSL * ssl,
char * buf,
int sz,
void * context );
/*
* @brief Load credentials from file/buffer
*
* @param[in] pNetCtx NetworkContext_t
* @param[in] pNetCred NetworkCredentials_t
*
* @return #TLS_TRANSPORT_SUCCESS, #TLS_TRANSPORT_INVALID_CREDENTIALS.
*/
static TlsTransportStatus_t loadCredentials( NetworkContext_t * pNetCtx,
const NetworkCredentials_t * pNetCred );
/*-----------------------------------------------------------*/
static int wolfSSL_IORecvGlue( WOLFSSL * ssl,
char * buf,
int sz,
void * context )
{
( void ) ssl; /* to prevent unused warning*/
BaseType_t read = 0;
Socket_t xSocket = ( Socket_t ) context;
read = FreeRTOS_recv( xSocket, ( void * ) buf, ( size_t ) sz, 0 );
if( ( read == 0 ) ||
( read == -pdFREERTOS_ERRNO_EWOULDBLOCK ) )
{
read = WOLFSSL_CBIO_ERR_WANT_READ;
}
else if( read == -pdFREERTOS_ERRNO_ENOTCONN )
{
read = WOLFSSL_CBIO_ERR_CONN_CLOSE;
}
else
{
/* do nothing */
}
return ( int ) read;
}
/*-----------------------------------------------------------*/
static int wolfSSL_IOSendGlue( WOLFSSL * ssl,
char * buf,
int sz,
void * context )
{
( void ) ssl; /* to prevent unused warning*/
Socket_t xSocket = ( Socket_t ) context;
BaseType_t sent = FreeRTOS_send( xSocket, ( void * ) buf, ( size_t ) sz, 0 );
if( sent == -pdFREERTOS_ERRNO_EWOULDBLOCK )
{
sent = WOLFSSL_CBIO_ERR_WANT_WRITE;
}
else if( sent == -pdFREERTOS_ERRNO_ENOTCONN )
{
sent = WOLFSSL_CBIO_ERR_CONN_CLOSE;
}
else
{
/* do nothing */
}
return ( int ) sent;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t initTLS( void )
{
/* initialize wolfSSL */
wolfSSL_Init();
#ifdef DEBUG_WOLFSSL
wolfSSL_Debugging_ON();
#endif
return TLS_TRANSPORT_SUCCESS;
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t loadCredentials( NetworkContext_t * pNetCtx,
const NetworkCredentials_t * pNetCred )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
configASSERT( pNetCtx != NULL );
configASSERT( pNetCred != NULL );
#if defined( democonfigCREDENTIALS_IN_BUFFER )
if( wolfSSL_CTX_load_verify_buffer( pNetCtx->sslContext.ctx,
( const byte * ) ( pNetCred->pRootCa ), ( long ) ( pNetCred->rootCaSize ),
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
{
if( wolfSSL_CTX_use_certificate_buffer( pNetCtx->sslContext.ctx,
( const byte * ) ( pNetCred->pClientCert ), ( long ) ( pNetCred->clientCertSize ),
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
{
if( wolfSSL_CTX_use_PrivateKey_buffer( pNetCtx->sslContext.ctx,
( const byte * ) ( pNetCred->pPrivateKey ), ( long ) ( pNetCred->privateKeySize ),
SSL_FILETYPE_PEM ) == SSL_SUCCESS )
{
returnStatus = TLS_TRANSPORT_SUCCESS;
}
else
{
LogError( ( "Failed to load client-private-key from buffer" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
}
else
{
LogError( ( "Failed to load client-certificate from buffer" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
}
else
{
LogError( ( "Failed to load ca-certificate from buffer" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
return returnStatus;
#else /* if defined( democonfigCREDENTIALS_IN_BUFFER ) */
if( wolfSSL_CTX_load_verify_locations( pNetCtx->sslContext.ctx,
( const char * ) ( pNetCred->pRootCa ), NULL ) == SSL_SUCCESS )
{
if( wolfSSL_CTX_use_certificate_file( pNetCtx->sslContext.ctx,
( const char * ) ( pNetCred->pClientCert ), SSL_FILETYPE_PEM )
== SSL_SUCCESS )
{
if( wolfSSL_CTX_use_PrivateKey_file( pNetCtx->sslContext.ctx,
( const char * ) ( pNetCred->pPrivateKey ), SSL_FILETYPE_PEM )
== SSL_SUCCESS )
{
returnStatus = TLS_TRANSPORT_SUCCESS;
}
else
{
LogError( ( "Failed to load client-private-key file" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
}
else
{
LogError( ( "Failed to load client-certificate file" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
}
else
{
LogError( ( "Failed to load ca-certificate file" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
return returnStatus;
#endif /* if defined( democonfigCREDENTIALS_IN_BUFFER ) */
}
/*-----------------------------------------------------------*/
static TlsTransportStatus_t tlsSetup( NetworkContext_t * pNetCtx,
const char * pHostName,
const NetworkCredentials_t * pNetCred )
{
TlsTransportStatus_t returnStatus = TLS_TRANSPORT_SUCCESS;
Socket_t xSocket = { 0 };
configASSERT( pNetCtx != NULL );
configASSERT( pHostName != NULL );
configASSERT( pNetCred != NULL );
configASSERT( pNetCred->pRootCa != NULL );
configASSERT( pNetCtx->tcpSocket != NULL );
if( pNetCtx->sslContext.ctx == NULL )
{
/* Attempt to create a context that uses the TLS 1.3 or 1.2 */
pNetCtx->sslContext.ctx =
wolfSSL_CTX_new( wolfSSLv23_client_method_ex( NULL ) );
}
if( pNetCtx->sslContext.ctx != NULL )
{
/* load credentials from file */
if( loadCredentials( pNetCtx, pNetCred ) == TLS_TRANSPORT_SUCCESS )
{
/* create a ssl object */
pNetCtx->sslContext.ssl =
wolfSSL_new( pNetCtx->sslContext.ctx );
if( pNetCtx->sslContext.ssl != NULL )
{
xSocket = pNetCtx->tcpSocket;
/* set Recv/Send glue functions to the WOLFSSL object */
wolfSSL_SSLSetIORecv( pNetCtx->sslContext.ssl,
wolfSSL_IORecvGlue );
wolfSSL_SSLSetIOSend( pNetCtx->sslContext.ssl,
wolfSSL_IOSendGlue );
/* set socket as a context of read/send glue funcs */
wolfSSL_SetIOReadCtx( pNetCtx->sslContext.ssl, xSocket );
wolfSSL_SetIOWriteCtx( pNetCtx->sslContext.ssl, xSocket );
/* let wolfSSL perform tls handshake */
if( wolfSSL_connect( pNetCtx->sslContext.ssl )
== SSL_SUCCESS )
{
returnStatus = TLS_TRANSPORT_SUCCESS;
}
else
{
wolfSSL_shutdown( pNetCtx->sslContext.ssl );
wolfSSL_free( pNetCtx->sslContext.ssl );
pNetCtx->sslContext.ssl = NULL;
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
pNetCtx->sslContext.ctx = NULL;
LogError( ( "Failed to establish a TLS connection" ) );
returnStatus = TLS_TRANSPORT_HANDSHAKE_FAILED;
}
}
else
{
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
pNetCtx->sslContext.ctx = NULL;
LogError( ( "Failed to create wolfSSL object" ) );
returnStatus = TLS_TRANSPORT_INTERNAL_ERROR;
}
}
else
{
wolfSSL_CTX_free( pNetCtx->sslContext.ctx );
pNetCtx->sslContext.ctx = NULL;
LogError( ( "Failed to load credentials" ) );
returnStatus = TLS_TRANSPORT_INVALID_CREDENTIALS;
}
}
else
{
LogError( ( "Failed to create a wolfSSL_CTX" ) );
returnStatus = TLS_TRANSPORT_CONNECT_FAILURE;
}
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 tls. */
if( returnStatus == TLS_TRANSPORT_SUCCESS )
{
returnStatus = initTLS();
}
/* 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 )
{
WOLFSSL * pSsl = pNetworkContext->sslContext.ssl;
WOLFSSL_CTX * pCtx = NULL;
/* shutdown an active TLS connection */
wolfSSL_shutdown( pSsl );
/* cleanup WOLFSSL object */
wolfSSL_free( pSsl );
pNetworkContext->sslContext.ssl = NULL;
/* Call socket shutdown function to close connection. */
Sockets_Disconnect( pNetworkContext->tcpSocket );
/* free WOLFSSL_CTX object*/
pCtx = pNetworkContext->sslContext.ctx;
wolfSSL_CTX_free( pCtx );
pNetworkContext->sslContext.ctx = NULL;
wolfSSL_Cleanup();
}
/*-----------------------------------------------------------*/
int32_t TLS_FreeRTOS_recv( NetworkContext_t * pNetworkContext,
void * pBuffer,
size_t bytesToRecv )
{
int32_t tlsStatus = 0;
int iResult = 0;
WOLFSSL * pSsl = pNetworkContext->sslContext.ssl;
iResult = wolfSSL_read( pSsl, pBuffer, bytesToRecv );
if( iResult > 0 )
{
tlsStatus = iResult;
}
else if( wolfSSL_want_read( pSsl ) == 1 )
{
tlsStatus = 0;
}
else
{
tlsStatus = wolfSSL_state( pSsl );
LogError( ( "Error from wolfSSL_read %d : %s ",
iResult, wolfSSL_ERR_reason_error_string( tlsStatus ) ) );
}
return tlsStatus;
}
/*-----------------------------------------------------------*/
int32_t TLS_FreeRTOS_send( NetworkContext_t * pNetworkContext,
const void * pBuffer,
size_t bytesToSend )
{
int32_t tlsStatus = 0;
int iResult = 0;
WOLFSSL * pSsl = pNetworkContext->sslContext.ssl;
iResult = wolfSSL_write( pSsl, pBuffer, bytesToSend );
if( iResult > 0 )
{
tlsStatus = iResult;
}
else if( wolfSSL_want_write( pSsl ) == 1 )
{
tlsStatus = 0;
}
else
{
tlsStatus = wolfSSL_state( pSsl );
LogError( ( "Error from wolfSL_write %d : %s ",
iResult, wolfSSL_ERR_reason_error_string( tlsStatus ) ) );
}
return tlsStatus;
}
/*-----------------------------------------------------------*/

View file

@ -0,0 +1,199 @@
/*
* FreeRTOS V202107.00
* 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.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/**
* @file using_wolfSSL.h
* @brief TLS transport interface header.
*/
#ifndef USING_WOLFSSL_H
#define USING_WOLFSSL_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_INFO
#endif
#include "logging_stack.h"
/************ End of logging configuration ****************/
/* FreeRTOS+TCP include. */
#include "FreeRTOS_Sockets.h"
/* Transport interface include. */
#include "transport_interface.h"
/* wolfSSL interface include. */
#include "wolfssl/ssl.h"
/**
* @brief Secured connection context.
*/
typedef struct SSLContext
{
WOLFSSL_CTX* ctx; /**< @brief wolfSSL context */
WOLFSSL* ssl; /**< @brief wolfSSL ssl session 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 USING_WOLFSSL_H */