diff --git a/Makefile.am b/Makefile.am index 9c219d16..59f191f2 100644 --- a/Makefile.am +++ b/Makefile.am @@ -77,6 +77,7 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \ src/coap_hashkey.c \ src/coap_gnutls.c \ src/coap_io.c \ + src/coap_mbedtls.c \ src/coap_notls.c \ src/coap_openssl.c \ src/coap_session.c \ diff --git a/README.md b/README.md index 72297e83..36cf9773 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Static Analysis](https://scan.coverity.com/projects/10970/badge.svg?flat=1)](https://scan.coverity.com/projects/obgm-libcoap) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/libcoap.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:libcoap) -Copyright (C) 2010—2019 by Olaf Bergmann and others +Copyright (C) 2010—2020 by Olaf Bergmann and others ABOUT LIBCOAP ============= @@ -49,11 +49,15 @@ The following RFCs are supported There is (D)TLS support for the following libraries -* OpenSSL (Minimum verion 1.1.0) +* OpenSSL (Minimum version 1.1.0) * GnuTLS (Minimum version 3.3.0) +* MbedTLS (Minimum version 2.7.10) + [Currently only DTLS] + * TinyDTLS + [DTLS Only] The examples directory contain a CoAP client, CoAP Resource Directory server and a CoAP server to demonstrate the use of this library. diff --git a/configure.ac b/configure.ac index 762bb3af..31a93294 100644 --- a/configure.ac +++ b/configure.ac @@ -304,6 +304,7 @@ AM_CONDITIONAL(BUILD_MANPAGES, [test "x$build_manpages" = "xyes"]) gnutls_version_required=3.3.0 openssl_version_required=1.1.0 +mbedtls_version_required=2.7.10 AC_ARG_ENABLE([dtls], [AS_HELP_STRING([--enable-dtls], @@ -323,25 +324,44 @@ AC_ARG_WITH([openssl], [with_openssl="$withval"], [with_openssl="no"]) +AC_ARG_WITH([mbedtls], + [AS_HELP_STRING([--with-mbedtls], + [Use mbed TLS for DTLS functions])], + [with_mbedtls="$withval"], + [with_mbedtls="no"]) + AC_ARG_WITH([tinydtls], [AS_HELP_STRING([--with-tinydtls], [Use TinyDTLS for DTLS functions])], [with_tinydtls="$withval"], [with_tinydtls="no"]) -if test "x$with_gnutls" = "xyes" -o "x$with_openssl" = "xyes"; then +if test "x$with_gnutls" = "xyes" -o "x$with_openssl" = "xyes" -o "x$with_mbedtls" = "xyes" -o "x$with_tinydtls" = "xyes"; then if test "x$build_dtls" = "x"; then - # Give an advice that '--with_gnutls' or '--with_openssl' was used but + # Give an advice that '--with_gnutls', '--with_openssl', '--with-mbedtls' or '--with-tinydtls' was used but # DTLS support isn't configured. - AC_MSG_NOTICE([==> Using the configure options '--with-gnutls' or '--with-openssl' without '--enable-dtls' is useles and will be ignored.]) + AC_MSG_NOTICE([==> Using the configure options '--with-gnutls', '--with-openssl', '--with-mbedtls' or '--with-tinydtls' without '--enable-dtls' is useles and will be ignored.]) fi fi # O.K. the user hasn't de-selected DTLS if test "x$build_dtls" = "xyes"; then # The user can't select multiple crypto libraries. - if test "x$with_gnutls" = "xyes" -a "x$with_openssl" = "xyes"; then - AC_MSG_ERROR([==> You can't use the options '--with-gnutls' and '--with-openssl' at the same time while '--enable-dtls' is selected! + TLSCOUNT=0 + if test "x$with_gnutls" = "xyes"; then + TLSCOUNT=`expr $TLSCOUNT + 1` + fi + if test "x$with_openssl" = "xyes"; then + TLSCOUNT=`expr $TLSCOUNT + 1` + fi + if test "x$with_mbedtls" = "xyes"; then + TLSCOUNT=`expr $TLSCOUNT + 1` + fi + if test "x$with_tinydtls" = "xyes"; then + TLSCOUNT=`expr $TLSCOUNT + 1` + fi + if test "$TLSCOUNT" -gt 1; then + AC_MSG_ERROR([==> You can't use more than 1 of the options '--with-gnutls', '--with-openssl', '--with-mbedtls' or '--with-tinydtls' at the same time while '--enable-dtls' is selected! ==> Please note, the option '--enable-dtls' is turned on by default if not explicitly disabled!]) fi @@ -358,6 +378,11 @@ if test "x$build_dtls" = "xyes"; then [have_openssl="yes"], [have_openssl="no"]) + # mbed TLS [does not have mbedtls.pc pkg-config file] + AC_CHECK_LIB(mbedtls, mbedtls_ssl_handshake, + [have_mbedtls="yes"; MbedTLS_CFLAGS="" ; MbedTLS_LIBS="-lmbedtls -lmbedcrypto -lmbedx509"], + [have_mbedtls="no"]) + # TinyDTLS ? # TBD ? @@ -367,14 +392,16 @@ if test "x$build_dtls" = "xyes"; then if test "x$have_gnutls" != "xyes"; then AC_MSG_ERROR([==> You want to build libcoap with DTLS support by the GnuTLS library but pkg-config file 'gnutls.pc' could not be found! Install the package(s) that contains the development files for GnuTLS, - or use '--with-openssl' or disable the DTLS support using '--disable-dtls'.]) + or select a different TLS library or disable the DTLS support using '--disable-dtls'.]) fi - AC_MSG_NOTICE([The use of GnuTLS was explicit requested due configure option '--with-gnutls'!]) + AC_MSG_NOTICE([The use of GnuTLS was explicitly requested with configure option '--with-gnutls'!]) # check for valid GnuTLS version gnutls_version=`pkg-config --modversion gnutls` AX_CHECK_GNUTLS_VERSION have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script + have_mbedtls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script fi # The user wants to use explicit OpenSSL if '--with-openssl was set'. @@ -383,52 +410,89 @@ if test "x$build_dtls" = "xyes"; then if test "x$have_openssl" != "xyes"; then AC_MSG_ERROR([==> You want to build libcoap with DTLS support by the OpenSSL library but pkg-config file 'openssl.pc' could not be found! Install the package(s) that contains the development files for OpenSSL, - or use '--with-gnutls' or disable the DTLS support using '--disable-dtls'.]) + or select a different TLS library or disable the DTLS support using '--disable-dtls'.]) fi - AC_MSG_NOTICE([The use of OpenSSL was explicit requested due configure option '--with-openssl'!]) + AC_MSG_NOTICE([The use of OpenSSL was explicitly requested with configure option '--with-openssl'!]) # check for valid OpenSSL version openssl_version=`pkg-config --modversion openssl` AX_CHECK_OPENSSL_VERSION have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_mbedtls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script fi - # The user wants to use explicit OpenSSL if '--with-tinydtls was set'. + # The user wants to use explicit mbed TLS if '--with-mbedtls was set'. + if test "x$with_mbedtls" = "xyes"; then + # Some more sanity checking. + if test "x$have_mbedtls" != "xyes"; then + AC_MSG_ERROR([==> You want to build libcoap with DTLS support by the mbed TLS library but library 'mbedtls' could not be found! + Install the package(s) that contains the development files for mbed TLS, + or select a different TLS library or disable the DTLS support using '--disable-dtls'.]) + fi + AC_MSG_NOTICE([The use of mbed TLS was explicitly requested with configure option '--with-mbedtls'!]) + + # check for valid mbed TLS version (mbedtls.pc does not exist - hmm) + # mbedtls_version=`pkg-config --modversion mbedtls` + # AX_CHECK_MBEDTLS_VERSION + have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script + fi + + # The user wants to use explicit TinyDTLS if '--with-tinydtls was set'. if test "x$with_tinydtls" = "xyes" ; then if test -d "$srcdir/ext/tinydtls"; then AC_CONFIG_SUBDIRS([ext/tinydtls]) have_tinydtls="yes" else - have_tinydtls="no" + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script fi + have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script + have_mbedtls="no" # don't confuse AC_MSG_RESULT at the end of the script fi - # The user hasn't requested the use of a specific cryptography library - # we try first GnuTLS for usability ... - if test "x$have_gnutls" = "xyes" -a "x$with_gnutls" = "xno" -a "x$with_tinydtls" = "xno"; then - gnutls_version=`pkg-config --modversion gnutls` - AX_CHECK_GNUTLS_VERSION - AC_MSG_NOTICE([Using auto selected library GnuTLS for DTLS support!]) - with_gnutls_auto="yes" - have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script - fi + if test "$TLSCOUNT" -eq 0; then + # The user hasn't requested the use of a specific cryptography library + # we try first GnuTLS for usability ... + if test "x$have_gnutls" = "xyes"; then + gnutls_version=`pkg-config --modversion gnutls` + AX_CHECK_GNUTLS_VERSION + AC_MSG_NOTICE([Using auto selected library GnuTLS for DTLS support!]) + with_gnutls_auto="yes" + have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script + have_mbedtls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script - # ... and if not found check OpenSSL is suitable. - if test "x$have_openssl" = "xyes" -a "x$with_openssl" = "xno" -a "x$with_gnutls_auto" = "x" -a "x$with_tinydtls" = "xno"; then - openssl_version=`pkg-config --modversion openssl` - AX_CHECK_OPENSSL_VERSION - AC_MSG_NOTICE([Using auto selected library OpenSSL for DTLS support!]) - with_openssl_auto="yes" - have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script - fi + # ... and if not found check OpenSSL is suitable. + elif test "x$have_openssl" = "xyes"; then + openssl_version=`pkg-config --modversion openssl` + AX_CHECK_OPENSSL_VERSION + AC_MSG_NOTICE([Using auto selected library OpenSSL for DTLS support!]) + with_openssl_auto="yes" + have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_mbedtls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script - # Note that tinyDTLS is used only when explicitly requested. + # ... and if not found check mbed TLS is suitable. + elif test "x$have_mbedtls" = "xyes"; then + # mbed TLS [does not have mbedtls.pc pkg-config file] + # mbedtls_version=`pkg-config --modversion mbedtls` + # AX_CHECK_MBEDTLS_VERSION + AC_MSG_NOTICE([Using auto selected library mbed TLS for DTLS support!]) + with_mbedtls_auto="yes" + have_gnutls="no" # don't confuse AC_MSG_RESULT at the end of the script + have_openssl="no" # don't confuse AC_MSG_RESULT at the end of the script + have_tinydtls="no" # don't confuse AC_MSG_RESULT at the end of the script - # Giving out an error message if we haven't found at least one crypto library. - if test "x$have_gnutls" = "xno" -a "x$have_openssl" = "xno" -a "x$have_tinydtls" = "xno"; then - AC_MSG_ERROR([==> Option '--enable-dtls' is set but one of the needed cryptography library GnuTLS nor OpenSSL nor tinyDTLS could be found! - Install at least one of the package(s) that contains the development files for GnuTLS (>= $gnutls_version_required) or OpenSSL(>= $openssl_version_required) - or disable the DTLS support using '--disable-dtls'.]) + # Note that tinyDTLS is used only when explicitly requested. + # Giving out an error message if we haven't found at least one crypto library. + else + AC_MSG_ERROR([==> Option '--enable-dtls' is set but none of the needed cryptography libraries GnuTLS, OpenSSL or mbed TLS could be found! + Install at least one of the package(s) that contains the development files for GnuTLS (>= $gnutls_version_required), OpenSSL(>= $openssl_version_required), or mbed TLS(>= $mbedtls_version_required) + or disable the DTLS support using '--disable-dtls'.]) + fi fi # Saving the DTLS related Compiler flags. @@ -442,6 +506,11 @@ if test "x$build_dtls" = "xyes"; then DTLS_LIBS="$OpenSSL_LIBS" AC_DEFINE(HAVE_OPENSSL, [1], [Define if the system has libssl1.1]) fi + if test "x$with_mbedtls" = "xyes" -o "x$with_mbedtls_auto" = "xyes"; then + DTLS_CFLAGS="$MbedTLS_CFLAGS" + DTLS_LIBS="$MbedTLS_LIBS" + AC_DEFINE(HAVE_MBEDTLS, [1], [Define if the system has libmbedtls2.7.10]) + fi if test "x$with_tinydtls" = "xyes"; then DTLS_CFLAGS="-I \$(top_srcdir)/ext/tinydtls" if test "x$enable_shared" = "xyes"; then @@ -462,6 +531,8 @@ if test "x$with_openssl" = "xyes" -o "x$with_openssl_auto" = "xyes"; then LIBCOAP_DTLS_LIB_EXTENSION_NAME=-openssl elif test "x$with_gnutls" = "xyes" -o "x$with_gnutls_auto" = "xyes"; then LIBCOAP_DTLS_LIB_EXTENSION_NAME=-gnutls +elif test "x$with_mbedtls" = "xyes" -o "x$with_mbedtls_auto" = "xyes"; then + LIBCOAP_DTLS_LIB_EXTENSION_NAME=-mbedtls elif test "x$with_tinydtls" = "xyes"; then LIBCOAP_DTLS_LIB_EXTENSION_NAME=-tinydtls else @@ -736,6 +807,13 @@ if test "x$with_openssl" = "xyes" -o "x$with_openssl_auto" = "xyes"; then AC_MSG_RESULT([ OPENSSL_CFLAGS : "$OpenSSL_CFLAGS"]) AC_MSG_RESULT([ OPENSSL_LIBS : "$OpenSSL_LIBS"]) fi +if test "x$with_mbedtls" = "xyes" -o "x$with_mbedtls_auto" = "xyes"; then + AC_MSG_RESULT([ build DTLS support : "yes"]) + # mbed TLS [does not have mbedtls.pc pkg-config file, hence no mbedtls_version] + AC_MSG_RESULT([ --> mbed TLS around : "yes" (found mbed TLS)]) + AC_MSG_RESULT([ MBEDTLS_CFLAGS : "$MbedTLS_CFLAGS"]) + AC_MSG_RESULT([ MBEDTLS_LIBS : "$MbedTLS_LIBS"]) +fi if test "x$with_tinydtls" = "xyes"; then AC_MSG_RESULT([ build DTLS support : "yes"]) AC_MSG_RESULT([ --> tinyDTLS around : "yes"]) diff --git a/include/coap2/coap_dtls.h b/include/coap2/coap_dtls.h index 5ca40034..52f2acc9 100644 --- a/include/coap2/coap_dtls.h +++ b/include/coap2/coap_dtls.h @@ -30,6 +30,16 @@ struct coap_dtls_pki_t; #define COAP_DTLS_HINT_LENGTH 128 #endif +/* https://tools.ietf.org/html/rfc6347#section-4.2.4.1 */ +#ifndef COAP_DTLS_RETRANSMIT_MS +#define COAP_DTLS_RETRANSMIT_MS 1000 +#endif +#ifndef COAP_DTLS_RETRANSMIT_TOTAL_MS +#define COAP_DTLS_RETRANSMIT_TOTAL_MS 60000 +#endif + +#define COAP_DTLS_RETRANSMIT_COAP_TICKS (COAP_DTLS_RETRANSMIT_MS * COAP_TICKS_PER_SECOND / 1000) + /** * Check whether DTLS is available. * @@ -49,6 +59,7 @@ typedef enum coap_tls_library_t { COAP_TLS_LIBRARY_TINYDTLS, /**< Using TinyDTLS library */ COAP_TLS_LIBRARY_OPENSSL, /**< Using OpenSSL library */ COAP_TLS_LIBRARY_GNUTLS, /**< Using GnuTLS library */ + COAP_TLS_LIBRARY_MBEDTLS, /**< Using MbedTLS library */ } coap_tls_library_t; /** @@ -138,8 +149,9 @@ typedef enum coap_asn1_privatekey_type_t { * The enum used for determining the PKI key formats. */ typedef enum coap_pki_key_t { - COAP_PKI_KEY_PEM = 0, /**< The PKI key type is PEM */ - COAP_PKI_KEY_ASN1, /**< The PKI key type is ASN.1 (DER) */ + COAP_PKI_KEY_PEM = 0, /**< The PKI key type is PEM file */ + COAP_PKI_KEY_ASN1, /**< The PKI key type is ASN.1 (DER) */ + COAP_PKI_KEY_PEM_BUF, /**< The PKI key type is PEM buffer */ } coap_pki_key_t; /** @@ -151,6 +163,24 @@ typedef struct coap_pki_key_pem_t { const char *private_key; /**< File location of Private Key in PEM format */ } coap_pki_key_pem_t; +/** + * The structure that holds the PKI PEM buffer definitions. + * The certificates and private key data must be in PEM format. + * + * Note: The Certs and Key should be NULL terminated strings for + * performance reasons (to save a potential buffer copy) and the length include + * this NULL terminator. It is not a requirement to have the NULL terminator + * though and the length must then reflect the actual data size. + */ +typedef struct coap_pki_key_pem_buf_t { + const uint8_t *ca_cert; /**< PEM buffer Common CA Cert */ + const uint8_t *public_cert; /**< PEM buffer Public Cert */ + const uint8_t *private_key; /**< PEM buffer Private Key */ + size_t ca_cert_len; /**< PEM buffer CA Cert length */ + size_t public_cert_len; /**< PEM buffer Public Cert length */ + size_t private_key_len; /**< PEM buffer Private Key length */ +} coap_pki_key_pem_buf_t; + /** * The structure that holds the PKI ASN.1 (DER) definitions. */ @@ -170,8 +200,9 @@ typedef struct coap_pki_key_asn1_t { typedef struct coap_dtls_key_t { coap_pki_key_t key_type; /**< key format type */ union { - coap_pki_key_pem_t pem; /**< for PEM keys */ - coap_pki_key_asn1_t asn1; /**< for ASN.1 (DER) keys */ + coap_pki_key_pem_t pem; /**< for PEM file keys */ + coap_pki_key_pem_buf_t pem_buf; /**< for PEM memory keys */ + coap_pki_key_asn1_t asn1; /**< for ASN.1 (DER) file keys */ } key; } coap_dtls_key_t; @@ -211,9 +242,11 @@ typedef struct coap_dtls_pki_t { uint8_t check_cert_revocation; /**< 1 if revocation checks wanted */ uint8_t allow_no_crl; /**< 1 ignore if CRL not there */ uint8_t allow_expired_crl; /**< 1 if expired crl is allowed */ - uint8_t reserved[6]; /**< Reserved - must be set to 0 for + uint8_t allow_bad_md_hash; /**< 1 if unsupported MD hashes are allowed */ + uint8_t allow_short_rsa_length; /**< 1 if small RSA keysizes are allowed */ + uint8_t reserved[4]; /**< Reserved - must be set to 0 for future compatibility */ - /* Size of 6 chosen to align to next + /* Size of 4 chosen to align to next * parameter, so if newly defined option * it can use one of the reserverd slot so * no need to change diff --git a/src/coap_debug.c b/src/coap_debug.c index 7dbba491..3ed0e4a7 100644 --- a/src/coap_debug.c +++ b/src/coap_debug.c @@ -741,6 +741,16 @@ char *coap_string_tls_version(char *buffer, size_t bufsize) (unsigned long)((tls_version->built_version >> 8) & 0xff), (unsigned long)(tls_version->built_version & 0xff)); break; + case COAP_TLS_LIBRARY_MBEDTLS: + snprintf(buffer, bufsize, "TLS Library: MbedTLS - runtime %lu.%lu.%lu, " + "libcoap built for %lu.%lu.%lu", + (unsigned long)(tls_version->version >> 24), + (unsigned long)((tls_version->version >> 16) & 0xff), + (unsigned long)((tls_version->version >> 8) & 0xff), + (unsigned long)(tls_version->built_version >> 24), + (unsigned long)((tls_version->built_version >> 16) & 0xff), + (unsigned long)((tls_version->built_version >> 8) & 0xff)); + break; default: snprintf(buffer, bufsize, "Library type %d unknown", tls_version->type); break; diff --git a/src/coap_mbedtls.c b/src/coap_mbedtls.c new file mode 100644 index 00000000..1264549a --- /dev/null +++ b/src/coap_mbedtls.c @@ -0,0 +1,1843 @@ +/* +* coap_mbedtls.c -- mbedTLS Datagram Transport Layer Support for libcoap +* +* Copyright (C) 2019-2020 Jon Shallow +* 2019 Jitin George +* +* This file is part of the CoAP library libcoap. Please see README for terms +* of use. +*/ + +/* + * Naming used to prevent confusion between coap sessions, mbedtls sessions etc. + * when reading the code. + * + * c_context A coap_context_t * + * c_session A coap_session_t * + * m_context A coap_mbedtls_context_t * (held in c_context->dtls_context) + * m_env A coap_mbedtls_env_t * (held in c_session->tls) + */ + +#include "coap_internal.h" + +#ifdef HAVE_MBEDTLS + +/* + * This code can be conditionally compiled to remove some components if + * they are not required to make a lighter footprint - all based on how + * the mbedtls library has been built. These are not defined within the + * libcoap environment. + * + * MBEDTLS_SSL_SRV_C - defined for server side functionality + * MBEDTLS_SSL_CLI_C - defined for client side functionality + * MBEDTLS_SSL_PROTO_DTLS - defined for DTLS support + * MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED - defined if PSK is to be supported + * + * Note: TLS is not currently supported until additional code is added + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG) +#include +#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */ +#include + +#define mbedtls_malloc(a) malloc(a) +#define mbedtls_realloc(a,b) realloc(a,b) +#define mbedtls_strdup(a) strdup(a) +#define mbedtls_strndup(a,b) strndup(a,b) + +#ifdef __GNUC__ +#define UNUSED __attribute__((unused)) +#else /* __GNUC__ */ +#define UNUSED +#endif /* __GNUC__ */ + +#ifdef _WIN32 +#define strcasecmp _stricmp +#endif + +#define IS_PSK (1 << 0) +#define IS_PKI (1 << 1) +#define IS_CLIENT (1 << 6) +#define IS_SERVER (1 << 7) + +typedef struct coap_ssl_t { + const uint8_t *pdu; + unsigned pdu_len; + unsigned peekmode; +} coap_ssl_t; + +/* + * This structure encapsulates the mbedTLS session object. + * It handles both TLS and DTLS. + * c_session->tls points to this. + */ +typedef struct coap_mbedtls_env_t { + mbedtls_ssl_context ssl; + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_config conf; + mbedtls_timing_delay_context timer; + mbedtls_x509_crt cacert; + mbedtls_x509_crt public_cert; + mbedtls_pk_context private_key; + mbedtls_ssl_cookie_ctx cookie_ctx; + /* If not set, need to do do_mbedtls_handshake */ + int established; + int seen_client_hello; + coap_tick_t last_timeout; + unsigned int retry_scalar; + coap_ssl_t coap_ssl_data; +} coap_mbedtls_env_t; + +typedef struct pki_sni_entry { + char *sni; + coap_dtls_key_t pki_key; + mbedtls_x509_crt cacert; + mbedtls_x509_crt public_cert; + mbedtls_pk_context private_key; +} pki_sni_entry; + +typedef struct psk_sni_entry { + char* sni; + coap_dtls_spsk_info_t psk_info; +} psk_sni_entry; + +typedef struct coap_mbedtls_context_t { + coap_dtls_pki_t setup_data; + size_t pki_sni_count; + pki_sni_entry *pki_sni_entry_list; + size_t psk_sni_count; + psk_sni_entry *psk_sni_entry_list; + char *root_ca_file; + char *root_ca_path; + int psk_pki_enabled; +} coap_mbedtls_context_t; + +typedef enum coap_enc_method_t { + COAP_ENC_PSK, + COAP_ENC_PKI, +} coap_enc_method_t; + +static int coap_dgram_read(void *ctx, unsigned char *out, size_t outl) +{ + ssize_t ret = 0; + coap_session_t *c_session = (struct coap_session_t *)ctx; + coap_ssl_t *data; + + if (!c_session->tls) { + errno = EAGAIN; + return MBEDTLS_ERR_SSL_WANT_READ; + } + data = &((coap_mbedtls_env_t *)c_session->tls)->coap_ssl_data; + + if (out != NULL) { + if (data->pdu_len > 0) { + if (outl < data->pdu_len) { + memcpy(out, data->pdu, outl); + ret = outl; + data->pdu += outl; + data->pdu_len -= outl; + } + else { + memcpy(out, data->pdu, data->pdu_len); + ret = data->pdu_len; + if (!data->peekmode) { + data->pdu_len = 0; + data->pdu = NULL; + } + } + } + else { + ret = MBEDTLS_ERR_SSL_WANT_READ; + errno = EAGAIN; + } + } + return ret; +} + +/* + * return +ve data amount + * 0 no more + * -1 error (error in errno) + */ +/* callback function given to mbedtls for sending data over socket */ +static int +coap_dgram_write(void *ctx, const unsigned char *send_buffer, + size_t send_buffer_length) +{ + ssize_t result = -1; + coap_session_t *c_session = (struct coap_session_t *)ctx; + + if (c_session) { + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + result = coap_session_send(c_session, send_buffer, send_buffer_length); + if (result != (ssize_t)send_buffer_length) { + coap_log(LOG_WARNING, "coap_network_send failed (%zd != %zu)\n", + result, send_buffer_length); + result = 0; + } + else if (m_env) { + coap_tick_t now; + coap_ticks(&now); + m_env->last_timeout = now; + } + } else { + result = 0; + } + return result; +} + +#if defined(MBEDTLS_SSL_PROTO_DTLS) && defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && defined(MBEDTLS_SSL_SRV_C) +/* + * Server side PSK callback + */ +static int psk_server_callback(void *p_info, mbedtls_ssl_context *ssl, + const unsigned char *name, size_t name_len ) +{ + coap_session_t *c_session = (coap_session_t *)p_info; + uint8_t buf[128]; + size_t psk_len; + coap_dtls_spsk_t *setup_data; + coap_mbedtls_env_t *m_env; + + coap_log(LOG_DEBUG, "got psk_identity: '%.*s'\n", + (int)name_len, name); + + if (c_session == NULL || c_session->context == NULL || + c_session->context->get_server_psk == NULL) { + return -1; + } + m_env = (coap_mbedtls_env_t *)c_session->tls; + setup_data = &c_session->context->spsk_setup_data; + + if (setup_data->validate_id_call_back) { + coap_bin_const_t lidentity; + lidentity.length = name_len; + lidentity.s = (const uint8_t*)name; + const coap_bin_const_t *psk_key = + setup_data->validate_id_call_back(&lidentity, + c_session, + setup_data->id_call_back_arg); + + if (psk_key == NULL) + return -1; + mbedtls_ssl_set_hs_psk(ssl, psk_key->s, psk_key->length); + coap_session_refresh_psk_key(c_session, psk_key); + m_env->seen_client_hello = 1; + return 0; + } + + psk_len = c_session->context->get_server_psk(c_session, + (const uint8_t*)name, + name_len, + (uint8_t*)buf, sizeof(buf)); + m_env->seen_client_hello = 1; + mbedtls_ssl_set_hs_psk(ssl, buf, psk_len); + return 0; +} +#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED && MBEDTLS_SSL_SRV_C */ + +static char* +get_san_or_cn_from_cert(mbedtls_x509_crt *crt) +{ + if (crt) { + mbedtls_asn1_named_data * cn_data; + + if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) { + mbedtls_asn1_sequence *seq = &crt->subject_alt_names; + while (seq && seq->buf.p == NULL) { + seq = seq->next; + } + if (seq) { + /* Return the Subject Alt Name */ + return mbedtls_strndup((const char *)seq->buf.p, + seq->buf.len); + } + } + + cn_data = mbedtls_asn1_find_named_data(&crt->subject, + MBEDTLS_OID_AT_CN, + MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN)); + if (cn_data) { + /* Return the Common Name */ + return mbedtls_strndup((const char *)cn_data->val.p, + cn_data->val.len); + } + } + return NULL; +} + +static char * +get_error_string(int ret) { + static char buf[128] = {0}; + mbedtls_strerror(ret, buf, sizeof(buf)-1); + return buf; +} + +/* + * return 0 All OK + * -ve Error Code + */ +static int +cert_verify_callback_mbedtls(void *data, mbedtls_x509_crt *crt, + int depth, uint32_t *flags) +{ + coap_session_t *c_session = (coap_session_t*)data; + coap_mbedtls_context_t *m_context = + (coap_mbedtls_context_t *)c_session->context->dtls_context; + coap_dtls_pki_t *setup_data = &m_context->setup_data; + char *cn = NULL; + + if (*flags == 0) + return 0; + + if (!setup_data->verify_peer_cert) { + /* Nothing is being checked */ + *flags = 0; + return 0; + } + + cn = get_san_or_cn_from_cert(crt); + + if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) { + if (setup_data->allow_expired_certs) { + *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate has expired", cn ? cn : "?", depth); + } + } + if (*flags & MBEDTLS_X509_BADCERT_FUTURE) { + if (setup_data->allow_expired_certs) { + *flags &= ~MBEDTLS_X509_BADCERT_FUTURE; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate has a future date", cn ? cn : "?", depth); + } + } + if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) { + if (setup_data->allow_bad_md_hash) { + *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate has a bad MD hash", cn ? cn : "?", depth); + } + } + if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) { + if (setup_data->allow_short_rsa_length) { + *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate has a short RSA length", cn ? cn : "?", depth); + } + } + if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) { + if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) { + *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate's CRL has expired", cn ? cn : "?", depth); + } + else if (!setup_data->check_cert_revocation) { + *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED; + } + } + if (*flags & MBEDTLS_X509_BADCRL_FUTURE) { + if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) { + *flags &= ~MBEDTLS_X509_BADCRL_FUTURE; + coap_log(LOG_WARNING, + " %s: %s: overridden: '%s' depth %d\n", + coap_session_str(c_session), + "The certificate's CRL has a future date", cn ? cn : "?", depth); + } + else if (!setup_data->check_cert_revocation) { + *flags &= ~MBEDTLS_X509_BADCRL_FUTURE; + } + } + + if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) { + *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH; + } + if (setup_data->validate_cn_call_back) { + if (!setup_data->validate_cn_call_back(cn, + crt->raw.p, + crt->raw.len, + c_session, + depth, + *flags == 0, + setup_data->cn_call_back_arg)) { + *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; + } + } + if (*flags != 0) { + char buf[128]; + char *tcp; + int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags); + + if (ret >= 0) { + tcp = strchr(buf, '\n'); + while (tcp) { + *tcp = '\000'; + coap_log(LOG_WARNING, + " %s: %s: issue 0x%x: '%s' depth %d\n", + coap_session_str(c_session), + buf, *flags, cn ? cn : "?", depth); + tcp = strchr(tcp+1, '\n'); + } + } + else { + coap_log(LOG_ERR, "mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + } + } + + if (cn) + mbedtls_free(cn); + + return 0; +} + +static int +setup_pki_credentials(mbedtls_x509_crt *cacert, + mbedtls_x509_crt *public_cert, + mbedtls_pk_context *private_key, + coap_mbedtls_env_t *m_env, + coap_mbedtls_context_t *m_context, + coap_session_t *c_session, + coap_dtls_pki_t *setup_data, + coap_dtls_role_t role) +{ + int ret; + + switch (setup_data->pki_key.key_type) { + case COAP_PKI_KEY_PEM: + if (setup_data->pki_key.key.pem.public_cert && + setup_data->pki_key.key.pem.public_cert[0] && + setup_data->pki_key.key.pem.private_key && + setup_data->pki_key.key.pem.private_key[0]) { + + mbedtls_x509_crt_init(public_cert); + mbedtls_pk_init(private_key); + + ret = mbedtls_x509_crt_parse_file(public_cert, + setup_data->pki_key.key.pem.public_cert); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse_file returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + ret = mbedtls_pk_parse_keyfile(private_key, + setup_data->pki_key.key.pem.private_key, NULL); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + } + else if (role == COAP_DTLS_ROLE_SERVER) { + coap_log(LOG_ERR, + "***setup_pki: (D)TLS: No Server Certificate + Private " + "Key defined\n"); + return -1; + } + + if (setup_data->pki_key.key.pem.ca_file && + setup_data->pki_key.key.pem.ca_file[0]) { + mbedtls_x509_crt_init(cacert); + ret = mbedtls_x509_crt_parse_file(cacert, + setup_data->pki_key.key.pem.ca_file); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->require_peer_cert ? + MBEDTLS_SSL_VERIFY_REQUIRED : + MBEDTLS_SSL_VERIFY_OPTIONAL); + mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL); + } + break; + case COAP_PKI_KEY_PEM_BUF: + if (setup_data->pki_key.key.pem_buf.public_cert && + setup_data->pki_key.key.pem_buf.public_cert_len && + setup_data->pki_key.key.pem_buf.private_key && + setup_data->pki_key.key.pem_buf.private_key_len) { + uint8_t *buffer; + size_t length; + + mbedtls_x509_crt_init(public_cert); + mbedtls_pk_init(private_key); + + length = setup_data->pki_key.key.pem_buf.public_cert_len; + if (setup_data->pki_key.key.pem_buf.public_cert[length-1] != '\000') { + /* Need to allocate memory to add in NULL terminator */ + buffer = mbedtls_malloc(length + 1); + if (!buffer) { + coap_log(LOG_ERR, "mbedtls_malloc failed\n"); + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + memcpy(buffer, setup_data->pki_key.key.pem_buf.public_cert, length); + buffer[length] = '\000'; + length++; + ret = mbedtls_x509_crt_parse(public_cert, buffer, length); + mbedtls_free(buffer); + } + else { + ret = mbedtls_x509_crt_parse(public_cert, + setup_data->pki_key.key.pem_buf.public_cert, + setup_data->pki_key.key.pem_buf.public_cert_len); + } + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + length = setup_data->pki_key.key.pem_buf.private_key_len; + if (setup_data->pki_key.key.pem_buf.private_key[length-1] != '\000') { + /* Need to allocate memory to add in NULL terminator */ + buffer = mbedtls_malloc(length + 1); + if (!buffer) { + coap_log(LOG_ERR, "mbedtls_malloc failed\n"); + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + memcpy(buffer, setup_data->pki_key.key.pem_buf.private_key, length); + buffer[length] = '\000'; + length++; + ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0); + mbedtls_free(buffer); + } + else { + ret = mbedtls_pk_parse_key(private_key, + setup_data->pki_key.key.pem_buf.private_key, + setup_data->pki_key.key.pem_buf.private_key_len, NULL, 0); + } + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + } else if (role == COAP_DTLS_ROLE_SERVER) { + coap_log(LOG_ERR, + "***setup_pki: (D)TLS: No Server Certificate + Private " + "Key defined\n"); + return -1; + } + + if (setup_data->pki_key.key.pem_buf.ca_cert && + setup_data->pki_key.key.pem_buf.ca_cert_len) { + uint8_t *buffer; + size_t length; + + mbedtls_x509_crt_init(cacert); + length = setup_data->pki_key.key.pem_buf.ca_cert_len; + if (setup_data->pki_key.key.pem_buf.ca_cert[length-1] != '\000') { + /* Need to allocate memory to add in NULL terminator */ + buffer = mbedtls_malloc(length + 1); + if (!buffer) { + coap_log(LOG_ERR, "mbedtls_malloc failed\n"); + return MBEDTLS_ERR_SSL_ALLOC_FAILED; + } + memcpy(buffer, setup_data->pki_key.key.pem_buf.ca_cert, length); + buffer[length] = '\000'; + length++; + ret = mbedtls_x509_crt_parse(cacert, buffer, length); + mbedtls_free(buffer); + } + else { + ret = mbedtls_x509_crt_parse(cacert, + setup_data->pki_key.key.pem_buf.ca_cert, + setup_data->pki_key.key.pem_buf.ca_cert_len); + } + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->require_peer_cert ? + MBEDTLS_SSL_VERIFY_REQUIRED : + MBEDTLS_SSL_VERIFY_OPTIONAL); + mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL); + } + break; + case COAP_PKI_KEY_ASN1: + if (setup_data->pki_key.key.asn1.public_cert && + setup_data->pki_key.key.asn1.public_cert_len && + setup_data->pki_key.key.asn1.private_key && + setup_data->pki_key.key.asn1.private_key_len > 0) { + + mbedtls_x509_crt_init(public_cert); + mbedtls_pk_init(private_key); + ret = mbedtls_x509_crt_parse(public_cert, + (const unsigned char *)setup_data->pki_key.key.asn1.public_cert, + setup_data->pki_key.key.asn1.public_cert_len); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + ret = mbedtls_pk_parse_key(private_key, + (const unsigned char *)setup_data->pki_key.key.asn1.private_key, + setup_data->pki_key.key.asn1.private_key_len, NULL, 0); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + + ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + } else if (role == COAP_DTLS_ROLE_SERVER) { + coap_log(LOG_ERR, + "***setup_pki: (D)TLS: No Server Certificate + Private " + "Key defined\n"); + return -1; + } + + if (setup_data->pki_key.key.asn1.ca_cert && + setup_data->pki_key.key.asn1.ca_cert_len > 0) { + mbedtls_x509_crt_init(cacert); + ret = mbedtls_x509_crt_parse(cacert, + (const unsigned char *)setup_data->pki_key.key.asn1.ca_cert, + setup_data->pki_key.key.asn1.ca_cert_len); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->require_peer_cert ? + MBEDTLS_SSL_VERIFY_REQUIRED : + MBEDTLS_SSL_VERIFY_OPTIONAL); + mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL); + } + break; + default: + coap_log(LOG_ERR, + "***setup_pki: (D)TLS: Unknown key type %d\n", + setup_data->pki_key.key_type); + return -1; + } + + if (m_context->root_ca_file) { + ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL); + } + if (m_context->root_ca_path) { + ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_path); + if (ret < 0) { + coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return ret; + } + mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL); + } + + /* + * Verify Peer. + * Need to do all checking, even if setup_data->verify_peer_cert is not set + */ + mbedtls_ssl_conf_verify(&m_env->conf, + cert_verify_callback_mbedtls, c_session); + + return 0; +} + +#if defined(MBEDTLS_SSL_SRV_C) +/* + * PKI SNI callback. + */ +static int +pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl, + const unsigned char *uname, size_t name_len) +{ + unsigned int i; + coap_dtls_pki_t sni_setup_data; + coap_session_t *c_session = (coap_session_t *)p_info; + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + coap_mbedtls_context_t *m_context = + (coap_mbedtls_context_t *)c_session->context->dtls_context; + int ret = 0; + char *name; + + name = mbedtls_malloc(name_len+1); + if (!name) + return -1; + + memcpy(name, uname, name_len); + name[name_len] = '\000'; + + /* Is this a cached entry? */ + for (i = 0; i < m_context->pki_sni_count; i++) { + if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) { + break; + } + } + if (i == m_context->pki_sni_count) { + /* + * New PKI SNI request + */ + coap_dtls_key_t *new_entry; + + new_entry = + m_context->setup_data.validate_sni_call_back(name, + m_context->setup_data.sni_call_back_arg); + if (!new_entry) { + mbedtls_free(name); + return -1; + } + + m_context->pki_sni_entry_list = + mbedtls_realloc(m_context->pki_sni_entry_list, + (i+1)*sizeof(pki_sni_entry)); + m_context->pki_sni_entry_list[i].sni = name; + m_context->pki_sni_entry_list[i].pki_key = *new_entry; + sni_setup_data = m_context->setup_data; + sni_setup_data.pki_key = *new_entry; + if ((ret = setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert, + &m_context->pki_sni_entry_list[i].public_cert, + &m_context->pki_sni_entry_list[i].private_key, + m_env, + m_context, + c_session, + &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) { + mbedtls_free(name); + return -1; + } + /* name has been absorbed into pki_sni_entry_list[].sni entry */ + m_context->pki_sni_count++; + } + else { + mbedtls_free(name); + } + + mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert, + NULL); + return mbedtls_ssl_set_hs_own_cert(ssl, + &m_context->pki_sni_entry_list[i].public_cert, + &m_context->pki_sni_entry_list[i].private_key); +} +#endif /* MBEDTLS_SSL_SRV_C */ + +/* + * PSK SNI callback. + */ +static int +psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl, + const unsigned char *uname, size_t name_len) +{ + unsigned int i; + coap_session_t *c_session = (coap_session_t *)p_info; + coap_mbedtls_context_t *m_context = + (coap_mbedtls_context_t *)c_session->context->dtls_context; + char *name; + + name = mbedtls_malloc(name_len+1); + if (!name) + return -1; + + memcpy(name, uname, name_len); + name[name_len] = '\000'; + + /* Is this a cached entry? */ + for (i = 0; i < m_context->psk_sni_count; i++) { + if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) { + break; + } + } + if (i == m_context->psk_sni_count) { + /* + * New PSK SNI request + */ + const coap_dtls_spsk_info_t *new_entry; + + new_entry = + c_session->context->spsk_setup_data.validate_sni_call_back(name, + c_session, + c_session->context->spsk_setup_data.sni_call_back_arg); + if (!new_entry) { + mbedtls_free(name); + return -1; + } + + m_context->psk_sni_entry_list = + mbedtls_realloc(m_context->psk_sni_entry_list, + (i+1)*sizeof(psk_sni_entry)); + + m_context->psk_sni_entry_list[i].sni = name; + m_context->psk_sni_entry_list[i].psk_info = *new_entry; + /* name has been absorbed into psk_sni_entry_list[].sni entry */ + m_context->psk_sni_count++; + } + else { + mbedtls_free(name); + } + + coap_session_refresh_psk_hint(c_session, + &m_context->psk_sni_entry_list[i].psk_info.hint); + coap_session_refresh_psk_key(c_session, + &m_context->psk_sni_entry_list[i].psk_info.key); + return mbedtls_ssl_set_hs_psk(ssl, + m_context->psk_sni_entry_list[i].psk_info.key.s, + m_context->psk_sni_entry_list[i].psk_info.key.length); +} + +#if defined(MBEDTLS_SSL_SRV_C) + +static int setup_server_ssl_session(coap_session_t *c_session, + coap_mbedtls_env_t *m_env) +{ + coap_mbedtls_context_t *m_context = + (coap_mbedtls_context_t *)c_session->context->dtls_context; + int ret = 0; + m_context->psk_pki_enabled |= IS_SERVER; + + mbedtls_ssl_cookie_init(&m_env->cookie_ctx); + if ((ret = mbedtls_ssl_config_defaults(&m_env->conf, + MBEDTLS_SSL_IS_SERVER, + c_session->proto == COAP_PROTO_DTLS ? + MBEDTLS_SSL_TRANSPORT_DATAGRAM : + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + goto fail; + } + + mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg); + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS, + COAP_DTLS_RETRANSMIT_TOTAL_MS); + + if (m_context->psk_pki_enabled & IS_PSK) { +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session); + if (c_session->context->spsk_setup_data.validate_sni_call_back) { + mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session); + } +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + if (m_context->psk_pki_enabled & IS_PKI) { + ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert, + &m_env->private_key, m_env, m_context, + c_session, &m_context->setup_data, + COAP_DTLS_ROLE_SERVER); + if (ret < 0) { + coap_log(LOG_ERR, "PKI setup failed\n"); + return ret; + } + if (m_context->setup_data.validate_sni_call_back) { + mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session); + } + } + + if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx, + mbedtls_ctr_drbg_random, + &m_env->ctr_drbg)) != 0) { + coap_log(LOG_ERR, "mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + goto fail; + } + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write, + mbedtls_ssl_cookie_check, + &m_env->cookie_ctx ); +#if MBEDTLS_VERSION_NUMBER >= 0x02100100 + mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu); +#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ +fail: + return ret; +} +#endif /* MBEDTLS_SSL_SRV_C */ + +static int *psk_ciphers = NULL; +static int *pki_ciphers = NULL; +static int processed_ciphers = 0; + +static void +set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) +{ + if (!processed_ciphers) { + const int *list = mbedtls_ssl_list_ciphersuites(); + const int *base = list; + int *psk_list; + int *pki_list; + int psk_count = 1; /* account for empty terminator */ + int pki_count = 1; + + while (*list) { + const mbedtls_ssl_ciphersuite_t *cur = + mbedtls_ssl_ciphersuite_from_id(*list); + + if (cur) { + if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) { + /* Minimum of TLS1.2 required - skip */ + } + else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) { + psk_count++; + } + else { + pki_count++; + } + } + list++; + } + list = base; + + psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0])); + if (psk_ciphers == NULL) { + coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", psk_count); + return; + } + pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0])); + if (pki_ciphers == NULL) { + coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", pki_count); + return; + } + + psk_list = psk_ciphers; + pki_list = pki_ciphers; + + while (*list) { + const mbedtls_ssl_ciphersuite_t *cur = + mbedtls_ssl_ciphersuite_from_id(*list); + if (cur) { + if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) { + /* Minimum of TLS1.2 required - skip */ + } + else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) { + *psk_list = *list; + psk_list++; + } + else { + *pki_list = *list; + pki_list++; + } + } + list++; + } + /* zero terminate */ + *psk_list = 0; + *pki_list = 0; + processed_ciphers = 1; + } + mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers); +} + +static int setup_client_ssl_session(coap_session_t *c_session, + coap_mbedtls_env_t *m_env) +{ + int ret; + + coap_mbedtls_context_t *m_context = + (coap_mbedtls_context_t *)c_session->context->dtls_context; + + m_context->psk_pki_enabled |= IS_CLIENT; + + if ((ret = mbedtls_ssl_config_defaults(&m_env->conf, + MBEDTLS_SSL_IS_CLIENT, + c_session->proto == COAP_PROTO_DTLS ? + MBEDTLS_SSL_TRANSPORT_DATAGRAM : + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + goto fail; + } + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS, + COAP_DTLS_RETRANSMIT_TOTAL_MS); +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED); + mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg); + + if (m_context->psk_pki_enabled & IS_PSK) { +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + uint8_t identity[64]; + size_t identity_len; + uint8_t psk_key[64]; + size_t psk_len; + size_t max_identity_len = sizeof(identity); + + coap_log(LOG_INFO, "Setting PSK key\n"); + psk_len = c_session->context->get_client_psk(c_session, + NULL, + 0, + identity, + &identity_len, + max_identity_len, + psk_key, + sizeof(psk_key)); + assert(identity_len <= sizeof(identity)); + mbedtls_ssl_conf_psk(&m_env->conf, (const unsigned char *)psk_key, + psk_len, (const unsigned char *)identity, + identity_len); + if (c_session->cpsk_setup_data.client_sni) { + mbedtls_ssl_set_hostname(&m_env->ssl, + c_session->cpsk_setup_data.client_sni); + } + /* Identity Hint currently not supported in MbedTLS so code removed */ + + set_ciphersuites(&m_env->conf, COAP_ENC_PSK); +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + } + else if ((m_context->psk_pki_enabled & IS_PKI) || + (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) { + /* + * If neither PSK or PKI have been set up, use PKI basics. + * This works providing COAP_PKI_KEY_PEM has a value of 0. + */ + mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL); + ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert, + &m_env->private_key, m_env, m_context, + c_session, &m_context->setup_data, + COAP_DTLS_ROLE_CLIENT); + if (ret < 0) { + coap_log(LOG_ERR, "PKI setup failed\n"); + return ret; + } +#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN) + if (c_session->proto == COAP_PROTO_TLS) { + const char *alpn_list[] = { "coap", NULL }; + + ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list); + if (ret != 0) { + coap_log(LOG_ERR, "ALPN setup failed %d)\n", ret); + } + } +#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */ + if (m_context->setup_data.client_sni) { + mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni); + } +#if defined(MBEDTLS_SSL_PROTO_DTLS) +#if MBEDTLS_VERSION_NUMBER >= 0x02100100 + mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu); +#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + set_ciphersuites(&m_env->conf, COAP_ENC_PKI); + } + return 0; + +fail: + return ret; +} + +static void mbedtls_cleanup(coap_mbedtls_env_t *m_env) +{ + if (!m_env) { + return; + } + + mbedtls_x509_crt_free(&m_env->cacert); + mbedtls_x509_crt_free(&m_env->public_cert); + mbedtls_pk_free(&m_env->private_key); + mbedtls_entropy_free(&m_env->entropy); + mbedtls_ssl_config_free(&m_env->conf); + mbedtls_ctr_drbg_free(&m_env->ctr_drbg); + mbedtls_ssl_free(&m_env->ssl); + mbedtls_ssl_cookie_free(&m_env->cookie_ctx); +} + +static void +coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) { + if (m_env) { + mbedtls_cleanup(m_env); + mbedtls_free(m_env); + } +} + +/* + * return -1 failure + * 0 not completed + * 1 established + */ +static int do_mbedtls_handshake(coap_session_t *c_session, + coap_mbedtls_env_t *m_env) { + int ret; + + ret = mbedtls_ssl_handshake(&m_env->ssl); + switch (ret) { + case 0: + m_env->established = 1; + coap_log(LOG_DEBUG, "* %s: MbedTLS established\n", + coap_session_str(c_session)); + ret = 1; + break; + case MBEDTLS_ERR_SSL_WANT_READ: + case MBEDTLS_ERR_SSL_WANT_WRITE: + errno = EAGAIN; + ret = 0; + break; + case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED: + coap_log(LOG_INFO, "hello verification requested\n"); + ret = -1; + mbedtls_ssl_session_reset(&m_env->ssl); + break; + case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE: + case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: + c_session->dtls_event = COAP_EVENT_DTLS_CLOSED; + ret = -1; + break; + default: + coap_log(LOG_WARNING, + "do_mbedtls_handshake: session establish " + "returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + ret = -1; + break; + } + return ret; +} + +static void +mbedtls_debug_out(void *ctx UNUSED, int level, + const char *file, int line, const char *str) { + int log_level; + /* + * 0 No debug + * 1 Error + * 2 State change + * 3 Informational + * 4 Verbose + */ + switch (level) { + case 4: + case 3: + case 2: + log_level = COAP_LOG_CIPHERS; + break; + case 1: + log_level = LOG_ERR; + break; + case 0: + default: + log_level = 0; + break; + } + coap_log(log_level, "%s:%04d: %s", file, line, str); +} + +static coap_mbedtls_env_t *coap_dtls_new_mbedtls_env(coap_session_t *c_session, + coap_dtls_role_t role) +{ + int ret = 0; + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + + if (m_env) + return m_env; + + m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t)); + if (!m_env) { + return NULL; + } + memset(m_env, 0, sizeof(coap_mbedtls_env_t)); + + mbedtls_ssl_init(&m_env->ssl); + mbedtls_ctr_drbg_init(&m_env->ctr_drbg); + mbedtls_ssl_config_init(&m_env->conf); + mbedtls_entropy_init(&m_env->entropy); + +#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG) + mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL); +#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */ + if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg, + mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) { + coap_log(LOG_ERR, "mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + goto fail; + } + + if (role == COAP_DTLS_ROLE_CLIENT) { + if (setup_client_ssl_session(c_session, m_env) != 0) { + goto fail; + } +#if defined(MBEDTLS_SSL_SRV_C) + } else if (role == COAP_DTLS_ROLE_SERVER) { + if (setup_server_ssl_session(c_session, m_env) != 0) { + goto fail; + } +#endif /* MBEDTLS_SSL_SRV_C */ + } else { + goto fail; + } + + mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3, + MBEDTLS_SSL_MINOR_VERSION_3); + + if ((ret = mbedtls_ssl_setup(&m_env->ssl, &m_env->conf)) != 0) { + goto fail; + } + mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write, + coap_dgram_read, NULL); + mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer, + mbedtls_timing_set_delay, + mbedtls_timing_get_delay); + + mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout); + return m_env; + +fail: + if (m_env) { + mbedtls_free(m_env); + } + return NULL; +} + +int coap_dtls_is_supported(void) { +#if defined(MBEDTLS_SSL_PROTO_DTLS) + return 1; +#else /* !MBEDTLS_SSL_PROTO_DTLS */ + coap_log(LOG_EMERG, + "libcoap not compiled for DTLS with MbedTLS" + " - update MbedTLS to include DTLS\n"); + return 0; +#endif /* !MBEDTLS_SSL_PROTO_DTLS */ +} + +int coap_tls_is_supported(void) +{ + return 0; +} + +void *coap_dtls_new_context(struct coap_context_t *c_context) +{ + coap_mbedtls_context_t *m_context; + (void)c_context; + + m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t)); + if (m_context) { + memset(m_context, 0, sizeof(coap_mbedtls_context_t)); + } + return m_context; +} + +/* + * return 0 failed + * 1 passed + */ +int +coap_dtls_context_set_spsk(coap_context_t *c_context, + coap_dtls_spsk_t *setup_data +) { + coap_mbedtls_context_t *m_context = + ((coap_mbedtls_context_t *)c_context->dtls_context); + +#if !defined(MBEDTLS_SSL_SRV_C) + coap_log(LOG_EMERG, "coap_context_set_spsk:" + " libcoap not compiled for Server Mode for MbedTLS" + " - update MbedTLS to include Server Mode\n"); + return 0; +#endif /* !MBEDTLS_SSL_SRV_C */ + if (!m_context || !setup_data) + return 0; + + m_context->psk_pki_enabled |= IS_PSK; + return 1; +} + +/* + * return 0 failed + * 1 passed + */ +int +coap_dtls_context_set_cpsk(coap_context_t *c_context, + coap_dtls_cpsk_t *setup_data +) { +#if !defined(MBEDTLS_SSL_CLI_C) + coap_log(LOG_EMERG, "coap_context_set_spsk:" + " libcoap not compiled for Client Mode for MbedTLS" + " - update MbedTLS to include Client Mode\n"); + return 0; +#endif /* !MBEDTLS_SSL_CLI_C */ + coap_mbedtls_context_t *m_context = + ((coap_mbedtls_context_t *)c_context->dtls_context); + + if (!m_context || !setup_data) + return 0; + + if (setup_data->validate_ih_call_back) { + coap_log(LOG_WARNING, + "CoAP Client with MbedTLS does not support Identity Hint selection\n"); + } + m_context->psk_pki_enabled |= IS_PSK; + return 1; +} + +int coap_dtls_context_set_pki(struct coap_context_t *c_context, + coap_dtls_pki_t *setup_data, + coap_dtls_role_t role UNUSED) +{ + coap_mbedtls_context_t *m_context = + ((coap_mbedtls_context_t *)c_context->dtls_context); + + m_context->setup_data = *setup_data; + m_context->psk_pki_enabled |= IS_PKI; + return 1; +} + +int coap_dtls_context_set_pki_root_cas(struct coap_context_t *c_context, + const char *ca_file, + const char *ca_path) +{ + coap_mbedtls_context_t *m_context = + ((coap_mbedtls_context_t *)c_context->dtls_context); + + if (!m_context) { + coap_log(LOG_WARNING, + "coap_context_set_pki_root_cas: (D)TLS environment " + "not set up\n"); + return 0; + } + + if (ca_file == NULL && ca_path == NULL) { + coap_log(LOG_WARNING, + "coap_context_set_pki_root_cas: ca_file and/or ca_path " + "not defined\n"); + return 0; + } + if (m_context->root_ca_file) { + mbedtls_free(m_context->root_ca_file); + m_context->root_ca_file = NULL; + } + + if (ca_file) { + m_context->root_ca_file = mbedtls_strdup(ca_file); + } + + if (m_context->root_ca_path) { + mbedtls_free(m_context->root_ca_path); + m_context->root_ca_path = NULL; + } + + if (ca_path) { + m_context->root_ca_path = mbedtls_strdup(ca_path); + } + return 1; +} + +int coap_dtls_context_check_keys_enabled(struct coap_context_t *c_context) +{ + coap_mbedtls_context_t *m_context = + ((coap_mbedtls_context_t *)c_context->dtls_context); + return m_context->psk_pki_enabled ? 1 : 0; +} + +void coap_dtls_free_context(void *dtls_context) +{ + coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context; + unsigned int i; + + for (i = 0; i < m_context->pki_sni_count; i++) { + mbedtls_free(m_context->pki_sni_entry_list[i].sni); + + mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert); + + mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key); + + mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert); + } + if (m_context->pki_sni_entry_list) + mbedtls_free(m_context->pki_sni_entry_list); + + for (i = 0; i < m_context->psk_sni_count; i++) { + mbedtls_free(m_context->psk_sni_entry_list[i].sni); + } + if (m_context->psk_sni_entry_list) + mbedtls_free(m_context->psk_sni_entry_list); + + mbedtls_free(m_context); +} + +void *coap_dtls_new_client_session(coap_session_t *c_session) +{ +#if !defined(MBEDTLS_SSL_CLI_C) + (void)c_session; + coap_log(LOG_EMERG, "coap_dtls_new_client_session:" + " libcoap not compiled for Client Mode for MbedTLS" + " - update MbedTLS to include Client Mode\n"); + return NULL; +#else /* MBEDTLS_SSL_CLI_C */ + coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session, + COAP_DTLS_ROLE_CLIENT); + int ret; + + if (m_env) { + coap_tick_t now; + coap_ticks(&now); + m_env->last_timeout = now; + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == -1) { + coap_dtls_free_mbedtls_env(m_env); + return NULL; + } + } + return m_env; +#endif /* MBEDTLS_SSL_CLI_C */ +} + +void *coap_dtls_new_server_session(coap_session_t *c_session) +{ + coap_mbedtls_env_t *m_env = + (coap_mbedtls_env_t *)c_session->tls; + if (m_env) { + m_env->seen_client_hello = 1; +#if defined(MBEDTLS_SSL_PROTO_DTLS) +#if MBEDTLS_VERSION_NUMBER >= 0x02100100 + mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu); +#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + } + return m_env; +} + +void coap_dtls_free_session(coap_session_t *c_session) +{ + if (c_session && c_session->context) { + coap_dtls_free_mbedtls_env(c_session->tls); + c_session->tls = NULL; + coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session); + } + return; +} + +void coap_dtls_session_update_mtu(coap_session_t *c_session) +{ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + coap_mbedtls_env_t *m_env = + (coap_mbedtls_env_t *)c_session->tls; + if (m_env) { +#if MBEDTLS_VERSION_NUMBER >= 0x02100100 + mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu); +#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */ + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ +} + +int coap_dtls_send(coap_session_t *c_session, + const uint8_t *data, + size_t data_len) +{ + int ret; + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + + assert(m_env != NULL); + + if (!m_env) { + return -1; + } + c_session->dtls_event = -1; + if (m_env->established) { + ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char*) data, data_len); + if (ret <= 0) { + switch (ret) { + case MBEDTLS_ERR_SSL_WANT_READ: + case MBEDTLS_ERR_SSL_WANT_WRITE: + ret = 0; + break; + case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE: + c_session->dtls_event = COAP_EVENT_DTLS_CLOSED; + ret = -1; + break; + default: + coap_log(LOG_WARNING, + "coap_dtls_send: " + "returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + ret = -1; + break; + } + if (ret == -1) { + coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n"); + } + } + } else { + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == 1) { + /* Just connected, so send the data */ + return coap_dtls_send(c_session, data, data_len); + } + ret = -1; + } + + if (c_session->dtls_event >= 0) { + /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */ + if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED) + coap_handle_event(c_session->context, c_session->dtls_event, c_session); + if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR || + c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) { + coap_session_disconnected(c_session, COAP_NACK_TLS_FAILED); + ret = -1; + } + } + return ret; +} + +int coap_dtls_is_context_timeout(void) +{ + return 0; +} + +coap_tick_t coap_dtls_get_context_timeout(void *dtls_context UNUSED) +{ + return 0; +} + +coap_tick_t coap_dtls_get_timeout(coap_session_t *c_session, coap_tick_t now) +{ + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + int ret = mbedtls_timing_get_delay(&m_env->timer); + unsigned int scalar = 1 << m_env->retry_scalar; + + switch (ret) { + case 0: + /* int_ms has not timed out */ + if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) { + /* Need to indicate remaining timeout time */ + return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar; + } + m_env->last_timeout = now; + /* This may cause a minor extra delay */ + return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar; + case 1: + /* int_ms has timed out, but not fin_ms */ + /* + * Need to make sure that we do not do this too frequently + */ + if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) { + return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar; + } + + /* Reset for the next time */ + m_env->last_timeout = now; + return now; + case 2: + /* fin_ms has timed out - timed out - one final try */ + return now; + default: + break; + } + + return 0; +} + +void coap_dtls_handle_timeout(coap_session_t *c_session) +{ + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + + assert(m_env != NULL); + m_env->retry_scalar++; + if (((c_session->state == COAP_SESSION_STATE_HANDSHAKE) && + (++c_session->dtls_timeout_count > c_session->max_retransmit)) || + (do_mbedtls_handshake(c_session, m_env) < 0)) { + /* Too many retries */ + coap_session_disconnected(c_session, COAP_NACK_TLS_FAILED); + } + return; +} + +int coap_dtls_receive(coap_session_t *c_session, + const uint8_t *data, + size_t data_len) +{ + int ret = 1; + + c_session->dtls_event = -1; + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + assert(m_env != NULL); + + coap_ssl_t *ssl_data = &m_env->coap_ssl_data; + if (ssl_data->pdu_len) { + coap_log(LOG_INFO, "** %s: Previous data not read %u bytes\n", + coap_session_str(c_session), ssl_data->pdu_len); + } + ssl_data->pdu = data; + ssl_data->pdu_len = (unsigned)data_len; + + if (m_env->established) { +#if COAP_CONSTRAINED_STACK + static coap_mutex_t b_static_mutex = COAP_MUTEX_INITIALIZER; + static uint8_t pdu[COAP_RXBUFFER_SIZE]; +#else /* ! COAP_CONSTRAINED_STACK */ + uint8_t pdu[COAP_RXBUFFER_SIZE]; +#endif /* ! COAP_CONSTRAINED_STACK */ + +#if COAP_CONSTRAINED_STACK + coap_mutex_lock(&b_static_mutex); +#endif /* COAP_CONSTRAINED_STACK */ + + if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) { + coap_handle_event(c_session->context, COAP_EVENT_DTLS_CONNECTED, + c_session); + coap_session_connected(c_session); + } + + ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu)); + if (ret > 0) { + ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret); +#if COAP_CONSTRAINED_STACK + coap_mutex_unlock(&b_static_mutex); +#endif /* COAP_CONSTRAINED_STACK */ + return ret; + } + else if (ret == 0 || ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + c_session->dtls_event = COAP_EVENT_DTLS_CLOSED; + } + else if (ret != MBEDTLS_ERR_SSL_WANT_READ) { + coap_log(LOG_WARNING, + "coap_dtls_receive: " + "returned -0x%x: '%s' (length %zd)\n", + -ret, get_error_string(ret), data_len); + } +#if COAP_CONSTRAINED_STACK + coap_mutex_unlock(&b_static_mutex); +#endif /* COAP_CONSTRAINED_STACK */ + ret = -1; + } + else { + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == 1) { + /* Just connected, so send the data */ + coap_session_connected(c_session); + } else { + if (ssl_data->pdu_len) { + /* Do the handshake again incase of internal timeout */ + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == 1) { + /* Just connected, so send the data */ + coap_session_connected(c_session); + } else { + ret = -1; + } + } + ret = -1; + } + } + if (c_session->dtls_event >= 0) { + /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */ + if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED) + coap_handle_event(c_session->context, c_session->dtls_event, c_session); + if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR || + c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) { + coap_session_disconnected(c_session, COAP_NACK_TLS_FAILED); + ret = -1; + } + } + return ret; +} + +int coap_dtls_hello(coap_session_t *c_session, + const uint8_t *data, + size_t data_len) +{ +#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C) + (void)c_session; + (void)data; + (void)data_len; + coap_log(LOG_EMERG, "coap_dtls_hello:" + " libcoap not compiled for DTLS or Server Mode for MbedTLS" + " - update MbedTLS to include DTLS and Server Mode\n"); + return -1; +#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */ + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + coap_ssl_t *ssl_data = m_env ? &m_env->coap_ssl_data : NULL; + int ret; + + if (m_env) { + if((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl, + (unsigned char *)&c_session->addr_info.remote, + sizeof(c_session->addr_info.remote))) != 0) { + coap_log(LOG_ERR, + "mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return -1; + } + } + + if (!m_env) { + m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER); + if (m_env) { + c_session->tls = m_env; + ssl_data = &m_env->coap_ssl_data; + ssl_data->pdu = data; + ssl_data->pdu_len = (unsigned)data_len; + if((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl, + (unsigned char *)&c_session->addr_info.remote, + sizeof(c_session->addr_info.remote))) != 0) { + coap_log(LOG_ERR, + "mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n", + -ret, get_error_string(ret)); + return -1; + } + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == 0 || m_env->seen_client_hello) { + m_env->seen_client_hello = 0; + return 1; + } + } + return 0; + } + + ssl_data->pdu = data; + ssl_data->pdu_len = (unsigned)data_len; + ret = do_mbedtls_handshake(c_session, m_env); + if (ret == 0 || m_env->seen_client_hello) { + /* The test for seen_client_hello gives the ability to setup a new + c_session to continue the do_mbedtls_handshake past the client hello + and safely allow updating of the m_env and separately + letting a new session cleanly start up. + */ + m_env->seen_client_hello = 0; + return 1; + } + return 0; +#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */ +} + +unsigned int coap_dtls_get_overhead(coap_session_t *c_session) +{ + coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls; + int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl); + + if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) { + return 13 + 8 + 8; + } + return expansion; +} + +#if !COAP_DISABLE_TCP +void *coap_tls_new_client_session(coap_session_t *c_session UNUSED, int *connected UNUSED) +{ + return NULL; +} + +void *coap_tls_new_server_session(coap_session_t *c_session UNUSED, int *connected UNUSED) +{ + return NULL; +} + +void coap_tls_free_session( coap_session_t *c_session UNUSED) +{ +} + +ssize_t coap_tls_write(coap_session_t *c_session UNUSED, + const uint8_t *data UNUSED, + size_t data_len UNUSED + ) +{ + return 0; +} + +ssize_t coap_tls_read(coap_session_t *c_session UNUSED, + uint8_t *data UNUSED, + size_t data_len UNUSED + ) +{ + return 0; +} +#endif /* !COAP_DISABLE_TCP */ + +void coap_dtls_startup(void) +{ +} + +static int keep_log_level = 0; + +void coap_dtls_set_log_level(int level) +{ +#if !defined(ESPIDF_VERSION) + int use_level; + /* + * MbedTLS debug levels filter + * 0 No debug + * 1 Error + * 2 State change + * 3 Informational + * 4 Verbose + */ + + if (level <= LOG_ERR) { + use_level = 1; + } + else { + use_level = (level >= LOG_DEBUG) ? level - LOG_DEBUG + 2 : 0; + } + mbedtls_debug_set_threshold(use_level); +#endif /* !ESPIDF_VERSION) */ + keep_log_level = level; +} + +int coap_dtls_get_log_level(void) +{ + return keep_log_level; +} + +coap_tls_version_t * coap_get_tls_library_version(void) +{ + static coap_tls_version_t version; + version.version = mbedtls_version_get_number(); + version.built_version = MBEDTLS_VERSION_NUMBER; + version.type = COAP_TLS_LIBRARY_MBEDTLS; + return &version; +} + +#else /* !HAVE_MBEDTLS */ + +#ifdef __clang__ +/* Make compilers happy that do not like empty modules. As this function is + * never used, we ignore -Wunused-function at the end of compiling this file + */ +#pragma GCC diagnostic ignored "-Wunused-function" +#endif +static inline void dummy(void) { +} + +#endif /* HAVE_MBEDTLS */ diff --git a/src/coap_notls.c b/src/coap_notls.c index a0c04852..de6cd08c 100644 --- a/src/coap_notls.c +++ b/src/coap_notls.c @@ -9,7 +9,7 @@ #include "coap_internal.h" -#if !defined(HAVE_LIBTINYDTLS) && !defined(HAVE_OPENSSL) && !defined(HAVE_LIBGNUTLS) +#if !defined(HAVE_LIBTINYDTLS) && !defined(HAVE_OPENSSL) && !defined(HAVE_LIBGNUTLS) && !defined(HAVE_MBEDTLS) #ifdef __GNUC__ #define UNUSED __attribute__((unused)) @@ -191,4 +191,4 @@ ssize_t coap_tls_read(coap_session_t *session UNUSED, static inline void dummy(void) { } -#endif /* !HAVE_LIBTINYDTLS && !HAVE_OPENSSL && !HAVE_LIBGNUTLS */ +#endif /* !HAVE_LIBTINYDTLS && !HAVE_OPENSSL && !HAVE_LIBGNUTLS && !HAVE_MBEDTLS */ diff --git a/tests/test_tls.c b/tests/test_tls.c index 517f14f1..4dacff4f 100644 --- a/tests/test_tls.c +++ b/tests/test_tls.c @@ -39,6 +39,11 @@ #include #endif /* HAVE_LIBGNUTLS */ +#ifdef HAVE_MBEDTLS +#define HAVE_DTLS 1 +#include +#endif /* HAVE_MBEDTLS */ + static void t_tls1(void) { int need_dtls = 0; @@ -79,6 +84,9 @@ t_tls2(void) { #elif defined(HAVE_LIBGNUTLS) version.version = GNUTLS_VERSION_NUMBER; version.type = COAP_TLS_LIBRARY_GNUTLS; +#elif defined(HAVE_MBEDTLS) + version.version = MBEDTLS_VERSION_NUMBER; + version.type = COAP_TLS_LIBRARY_MBEDTLS; #else /* no DTLS */ version.version = 0; version.type = COAP_TLS_LIBRARY_NOTLS;