From 39d1dae06cea4ae46cc87541c4a41f12bbe2b480 Mon Sep 17 00:00:00 2001 From: Jitin George Date: Wed, 19 Dec 2018 12:03:52 +0530 Subject: [PATCH] esp-tls: Add support for simplified TLS This is based on from esp-idf's esp-tls component. Latest commit ID on esp-idf: dec70a760120d3c6d1d63ac0257dce6a8561879c Some HTTP convenience APIs have been removed from esp-idf's esp-tls component while porting it ESP8266-RTOS-SDK due to non-availabilty of http_parser --- components/esp-tls/CMakeLists.txt | 7 + components/esp-tls/component.mk | 7 + components/esp-tls/esp_tls.c | 492 ++++++++++++++++++++++++++++++ components/esp-tls/esp_tls.h | 276 +++++++++++++++++ 4 files changed, 782 insertions(+) create mode 100644 components/esp-tls/CMakeLists.txt create mode 100644 components/esp-tls/component.mk create mode 100644 components/esp-tls/esp_tls.c create mode 100644 components/esp-tls/esp_tls.h diff --git a/components/esp-tls/CMakeLists.txt b/components/esp-tls/CMakeLists.txt new file mode 100644 index 00000000..23f953d9 --- /dev/null +++ b/components/esp-tls/CMakeLists.txt @@ -0,0 +1,7 @@ +set(COMPONENT_SRCS "esp_tls.c") +set(COMPONENT_ADD_INCLUDEDIRS ".") + +set(COMPONENT_REQUIRES mbedtls) +set(COMPONENT_PRIV_REQUIRES lwip nghttp) + +register_component() diff --git a/components/esp-tls/component.mk b/components/esp-tls/component.mk new file mode 100644 index 00000000..680168b7 --- /dev/null +++ b/components/esp-tls/component.mk @@ -0,0 +1,7 @@ +ifdef CONFIG_SSL_USING_MBEDTLS +COMPONENT_SRCDIRS := . +COMPONENT_ADD_INCLUDEDIRS := . +else +COMPONENT_SRCDIRS := +COMPONENT_ADD_INCLUDEDIRS := +endif diff --git a/components/esp-tls/esp_tls.c b/components/esp-tls/esp_tls.c new file mode 100644 index 00000000..8737d420 --- /dev/null +++ b/components/esp-tls/esp_tls.c @@ -0,0 +1,492 @@ +// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include +#include +#include + +#include +#include +#include + +#include "esp_tls.h" +#include + +static const char *TAG = "esp-tls"; +static mbedtls_x509_crt *global_cacert = NULL; + +#ifdef ESP_PLATFORM +#include +#else +#define ESP_LOGD(TAG, ...) //printf(__VA_ARGS__); +#define ESP_LOGE(TAG, ...) printf(__VA_ARGS__); +#endif + +static struct addrinfo *resolve_host_name(const char *host, size_t hostlen) +{ + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + char *use_host = strndup(host, hostlen); + if (!use_host) { + return NULL; + } + + ESP_LOGD(TAG, "host:%s: strlen %lu", use_host, (unsigned long)hostlen); + struct addrinfo *res; + if (getaddrinfo(use_host, NULL, &hints, &res)) { + ESP_LOGE(TAG, "couldn't get hostname for :%s:", use_host); + free(use_host); + return NULL; + } + free(use_host); + return res; +} + +static ssize_t tcp_read(esp_tls_t *tls, char *data, size_t datalen) +{ + return recv(tls->sockfd, data, datalen, 0); +} + +static ssize_t tls_read(esp_tls_t *tls, char *data, size_t datalen) +{ + ssize_t ret = mbedtls_ssl_read(&tls->ssl, (unsigned char *)data, datalen); + if (ret < 0) { + if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + return 0; + } + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + ESP_LOGE(TAG, "read error :%d:", ret); + } + } + return ret; +} + +static void ms_to_timeval(int timeout_ms, struct timeval *tv) +{ + tv->tv_sec = timeout_ms / 1000; + tv->tv_usec = (timeout_ms % 1000) * 1000; +} + +static int esp_tcp_connect(const char *host, int hostlen, int port, int *sockfd, const esp_tls_cfg_t *cfg) +{ + int ret = -1; + struct addrinfo *res = resolve_host_name(host, hostlen); + if (!res) { + return ret; + } + + int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if (fd < 0) { + ESP_LOGE(TAG, "Failed to create socket (family %d socktype %d protocol %d)", res->ai_family, res->ai_socktype, res->ai_protocol); + goto err_freeaddr; + } + *sockfd = fd; + + void *addr_ptr; + if (res->ai_family == AF_INET) { + struct sockaddr_in *p = (struct sockaddr_in *)res->ai_addr; + p->sin_port = htons(port); + addr_ptr = p; + } else if (res->ai_family == AF_INET6) { + struct sockaddr_in6 *p = (struct sockaddr_in6 *)res->ai_addr; + p->sin6_port = htons(port); + p->sin6_family = AF_INET6; + addr_ptr = p; + } else { + ESP_LOGE(TAG, "Unsupported protocol family %d", res->ai_family); + goto err_freesocket; + } + + if (cfg) { + if (cfg->timeout_ms >= 0) { + struct timeval tv; + ms_to_timeval(cfg->timeout_ms, &tv); + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + } + if (cfg->non_block) { + int flags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + } + + ret = connect(fd, addr_ptr, res->ai_addrlen); + if (ret < 0 && !(errno == EINPROGRESS && cfg->non_block)) { + + ESP_LOGE(TAG, "Failed to connnect to host (errno %d)", errno); + goto err_freesocket; + } + + freeaddrinfo(res); + return 0; + +err_freesocket: + close(fd); +err_freeaddr: + freeaddrinfo(res); + return ret; +} + +esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes) +{ + if (cacert_pem_buf == NULL) { + ESP_LOGE(TAG, "cacert_pem_buf is null"); + return ESP_ERR_INVALID_ARG; + } + if (global_cacert != NULL) { + mbedtls_x509_crt_free(global_cacert); + } + global_cacert = (mbedtls_x509_crt *)calloc(1, sizeof(mbedtls_x509_crt)); + if (global_cacert == NULL) { + ESP_LOGE(TAG, "global_cacert not allocated"); + return ESP_ERR_NO_MEM; + } + mbedtls_x509_crt_init(global_cacert); + int ret = mbedtls_x509_crt_parse(global_cacert, cacert_pem_buf, cacert_pem_bytes); + if (ret < 0) { + ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); + mbedtls_x509_crt_free(global_cacert); + global_cacert = NULL; + return ESP_FAIL; + } else if (ret > 0) { + ESP_LOGE(TAG, "mbedtls_x509_crt_parse was partly successful. No. of failed certificates: %d", ret); + } + return ESP_OK; +} + +mbedtls_x509_crt *esp_tls_get_global_ca_store() +{ + return global_cacert; +} + +void esp_tls_free_global_ca_store() +{ + if (global_cacert) { + mbedtls_x509_crt_free(global_cacert); + global_cacert = NULL; + } +} + +static void verify_certificate(esp_tls_t *tls) +{ + int flags; + char buf[100]; + if ((flags = mbedtls_ssl_get_verify_result(&tls->ssl)) != 0) { + ESP_LOGI(TAG, "Failed to verify peer certificate!"); + bzero(buf, sizeof(buf)); + mbedtls_x509_crt_verify_info(buf, sizeof(buf), " ! ", flags); + ESP_LOGI(TAG, "verification info: %s", buf); + } else { + ESP_LOGI(TAG, "Certificate verified."); + } +} + +static void mbedtls_cleanup(esp_tls_t *tls) +{ + if (!tls) { + return; + } + if (tls->cacert_ptr != global_cacert) { + mbedtls_x509_crt_free(tls->cacert_ptr); + } + tls->cacert_ptr = NULL; + mbedtls_x509_crt_free(&tls->cacert); + mbedtls_x509_crt_free(&tls->clientcert); + mbedtls_pk_free(&tls->clientkey); + mbedtls_entropy_free(&tls->entropy); + mbedtls_ssl_config_free(&tls->conf); + mbedtls_ctr_drbg_free(&tls->ctr_drbg); + mbedtls_ssl_free(&tls->ssl); + mbedtls_net_free(&tls->server_fd); +} + +static int create_ssl_handle(esp_tls_t *tls, const char *hostname, size_t hostlen, const esp_tls_cfg_t *cfg) +{ + int ret; + + mbedtls_net_init(&tls->server_fd); + tls->server_fd.fd = tls->sockfd; + mbedtls_ssl_init(&tls->ssl); + mbedtls_ctr_drbg_init(&tls->ctr_drbg); + mbedtls_ssl_config_init(&tls->conf); + mbedtls_entropy_init(&tls->entropy); + + if ((ret = mbedtls_ctr_drbg_seed(&tls->ctr_drbg, + mbedtls_entropy_func, &tls->entropy, NULL, 0)) != 0) { + ESP_LOGE(TAG, "mbedtls_ctr_drbg_seed returned %d", ret); + goto exit; + } + + /* Hostname set here should match CN in server certificate */ + char *use_host = strndup(hostname, hostlen); + if (!use_host) { + goto exit; + } + + if ((ret = mbedtls_ssl_set_hostname(&tls->ssl, use_host)) != 0) { + ESP_LOGE(TAG, "mbedtls_ssl_set_hostname returned -0x%x", -ret); + free(use_host); + goto exit; + } + free(use_host); + + if ((ret = mbedtls_ssl_config_defaults(&tls->conf, + MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + ESP_LOGE(TAG, "mbedtls_ssl_config_defaults returned %d", ret); + goto exit; + } + +#ifdef CONFIG_MBEDTLS_SSL_ALPN + if (cfg->alpn_protos) { + mbedtls_ssl_conf_alpn_protocols(&tls->conf, cfg->alpn_protos); + } +#endif + + if (cfg->use_global_ca_store == true) { + if (global_cacert == NULL) { + ESP_LOGE(TAG, "global_cacert is NULL"); + goto exit; + } + tls->cacert_ptr = global_cacert; + mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); + mbedtls_ssl_conf_ca_chain(&tls->conf, tls->cacert_ptr, NULL); + } else if (cfg->cacert_pem_buf != NULL) { + tls->cacert_ptr = &tls->cacert; + mbedtls_x509_crt_init(tls->cacert_ptr); + ret = mbedtls_x509_crt_parse(tls->cacert_ptr, cfg->cacert_pem_buf, cfg->cacert_pem_bytes); + if (ret < 0) { + ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); + goto exit; + } + mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED); + mbedtls_ssl_conf_ca_chain(&tls->conf, tls->cacert_ptr, NULL); + } else { + mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE); + } + + if (cfg->clientcert_pem_buf != NULL && cfg->clientkey_pem_buf != NULL) { + mbedtls_x509_crt_init(&tls->clientcert); + mbedtls_pk_init(&tls->clientkey); + + ret = mbedtls_x509_crt_parse(&tls->clientcert, cfg->clientcert_pem_buf, cfg->clientcert_pem_bytes); + if (ret < 0) { + ESP_LOGE(TAG, "mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); + goto exit; + } + + ret = mbedtls_pk_parse_key(&tls->clientkey, cfg->clientkey_pem_buf, cfg->clientkey_pem_bytes, + cfg->clientkey_password, cfg->clientkey_password_len); + if (ret < 0) { + ESP_LOGE(TAG, "mbedtls_pk_parse_keyfile returned -0x%x\n\n", -ret); + goto exit; + } + + ret = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->clientcert, &tls->clientkey); + if (ret < 0) { + ESP_LOGE(TAG, "mbedtls_ssl_conf_own_cert returned -0x%x\n\n", -ret); + goto exit; + } + } else if (cfg->clientcert_pem_buf != NULL || cfg->clientkey_pem_buf != NULL) { + ESP_LOGE(TAG, "You have to provide both clientcert_pem_buf and clientkey_pem_buf for mutual authentication\n\n"); + goto exit; + } + + mbedtls_ssl_conf_rng(&tls->conf, mbedtls_ctr_drbg_random, &tls->ctr_drbg); + +#ifdef CONFIG_MBEDTLS_DEBUG + mbedtls_esp_enable_debug_log(&tls->conf, 4); +#endif + + if ((ret = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) { + ESP_LOGE(TAG, "mbedtls_ssl_setup returned -0x%x\n\n", -ret); + goto exit; + } + mbedtls_ssl_set_bio(&tls->ssl, &tls->server_fd, mbedtls_net_send, mbedtls_net_recv, NULL); + + return 0; +exit: + mbedtls_cleanup(tls); + return -1; +} + +/** + * @brief Close the TLS connection and free any allocated resources. + */ +void esp_tls_conn_delete(esp_tls_t *tls) +{ + if (tls != NULL) { + mbedtls_cleanup(tls); + if (tls->sockfd) { + close(tls->sockfd); + } + free(tls); + } +}; + +static ssize_t tcp_write(esp_tls_t *tls, const char *data, size_t datalen) +{ + return send(tls->sockfd, data, datalen, 0); +} + +static ssize_t tls_write(esp_tls_t *tls, const char *data, size_t datalen) +{ + ssize_t ret = mbedtls_ssl_write(&tls->ssl, (unsigned char*) data, datalen); + if (ret < 0) { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + ESP_LOGE(TAG, "write error :%d:", ret); + } + } + return ret; +} + +static int esp_tls_low_level_conn(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls) +{ + if (!tls) { + ESP_LOGE(TAG, "empty esp_tls parameter"); + return -1; + } + /* These states are used to keep a tab on connection progress in case of non-blocking connect, + and in case of blocking connect these cases will get executed one after the other */ + switch (tls->conn_state) { + case ESP_TLS_INIT: + ; + int sockfd; + int ret = esp_tcp_connect(hostname, hostlen, port, &sockfd, cfg); + if (ret < 0) { + return -1; + } + tls->sockfd = sockfd; + if (!cfg) { + tls->esp_tls_read = tcp_read; + tls->esp_tls_write = tcp_write; + ESP_LOGD(TAG, "non-tls connection established"); + return 1; + } + if (cfg->non_block) { + FD_ZERO(&tls->rset); + FD_SET(tls->sockfd, &tls->rset); + tls->wset = tls->rset; + } + tls->conn_state = ESP_TLS_CONNECTING; + /* falls through */ + case ESP_TLS_CONNECTING: + if (cfg->non_block) { + ESP_LOGD(TAG, "connecting..."); + struct timeval tv; + ms_to_timeval(cfg->timeout_ms, &tv); + + /* In case of non-blocking I/O, we use the select() API to check whether + connection has been estbalished or not*/ + if (select(tls->sockfd + 1, &tls->rset, &tls->wset, NULL, + cfg->timeout_ms ? &tv : NULL) == 0) { + ESP_LOGD(TAG, "select() timed out"); + return 0; + } + if (FD_ISSET(tls->sockfd, &tls->rset) || FD_ISSET(tls->sockfd, &tls->wset)) { + int error; + unsigned int len = sizeof(error); + /* pending error check */ + if (getsockopt(tls->sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) { + ESP_LOGD(TAG, "Non blocking connect failed"); + tls->conn_state = ESP_TLS_FAIL; + return -1; + } + } + } + /* By now, the connection has been established */ + ret = create_ssl_handle(tls, hostname, hostlen, cfg); + if (ret != 0) { + ESP_LOGD(TAG, "create_ssl_handshake failed"); + tls->conn_state = ESP_TLS_FAIL; + return -1; + } + tls->esp_tls_read = tls_read; + tls->esp_tls_write = tls_write; + tls->conn_state = ESP_TLS_HANDSHAKE; + /* falls through */ + case ESP_TLS_HANDSHAKE: + ESP_LOGD(TAG, "handshake in progress..."); + ret = mbedtls_ssl_handshake(&tls->ssl); + if (ret == 0) { + tls->conn_state = ESP_TLS_DONE; + return 1; + } else { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + ESP_LOGE(TAG, "mbedtls_ssl_handshake returned -0x%x", -ret); + if (cfg->cacert_pem_buf != NULL || cfg->use_global_ca_store == true) { + /* This is to check whether handshake failed due to invalid certificate*/ + verify_certificate(tls); + } + tls->conn_state = ESP_TLS_FAIL; + return -1; + } + /* Irrespective of blocking or non-blocking I/O, we return on getting MBEDTLS_ERR_SSL_WANT_READ + or MBEDTLS_ERR_SSL_WANT_WRITE during handshake */ + return 0; + } + break; + case ESP_TLS_FAIL: + ESP_LOGE(TAG, "failed to open a new connection");; + break; + default: + ESP_LOGE(TAG, "invalid esp-tls state"); + break; + } + return -1; +} + +/** + * @brief Create a new TLS/SSL connection + */ +esp_tls_t *esp_tls_conn_new(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg) +{ + esp_tls_t *tls = (esp_tls_t *)calloc(1, sizeof(esp_tls_t)); + if (!tls) { + return NULL; + } + /* esp_tls_conn_new() API establishes connection in a blocking manner thus this loop ensures that esp_tls_conn_new() + API returns only after connection is established unless there is an error*/ + while (1) { + int ret = esp_tls_low_level_conn(hostname, hostlen, port, cfg, tls); + if (ret == 1) { + return tls; + } else if (ret == -1) { + esp_tls_conn_delete(tls); + ESP_LOGE(TAG, "Failed to open new connection"); + return NULL; + } + } + return NULL; +} + +/* + * @brief Create a new TLS/SSL non-blocking connection + */ +int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg , esp_tls_t *tls) +{ + return esp_tls_low_level_conn(hostname, hostlen, port, cfg, tls); +} + +size_t esp_tls_get_bytes_avail(esp_tls_t *tls) +{ + if (!tls) { + ESP_LOGE(TAG, "empty arg passed to esp_tls_get_bytes_avail()"); + return ESP_FAIL; + } + return mbedtls_ssl_get_bytes_avail(&tls->ssl); +} diff --git a/components/esp-tls/esp_tls.h b/components/esp-tls/esp_tls.h new file mode 100644 index 00000000..3782c0e9 --- /dev/null +++ b/components/esp-tls/esp_tls.h @@ -0,0 +1,276 @@ +// Copyright 2017-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_TLS_H_ +#define _ESP_TLS_H_ + +#include +#include +#include + +#include "mbedtls/platform.h" +#include "mbedtls/net_sockets.h" +#include "mbedtls/esp_debug.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/error.h" +#include "mbedtls/certs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief ESP-TLS Connection State + */ +typedef enum esp_tls_conn_state { + ESP_TLS_INIT = 0, + ESP_TLS_CONNECTING, + ESP_TLS_HANDSHAKE, + ESP_TLS_FAIL, + ESP_TLS_DONE, +} esp_tls_conn_state_t; + +/** + * @brief ESP-TLS configuration parameters + */ +typedef struct esp_tls_cfg { + const char **alpn_protos; /*!< Application protocols required for HTTP2. + If HTTP2/ALPN support is required, a list + of protocols that should be negotiated. + The format is length followed by protocol + name. + For the most common cases the following is ok: + "\x02h2" + - where the first '2' is the length of the protocol and + - the subsequent 'h2' is the protocol name */ + + const unsigned char *cacert_pem_buf; /*!< Certificate Authority's certificate in a buffer */ + + unsigned int cacert_pem_bytes; /*!< Size of Certificate Authority certificate + pointed to by cacert_pem_buf */ + + const unsigned char *clientcert_pem_buf;/*!< Client certificate in a buffer */ + + unsigned int clientcert_pem_bytes; /*!< Size of client certificate pointed to by + clientcert_pem_buf */ + + const unsigned char *clientkey_pem_buf; /*!< Client key in a buffer */ + + unsigned int clientkey_pem_bytes; /*!< Size of client key pointed to by + clientkey_pem_buf */ + + const unsigned char *clientkey_password;/*!< Client key decryption password string */ + + unsigned int clientkey_password_len; /*!< String length of the password pointed to by + clientkey_password */ + + bool non_block; /*!< Configure non-blocking mode. If set to true the + underneath socket will be configured in non + blocking mode after tls session is established */ + + int timeout_ms; /*!< Network timeout in milliseconds */ + + bool use_global_ca_store; /*!< Use a global ca_store for all the connections in which + this bool is set. */ +} esp_tls_cfg_t; + +/** + * @brief ESP-TLS Connection Handle + */ +typedef struct esp_tls { + mbedtls_ssl_context ssl; /*!< TLS/SSL context */ + + mbedtls_entropy_context entropy; /*!< mbedTLS entropy context structure */ + + mbedtls_ctr_drbg_context ctr_drbg; /*!< mbedTLS ctr drbg context structure. + CTR_DRBG is deterministic random + bit generation based on AES-256 */ + + mbedtls_ssl_config conf; /*!< TLS/SSL configuration to be shared + between mbedtls_ssl_context + structures */ + + mbedtls_net_context server_fd; /*!< mbedTLS wrapper type for sockets */ + + mbedtls_x509_crt cacert; /*!< Container for the X.509 CA certificate */ + + mbedtls_x509_crt *cacert_ptr; /*!< Pointer to the cacert being used. */ + + mbedtls_x509_crt clientcert; /*!< Container for the X.509 client certificate */ + + mbedtls_pk_context clientkey; /*!< Container for the private key of the client + certificate */ + + int sockfd; /*!< Underlying socket file descriptor. */ + + ssize_t (*esp_tls_read)(struct esp_tls *tls, char *data, size_t datalen); /*!< Callback function for reading data from TLS/SSL + connection. */ + + ssize_t (*esp_tls_write)(struct esp_tls *tls, const char *data, size_t datalen); /*!< Callback function for writing data to TLS/SSL + connection. */ + + esp_tls_conn_state_t conn_state; /*!< ESP-TLS Connection state */ + + fd_set rset; /*!< read file descriptors */ + + fd_set wset; /*!< write file descriptors */ +} esp_tls_t; + +/** + * @brief Create a new blocking TLS/SSL connection + * + * This function establishes a TLS/SSL connection with the specified host in blocking manner. + * + * @param[in] hostname Hostname of the host. + * @param[in] hostlen Length of hostname. + * @param[in] port Port number of the host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. If you wish to open + * non-TLS connection, keep this NULL. For TLS connection, + * a pass pointer to esp_tls_cfg_t. At a minimum, this + * structure should be zero-initialized. + * @return pointer to esp_tls_t, or NULL if connection couldn't be opened. + */ +esp_tls_t *esp_tls_conn_new(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg); + +/** + * @brief Create a new non-blocking TLS/SSL connection + * + * This function initiates a non-blocking TLS/SSL connection with the specified host, but due to + * its non-blocking nature, it doesn't wait for the connection to get established. + * + * @param[in] hostname Hostname of the host. + * @param[in] hostlen Length of hostname. + * @param[in] port Port number of the host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. `non_block` member of + * this structure should be set to be true. + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 If connection establishment fails. + * - 0 If connection establishment is in progress. + * - 1 If connection establishment is successful. + */ +int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls); + +/** + * @brief Write from buffer 'data' into specified tls connection. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * @param[in] data Buffer from which data will be written. + * @param[in] datalen Length of data buffer. + * + * @return + * - >0 if write operation was successful, the return value is the number + * of bytes actually written to the TLS/SSL connection. + * - 0 if write operation was not successful. The underlying + * connection was closed. + * - <0 if write operation was not successful, because either an + * error occured or an action must be taken by the calling process. + */ +static inline ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen) +{ + return tls->esp_tls_write(tls, (char *)data, datalen); +} + +/** + * @brief Read from specified tls connection into the buffer 'data'. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * @param[in] data Buffer to hold read data. + * @param[in] datalen Length of data buffer. + * + * @return + * - >0 if read operation was successful, the return value is the number + * of bytes actually read from the TLS/SSL connection. + * - 0 if read operation was not successful. The underlying + * connection was closed. + * - <0 if read operation was not successful, because either an + * error occured or an action must be taken by the calling process. + */ +static inline ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen) +{ + return tls->esp_tls_read(tls, (char *)data, datalen); +} + +/** + * @brief Close the TLS/SSL connection and free any allocated resources. + * + * This function should be called to close each tls connection opened with esp_tls_conn_new() or + * esp_tls_conn_http_new() APIs. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + */ +void esp_tls_conn_delete(esp_tls_t *tls); + +/** + * @brief Return the number of application data bytes remaining to be + * read from the current record + * + * This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 in case of invalid arg + * - bytes available in the application data + * record read buffer + */ +size_t esp_tls_get_bytes_avail(esp_tls_t *tls); + +/** + * @brief Create a global CA store with the buffer provided in cfg. + * + * This function should be called if the application wants to use the same CA store for + * multiple connections. The application must call this function before calling esp_tls_conn_new(). + * + * @param[in] cacert_pem_buf Buffer which has certificates in pem format. This buffer + * is used for creating a global CA store, which can be used + * by other tls connections. + * @param[in] cacert_pem_bytes Length of the buffer. + * + * @return + * - ESP_OK if creating global CA store was successful. + * - Other if an error occured or an action must be taken by the calling process. + */ +esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes); + +/** + * @brief Get the pointer to the global CA store currently being used. + * + * The application must first call esp_tls_set_global_ca_store(). Then the same + * CA store could be used by the application for APIs other than esp_tls. + * + * @note Modifying the pointer might cause a failure in verifying the certificates. + * + * @return + * - Pointer to the global CA store currently being used if successful. + * - NULL if there is no global CA store set. + */ +mbedtls_x509_crt *esp_tls_get_global_ca_store(); + +/** + * @brief Free the global CA store currently being used. + * + * The memory being used by the global CA store to store all the parsed certificates is + * freed up. The application can call this API if it no longer needs the global CA store. + */ +void esp_tls_free_global_ca_store(); + + +#ifdef __cplusplus +} +#endif + +#endif /* ! _ESP_TLS_H_ */