libcoap 4.3.5-develop-0869dea
Loading...
Searching...
No Matches
coap_mbedtls.c
Go to the documentation of this file.
1/*
2 * coap_mbedtls.c -- Mbed TLS Datagram Transport Layer Support for libcoap
3 *
4 * Copyright (C) 2019-2026 Jon Shallow <supjps-libcoap@jpshallow.com>
5 * 2019 Jitin George <jitin@espressif.com>
6 *
7 * SPDX-License-Identifier: BSD-2-Clause
8 *
9 * This file is part of the CoAP library libcoap. Please see README for terms
10 * of use.
11 */
12
17
18/*
19 * Naming used to prevent confusion between coap sessions, mbedtls sessions etc.
20 * when reading the code.
21 *
22 * c_context A coap_context_t *
23 * c_session A coap_session_t *
24 * m_context A coap_mbedtls_context_t * (held in c_context->dtls_context)
25 * m_env A coap_mbedtls_env_t * (held in c_session->tls)
26 */
27
28/*
29 * Notes
30 *
31 * Version 3.2.0 or later is needed to provide Connection ID support (RFC9146).
32 *
33 */
34
36
37#if COAP_WITH_LIBMBEDTLS || COAP_WITH_LIBMBEDTLS_OSCORE
38
39/*
40 * This code can be conditionally compiled to remove some components if
41 * they are not required to make a lighter footprint - all based on how
42 * the mbedtls library has been built. These are not defined within the
43 * libcoap environment.
44 *
45 * MBEDTLS_SSL_SRV_C - defined for server side functionality
46 * MBEDTLS_SSL_CLI_C - defined for client side functionality
47 * MBEDTLS_SSL_PROTO_DTLS - defined for DTLS support
48 * MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED - defined if PSK is to be supported
49 * or MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED - defined if PSK is to be supported
50 *
51 */
52
53#include <mbedtls/version.h>
54
55/* Keep forward-compatibility with Mbed TLS 3.x */
56#if (MBEDTLS_VERSION_NUMBER < 0x03000000)
57#define MBEDTLS_2_X_COMPAT
58#else /* !(MBEDTLS_VERSION_NUMBER < 0x03000000) */
59/* Macro wrapper for struct's private members */
60#ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS
61#define MBEDTLS_ALLOW_PRIVATE_ACCESS
62#endif /* MBEDTLS_ALLOW_PRIVATE_ACCESS */
63#endif /* !(MBEDTLS_VERSION_NUMBER < 0x03000000) */
64
65#include <mbedtls/platform.h>
66#include <mbedtls/net_sockets.h>
67#include <mbedtls/ssl.h>
68#include <mbedtls/version.h>
69
70/* Auto-detect mbedTLS 4.x which requires PSA Crypto APIs */
71#if MBEDTLS_VERSION_NUMBER >= 0x04000000
72#define COAP_USE_PSA_CRYPTO 1
73#else
74#define COAP_USE_PSA_CRYPTO 0
75#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
76
77#if COAP_USE_PSA_CRYPTO
78#include <psa/crypto.h>
79#else
80#include <mbedtls/entropy.h>
81#include <mbedtls/ctr_drbg.h>
82#include <mbedtls/sha256.h>
83#include <mbedtls/md.h>
84#include <mbedtls/cipher.h>
85#endif /* COAP_USE_PSA_CRYPTO */
86
87#include <mbedtls/error.h>
88#include <mbedtls/timing.h>
89#include <mbedtls/ssl_cookie.h>
90#include <mbedtls/oid.h>
91#include <mbedtls/debug.h>
92#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
93#include <mbedtls/esp_debug.h>
94#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
95#if !COAP_USE_PSA_CRYPTO && defined(MBEDTLS_PSA_CRYPTO_C)
96#include <psa/crypto.h>
97#endif /* !COAP_USE_PSA_CRYPTO && MBEDTLS_PSA_CRYPTO_C */
98
99/*
100 * Crypto abstraction types for mbedTLS version compatibility
101 */
102#if COAP_USE_PSA_CRYPTO
103typedef psa_hash_operation_t coap_crypto_sha256_ctx_t;
104typedef psa_algorithm_t coap_crypto_md_type_t;
105
106#define COAP_CRYPTO_MD_SHA1 PSA_ALG_SHA_1
107#define COAP_CRYPTO_MD_SHA256 PSA_ALG_SHA_256
108#define COAP_CRYPTO_MD_SHA384 PSA_ALG_SHA_384
109#define COAP_CRYPTO_MD_SHA512 PSA_ALG_SHA_512
110#define COAP_CRYPTO_MD_NONE PSA_ALG_NONE
111
112#else /* !COAP_USE_PSA_CRYPTO */
113typedef mbedtls_sha256_context coap_crypto_sha256_ctx_t;
114typedef mbedtls_md_type_t coap_crypto_md_type_t;
115
116#define COAP_CRYPTO_MD_SHA1 MBEDTLS_MD_SHA1
117#define COAP_CRYPTO_MD_SHA256 MBEDTLS_MD_SHA256
118#define COAP_CRYPTO_MD_SHA384 MBEDTLS_MD_SHA384
119#define COAP_CRYPTO_MD_SHA512 MBEDTLS_MD_SHA512
120#define COAP_CRYPTO_MD_NONE MBEDTLS_MD_NONE
121#endif /* !COAP_USE_PSA_CRYPTO */
122
125 static coap_tls_version_t version;
126 version.version = mbedtls_version_get_number();
127 version.built_version = MBEDTLS_VERSION_NUMBER;
129 return &version;
130}
131
132#if COAP_WITH_LIBMBEDTLS_OSCORE
133void
134coap_dtls_startup(void) {
135#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
136 psa_crypto_init();
137#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
138}
139
140void
141coap_dtls_shutdown(void) {
143#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
144 mbedtls_psa_crypto_free();
145#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
146}
147
148#endif /* COAP_WITH_LIBMBEDTLS_OSCORE */
149
150void
152}
153
154#ifdef _WIN32
155#include <stdlib.h>
156#include <string.h>
157#endif /* _WIN32 */
158
159/*
160 * Default mbedTLS helpers in this file to the C library heap. Zephyr can set
161 * mbedtls_malloc / mbedtls_realloc / mbedtls_free via zephyr/CMakeLists.txt.
162 */
163
164#ifndef mbedtls_malloc
165#define mbedtls_malloc(a) malloc(a)
166#endif
167#ifndef mbedtls_realloc
168#define mbedtls_realloc(a, b) realloc((a), (b))
169#endif
170#ifndef mbedtls_free
171#define mbedtls_free(a) free(a)
172#endif
173
174#if ! COAP_WITH_LIBMBEDTLS_OSCORE
175static char *
176coap_mbedtls_strdup_alloc(const char *s) {
177 size_t len;
178 char *copy;
179
180 if (!s) {
181 return NULL;
182 }
183 len = strlen(s) + 1;
184 copy = (char *)mbedtls_malloc(len);
185 if (copy) {
186 memcpy(copy, s, len);
187 }
188 return copy;
189}
190
191static char *
192coap_mbedtls_strndup_alloc(const char *s, size_t n) {
193 size_t len;
194 char *copy;
195
196 if (!s) {
197 return NULL;
198 }
199 len = strnlen(s, n);
200 copy = (char *)mbedtls_malloc(len + 1);
201 if (copy) {
202 memcpy(copy, s, len);
203 copy[len] = '\0';
204 }
205 return copy;
206}
207#endif /* ! COAP_WITH_LIBMBEDTLS_OSCORE */
208
209#ifndef mbedtls_strdup
210#define mbedtls_strdup(a) coap_mbedtls_strdup_alloc(a)
211#endif
212#ifndef mbedtls_strndup
213#define mbedtls_strndup(a, b) coap_mbedtls_strndup_alloc((a), (b))
214#endif
215
216#ifndef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
217/* definition changed in later mbedtls code versions */
218#ifdef MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED
219#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
220#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
221#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
222
223#if ! COAP_SERVER_SUPPORT
224#undef MBEDTLS_SSL_SRV_C
225#endif /* ! COAP_SERVER_SUPPORT */
226#if ! COAP_CLIENT_SUPPORT
227#undef MBEDTLS_SSL_CLI_C
228#endif /* ! COAP_CLIENT_SUPPORT */
229
230#ifdef _WIN32
231#define strcasecmp _stricmp
232#endif
233
234/*
235 * Crypto Abstraction Functions
236 * These provide a unified API for both legacy mbedTLS and PSA Crypto.
237 */
238
239#if COAP_SERVER_SUPPORT
240/* SHA-256 Digest Functions */
241
242static int
243coap_crypto_sha256_init(coap_crypto_sha256_ctx_t *ctx) {
244#if COAP_USE_PSA_CRYPTO
245 *ctx = psa_hash_operation_init();
246 return (psa_hash_setup(ctx, PSA_ALG_SHA_256) == PSA_SUCCESS) ? 0 : -1;
247#else
248 mbedtls_sha256_init(ctx);
249#if (MBEDTLS_VERSION_NUMBER < 0x03000000)
250 return mbedtls_sha256_starts_ret(ctx, 0);
251#else
252 return mbedtls_sha256_starts(ctx, 0);
253#endif
254#endif
255}
256
257static int
258coap_crypto_sha256_update(coap_crypto_sha256_ctx_t *ctx,
259 const uint8_t *data, size_t len) {
260#if COAP_USE_PSA_CRYPTO
261 return (psa_hash_update(ctx, data, len) == PSA_SUCCESS) ? 0 : -1;
262#else
263#if (MBEDTLS_VERSION_NUMBER < 0x03000000)
264 return mbedtls_sha256_update_ret(ctx, data, len);
265#else
266 return mbedtls_sha256_update(ctx, data, len);
267#endif
268#endif
269}
270
271static int
272coap_crypto_sha256_finish(coap_crypto_sha256_ctx_t *ctx, uint8_t *output) {
273#if COAP_USE_PSA_CRYPTO
274 size_t hash_len;
275 return (psa_hash_finish(ctx, output, 32, &hash_len) == PSA_SUCCESS) ? 0 : -1;
276#else
277#if (MBEDTLS_VERSION_NUMBER < 0x03000000)
278 return mbedtls_sha256_finish_ret(ctx, output);
279#else
280 return mbedtls_sha256_finish(ctx, output);
281#endif
282#endif
283}
284
285static void
286coap_crypto_sha256_free(coap_crypto_sha256_ctx_t *ctx) {
287#if COAP_USE_PSA_CRYPTO
288 psa_hash_abort(ctx);
289#else
290 mbedtls_sha256_free(ctx);
291#endif
292}
293#endif /* COAP_SERVER_SUPPORT */
294
295/* General Hash Functions */
296#if COAP_WS_SUPPORT
297static size_t
298coap_crypto_hash_size(coap_crypto_md_type_t md_type) {
299#if COAP_USE_PSA_CRYPTO
300 switch ((int)md_type) {
301 case PSA_ALG_SHA_1:
302 return 20;
303 case PSA_ALG_SHA_256:
304 return 32;
305 case PSA_ALG_SHA_384:
306 return 48;
307 case PSA_ALG_SHA_512:
308 return 64;
309 default:
310 return 0;
311 }
312#else
313 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
314 return md_info ? mbedtls_md_get_size(md_info) : 0;
315#endif
316}
317
318static int
319coap_crypto_hash_compute(coap_crypto_md_type_t md_type,
320 const uint8_t *input, size_t ilen,
321 uint8_t *output, size_t output_size,
322 size_t *output_len) {
323#if COAP_USE_PSA_CRYPTO
324 size_t actual_len;
325 psa_status_t status = psa_hash_compute(md_type, input, ilen,
326 output, output_size, &actual_len);
327 if (output_len)
328 *output_len = actual_len;
329 return (status == PSA_SUCCESS) ? 0 : -1;
330#else
331 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
332 if (!md_info)
333 return -1;
334 size_t hash_len = mbedtls_md_get_size(md_info);
335 if (hash_len > output_size)
336 return -1;
337 if (output_len)
338 *output_len = hash_len;
339 return mbedtls_md(md_info, input, ilen, output);
340#endif
341}
342#endif /* COAP_WS_SUPPORT */
343
344
345#endif /* COAP_WITH_LIBMBEDTLS || COAP_WITH_LIBMBEDTLS_OSCORE */
346
347#if COAP_WITH_LIBMBEDTLS
348
349#define IS_PSK (1 << 0)
350#define IS_PKI (1 << 1)
351#define IS_CLIENT (1 << 6)
352#define IS_SERVER (1 << 7)
353
354typedef struct coap_ssl_t {
355 const uint8_t *pdu;
356 unsigned pdu_len;
357 unsigned peekmode;
358} coap_ssl_t;
359
360/*
361 * This structure encapsulates the Mbed TLS session object.
362 * It handles both TLS and DTLS.
363 * c_session->tls points to this.
364 */
365typedef struct coap_mbedtls_env_t {
366 mbedtls_ssl_context ssl;
367#if !COAP_USE_PSA_CRYPTO
368 mbedtls_entropy_context entropy;
369 mbedtls_ctr_drbg_context ctr_drbg;
370#endif /* !COAP_USE_PSA_CRYPTO */
371 mbedtls_ssl_config conf;
372 mbedtls_timing_delay_context timer;
373 mbedtls_x509_crt cacert;
374 mbedtls_x509_crt public_cert;
375 mbedtls_pk_context private_key;
376 mbedtls_ssl_cookie_ctx cookie_ctx;
377 /* If not set, need to do do_mbedtls_handshake */
378 int established;
379 int sent_alert;
380 int seen_client_hello;
381 int ec_jpake;
382 coap_tick_t last_timeout;
383 unsigned int retry_scalar;
384 coap_ssl_t coap_ssl_data;
385 uint32_t server_hello_cnt;
386} coap_mbedtls_env_t;
387
388typedef struct pki_sni_entry {
389 char *sni;
390 coap_dtls_key_t pki_key;
391 mbedtls_x509_crt cacert;
392 mbedtls_x509_crt public_cert;
393 mbedtls_pk_context private_key;
394} pki_sni_entry;
395
396typedef struct psk_sni_entry {
397 char *sni;
398 coap_dtls_spsk_info_t psk_info;
399} psk_sni_entry;
400
401typedef struct coap_mbedtls_context_t {
402 coap_dtls_pki_t setup_data;
403 size_t pki_sni_count;
404 pki_sni_entry *pki_sni_entry_list;
405 size_t psk_sni_count;
406 psk_sni_entry *psk_sni_entry_list;
407 char *root_ca_file;
408 char *root_ca_path;
409 int trust_store_defined;
410 int psk_pki_enabled;
411} coap_mbedtls_context_t;
412
413typedef enum coap_enc_method_t {
414 COAP_ENC_PSK,
415 COAP_ENC_PKI,
416 COAP_ENC_ECJPAKE,
417} coap_enc_method_t;
418
419#ifdef __ZEPHYR__
420
421typedef struct {
422 uint32_t start_time;
423 uint32_t int_time;
424 uint32_t fin_time;
425} zephyr_timing_delay_context;
426
427static void
428zephyr_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms) {
429 zephyr_timing_delay_context *ctx = (zephyr_timing_delay_context *)data;
430
431 if (ctx == NULL) {
432 return;
433 }
434
435 ctx->start_time = k_uptime_get_32();
436
437 if (fin_ms != 0) {
438 ctx->int_time = ctx->start_time + int_ms;
439 ctx->fin_time = ctx->start_time + fin_ms;
440 } else {
441 ctx->int_time = 0;
442 ctx->fin_time = 0;
443 }
444}
445
446static int
447zephyr_timing_get_delay(void *data) {
448 zephyr_timing_delay_context *ctx = (zephyr_timing_delay_context *)data;
449 uint32_t now;
450
451 if (ctx == NULL || ctx->fin_time == 0) {
452 return -1;
453 }
454
455 now = k_uptime_get_32();
456
457 if (now >= ctx->fin_time) {
458 return 2;
459 }
460
461 if (now >= ctx->int_time) {
462 return 1;
463 }
464
465 return 0;
466}
467
468#endif /* __ZEPHYR__ */
469
470#if !COAP_USE_PSA_CRYPTO
471#ifndef MBEDTLS_2_X_COMPAT
472/*
473 * mbedtls_ callback functions expect 0 on success, -ve on failure.
474 */
475static int
476coap_rng(void *ctx COAP_UNUSED, unsigned char *buf, size_t len) {
477 return coap_prng_lkd(buf, len) ? 0 : MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED;
478}
479#endif /* MBEDTLS_2_X_COMPAT */
480#endif /* !COAP_USE_PSA_CRYPTO */
481
482static int
483coap_dgram_read(void *ctx, unsigned char *out, size_t outl) {
484 ssize_t ret = 0;
485 coap_session_t *c_session = (coap_session_t *)ctx;
486 coap_ssl_t *data;
487
488 if (!c_session->tls) {
489 errno = EAGAIN;
490 return MBEDTLS_ERR_SSL_WANT_READ;
491 }
492 data = &((coap_mbedtls_env_t *)c_session->tls)->coap_ssl_data;
493
494 if (out != NULL) {
495 if (data->pdu_len > 0) {
496 if (outl < data->pdu_len) {
497 memcpy(out, data->pdu, outl);
498 ret = outl;
499 data->pdu += outl;
500 data->pdu_len -= outl;
501 } else {
502 memcpy(out, data->pdu, data->pdu_len);
503 ret = data->pdu_len;
504 if (!data->peekmode) {
505 data->pdu_len = 0;
506 data->pdu = NULL;
507 }
508 }
509 } else {
510 ret = MBEDTLS_ERR_SSL_WANT_READ;
511 errno = EAGAIN;
512 }
513 }
514 return ret;
515}
516
517/*
518 * return +ve data amount
519 * 0 no more
520 * -ve Mbed TLS error
521 */
522/* callback function given to mbedtls for sending data over socket */
523static int
524coap_dgram_write(void *ctx, const unsigned char *send_buffer,
525 size_t send_buffer_length) {
526 ssize_t result = -1;
527 coap_session_t *c_session = (coap_session_t *)ctx;
528
529 if (c_session) {
530 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
531
532 if (!coap_netif_available(c_session)
534 && c_session->endpoint == NULL
535#endif /* COAP_SERVER_SUPPORT */
536 ) {
537 /* socket was closed on client due to error */
538 errno = ECONNRESET;
539 return -1;
540 }
541 result = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
542 send_buffer, send_buffer_length);
543 if (result != (ssize_t)send_buffer_length) {
544 int keep_errno = errno;
545
546 coap_log_warn("coap_netif_dgrm_write failed (%" PRIdS " != %" PRIuS ")\n",
547 result, send_buffer_length);
548 errno = keep_errno;
549 if (result < 0) {
550 if (errno == ENOTCONN || errno == ECONNREFUSED)
552 return -1;
553 } else {
554 result = 0;
555 }
556 } else if (m_env) {
557 coap_tick_t now;
558 coap_ticks(&now);
559 m_env->last_timeout = now;
560 }
561 } else {
562 result = 0;
563 }
564 return result;
565}
566
567#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && defined(MBEDTLS_SSL_SRV_C)
568/*
569 * Server side PSK callback
570 */
571static int
572psk_server_callback(void *p_info, mbedtls_ssl_context *ssl,
573 const unsigned char *identity, size_t identity_len) {
574 coap_session_t *c_session = (coap_session_t *)p_info;
575 coap_dtls_spsk_t *setup_data;
576 coap_mbedtls_env_t *m_env;
577 coap_bin_const_t lidentity;
578 const coap_bin_const_t *psk_key;
579
580 if (c_session == NULL)
581 return -1;
582
583 /* Track the Identity being used */
584 lidentity.s = identity ? (const uint8_t *)identity : (const uint8_t *)"";
585 lidentity.length = identity ? identity_len : 0;
586 coap_session_refresh_psk_identity(c_session, &lidentity);
587
588 coap_log_debug("got psk_identity: '%.*s'\n",
589 (int)lidentity.length, (const char *)lidentity.s);
590
591 m_env = (coap_mbedtls_env_t *)c_session->tls;
592 setup_data = &c_session->context->spsk_setup_data;
593
594 if (setup_data->validate_id_call_back) {
595 psk_key = setup_data->validate_id_call_back(&lidentity,
596 c_session,
597 setup_data->id_call_back_arg);
598
599 coap_session_refresh_psk_key(c_session, psk_key);
600 } else {
601 psk_key = coap_get_session_server_psk_key(c_session);
602 }
603
604 if (psk_key == NULL)
605 return -1;
606 mbedtls_ssl_set_hs_psk(ssl, psk_key->s, psk_key->length);
607 m_env->seen_client_hello = 1;
608 return 0;
609}
610#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED && MBEDTLS_SSL_SRV_C */
611
612static char *
613get_san_or_cn_from_cert(mbedtls_x509_crt *crt) {
614 if (crt) {
615 const mbedtls_asn1_named_data *cn_data;
616
617 if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
618 mbedtls_asn1_sequence *seq = &crt->subject_alt_names;
619 while (seq && seq->buf.p == NULL) {
620 seq = seq->next;
621 }
622 if (seq) {
623 /* Return the Subject Alt Name */
624 return mbedtls_strndup((const char *)seq->buf.p,
625 seq->buf.len);
626 }
627 }
628
629 cn_data = mbedtls_asn1_find_named_data(&crt->subject,
630 MBEDTLS_OID_AT_CN,
631 MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN));
632 if (cn_data) {
633 /* Return the Common Name */
634 return mbedtls_strndup((const char *)cn_data->val.p,
635 cn_data->val.len);
636 }
637 }
638 return NULL;
639}
640
641#if COAP_MAX_LOGGING_LEVEL > 0
642static char *
643get_error_string(int ret) {
644 static char buf[128] = {0};
645 mbedtls_strerror(ret, buf, sizeof(buf)-1);
646 return buf;
647}
648#endif /* COAP_MAX_LOGGING_LEVEL */
649
650static int
651self_signed_cert_verify_callback_mbedtls(void *data,
652 mbedtls_x509_crt *crt COAP_UNUSED,
653 int depth COAP_UNUSED,
654 uint32_t *flags) {
655 const coap_session_t *c_session = (coap_session_t *)data;
656 const coap_mbedtls_context_t *m_context =
657 (coap_mbedtls_context_t *)c_session->context->dtls_context;
658 const coap_dtls_pki_t *setup_data = &m_context->setup_data;
659
660 if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
661 if (setup_data->allow_expired_certs) {
662 *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
663 }
664 }
665 return 0;
666}
667
668/*
669 * return 0 All OK
670 * -ve Error Code
671 */
672static int
673cert_verify_callback_mbedtls(void *data, mbedtls_x509_crt *crt,
674 int depth, uint32_t *flags) {
675 coap_session_t *c_session = (coap_session_t *)data;
676 coap_mbedtls_context_t *m_context =
677 (coap_mbedtls_context_t *)c_session->context->dtls_context;
678 coap_dtls_pki_t *setup_data = &m_context->setup_data;
679 char *cn = NULL;
680
681 cn = get_san_or_cn_from_cert(crt);
682 if (setup_data->validate_cn_call_back) {
683 int ret;
684
685 if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
686 *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
687 }
689 setup_data->validate_cn_call_back(cn,
690 crt->raw.p,
691 crt->raw.len,
692 c_session,
693 depth,
694 *flags == 0,
695 setup_data->cn_call_back_arg));
696 if (!ret) {
697 *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
698 }
699 }
700 if (*flags == 0) {
701 if (cn)
702 mbedtls_free(cn);
703 return 0;
704 }
705
706 if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
707 if (setup_data->allow_expired_certs) {
708 *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
709 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
710 coap_session_str(c_session),
711 "The certificate has expired", cn ? cn : "?", depth);
712 }
713 }
714 if (*flags & MBEDTLS_X509_BADCERT_FUTURE) {
715 if (setup_data->allow_expired_certs) {
716 *flags &= ~MBEDTLS_X509_BADCERT_FUTURE;
717 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
718 coap_session_str(c_session),
719 "The certificate has a future date", cn ? cn : "?", depth);
720 }
721 }
722 if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) {
723 if (setup_data->allow_bad_md_hash) {
724 *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD;
725 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
726 coap_session_str(c_session),
727 "The certificate has a bad MD hash", cn ? cn : "?", depth);
728 }
729 }
730 if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) {
731 if (setup_data->allow_short_rsa_length) {
732 *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY;
733 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
734 coap_session_str(c_session),
735 "The certificate has a short RSA length", cn ? cn : "?", depth);
736 }
737 }
738 if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
739 uint32_t lflags;
740 int self_signed = !mbedtls_x509_crt_verify(crt, crt, NULL, NULL, &lflags,
741 self_signed_cert_verify_callback_mbedtls,
742 data);
743 if (self_signed && depth == 0) {
744 if (setup_data->allow_self_signed &&
745 !setup_data->check_common_ca) {
746 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
747 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
748 coap_session_str(c_session),
749 "Self-signed",
750 cn ? cn : "?", depth);
751 }
752 } else if (self_signed) {
753 if (!setup_data->verify_peer_cert) {
754 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
755 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
756 coap_session_str(c_session),
757 "Self-signed", cn ? cn : "?", depth);
758 }
759 } else {
760 if (!setup_data->verify_peer_cert) {
761 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
762 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
763 coap_session_str(c_session),
764 "The certificate's CA is not trusted", cn ? cn : "?", depth);
765 }
766 }
767 }
768 if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) {
769 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
770 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
771 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
772 coap_session_str(c_session),
773 "The certificate's CRL has expired", cn ? cn : "?", depth);
774 } else if (!setup_data->check_cert_revocation) {
775 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
776 }
777 }
778 if (*flags & MBEDTLS_X509_BADCRL_FUTURE) {
779 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
780 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
781 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
782 coap_session_str(c_session),
783 "The certificate's CRL has a future date", cn ? cn : "?", depth);
784 } else if (!setup_data->check_cert_revocation) {
785 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
786 }
787 }
788 if (setup_data->cert_chain_validation &&
789 depth > (setup_data->cert_chain_verify_depth + 1)) {
790 *flags |= MBEDTLS_X509_BADCERT_OTHER;
791 coap_log_warn(" %s: %s: '%s' depth %d\n",
792 coap_session_str(c_session),
793 "The certificate's verify depth is too long",
794 cn ? cn : "?", depth);
795 }
796
797 if (*flags != 0) {
798 char buf[128];
799 char *tcp;
800 int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
801
802 if (ret >= 0) {
803 tcp = strchr(buf, '\n');
804 while (tcp) {
805 *tcp = '\000';
806 coap_log_warn(" %s: %s: issue 0x%" PRIx32 ": '%s' depth %d\n",
807 coap_session_str(c_session),
808 buf, *flags, cn ? cn : "?", depth);
809 tcp = strchr(tcp+1, '\n');
810 }
811 } else {
812 coap_log_err("mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n",
813 -ret, get_error_string(ret));
814 }
815 }
816
817 if (cn)
818 mbedtls_free(cn);
819
820 return 0;
821}
822
823static int
824setup_pki_credentials(mbedtls_x509_crt *cacert,
825 mbedtls_x509_crt *public_cert,
826 mbedtls_pk_context *private_key,
827 coap_mbedtls_env_t *m_env,
828 coap_mbedtls_context_t *m_context,
829 coap_session_t *c_session,
830 coap_dtls_pki_t *setup_data,
831 coap_dtls_role_t role) {
832 coap_dtls_key_t key;
833 int ret;
834 int done_private_key = 0;
835 int done_public_cert = 0;
836 uint8_t *buffer;
837 size_t length;
838
839 /* Map over to the new define format to save code duplication */
840 coap_dtls_map_key_type_to_define(setup_data, &key);
841
842 assert(key.key_type == COAP_PKI_KEY_DEFINE);
843
844 /*
845 * Configure the Private Key
846 */
847 if (key.key.define.private_key.u_byte &&
848 key.key.define.private_key.u_byte[0]) {
849 switch (key.key.define.private_key_def) {
850 case COAP_PKI_KEY_DEF_DER: /* define private key */
851 /* Fall Through */
852 case COAP_PKI_KEY_DEF_PEM: /* define private key */
853#if defined(MBEDTLS_FS_IO)
854 mbedtls_pk_init(private_key);
855#if COAP_USE_PSA_CRYPTO
856 ret = mbedtls_pk_parse_keyfile(private_key,
858#elif defined(MBEDTLS_2_X_COMPAT)
859 ret = mbedtls_pk_parse_keyfile(private_key,
861#else
862 ret = mbedtls_pk_parse_keyfile(private_key,
864 NULL, coap_rng, (void *)&m_env->ctr_drbg);
865#endif
866 if (ret < 0) {
869 &key, role, ret);
870 }
871 done_private_key = 1;
872 break;
873#else /* ! MBEDTLS_FS_IO */
876 &key, role, -1);
877#endif /* ! MBEDTLS_FS_IO */
878 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
879 mbedtls_pk_init(private_key);
880 length = key.key.define.private_key_len;
881 if (key.key.define.private_key.u_byte[length-1] != '\000') {
882 /* Need to allocate memory to add in NULL terminator */
883 buffer = mbedtls_malloc(length + 1);
884 if (!buffer) {
885 coap_log_err("mbedtls_malloc failed\n");
886 return 0;
887 }
888 memcpy(buffer, key.key.define.private_key.u_byte, length);
889 buffer[length] = '\000';
890 length++;
891#if COAP_USE_PSA_CRYPTO
892 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
893#elif defined(MBEDTLS_2_X_COMPAT)
894 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
895#else
896 ret = mbedtls_pk_parse_key(private_key, buffer, length,
897 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
898#endif
899 mbedtls_free(buffer);
900 } else {
901#if COAP_USE_PSA_CRYPTO
902 ret = mbedtls_pk_parse_key(private_key,
905#elif defined(MBEDTLS_2_X_COMPAT)
906 ret = mbedtls_pk_parse_key(private_key,
909#else
910 ret = mbedtls_pk_parse_key(private_key,
913 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
914#endif
915 }
916 if (ret < 0) {
919 &key, role, ret);
920 }
921 done_private_key = 1;
922 break;
923 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
924 mbedtls_pk_init(private_key);
925#if COAP_USE_PSA_CRYPTO
926 ret = mbedtls_pk_parse_key(private_key,
929#elif defined(MBEDTLS_2_X_COMPAT)
930 ret = mbedtls_pk_parse_key(private_key,
933#else
934 ret = mbedtls_pk_parse_key(private_key,
936 key.key.define.private_key_len, NULL, 0, coap_rng,
937 (void *)&m_env->ctr_drbg);
938#endif
939 if (ret < 0) {
942 &key, role, ret);
943 }
944 done_private_key = 1;
945 break;
946 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
947 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
948 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
949 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
950 default:
953 &key, role, -1);
954 }
955 } else if (role == COAP_DTLS_ROLE_SERVER ||
957 key.key.define.public_cert.u_byte[0])) {
960 &key, role, -1);
961 }
962
963 /*
964 * Configure the Public Certificate / Key
965 */
966 if (key.key.define.public_cert.u_byte &&
967 key.key.define.public_cert.u_byte[0]) {
968 switch (key.key.define.public_cert_def) {
969 case COAP_PKI_KEY_DEF_DER: /* define public cert */
970 /* Fall Through */
971 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
972#if defined(MBEDTLS_FS_IO)
973 mbedtls_x509_crt_init(public_cert);
974 ret = mbedtls_x509_crt_parse_file(public_cert,
976 if (ret < 0) {
979 &key, role, ret);
980 }
981 done_public_cert = 1;
982 break;
983#else /* ! MBEDTLS_FS_IO */
986 &key, role, -1);
987#endif /* ! MBEDTLS_FS_IO */
988 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
989 mbedtls_x509_crt_init(public_cert);
990
991 length = key.key.define.public_cert_len;
992 if (key.key.define.public_cert.u_byte[length-1] != '\000') {
993 /* Need to allocate memory to add in NULL terminator */
994 buffer = mbedtls_malloc(length + 1);
995 if (!buffer) {
996 coap_log_err("mbedtls_malloc failed\n");
997 return 0;
998 }
999 memcpy(buffer, key.key.define.public_cert.u_byte, length);
1000 buffer[length] = '\000';
1001 length++;
1002 ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
1003 mbedtls_free(buffer);
1004 } else {
1005 ret = mbedtls_x509_crt_parse(public_cert,
1008 }
1009 if (ret < 0) {
1012 &key, role, ret);
1013 }
1014 done_public_cert = 1;
1015 break;
1016 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
1019 &key, role, -1);
1020 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
1021 mbedtls_x509_crt_init(public_cert);
1022 ret = mbedtls_x509_crt_parse(public_cert,
1025 if (ret < 0) {
1028 &key, role, ret);
1029 }
1030 done_public_cert = 1;
1031 break;
1032 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
1033 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
1034 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
1035 default:
1038 &key, role, -1);
1039 }
1040 } else if (role == COAP_DTLS_ROLE_SERVER ||
1042 key.key.define.private_key.u_byte[0])) {
1045 &key, role, -1);
1046 }
1047
1048 if (done_private_key && done_public_cert) {
1049 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
1050 if (ret < 0) {
1051 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
1052 -ret, get_error_string(ret));
1053 return 0;
1054 }
1055 }
1056
1057 /*
1058 * Configure the CA
1059 */
1060 if (
1061 key.key.define.ca.u_byte &&
1062 key.key.define.ca.u_byte[0]) {
1063 switch (key.key.define.ca_def) {
1064 case COAP_PKI_KEY_DEF_DER: /* define ca */
1065 /* Fall Through */
1067#if defined(MBEDTLS_FS_IO)
1068 mbedtls_x509_crt_init(cacert);
1069 ret = mbedtls_x509_crt_parse_file(cacert,
1070 key.key.define.ca.s_byte);
1071 if (ret < 0) {
1074 &key, role, ret);
1075 }
1076 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1077#else /* ! MBEDTLS_FS_IO */
1080 &key, role, -1);
1081#endif /* ! MBEDTLS_FS_IO */
1082 break;
1083 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
1084 mbedtls_x509_crt_init(cacert);
1085 length = key.key.define.ca_len;
1086 if (key.key.define.ca.u_byte[length-1] != '\000') {
1087 /* Need to allocate memory to add in NULL terminator */
1088 buffer = mbedtls_malloc(length + 1);
1089 if (!buffer) {
1090 coap_log_err("mbedtls_malloc failed\n");
1091 return 0;
1092 }
1093 memcpy(buffer, key.key.define.ca.u_byte, length);
1094 buffer[length] = '\000';
1095 length++;
1096 ret = mbedtls_x509_crt_parse(cacert, buffer, length);
1097 mbedtls_free(buffer);
1098 } else {
1099 ret = mbedtls_x509_crt_parse(cacert,
1100 key.key.define.ca.u_byte,
1101 key.key.define.ca_len);
1102 }
1103 if (ret < 0) {
1106 &key, role, ret);
1107 }
1108 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1109 break;
1110 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
1113 &key, role, -1);
1114 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
1115 mbedtls_x509_crt_init(cacert);
1116 ret = mbedtls_x509_crt_parse(cacert,
1117 key.key.define.ca.u_byte,
1118 key.key.define.ca_len);
1119 if (ret < 0) {
1122 &key, role, ret);
1123 }
1124 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1125 break;
1126 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
1127 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
1128 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
1129 default:
1132 &key, role, -1);
1133 }
1134 }
1135
1136 /* Add in any root CA definitons */
1137
1138#if defined(MBEDTLS_FS_IO)
1139 if (m_context->root_ca_file) {
1140 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
1141 if (ret < 0) {
1145 &key, role, ret);
1146 }
1147 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1148 }
1149 if (m_context->root_ca_path) {
1150 ret = mbedtls_x509_crt_parse_path(cacert, m_context->root_ca_path);
1151 if (ret < 0) {
1155 &key, role, ret);
1156 }
1157 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1158 }
1159#if MBEDTLS_VERSION_NUMBER >= 0x04000000
1160 if (m_context->trust_store_defined)
1161#else /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1162 if (m_context->trust_store_defined ||
1163 (role == COAP_DTLS_ROLE_CLIENT && !m_context->setup_data.verify_peer_cert))
1164#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1165 {
1166 /* Until Trust Store is implemented in MbedTLS */
1167 const char *trust_list[] = {
1168 "/etc/ssl/ca-bundle.pem",
1169 "/etc/ssl/certs/ca-certificates.crt",
1170 "/etc/pki/tls/cert.pem",
1171 "/usr/local/share/certs/ca-root-nss.crt",
1172 "/etc/ssl/cert.pem"
1173 };
1174 static const char *trust_file_found = NULL;
1175 static int trust_file_done = 0;
1176 unsigned int i;
1177
1178 if (trust_file_found) {
1179 ret = mbedtls_x509_crt_parse_file(cacert, trust_file_found);
1180 if (ret >= 0) {
1181 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1182 } else {
1183 coap_log_warn("Unable to load trusted root CAs (%s)\n",
1184 trust_file_found);
1185 }
1186 } else if (!trust_file_done) {
1187 trust_file_done = 1;
1188 for (i = 0; i < sizeof(trust_list)/sizeof(trust_list[0]); i++) {
1189 ret = mbedtls_x509_crt_parse_file(cacert, trust_list[i]);
1190 if (ret >= 0) {
1191 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1192 trust_file_found = trust_list[i];
1193 break;
1194 }
1195 }
1196 if (i == sizeof(trust_list)/sizeof(trust_list[0])) {
1197 coap_log_warn("Unable to load trusted root CAs\n");
1198 }
1199 }
1200 }
1201#else /* ! MBEDTLS_FS_IO */
1202 if (m_context->root_ca_file || m_context->root_ca_path ||
1203 m_context->trust_store_defined) {
1204 /* No FS to read these files */
1207 &key, role, -1);
1208 }
1209#endif /* ! MBEDTLS_FS_IO */
1210
1211#if defined(MBEDTLS_SSL_SRV_C)
1212 mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
1213 setup_data->check_common_ca ?
1214 MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
1215 MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
1216#endif
1217 mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
1218 MBEDTLS_SSL_VERIFY_REQUIRED :
1219 MBEDTLS_SSL_VERIFY_NONE);
1220 /*
1221 * Verify Peer.
1222 * Need to do all checking, even if setup_data->verify_peer_cert is not set
1223 */
1224 mbedtls_ssl_conf_verify(&m_env->conf,
1225 cert_verify_callback_mbedtls, c_session);
1226
1227 return 1;
1228}
1229
1230#if defined(MBEDTLS_SSL_SRV_C)
1231/*
1232 * PKI SNI callback.
1233 */
1234static int
1235pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
1236 const unsigned char *uname, size_t name_len) {
1237 unsigned int i;
1238 coap_dtls_pki_t sni_setup_data;
1239 coap_session_t *c_session = (coap_session_t *)p_info;
1240 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1241 coap_mbedtls_context_t *m_context =
1242 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1243 char *name;
1244
1245 name = mbedtls_malloc(name_len+1);
1246 if (!name)
1247 return -1;
1248
1249 memcpy(name, uname, name_len);
1250 name[name_len] = '\000';
1251
1252 /* Is this a cached entry? */
1253 for (i = 0; i < m_context->pki_sni_count; i++) {
1254 if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
1255 break;
1256 }
1257 }
1258 if (i == m_context->pki_sni_count) {
1259 /*
1260 * New PKI SNI request
1261 */
1262 coap_dtls_key_t *new_entry;
1263 pki_sni_entry *pki_sni_entry_list;
1264
1265 coap_lock_callback_ret(new_entry,
1266 m_context->setup_data.validate_sni_call_back(name,
1267 m_context->setup_data.sni_call_back_arg));
1268 if (!new_entry) {
1269 mbedtls_free(name);
1270 return -1;
1271 }
1272
1273 pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
1274 (i+1)*sizeof(pki_sni_entry));
1275
1276 if (pki_sni_entry_list == NULL) {
1277 mbedtls_free(name);
1278 return -1;
1279 }
1280 m_context->pki_sni_entry_list = pki_sni_entry_list;
1281 memset(&m_context->pki_sni_entry_list[i], 0,
1282 sizeof(m_context->pki_sni_entry_list[i]));
1283 m_context->pki_sni_entry_list[i].sni = name;
1284 m_context->pki_sni_entry_list[i].pki_key = *new_entry;
1285 sni_setup_data = m_context->setup_data;
1286 sni_setup_data.pki_key = *new_entry;
1287 if (setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
1288 &m_context->pki_sni_entry_list[i].public_cert,
1289 &m_context->pki_sni_entry_list[i].private_key,
1290 m_env,
1291 m_context,
1292 c_session,
1293 &sni_setup_data, COAP_DTLS_ROLE_SERVER) < 0) {
1294 mbedtls_free(name);
1295 return -1;
1296 }
1297 /* name has been absorbed into pki_sni_entry_list[].sni entry */
1298 m_context->pki_sni_count++;
1299 } else {
1300 mbedtls_free(name);
1301 }
1302
1303 mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
1304 NULL);
1305 return mbedtls_ssl_set_hs_own_cert(ssl,
1306 &m_context->pki_sni_entry_list[i].public_cert,
1307 &m_context->pki_sni_entry_list[i].private_key);
1308}
1309
1310#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1311/*
1312 * PSK SNI callback.
1313 */
1314static int
1315psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
1316 const unsigned char *uname, size_t name_len) {
1317 unsigned int i;
1318 coap_session_t *c_session = (coap_session_t *)p_info;
1319 coap_mbedtls_context_t *m_context =
1320 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1321 char *name;
1322
1323 name = mbedtls_malloc(name_len+1);
1324 if (!name)
1325 return -1;
1326
1327 memcpy(name, uname, name_len);
1328 name[name_len] = '\000';
1329
1330 /* Is this a cached entry? */
1331 for (i = 0; i < m_context->psk_sni_count; i++) {
1332 if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
1333 break;
1334 }
1335 }
1336 if (i == m_context->psk_sni_count) {
1337 /*
1338 * New PSK SNI request
1339 */
1340 const coap_dtls_spsk_info_t *new_entry;
1341 psk_sni_entry *psk_sni_entry_list;
1342
1343 coap_lock_callback_ret(new_entry,
1344 c_session->context->spsk_setup_data.validate_sni_call_back(name,
1345 c_session,
1346 c_session->context->spsk_setup_data.sni_call_back_arg));
1347 if (!new_entry) {
1348 mbedtls_free(name);
1349 return -1;
1350 }
1351
1352 psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
1353 (i+1)*sizeof(psk_sni_entry));
1354
1355 if (psk_sni_entry_list == NULL) {
1356 mbedtls_free(name);
1357 return -1;
1358 }
1359 m_context->psk_sni_entry_list = psk_sni_entry_list;
1360 m_context->psk_sni_entry_list[i].sni = name;
1361 m_context->psk_sni_entry_list[i].psk_info = *new_entry;
1362 /* name has been absorbed into psk_sni_entry_list[].sni entry */
1363 m_context->psk_sni_count++;
1364 } else {
1365 mbedtls_free(name);
1366 }
1367
1369 &m_context->psk_sni_entry_list[i].psk_info.hint);
1371 &m_context->psk_sni_entry_list[i].psk_info.key);
1372#if MBEDTLS_VERSION_NUMBER >= 0x04000000
1373 (void)ssl;
1374 return 0;
1375#else /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1376 return mbedtls_ssl_set_hs_psk(ssl,
1377 m_context->psk_sni_entry_list[i].psk_info.key.s,
1378 m_context->psk_sni_entry_list[i].psk_info.key.length);
1379#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1380}
1381#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1382
1383static int
1384setup_server_ssl_session(coap_session_t *c_session,
1385 coap_mbedtls_env_t *m_env) {
1386 coap_mbedtls_context_t *m_context =
1387 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1388 int ret = 0;
1389 m_context->psk_pki_enabled |= IS_SERVER;
1390
1391 mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
1392 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1393 MBEDTLS_SSL_IS_SERVER,
1394 c_session->proto == COAP_PROTO_DTLS ?
1395 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1396 MBEDTLS_SSL_TRANSPORT_STREAM,
1397 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1398 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1399 -ret, get_error_string(ret));
1400 goto fail;
1401 }
1402
1403#if !COAP_USE_PSA_CRYPTO
1404 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1405#endif /* !COAP_USE_PSA_CRYPTO */
1406
1407#if defined(MBEDTLS_SSL_PROTO_DTLS)
1408 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1410#endif /* MBEDTLS_SSL_PROTO_DTLS */
1411
1412 if (m_context->psk_pki_enabled & IS_PSK) {
1413#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1414 mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
1415 if (c_session->context->spsk_setup_data.validate_sni_call_back) {
1416 mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
1417 }
1418#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1419 m_env->ec_jpake = c_session->context->spsk_setup_data.ec_jpake;
1420#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1421#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1422 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1423#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1424 }
1425
1426 if (m_context->psk_pki_enabled & IS_PKI) {
1427 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1428 &m_env->private_key, m_env, m_context,
1429 c_session, &m_context->setup_data,
1431 if (ret < 0) {
1432 coap_log_err("PKI setup failed\n");
1433 return ret;
1434 }
1435 if (m_context->setup_data.validate_sni_call_back) {
1436 mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1437 }
1438 }
1439
1440#if COAP_USE_PSA_CRYPTO
1441 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx)) != 0) {
1442#else /* !COAP_USE_PSA_CRYPTO */
1443 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1444 mbedtls_ctr_drbg_random,
1445 &m_env->ctr_drbg)) != 0) {
1446#endif /* !COAP_USE_PSA_CRYPTO */
1447 coap_log_err("mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1448 -ret, get_error_string(ret));
1449 goto fail;
1450 }
1451
1452#if defined(MBEDTLS_SSL_PROTO_DTLS)
1453 mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1454 mbedtls_ssl_cookie_check,
1455 &m_env->cookie_ctx);
1456#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1457 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1458#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1459#endif /* MBEDTLS_SSL_PROTO_DTLS */
1460#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1461 /*
1462 * Configure CID max length.
1463 *
1464 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1465 * to use RFC9146 extension ID of 54, rather than the draft version -05
1466 * value of 254.
1467 */
1468 mbedtls_ssl_conf_cid(&m_env->conf, COAP_DTLS_CID_LENGTH, MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1469#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1470fail:
1471 return ret;
1472}
1473#endif /* MBEDTLS_SSL_SRV_C */
1474
1475#if COAP_CLIENT_SUPPORT
1476static int *psk_ciphers = NULL;
1477static int *pki_ciphers = NULL;
1478static int *ecjpake_ciphers = NULL;
1479static int processed_ciphers = 0;
1480
1481#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1482static int
1483coap_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info) {
1484#if COAP_USE_PSA_CRYPTO
1485 switch (info->key_exchange) {
1486 case MBEDTLS_KEY_EXCHANGE_PSK:
1487 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1488 return 1;
1489 case MBEDTLS_KEY_EXCHANGE_NONE:
1490 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1491 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1492 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1493 default:
1494 return 0;
1495 }
1496#elif MBEDTLS_VERSION_NUMBER >= 0x03060000
1497 switch (info->key_exchange) {
1498 case MBEDTLS_KEY_EXCHANGE_PSK:
1499 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
1500 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
1501 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1502 return 1;
1503 case MBEDTLS_KEY_EXCHANGE_NONE:
1504 case MBEDTLS_KEY_EXCHANGE_RSA:
1505 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
1506 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1507 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1508 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
1509 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
1510 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1511 default:
1512 return 0;
1513 }
1514#else /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1515 return mbedtls_ssl_ciphersuite_uses_psk(info);
1516#endif /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1517}
1518#endif /* defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) */
1519
1520static void
1521set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) {
1522 if (!processed_ciphers) {
1523 const int *list = mbedtls_ssl_list_ciphersuites();
1524 const int *base = list;
1525 int *psk_list;
1526 int *pki_list;
1527#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1528 int *ecjpake_list;
1529 int ecjpake_count = 1;
1530#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1531 int psk_count = 1; /* account for empty terminator */
1532 int pki_count = 1;
1533
1534 while (*list) {
1535 const mbedtls_ssl_ciphersuite_t *cur =
1536 mbedtls_ssl_ciphersuite_from_id(*list);
1537
1538 if (cur) {
1539#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1540 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1541 /* Minimum of TLS1.2 required - skip */
1542 }
1543#else
1544 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1545 /* Minimum of TLS1.2 required - skip */
1546 }
1547#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1548#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1549 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1550 ecjpake_count++;
1551 }
1552#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1553#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1554 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1555 psk_count++;
1556 pki_count++;
1557 }
1558#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1559#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1560 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1561 psk_count++;
1562 }
1563#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1564 else {
1565 pki_count++;
1566 }
1567 }
1568 list++;
1569 }
1570 list = base;
1571
1572 psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1573 if (psk_ciphers == NULL) {
1574 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1575 return;
1576 }
1577 pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1578 if (pki_ciphers == NULL) {
1579 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1580 mbedtls_free(psk_ciphers);
1581 psk_ciphers = NULL;
1582 return;
1583 }
1584#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1585 ecjpake_ciphers = mbedtls_malloc(ecjpake_count * sizeof(ecjpake_ciphers[0]));
1586 if (ecjpake_ciphers == NULL) {
1587 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1588 mbedtls_free(psk_ciphers);
1589 mbedtls_free(pki_ciphers);
1590 psk_ciphers = NULL;
1591 pki_ciphers = NULL;
1592 return;
1593 }
1594#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1595
1596 psk_list = psk_ciphers;
1597 pki_list = pki_ciphers;
1598#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1599 ecjpake_list = ecjpake_ciphers;
1600#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1601
1602 while (*list) {
1603 const mbedtls_ssl_ciphersuite_t *cur =
1604 mbedtls_ssl_ciphersuite_from_id(*list);
1605 if (cur) {
1606#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1607 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1608 /* Minimum of TLS1.2 required - skip */
1609 }
1610#else
1611 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1612 /* Minimum of TLS1.2 required - skip */
1613 }
1614#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1615#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1616 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1617 *ecjpake_list = *list;
1618 ecjpake_list++;
1619 }
1620#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1621#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1622 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1623 *psk_list = *list;
1624 psk_list++;
1625 *pki_list = *list;
1626 pki_list++;
1627 }
1628#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1629#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1630 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1631 *psk_list = *list;
1632 psk_list++;
1633 }
1634#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1635 else {
1636 *pki_list = *list;
1637 pki_list++;
1638 }
1639 }
1640 list++;
1641 }
1642 /* zero terminate */
1643 *psk_list = 0;
1644 *pki_list = 0;
1645 processed_ciphers = 1;
1646 }
1647 switch (method) {
1648 case COAP_ENC_PSK:
1649 mbedtls_ssl_conf_ciphersuites(conf, psk_ciphers);
1650 break;
1651 case COAP_ENC_PKI:
1652 mbedtls_ssl_conf_ciphersuites(conf, pki_ciphers);
1653 break;
1654 case COAP_ENC_ECJPAKE:
1655 mbedtls_ssl_conf_ciphersuites(conf, ecjpake_ciphers);
1656 break;
1657 default:
1658 assert(0);
1659 break;
1660 }
1661}
1662
1663static int
1664setup_client_ssl_session(coap_session_t *c_session,
1665 coap_mbedtls_env_t *m_env) {
1666 int ret;
1667
1668 coap_mbedtls_context_t *m_context =
1669 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1670
1671 m_context->psk_pki_enabled |= IS_CLIENT;
1672
1673 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1674 MBEDTLS_SSL_IS_CLIENT,
1675 c_session->proto == COAP_PROTO_DTLS ?
1676 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1677 MBEDTLS_SSL_TRANSPORT_STREAM,
1678 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1679 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1680 -ret, get_error_string(ret));
1681 goto fail;
1682 }
1683
1684#if defined(MBEDTLS_SSL_PROTO_DTLS)
1685 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1687#endif /* MBEDTLS_SSL_PROTO_DTLS */
1688
1689 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1690#if !COAP_USE_PSA_CRYPTO
1691 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1692#endif /* !COAP_USE_PSA_CRYPTO */
1693
1694 if (m_context->psk_pki_enabled & IS_PSK) {
1695#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1696 const coap_bin_const_t *psk_key;
1697 const coap_bin_const_t *psk_identity;
1698
1699 coap_log_info("Setting PSK key\n");
1700
1701 psk_key = coap_get_session_client_psk_key(c_session);
1702 psk_identity = coap_get_session_client_psk_identity(c_session);
1703 if (psk_key == NULL || psk_identity == NULL) {
1704 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1705 goto fail;
1706 }
1707
1708 if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1709 psk_key->length, psk_identity->s,
1710 psk_identity->length)) != 0) {
1711 coap_log_err("mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1712 -ret, get_error_string(ret));
1713 goto fail;
1714 }
1715 if (c_session->cpsk_setup_data.client_sni) {
1716 if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1717 c_session->cpsk_setup_data.client_sni)) != 0) {
1718 coap_log_err("mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1719 -ret, get_error_string(ret));
1720 goto fail;
1721 }
1722 }
1723 /* Identity Hint currently not supported in Mbed TLS so code removed */
1724
1725#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1726 if (c_session->cpsk_setup_data.ec_jpake) {
1727 m_env->ec_jpake = 1;
1728 set_ciphersuites(&m_env->conf, COAP_ENC_ECJPAKE);
1729#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1730 mbedtls_ssl_conf_max_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1731#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1732 } else {
1733 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1734 }
1735#else /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1736 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1737#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1738#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1739 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1740#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1741 } else if ((m_context->psk_pki_enabled & IS_PKI) ||
1742 (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1743 /*
1744 * If neither PSK or PKI have been set up, use PKI basics.
1745 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1746 */
1747 coap_dtls_pki_t *setup_data = &m_context->setup_data;
1748
1749 if (!(m_context->psk_pki_enabled & IS_PKI)) {
1750 /* PKI not defined - set up some defaults */
1751 setup_data->verify_peer_cert = 1;
1752 setup_data->check_common_ca = 0;
1753 setup_data->allow_self_signed = 1;
1754 setup_data->allow_expired_certs = 1;
1755 setup_data->cert_chain_validation = 1;
1756 setup_data->cert_chain_verify_depth = 2;
1757 setup_data->check_cert_revocation = 1;
1758 setup_data->allow_no_crl = 1;
1759 setup_data->allow_expired_crl = 1;
1760 setup_data->is_rpk_not_cert = 0;
1761 setup_data->use_cid = 0;
1762 }
1763 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1764 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1765 &m_env->private_key, m_env, m_context,
1766 c_session, setup_data,
1768 if (ret < 0) {
1769 coap_log_err("PKI setup failed\n");
1770 return ret;
1771 }
1772#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1773 if (c_session->proto == COAP_PROTO_TLS ||
1774 c_session->proto == COAP_PROTO_WSS) {
1775 static const char *alpn_list[] = { "coap", NULL };
1776
1777 ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1778 if (ret != 0) {
1779 coap_log_err("ALPN setup failed %d)\n", ret);
1780 }
1781 }
1782#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1783 mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1784#if defined(MBEDTLS_SSL_PROTO_DTLS)
1785#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1786 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1787#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1788#endif /* MBEDTLS_SSL_PROTO_DTLS */
1789 set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1790 }
1791 return 0;
1792
1793fail:
1794 return ret;
1795}
1796#endif /* COAP_CLIENT_SUPPORT */
1797
1798static void
1799mbedtls_cleanup(coap_mbedtls_env_t *m_env) {
1800 if (!m_env) {
1801 return;
1802 }
1803
1804 mbedtls_x509_crt_free(&m_env->cacert);
1805 mbedtls_x509_crt_free(&m_env->public_cert);
1806 mbedtls_pk_free(&m_env->private_key);
1807#if !COAP_USE_PSA_CRYPTO
1808 mbedtls_entropy_free(&m_env->entropy);
1809 mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1810#endif /* !COAP_USE_PSA_CRYPTO */
1811 mbedtls_ssl_config_free(&m_env->conf);
1812 mbedtls_ssl_free(&m_env->ssl);
1813 mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1814}
1815
1816static void
1817coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1818 if (m_env) {
1819 if (!m_env->sent_alert)
1820 mbedtls_ssl_close_notify(&m_env->ssl);
1821 mbedtls_cleanup(m_env);
1822 mbedtls_free(m_env);
1823 }
1824}
1825
1826#if COAP_MAX_LOGGING_LEVEL > 0
1827static const char *
1828report_mbedtls_alert(unsigned char alert) {
1829 switch (alert) {
1830 case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC:
1831 return ": Bad Record MAC";
1832 case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE:
1833 return ": Handshake failure";
1834 case MBEDTLS_SSL_ALERT_MSG_NO_CERT:
1835 return ": No Certificate provided";
1836 case MBEDTLS_SSL_ALERT_MSG_BAD_CERT:
1837 return ": Certificate is bad";
1838 case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN:
1839 return ": Certificate is unknown";
1840 case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA:
1841 return ": CA is unknown";
1842 case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED:
1843 return ": Access was denied";
1844 case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR:
1845 return ": Decrypt error";
1846 default:
1847 return "";
1848 }
1849}
1850#endif /* COAP_MAX_LOGGING_LEVEL */
1851
1852/*
1853 * return -1 failure
1854 * 0 not completed
1855 * 1 established
1856 */
1857static int
1858do_mbedtls_handshake(coap_session_t *c_session,
1859 coap_mbedtls_env_t *m_env) {
1860 int ret;
1861 int alert;
1862
1863 ret = mbedtls_ssl_handshake(&m_env->ssl);
1864 switch (ret) {
1865 case 0:
1866 m_env->established = 1;
1867 coap_log_debug("* %s: Mbed TLS established\n",
1868 coap_session_str(c_session));
1869 ret = 1;
1870#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1871#if COAP_CLIENT_SUPPORT
1872 if (c_session->type == COAP_SESSION_TYPE_CLIENT &&
1873 c_session->proto == COAP_PROTO_DTLS) {
1874 coap_mbedtls_context_t *m_context;
1875
1876 m_context = (coap_mbedtls_context_t *)c_session->context->dtls_context;
1877 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
1878 m_context->setup_data.use_cid) {
1879 unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
1880 int enabled;
1881 size_t peer_cid_len;
1882
1883 /* See whether CID was negotiated */
1884 if (mbedtls_ssl_get_peer_cid(&m_env->ssl, &enabled, peer_cid, &peer_cid_len) == 0 &&
1885 enabled == MBEDTLS_SSL_CID_ENABLED) {
1886 c_session->negotiated_cid = 1;
1887 } else {
1888 coap_log_info("** %s: CID was not negotiated\n", coap_session_str(c_session));
1889 c_session->negotiated_cid = 0;
1890 }
1891 }
1892 }
1893#endif /* COAP_CLIENT_SUPPORT */
1894#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1896 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
1897 break;
1898 case MBEDTLS_ERR_SSL_WANT_READ:
1899 case MBEDTLS_ERR_SSL_WANT_WRITE:
1900 if (m_env->ssl.state == MBEDTLS_SSL_SERVER_HELLO
1901#if MBEDTLS_VERSION_NUMBER >= 0x03030000
1902 || m_env->ssl.state == MBEDTLS_SSL_NEW_SESSION_TICKET
1903#endif /* MBEDTLS_VERSION_NUMBER >= 0x03030000 */
1904 ) {
1905 if (++m_env->server_hello_cnt > 10) {
1906 /* retried this too many times */
1907 goto fail;
1908 }
1909 }
1910 errno = EAGAIN;
1911 ret = 0;
1912 break;
1913 case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1914 coap_log_debug("hello verification requested\n");
1915 goto reset;
1916 case MBEDTLS_ERR_SSL_INVALID_MAC:
1917 goto fail;
1918#ifdef MBEDTLS_2_X_COMPAT
1919 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
1920#else /* ! MBEDTLS_2_X_COMPAT */
1921 case MBEDTLS_ERR_SSL_DECODE_ERROR:
1922#endif /* ! MBEDTLS_2_X_COMPAT */
1923 goto fail;
1924 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1925 alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1926 goto fail_alert;
1927#ifdef MBEDTLS_2_X_COMPAT
1928 case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1929 case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1930 alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1931 goto fail_alert;
1932#endif /* MBEDTLS_2_X_COMPAT */
1933 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1934 goto fail;
1935 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1936 if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1937 coap_log_warn("***%s: Alert '%d'%s\n",
1938 coap_session_str(c_session), m_env->ssl.in_msg[1],
1939 report_mbedtls_alert(m_env->ssl.in_msg[1]));
1940 /* Fall through */
1941 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1942 case MBEDTLS_ERR_SSL_CONN_EOF:
1943 case MBEDTLS_ERR_NET_CONN_RESET:
1945 ret = -1;
1946 break;
1947 default:
1948 coap_log_warn("do_mbedtls_handshake: session establish "
1949 "returned -0x%x: '%s'\n",
1950 -ret, get_error_string(ret));
1951 ret = -1;
1952 break;
1953 }
1954 return ret;
1955
1956fail_alert:
1957 mbedtls_ssl_send_alert_message(&m_env->ssl,
1958 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1959 alert);
1960 m_env->sent_alert = 1;
1961fail:
1962 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1963 coap_log_warn("do_mbedtls_handshake: session establish "
1964 "returned '%s'\n",
1965 get_error_string(ret));
1966reset:
1967 mbedtls_ssl_session_reset(&m_env->ssl);
1968#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1969 if (m_env->ec_jpake) {
1970 const coap_bin_const_t *psk_key;
1971
1972#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
1973 if (c_session->type == COAP_SESSION_TYPE_CLIENT) {
1974 psk_key = coap_get_session_client_psk_key(c_session);
1975 } else {
1976 psk_key = coap_get_session_server_psk_key(c_session);
1977 }
1978#elif COAP_CLIENT_SUPPORT
1979 psk_key = coap_get_session_client_psk_key(c_session);
1980#else /* COAP_SERVER_SUPPORT */
1981 psk_key = coap_get_session_server_psk_key(c_session);
1982#endif /* COAP_SERVER_SUPPORT */
1983 if (psk_key) {
1984 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
1985 }
1986 }
1987#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1988 return -1;
1989}
1990
1991static void
1992mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1993 const char *file COAP_UNUSED,
1994 int line COAP_UNUSED, const char *str) {
1995
1996 coap_log_t coap_level = COAP_LOG_DEBUG;
1997 /*
1998 * 0 No debug
1999 * 1 Error
2000 * 2 State change
2001 * 3 Informational
2002 * 4 Verbose
2003 */
2004 switch (level) {
2005 case 0:
2006 coap_level = COAP_LOG_EMERG;
2007 break;
2008 case 1:
2009 coap_level = COAP_LOG_WARN;
2010 break;
2011 case 2:
2012 coap_level = COAP_LOG_NOTICE;
2013 break;
2014 case 3:
2015 coap_level = COAP_LOG_INFO;
2016 break;
2017 case 4:
2018 default:
2019 coap_level = COAP_LOG_DEBUG;
2020 break;
2021 }
2022 coap_dtls_log(coap_level, "%s", str);
2023}
2024
2025#if !COAP_DISABLE_TCP
2026/*
2027 * strm
2028 * return +ve data amount
2029 * 0 no more
2030 * -ve Mbed TLS error
2031 */
2032static int
2033coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
2034 int ret = MBEDTLS_ERR_SSL_CONN_EOF;
2035 coap_session_t *c_session = (coap_session_t *)ctx;
2036
2037 if (out != NULL) {
2038 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
2039 /* Translate layer returns into what MbedTLS expects */
2040 if (ret == -1) {
2041 if (errno == ECONNRESET) {
2042 /* graceful shutdown */
2043 ret = MBEDTLS_ERR_SSL_CONN_EOF;
2044 } else {
2045 ret = MBEDTLS_ERR_NET_RECV_FAILED;
2046 }
2047 } else if (ret == 0) {
2048 errno = EAGAIN;
2049 ret = MBEDTLS_ERR_SSL_WANT_READ;
2050 }
2051 }
2052 return ret;
2053}
2054
2055/*
2056 * strm
2057 * return +ve data amount
2058 * 0 no more
2059 * -ve Mbed TLS error
2060 */
2061static int
2062coap_sock_write(void *context, const unsigned char *in, size_t inl) {
2063 int ret = 0;
2064 coap_session_t *c_session = (coap_session_t *)context;
2065
2066 ret = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
2067 (const uint8_t *)in,
2068 inl);
2069 /* Translate layer what returns into what MbedTLS expects */
2070 if (ret < 0) {
2071 if ((c_session->state == COAP_SESSION_STATE_CSM ||
2072 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
2073 (errno == EPIPE || errno == ECONNRESET)) {
2074 /*
2075 * Need to handle a TCP timing window where an agent continues with
2076 * the sending of the next handshake or a CSM.
2077 * However, the peer does not like a certificate and so sends a
2078 * fatal alert and closes the TCP session.
2079 * The sending of the next handshake or CSM may get terminated because
2080 * of the closed TCP session, but there is still an outstanding alert
2081 * to be read in and reported on.
2082 * In this case, pretend that sending the info was fine so that the
2083 * alert can be read (which effectively is what happens with DTLS).
2084 */
2085 ret = inl;
2086 } else {
2087#ifdef _WIN32
2088 int lasterror = WSAGetLastError();
2089
2090 if (lasterror == WSAEWOULDBLOCK) {
2091 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2092 } else if (lasterror == WSAECONNRESET) {
2093 ret = MBEDTLS_ERR_NET_CONN_RESET;
2094 }
2095#else
2096 if (errno == EAGAIN || errno == EINTR) {
2097 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2098 } else if (errno == EPIPE || errno == ECONNRESET) {
2099 ret = MBEDTLS_ERR_NET_CONN_RESET;
2100 }
2101#endif
2102 else {
2103 ret = MBEDTLS_ERR_NET_SEND_FAILED;
2104 }
2105 coap_log_debug("* %s: failed to send %" PRIdS " bytes (%s) state %d\n",
2106 coap_session_str(c_session), inl, coap_socket_strerror(),
2107 c_session->state);
2108 }
2109 }
2110 if (ret == 0) {
2111 errno = EAGAIN;
2112 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2113 }
2114 return ret;
2115}
2116#endif /* !COAP_DISABLE_TCP */
2117
2118static coap_mbedtls_env_t *
2119coap_dtls_new_mbedtls_env(coap_session_t *c_session,
2120 coap_dtls_role_t role,
2121 coap_proto_t proto) {
2122#if !COAP_USE_PSA_CRYPTO
2123 int ret = 0;
2124#endif /* !COAP_USE_PSA_CRYPTO */
2125 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2126
2127 if (m_env)
2128 return m_env;
2129
2130 m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
2131 if (!m_env) {
2132 return NULL;
2133 }
2134 memset(m_env, 0, sizeof(coap_mbedtls_env_t));
2135
2136 mbedtls_ssl_init(&m_env->ssl);
2137#if !COAP_USE_PSA_CRYPTO
2138 mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
2139 mbedtls_entropy_init(&m_env->entropy);
2140#endif /* !COAP_USE_PSA_CRYPTO */
2141 mbedtls_ssl_config_init(&m_env->conf);
2142
2143#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
2144 mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
2145#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
2146
2147#if !COAP_USE_PSA_CRYPTO
2148 if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
2149 mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
2150 if (ret != MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) {
2151 coap_log_info("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
2152 -ret, get_error_string(ret));
2153 goto fail;
2154 }
2155 coap_log_err("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
2156 -ret, get_error_string(ret));
2157 }
2158#endif /* !COAP_USE_PSA_CRYPTO */
2159
2160 if (role == COAP_DTLS_ROLE_CLIENT) {
2161#if COAP_CLIENT_SUPPORT
2162 if (setup_client_ssl_session(c_session, m_env) != 0) {
2163 goto fail;
2164 }
2165#else /* !COAP_CLIENT_SUPPORT */
2166 goto fail;
2167#endif /* !COAP_CLIENT_SUPPORT */
2168 } else if (role == COAP_DTLS_ROLE_SERVER) {
2169#if defined(MBEDTLS_SSL_SRV_C)
2170 if (setup_server_ssl_session(c_session, m_env) != 0) {
2171 goto fail;
2172 }
2173#else /* ! MBEDTLS_SSL_SRV_C */
2174 goto fail;
2175#endif /* ! MBEDTLS_SSL_SRV_C */
2176 } else {
2177 goto fail;
2178 }
2179
2180#if MBEDTLS_VERSION_NUMBER >= 0x03020000
2181 mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
2182#else
2183 mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
2184 MBEDTLS_SSL_MINOR_VERSION_3);
2185#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
2186
2187 if (mbedtls_ssl_setup(&m_env->ssl, &m_env->conf) != 0) {
2188 goto fail;
2189 }
2190 if (proto == COAP_PROTO_DTLS) {
2191 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
2192 coap_dgram_read, NULL);
2193#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2194 if (COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
2195 if (role == COAP_DTLS_ROLE_CLIENT) {
2196#if COAP_CLIENT_SUPPORT
2197 coap_mbedtls_context_t *m_context =
2198 (coap_mbedtls_context_t *)c_session->context->dtls_context;
2199
2200 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
2201 m_context->setup_data.use_cid) {
2202 /*
2203 * Enable passive DTLS CID support.
2204 *
2205 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
2206 * to use RFC9146 extension ID of 54, rather than the draft version -05
2207 * value of 254.
2208 */
2209 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, NULL, 0);
2210 }
2211#endif /* COAP_CLIENT_SUPPORT */
2212 } else {
2213#if COAP_SERVER_SUPPORT
2214 uint8_t cid[COAP_DTLS_CID_LENGTH];
2215 /*
2216 * Enable server DTLS CID support.
2217 *
2218 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
2219 * to use RFC9146 extension ID of 54, rather than the draft version -05
2220 * value of 254.
2221 */
2222 coap_prng_lkd(cid, sizeof(cid));
2223 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, cid,
2224 sizeof(cid));
2225 c_session->client_cid = coap_new_bin_const(cid, sizeof(cid));
2226#endif /* COAP_SERVER_SUPPORT */
2227 }
2228 }
2229#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2230 }
2231#if !COAP_DISABLE_TCP
2232 else {
2233 assert(proto == COAP_PROTO_TLS);
2234 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
2235 coap_sock_read, NULL);
2236 }
2237#endif /* ! COAP_DISABLE_TCP */
2238#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2239 coap_mbedtls_context_t *m_context =
2240 ((coap_mbedtls_context_t *)c_session->context->dtls_context);
2241 if ((m_context->psk_pki_enabled & IS_PSK) &&
2242 m_env->ec_jpake) {
2243 const coap_bin_const_t *psk_key;
2244
2245#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
2246 if (role == COAP_DTLS_ROLE_CLIENT) {
2247 psk_key = coap_get_session_client_psk_key(c_session);
2248 } else {
2249 psk_key = coap_get_session_server_psk_key(c_session);
2250 }
2251#elif COAP_CLIENT_SUPPORT
2252 psk_key = coap_get_session_client_psk_key(c_session);
2253#else /* COAP_SERVER_SUPPORT */
2254 psk_key = coap_get_session_server_psk_key(c_session);
2255#endif /* COAP_SERVER_SUPPORT */
2256 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
2257 }
2258#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2259#ifdef __ZEPHYR__
2260 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
2261 zephyr_timing_set_delay,
2262 zephyr_timing_get_delay);
2263#else
2264 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
2265 mbedtls_timing_set_delay,
2266 mbedtls_timing_get_delay);
2267#endif
2268
2269 mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
2270 return m_env;
2271
2272fail:
2273 if (m_env) {
2274 mbedtls_free(m_env);
2275 }
2276 return NULL;
2277}
2278
2279int
2281#if defined(MBEDTLS_SSL_PROTO_DTLS)
2282 return 1;
2283#else /* !MBEDTLS_SSL_PROTO_DTLS */
2284 static int reported = 0;
2285 if (!reported) {
2286 reported = 1;
2287 coap_log_emerg("libcoap not compiled for DTLS with Mbed TLS"
2288 " - update Mbed TLS to include DTLS\n");
2289 }
2290 return 0;
2291#endif /* !MBEDTLS_SSL_PROTO_DTLS */
2292}
2293
2294int
2296#if !COAP_DISABLE_TCP
2297 return 1;
2298#else /* COAP_DISABLE_TCP */
2299 return 0;
2300#endif /* COAP_DISABLE_TCP */
2301}
2302
2303/*
2304 * return 0 failed
2305 * 1 passed
2306 */
2307int
2309 return 1;
2310}
2311
2312/*
2313 * return 0 failed
2314 * 1 passed
2315 */
2316int
2318 return 1;
2319}
2320
2321/*
2322 * return 0 failed
2323 * 1 passed
2324 */
2325int
2327 return 0;
2328}
2329
2330/*
2331 * return 0 failed
2332 * 1 passed
2333 */
2334int
2336 return 0;
2337}
2338
2339/*
2340 * return 0 failed
2341 * 1 passed
2342 */
2343int
2345#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2346 return 1;
2347#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2348 return 0;
2349#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2350}
2351
2352#if COAP_CLIENT_SUPPORT
2353int
2354coap_dtls_set_cid_tuple_change(coap_context_t *c_context, uint8_t every) {
2355#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2356 c_context->testing_cids = every;
2357 return 1;
2358#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2359 (void)c_context;
2360 (void)every;
2361 return 0;
2362#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2363}
2364#endif /* COAP_CLIENT_SUPPORT */
2365
2366void *
2368 coap_mbedtls_context_t *m_context;
2369 (void)c_context;
2370
2371 m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
2372 if (m_context) {
2373 memset(m_context, 0, sizeof(coap_mbedtls_context_t));
2374 }
2375 return m_context;
2376}
2377
2378#if COAP_SERVER_SUPPORT
2379/*
2380 * return 0 failed
2381 * 1 passed
2382 */
2383int
2384coap_dtls_context_set_spsk(coap_context_t *c_context,
2385 coap_dtls_spsk_t *setup_data
2386 ) {
2387 coap_mbedtls_context_t *m_context =
2388 ((coap_mbedtls_context_t *)c_context->dtls_context);
2389
2390#if !defined(MBEDTLS_SSL_SRV_C)
2391 coap_log_emerg("coap_context_set_spsk:"
2392 " libcoap not compiled for Server Mode for Mbed TLS"
2393 " - update Mbed TLS to include Server Mode\n");
2394 return 0;
2395#endif /* !MBEDTLS_SSL_SRV_C */
2396 if (!m_context || !setup_data)
2397 return 0;
2398
2399 if (setup_data->ec_jpake) {
2400#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2401 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2402#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2403 }
2404 m_context->psk_pki_enabled |= IS_PSK;
2405 return 1;
2406}
2407#endif /* COAP_SERVER_SUPPORT */
2408
2409#if COAP_CLIENT_SUPPORT
2410/*
2411 * return 0 failed
2412 * 1 passed
2413 */
2414int
2415coap_dtls_context_set_cpsk(coap_context_t *c_context,
2416 coap_dtls_cpsk_t *setup_data
2417 ) {
2418#if !defined(MBEDTLS_SSL_CLI_C)
2419 (void)c_context;
2420 (void)setup_data;
2421
2422 coap_log_emerg("coap_context_set_cpsk:"
2423 " libcoap not compiled for Client Mode for Mbed TLS"
2424 " - update Mbed TLS to include Client Mode\n");
2425 return 0;
2426#else /* MBEDTLS_SSL_CLI_C */
2427 coap_mbedtls_context_t *m_context =
2428 ((coap_mbedtls_context_t *)c_context->dtls_context);
2429
2430 if (!m_context || !setup_data)
2431 return 0;
2432
2433 if (setup_data->validate_ih_call_back) {
2434 coap_log_warn("CoAP Client with Mbed TLS does not support Identity Hint selection\n");
2435 }
2436 if (setup_data->ec_jpake) {
2437#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2438 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2439#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2440 }
2441 if (setup_data->use_cid) {
2442#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2443 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2444#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2445 }
2446 m_context->psk_pki_enabled |= IS_PSK;
2447 return 1;
2448#endif /* MBEDTLS_SSL_CLI_C */
2449}
2450#endif /* COAP_CLIENT_SUPPORT */
2451
2452int
2454 const coap_dtls_pki_t *setup_data,
2455 const coap_dtls_role_t role COAP_UNUSED) {
2456 coap_mbedtls_context_t *m_context =
2457 ((coap_mbedtls_context_t *)c_context->dtls_context);
2458
2459 m_context->setup_data = *setup_data;
2460 if (!m_context->setup_data.verify_peer_cert) {
2461 /* Needs to be clear so that no CA DNs are transmitted */
2462 m_context->setup_data.check_common_ca = 0;
2463 /* Allow all of these but warn if issue */
2464 m_context->setup_data.allow_self_signed = 1;
2465 m_context->setup_data.allow_expired_certs = 1;
2466 m_context->setup_data.cert_chain_validation = 1;
2467 m_context->setup_data.cert_chain_verify_depth = 10;
2468 m_context->setup_data.check_cert_revocation = 1;
2469 m_context->setup_data.allow_no_crl = 1;
2470 m_context->setup_data.allow_expired_crl = 1;
2471 m_context->setup_data.allow_bad_md_hash = 1;
2472 m_context->setup_data.allow_short_rsa_length = 1;
2473 }
2474 m_context->psk_pki_enabled |= IS_PKI;
2475 if (setup_data->use_cid) {
2476#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2477 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2478#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2479 }
2480 return 1;
2481}
2482
2483int
2485 const char *ca_file,
2486 const char *ca_path) {
2487 coap_mbedtls_context_t *m_context =
2488 ((coap_mbedtls_context_t *)c_context->dtls_context);
2489
2490 if (!m_context) {
2491 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
2492 "not set up\n");
2493 return 0;
2494 }
2495
2496 if (ca_file == NULL && ca_path == NULL) {
2497 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
2498 "not defined\n");
2499 return 0;
2500 }
2501 if (m_context->root_ca_file) {
2502 mbedtls_free(m_context->root_ca_file);
2503 m_context->root_ca_file = NULL;
2504 }
2505
2506 if (ca_file) {
2507 m_context->root_ca_file = mbedtls_strdup(ca_file);
2508 }
2509
2510 if (m_context->root_ca_path) {
2511 mbedtls_free(m_context->root_ca_path);
2512 m_context->root_ca_path = NULL;
2513 }
2514
2515 if (ca_path) {
2516 m_context->root_ca_path = mbedtls_strdup(ca_path);
2517 }
2518 return 1;
2519}
2520
2521/*
2522 * return 0 failed
2523 * 1 passed
2524 */
2525int
2527 coap_mbedtls_context_t *m_context =
2528 ((coap_mbedtls_context_t *)c_context->dtls_context);
2529
2530 if (!m_context) {
2531 coap_log_warn("coap_context_load_pki_trust_store: (D)TLS environment "
2532 "not set up\n");
2533 return 0;
2534 }
2535 m_context->trust_store_defined = 1;
2536
2537 /* No proper support for this in MbedTLS at this point */
2538 return 1;
2539}
2540
2541
2542int
2544 coap_mbedtls_context_t *m_context =
2545 ((coap_mbedtls_context_t *)c_context->dtls_context);
2546 return m_context->psk_pki_enabled ? 1 : 0;
2547}
2548
2549void
2550coap_dtls_free_context(void *dtls_context) {
2551 coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
2552 unsigned int i;
2553
2554 for (i = 0; i < m_context->pki_sni_count; i++) {
2555 mbedtls_free(m_context->pki_sni_entry_list[i].sni);
2556
2557 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
2558
2559 mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
2560
2561 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
2562 }
2563 if (m_context->pki_sni_entry_list)
2564 mbedtls_free(m_context->pki_sni_entry_list);
2565
2566 for (i = 0; i < m_context->psk_sni_count; i++) {
2567 mbedtls_free(m_context->psk_sni_entry_list[i].sni);
2568 }
2569 if (m_context->psk_sni_entry_list)
2570 mbedtls_free(m_context->psk_sni_entry_list);
2571
2572 if (m_context->root_ca_path)
2573 mbedtls_free(m_context->root_ca_path);
2574 if (m_context->root_ca_file)
2575 mbedtls_free(m_context->root_ca_file);
2576
2577 mbedtls_free(m_context);
2578}
2579
2580#if COAP_CLIENT_SUPPORT
2581void *
2582coap_dtls_new_client_session(coap_session_t *c_session) {
2583#if !defined(MBEDTLS_SSL_CLI_C)
2584 (void)c_session;
2585 coap_log_emerg("coap_dtls_new_client_session:"
2586 " libcoap not compiled for Client Mode for Mbed TLS"
2587 " - update Mbed TLS to include Client Mode\n");
2588 return NULL;
2589#else /* MBEDTLS_SSL_CLI_C */
2590 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2593 int ret;
2594
2595 if (m_env) {
2596 coap_tick_t now;
2597
2598 coap_ticks(&now);
2599 m_env->last_timeout = now;
2600 ret = do_mbedtls_handshake(c_session, m_env);
2601 if (ret == -1) {
2602 coap_dtls_free_mbedtls_env(m_env);
2603 return NULL;
2604 }
2605 }
2606 return m_env;
2607#endif /* MBEDTLS_SSL_CLI_C */
2608}
2609#endif /* COAP_CLIENT_SUPPORT */
2610
2611#if COAP_SERVER_SUPPORT
2612void *
2613coap_dtls_new_server_session(coap_session_t *c_session) {
2614#if !defined(MBEDTLS_SSL_SRV_C)
2615 (void)c_session;
2616 coap_log_emerg("coap_dtls_new_server_session:"
2617 " libcoap not compiled for Server Mode for Mbed TLS"
2618 " - update Mbed TLS to include Server Mode\n");
2619 return NULL;
2620#else /* MBEDTLS_SSL_SRV_C */
2621 coap_mbedtls_env_t *m_env =
2622 (coap_mbedtls_env_t *)c_session->tls;
2623 if (m_env) {
2624#if defined(MBEDTLS_SSL_PROTO_DTLS)
2625#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2626 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2627#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2628#endif /* MBEDTLS_SSL_PROTO_DTLS */
2629 }
2630 return m_env;
2631#endif /* MBEDTLS_SSL_SRV_C */
2632}
2633#endif /* COAP_SERVER_SUPPORT */
2634
2635void
2637 if (c_session && c_session->context && c_session->tls) {
2638 coap_dtls_free_mbedtls_env(c_session->tls);
2639 c_session->tls = NULL;
2641 }
2642 return;
2643}
2644
2645void
2647#if defined(MBEDTLS_SSL_PROTO_DTLS)
2648 coap_mbedtls_env_t *m_env =
2649 (coap_mbedtls_env_t *)c_session->tls;
2650 if (m_env) {
2651#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2652 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2653#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2654 }
2655#else /* ! MBEDTLS_SSL_PROTO_DTLS */
2656 (void)c_session;
2657#endif /* MBEDTLS_SSL_PROTO_DTLS */
2658}
2659
2660ssize_t
2662 const uint8_t *data, size_t data_len) {
2663 int ret;
2664 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2665
2666 assert(m_env != NULL);
2667
2668 if (!m_env) {
2669 return -1;
2670 }
2671 c_session->dtls_event = -1;
2672 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2673 coap_session_str(c_session), (int)data_len);
2674 if (m_env->established) {
2675 ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char *) data, data_len);
2676 if (ret <= 0) {
2677 switch (ret) {
2678 case MBEDTLS_ERR_SSL_WANT_READ:
2679 case MBEDTLS_ERR_SSL_WANT_WRITE:
2680 ret = 0;
2681 break;
2682 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2684 ret = -1;
2685 break;
2686 default:
2687 coap_log_warn("coap_dtls_send: "
2688 "returned -0x%x: '%s'\n",
2689 -ret, get_error_string(ret));
2690 ret = -1;
2691 break;
2692 }
2693 if (ret == -1) {
2694 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2695 }
2696 }
2697 } else {
2698 ret = do_mbedtls_handshake(c_session, m_env);
2699 if (ret == 1) {
2700 /* Just connected, so send the data */
2701 return coap_dtls_send(c_session, data, data_len);
2702 }
2703 ret = -1;
2704 }
2705
2706 if (c_session->dtls_event >= 0) {
2707 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2708 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2709 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2710 ret = -1;
2711 }
2712 }
2713 return ret;
2714}
2715
2716int
2718 return 0;
2719}
2720
2722coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2723 return 0;
2724}
2725
2728 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2729#ifdef __ZEPHYR__
2730 int ret = zephyr_timing_get_delay(&m_env->timer);
2731#else
2732 int ret = mbedtls_timing_get_delay(&m_env->timer);
2733#endif
2734 unsigned int scalar = 1 << m_env->retry_scalar;
2735
2736 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2737 switch (ret) {
2738 case 0:
2739 /* int_ms has not timed out */
2740 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2741 /* Need to indicate remaining timeout time */
2742 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2743 }
2744 m_env->last_timeout = now;
2745 /* This may cause a minor extra delay */
2746 return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2747 case 1:
2748 /* int_ms has timed out, but not fin_ms */
2749 /*
2750 * Need to make sure that we do not do this too frequently
2751 */
2752 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2753 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2754 }
2755
2756 /* Reset for the next time */
2757 m_env->last_timeout = now;
2758 return now;
2759 case 2:
2760 /* fin_ms has timed out - timed out - one final try */
2761 return now;
2762 default:
2763 break;
2764 }
2765
2766 return 0;
2767}
2768
2769/*
2770 * return 1 timed out
2771 * 0 still timing out
2772 */
2773int
2775 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2776
2777 assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2778 m_env->retry_scalar++;
2779 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2780 (do_mbedtls_handshake(c_session, m_env) < 0)) {
2781 /* Too many retries */
2783 return 1;
2784 }
2785 return 0;
2786}
2787
2788/*
2789 * return +ve data amount
2790 * 0 no more
2791 * -1 error
2792 */
2793int
2795 const uint8_t *data,
2796 size_t data_len) {
2797 int ret = 1;
2798
2799 c_session->dtls_event = -1;
2800 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2801 coap_ssl_t *ssl_data;
2802
2803 assert(m_env != NULL);
2804
2805 ssl_data = &m_env->coap_ssl_data;
2806 if (ssl_data->pdu_len) {
2807 coap_log_err("** %s: Previous data not read %u bytes\n",
2808 coap_session_str(c_session), ssl_data->pdu_len);
2809 }
2810 ssl_data->pdu = data;
2811 ssl_data->pdu_len = (unsigned)data_len;
2812
2813 if (m_env->established) {
2814#if COAP_CONSTRAINED_STACK
2815 /* pdu can be protected by global_lock if needed */
2816 static uint8_t pdu[COAP_RXBUFFER_SIZE];
2817#else /* ! COAP_CONSTRAINED_STACK */
2818 uint8_t pdu[COAP_RXBUFFER_SIZE];
2819#endif /* ! COAP_CONSTRAINED_STACK */
2820
2821 ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2822 if (ret > 0) {
2823 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2824 coap_session_str(c_session), ret);
2825 ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2826 if (!c_session->tls) {
2827 /* Possible there was a DTLS error */
2828 ssl_data = NULL;
2829 }
2830 goto finish;
2831 }
2832 switch (ret) {
2833 case 0:
2834 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2835 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2837 break;
2838 case MBEDTLS_ERR_SSL_WANT_READ:
2839 break;
2840 default:
2841 coap_log_warn("coap_dtls_receive: "
2842 "returned -0x%x: '%s' (length %" PRIdS ")\n",
2843 -ret, get_error_string(ret), data_len);
2844 break;
2845 }
2846 ret = -1;
2847 } else {
2848 ret = do_mbedtls_handshake(c_session, m_env);
2849 if (ret == 1) {
2850 /* Just connected, so send the data */
2851 coap_session_connected(c_session);
2852 } else {
2853 if (ssl_data->pdu_len) {
2854 /* Do the handshake again incase of internal timeout */
2855 ret = do_mbedtls_handshake(c_session, m_env);
2856 if (ret == 1) {
2857 /* Just connected, so send the data */
2858 coap_session_connected(c_session);
2859 }
2860 }
2861 ret = -1;
2862 }
2863 }
2864 if (c_session->dtls_event >= 0) {
2865 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2866 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2867 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2869 ssl_data = NULL;
2870 ret = -1;
2871 }
2872 }
2873finish:
2874 if (ssl_data && ssl_data->pdu_len) {
2875 /* pdu data is held on stack which will not stay there */
2876 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2877 ssl_data->pdu_len = 0;
2878 ssl_data->pdu = NULL;
2879 }
2880 return ret;
2881}
2882
2883#if COAP_SERVER_SUPPORT
2884/*
2885 * return -1 failure
2886 * 0 not completed
2887 * 1 client hello seen
2888 */
2889int
2890coap_dtls_hello(coap_session_t *c_session,
2891 const uint8_t *data,
2892 size_t data_len) {
2893#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2894 (void)c_session;
2895 (void)data;
2896 (void)data_len;
2897 coap_log_emerg("coap_dtls_hello:"
2898 " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2899 " - update Mbed TLS to include DTLS and Server Mode\n");
2900 return -1;
2901#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2902 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2903 coap_ssl_t *ssl_data;
2904 int ret;
2905
2906 if (!m_env) {
2907 m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2909 if (m_env) {
2910 c_session->tls = m_env;
2911 } else {
2912 /* error should have already been reported */
2913 return -1;
2914 }
2915 }
2916
2917 if ((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2918 (unsigned char *)&c_session->addr_info.remote,
2919 sizeof(c_session->addr_info.remote))) != 0) {
2920 coap_log_err("mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2921 -ret, get_error_string(ret));
2922 return -1;
2923 }
2924
2925 ssl_data = &m_env->coap_ssl_data;
2926 if (ssl_data->pdu_len) {
2927 coap_log_err("** %s: Previous data not read %u bytes\n",
2928 coap_session_str(c_session), ssl_data->pdu_len);
2929 }
2930 ssl_data->pdu = data;
2931 ssl_data->pdu_len = (unsigned)data_len;
2932
2933 ret = do_mbedtls_handshake(c_session, m_env);
2934 if (ret == 0 || m_env->seen_client_hello) {
2935 /* The test for seen_client_hello gives the ability to setup a new
2936 c_session to continue the do_mbedtls_handshake past the client hello
2937 and safely allow updating of the m_env and separately
2938 letting a new session cleanly start up.
2939 */
2940 m_env->seen_client_hello = 0;
2941 ret = 1;
2942 } else {
2943 ret = 0;
2944 }
2945
2946 if (ssl_data->pdu_len) {
2947 /* pdu data is held on stack which will not stay there */
2948 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2949 ssl_data->pdu_len = 0;
2950 ssl_data->pdu = NULL;
2951 }
2952 return ret;
2953#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2954}
2955#endif /* COAP_SERVER_SUPPORT */
2956
2957unsigned int
2959 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2960 int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2961
2962 if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2963 return 13 + 8 + 8;
2964 }
2965 return expansion;
2966}
2967
2968#if !COAP_DISABLE_TCP
2969#if COAP_CLIENT_SUPPORT
2970void *
2971coap_tls_new_client_session(coap_session_t *c_session) {
2972#if !defined(MBEDTLS_SSL_CLI_C)
2973 (void)c_session;
2974 *connected = 0;
2975 coap_log_emerg("coap_tls_new_client_session:"
2976 " libcoap not compiled for Client Mode for Mbed TLS"
2977 " - update Mbed TLS to include Client Mode\n");
2978 return NULL;
2979#else /* MBEDTLS_SSL_CLI_C */
2980 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2983 coap_tick_t now;
2984 coap_ticks(&now);
2985
2986 if (!m_env)
2987 return NULL;
2988
2989 m_env->last_timeout = now;
2990 c_session->tls = m_env;
2991 do_mbedtls_handshake(c_session, m_env);
2992 return m_env;
2993#endif /* MBEDTLS_SSL_CLI_C */
2994}
2995#endif /* COAP_CLIENT_SUPPORT */
2996
2997#if COAP_SERVER_SUPPORT
2998void *
2999coap_tls_new_server_session(coap_session_t *c_session) {
3000#if !defined(MBEDTLS_SSL_SRV_C)
3001 (void)c_session;
3002 (void)connected;
3003
3004 coap_log_emerg("coap_tls_new_server_session:"
3005 " libcoap not compiled for Server Mode for Mbed TLS"
3006 " - update Mbed TLS to include Server Mode\n");
3007 return NULL;
3008#else /* MBEDTLS_SSL_SRV_C */
3009 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
3012
3013 if (!m_env)
3014 return NULL;
3015
3016 c_session->tls = m_env;
3017 do_mbedtls_handshake(c_session, m_env);
3018 return m_env;
3019#endif /* MBEDTLS_SSL_SRV_C */
3020}
3021#endif /* COAP_SERVER_SUPPORT */
3022
3023void
3025 coap_dtls_free_session(c_session);
3026 return;
3027}
3028
3029/*
3030 * strm
3031 * return +ve Number of bytes written.
3032 * -1 Error (error in errno).
3033 */
3034ssize_t
3035coap_tls_write(coap_session_t *c_session, const uint8_t *data,
3036 size_t data_len) {
3037 int ret = 0;
3038 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
3039 size_t amount_sent = 0;
3040
3041 assert(m_env != NULL);
3042
3043 if (!m_env) {
3044 errno = ENXIO;
3045 return -1;
3046 }
3047 c_session->dtls_event = -1;
3048 if (m_env->established) {
3049 while (amount_sent < data_len) {
3050 ret = mbedtls_ssl_write(&m_env->ssl, &data[amount_sent],
3051 data_len - amount_sent);
3052 if (ret <= 0) {
3053 switch (ret) {
3054 case MBEDTLS_ERR_SSL_WANT_READ:
3055 case MBEDTLS_ERR_SSL_WANT_WRITE:
3056 if (amount_sent)
3057 ret = amount_sent;
3058 else
3059 ret = 0;
3060 c_session->sock.flags |= COAP_SOCKET_WANT_WRITE;
3061 break;
3062 case MBEDTLS_ERR_NET_CONN_RESET:
3063 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
3065 break;
3066 default:
3067 coap_log_warn("coap_tls_write: "
3068 "returned -0x%x: '%s'\n",
3069 -ret, get_error_string(ret));
3070 ret = -1;
3071 break;
3072 }
3073 if (ret == -1) {
3074 coap_log_warn("coap_tls_write: cannot send PDU\n");
3075 }
3076 break;
3077 }
3078 amount_sent += ret;
3079 }
3080 } else {
3081 ret = do_mbedtls_handshake(c_session, m_env);
3082 if (ret != 1) {
3083 ret = -1;
3084 }
3085 }
3086
3087 if (c_session->dtls_event >= 0) {
3088 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
3089 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
3090 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
3091 ret = -1;
3092 }
3093 }
3094 if (ret > 0) {
3095 if (ret == (ssize_t)data_len)
3096 coap_log_debug("* %s: tls: sent %4d bytes\n",
3097 coap_session_str(c_session), ret);
3098 else
3099 coap_log_debug("* %s: tls: sent %4d of %4" PRIdS " bytes\n",
3100 coap_session_str(c_session), ret, data_len);
3101 }
3102 return ret;
3103}
3104
3105/*
3106 * strm
3107 * return >=0 Number of bytes read.
3108 * -1 Error (error in errno).
3109 */
3110ssize_t
3111coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
3112 int ret = -1;
3113
3114 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
3115
3116 if (!m_env) {
3117 errno = ENXIO;
3118 return -1;
3119 }
3120
3121 c_session->dtls_event = -1;
3122
3123 if (!m_env->established && !m_env->sent_alert) {
3124 ret = do_mbedtls_handshake(c_session, m_env);
3125 }
3126
3127 if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
3128 ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
3129 if (ret <= 0) {
3130 switch (ret) {
3131 case 0:
3132 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
3134 ret = -1;
3135 break;
3136 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
3137 /* Stop the sending of an alert on closedown */
3138 m_env->sent_alert = 1;
3140 break;
3141#if MBEDTLS_VERSION_NUMBER >= 0x03060000
3142 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
3143#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
3144 case MBEDTLS_ERR_SSL_WANT_READ:
3145 errno = EAGAIN;
3146 ret = 0;
3147 break;
3148 default:
3149 coap_log_warn("coap_tls_read: "
3150 "returned -0x%x: '%s' (length %" PRIdS ")\n",
3151 -ret, get_error_string(ret), data_len);
3152 ret = -1;
3153 break;
3154 }
3155 } else if (ret < (int)data_len) {
3156 c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
3157 }
3158 }
3159
3160 if (c_session->dtls_event >= 0) {
3161 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
3162 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
3163 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
3165 ret = -1;
3166 }
3167 }
3168 if (ret > 0) {
3169 coap_log_debug("* %s: tls: recv %4d bytes\n",
3170 coap_session_str(c_session), ret);
3171 }
3172 return ret;
3173}
3174#endif /* !COAP_DISABLE_TCP */
3175
3176void
3177coap_dtls_startup(void) {
3178#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
3179 psa_crypto_init();
3180#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
3181}
3182
3183void
3184coap_dtls_shutdown(void) {
3185#if COAP_CLIENT_SUPPORT
3186 mbedtls_free(psk_ciphers);
3187 mbedtls_free(pki_ciphers);
3188 mbedtls_free(ecjpake_ciphers);
3189 psk_ciphers = NULL;
3190 pki_ciphers = NULL;
3191 ecjpake_ciphers = NULL;
3192 processed_ciphers = 0;
3193#endif /* COAP_CLIENT_SUPPORT */
3195#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
3196 mbedtls_psa_crypto_free();
3197#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
3198}
3199
3200
3201void *
3202coap_dtls_get_tls(const coap_session_t *c_session,
3203 coap_tls_library_t *tls_lib) {
3204 if (tls_lib)
3205 *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
3206 if (c_session && c_session->tls) {
3207 coap_mbedtls_env_t *m_env;
3208
3209 /* To get around const issue */
3210 memcpy(&m_env, &c_session->tls, sizeof(m_env));
3211
3212 return (void *)&m_env->ssl;
3213 }
3214 return NULL;
3215}
3216
3217static coap_log_t keep_log_level = COAP_LOG_EMERG;
3218
3219void
3221#if !defined(ESPIDF_VERSION)
3222 int use_level;
3223 /*
3224 * Mbed TLS debug levels filter
3225 * 0 No debug
3226 * 1 Error
3227 * 2 State change
3228 * 3 Informational
3229 * 4 Verbose
3230 */
3231 switch ((int)level) {
3232 case COAP_LOG_EMERG:
3233 use_level = 0;
3234 break;
3235 case COAP_LOG_ALERT:
3236 case COAP_LOG_CRIT:
3237 case COAP_LOG_ERR:
3238 case COAP_LOG_WARN:
3239 use_level = 1;
3240 break;
3241 case COAP_LOG_NOTICE:
3242 use_level = 2;
3243 break;
3244 case COAP_LOG_INFO:
3245 use_level = 3;
3246 break;
3247 case COAP_LOG_DEBUG:
3248 default:
3249 use_level = 4;
3250 break;
3251 }
3252 mbedtls_debug_set_threshold(use_level);
3253#endif /* !ESPIDF_VERSION) */
3254 keep_log_level = level;
3255}
3256
3259 return keep_log_level;
3260}
3261
3262#endif /* COAP_WITH_LIBMBEDTLS */
3263
3264#if COAP_WITH_LIBMBEDTLS || COAP_WITH_LIBMBEDTLS_OSCORE
3265
3266#if COAP_SERVER_SUPPORT
3267coap_digest_ctx_t *
3268coap_digest_setup(void) {
3269 coap_crypto_sha256_ctx_t *digest_ctx = mbedtls_malloc(sizeof(coap_crypto_sha256_ctx_t));
3270
3271 if (digest_ctx) {
3272 if (coap_crypto_sha256_init(digest_ctx) != 0) {
3273 coap_digest_free(digest_ctx);
3274 return NULL;
3275 }
3276 }
3277 return digest_ctx;
3278}
3279
3280void
3281coap_digest_free(coap_digest_ctx_t *digest_ctx) {
3282 if (digest_ctx) {
3283 coap_crypto_sha256_free(digest_ctx);
3284 mbedtls_free(digest_ctx);
3285 }
3286}
3287
3288int
3289coap_digest_update(coap_digest_ctx_t *digest_ctx,
3290 const uint8_t *data,
3291 size_t data_len) {
3292 return coap_crypto_sha256_update(digest_ctx, data, data_len) == 0;
3293}
3294
3295int
3296coap_digest_final(coap_digest_ctx_t *digest_ctx,
3297 coap_digest_t *digest_buffer) {
3298 int ret = coap_crypto_sha256_finish(digest_ctx, (uint8_t *)digest_buffer) == 0;
3299 coap_digest_free(digest_ctx);
3300 return ret;
3301}
3302#endif /* COAP_SERVER_SUPPORT */
3303
3304#if COAP_WS_SUPPORT
3305int
3307 const coap_bin_const_t *data,
3308 coap_bin_const_t **hash) {
3309 coap_crypto_md_type_t md_type;
3310 size_t hash_len;
3311
3312 switch ((int)alg) {
3314 md_type = COAP_CRYPTO_MD_SHA1;
3315 break;
3317 md_type = COAP_CRYPTO_MD_SHA256;
3318 break;
3320 md_type = COAP_CRYPTO_MD_SHA512;
3321 break;
3322 default:
3323 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3324 return 0;
3325 }
3326
3327 hash_len = coap_crypto_hash_size(md_type);
3328 if (hash_len == 0)
3329 return 0;
3330
3331 coap_binary_t *dummy = coap_new_binary(hash_len);
3332 if (dummy == NULL)
3333 return 0;
3334
3335 if (coap_crypto_hash_compute(md_type, data->s, data->length,
3336 dummy->s, hash_len, NULL) != 0) {
3338 return 0;
3339 }
3340
3341 *hash = (coap_bin_const_t *)dummy;
3342 return 1;
3343}
3344#endif /* COAP_WS_SUPPORT */
3345
3346/* HMAC Functions */
3347
3348#if COAP_OSCORE_SUPPORT
3349static int
3350coap_crypto_hmac_compute(coap_crypto_md_type_t md_type,
3351 const uint8_t *key, size_t key_len,
3352 const uint8_t *input, size_t ilen,
3353 uint8_t *output, size_t output_size,
3354 size_t *output_len) {
3355#if COAP_USE_PSA_CRYPTO
3356 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3357 psa_key_id_t key_id;
3358 psa_algorithm_t psa_alg = PSA_ALG_HMAC(md_type);
3359 size_t mac_len;
3360 psa_status_t status;
3361
3362 psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
3363 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
3364 psa_set_key_algorithm(&attributes, psa_alg);
3365
3366 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3367 return -1;
3368 }
3369
3370 status = psa_mac_compute(key_id, psa_alg, input, ilen,
3371 output, output_size, &mac_len);
3372 psa_destroy_key(key_id);
3373
3374 if (output_len)
3375 *output_len = mac_len;
3376 return (status == PSA_SUCCESS) ? 0 : -1;
3377#else
3378 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
3379 if (!md_info)
3380 return -1;
3381 size_t mac_size = mbedtls_md_get_size(md_info);
3382 if (mac_size > output_size)
3383 return -1;
3384 if (output_len)
3385 *output_len = mac_size;
3386 return mbedtls_md_hmac(md_info, key, key_len, input, ilen, output);
3387#endif
3388}
3389
3390/* AEAD (AES-CCM) Functions */
3391
3392static int
3393coap_crypto_aead_encrypt_ccm(const uint8_t *key, size_t key_len,
3394 const uint8_t *nonce, size_t nonce_len,
3395 const uint8_t *aad, size_t aad_len,
3396 const uint8_t *plaintext, size_t plaintext_len,
3397 uint8_t *ciphertext, size_t ciphertext_size,
3398 size_t *ciphertext_len, size_t tag_len) {
3399#if COAP_USE_PSA_CRYPTO
3400 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3401 psa_key_id_t key_id;
3402 psa_algorithm_t psa_alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_len);
3403 size_t output_len;
3404 psa_status_t status;
3405
3406 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
3407 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
3408 psa_set_key_algorithm(&attributes, psa_alg);
3409 psa_set_key_bits(&attributes, key_len * 8);
3410
3411 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3412 return -1;
3413 }
3414
3415 status = psa_aead_encrypt(key_id, psa_alg,
3416 nonce, nonce_len,
3417 aad, aad_len,
3418 plaintext, plaintext_len,
3419 ciphertext, ciphertext_size, &output_len);
3420 psa_destroy_key(key_id);
3421
3422 if (ciphertext_len)
3423 *ciphertext_len = output_len;
3424 return (status == PSA_SUCCESS) ? 0 : -1;
3425#else
3426 mbedtls_cipher_context_t ctx;
3427 const mbedtls_cipher_info_t *cipher_info;
3428 mbedtls_cipher_type_t cipher_type;
3429 int ret = -1;
3430 size_t result_len = ciphertext_size;
3431
3432 if (key_len == 16) {
3433 cipher_type = MBEDTLS_CIPHER_AES_128_CCM;
3434 } else if (key_len == 32) {
3435 cipher_type = MBEDTLS_CIPHER_AES_256_CCM;
3436 } else {
3437 return -1;
3438 }
3439
3440 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
3441 if (!cipher_info)
3442 return -1;
3443
3444 mbedtls_cipher_init(&ctx);
3445 if (mbedtls_cipher_setup(&ctx, cipher_info) != 0)
3446 goto cleanup;
3447 if (mbedtls_cipher_setkey(&ctx, key, key_len * 8, MBEDTLS_ENCRYPT) != 0)
3448 goto cleanup;
3449
3450#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3451 {
3452 unsigned char tag[16];
3453 if (mbedtls_cipher_auth_encrypt(&ctx,
3454 nonce, nonce_len,
3455 aad, aad_len,
3456 plaintext, plaintext_len,
3457 ciphertext, &result_len,
3458 tag, tag_len) != 0) {
3459 goto cleanup;
3460 }
3461 if ((result_len + tag_len) > ciphertext_size)
3462 goto cleanup;
3463 memcpy(ciphertext + result_len, tag, tag_len);
3464 result_len += tag_len;
3465 }
3466#else
3467 if (mbedtls_cipher_auth_encrypt_ext(&ctx,
3468 nonce, nonce_len,
3469 aad, aad_len,
3470 plaintext, plaintext_len,
3471 ciphertext, ciphertext_size,
3472 &result_len, tag_len) != 0) {
3473 goto cleanup;
3474 }
3475#endif
3476
3477 if (ciphertext_len)
3478 *ciphertext_len = result_len;
3479 ret = 0;
3480
3481cleanup:
3482 mbedtls_cipher_free(&ctx);
3483 return ret;
3484#endif
3485}
3486
3487static int
3488coap_crypto_aead_decrypt_ccm(const uint8_t *key, size_t key_len,
3489 const uint8_t *nonce, size_t nonce_len,
3490 const uint8_t *aad, size_t aad_len,
3491 const uint8_t *ciphertext, size_t ciphertext_len,
3492 uint8_t *plaintext, size_t plaintext_size,
3493 size_t *plaintext_len, size_t tag_len) {
3494#if COAP_USE_PSA_CRYPTO
3495 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3496 psa_key_id_t key_id;
3497 psa_algorithm_t psa_alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_len);
3498 size_t output_len;
3499 psa_status_t status;
3500
3501 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
3502 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
3503 psa_set_key_algorithm(&attributes, psa_alg);
3504 psa_set_key_bits(&attributes, key_len * 8);
3505
3506 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3507 return -1;
3508 }
3509
3510 status = psa_aead_decrypt(key_id, psa_alg,
3511 nonce, nonce_len,
3512 aad, aad_len,
3513 ciphertext, ciphertext_len,
3514 plaintext, plaintext_size, &output_len);
3515 psa_destroy_key(key_id);
3516
3517 if (plaintext_len)
3518 *plaintext_len = output_len;
3519 return (status == PSA_SUCCESS) ? 0 : -1;
3520#else
3521 mbedtls_cipher_context_t ctx;
3522 const mbedtls_cipher_info_t *cipher_info;
3523 mbedtls_cipher_type_t cipher_type;
3524 int ret = -1;
3525 size_t result_len = plaintext_size;
3526
3527 if (key_len == 16) {
3528 cipher_type = MBEDTLS_CIPHER_AES_128_CCM;
3529 } else if (key_len == 32) {
3530 cipher_type = MBEDTLS_CIPHER_AES_256_CCM;
3531 } else {
3532 return -1;
3533 }
3534
3535 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
3536 if (!cipher_info)
3537 return -1;
3538
3539 mbedtls_cipher_init(&ctx);
3540 if (mbedtls_cipher_setup(&ctx, cipher_info) != 0)
3541 goto cleanup;
3542 if (mbedtls_cipher_setkey(&ctx, key, key_len * 8, MBEDTLS_DECRYPT) != 0)
3543 goto cleanup;
3544
3545#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3546 {
3547 const unsigned char *tag = ciphertext + ciphertext_len - tag_len;
3548 if (mbedtls_cipher_auth_decrypt(&ctx,
3549 nonce, nonce_len,
3550 aad, aad_len,
3551 ciphertext, ciphertext_len - tag_len,
3552 plaintext, &result_len,
3553 tag, tag_len) != 0) {
3554 goto cleanup;
3555 }
3556 }
3557#else
3558 if (mbedtls_cipher_auth_decrypt_ext(&ctx,
3559 nonce, nonce_len,
3560 aad, aad_len,
3561 ciphertext, ciphertext_len,
3562 plaintext, plaintext_size,
3563 &result_len, tag_len) != 0) {
3564 goto cleanup;
3565 }
3566#endif
3567
3568 if (plaintext_len)
3569 *plaintext_len = result_len;
3570 ret = 0;
3571
3572cleanup:
3573 mbedtls_cipher_free(&ctx);
3574 return ret;
3575#endif
3576}
3577
3578/* End of Crypto Abstraction Functions */
3579
3580int
3582 return 1;
3583}
3584
3585/*
3586 * Helper to check if COSE cipher algorithm is supported and get key size.
3587 */
3588static int
3589get_cipher_key_size(cose_alg_t alg, size_t *key_size) {
3590 switch ((int)alg) {
3592 if (key_size)
3593 *key_size = 16;
3594 return 1;
3596 if (key_size)
3597 *key_size = 32;
3598 return 1;
3599 default:
3600 coap_log_debug("get_cipher_key_size: COSE cipher %d not supported\n", alg);
3601 return 0;
3602 }
3603}
3604
3605/*
3606 * Helper to get HMAC algorithm parameters from COSE HMAC algorithm.
3607 */
3608static int
3609get_hmac_params(cose_hmac_alg_t hmac_alg,
3610 coap_crypto_md_type_t *md_type,
3611 size_t *mac_len) {
3612 switch ((int)hmac_alg) {
3614 if (md_type)
3615 *md_type = COAP_CRYPTO_MD_SHA256;
3616 if (mac_len)
3617 *mac_len = 32;
3618 return 1;
3620 if (md_type)
3621 *md_type = COAP_CRYPTO_MD_SHA384;
3622 if (mac_len)
3623 *mac_len = 48;
3624 return 1;
3626 if (md_type)
3627 *md_type = COAP_CRYPTO_MD_SHA512;
3628 if (mac_len)
3629 *mac_len = 64;
3630 return 1;
3631 default:
3632 coap_log_debug("get_hmac_params: COSE HMAC %d not supported\n", hmac_alg);
3633 return 0;
3634 }
3635}
3636
3637int
3639 return get_cipher_key_size(alg, NULL);
3640}
3641
3642int
3644 cose_hmac_alg_t hmac_alg;
3645
3646 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3647 return 0;
3648 return get_hmac_params(hmac_alg, NULL, NULL);
3649}
3650
3651int
3653 coap_bin_const_t *data,
3654 coap_bin_const_t *aad,
3655 uint8_t *result,
3656 size_t *max_result_len) {
3657 const coap_crypto_aes_ccm_t *ccm;
3658
3659 if (data == NULL)
3660 return 0;
3661
3662 assert(params != NULL);
3663
3664 if (!params) {
3665 return 0;
3666 }
3667
3668 if (!get_cipher_key_size(params->alg, NULL)) {
3669 coap_log_debug("coap_crypto_aead_encrypt: algorithm %d not supported\n",
3670 params->alg);
3671 return 0;
3672 }
3673
3674 ccm = &params->params.aes;
3675
3676 if (coap_crypto_aead_encrypt_ccm(ccm->key.s, ccm->key.length,
3677 ccm->nonce, 15 - ccm->l,
3678 aad ? aad->s : NULL, aad ? aad->length : 0,
3679 data->s, data->length,
3680 result, *max_result_len, max_result_len,
3681 ccm->tag_len) != 0) {
3682 coap_log_debug("coap_crypto_aead_encrypt: encryption failed\n");
3683 return 0;
3684 }
3685
3686 return 1;
3687}
3688
3689int
3691 coap_bin_const_t *data,
3692 coap_bin_const_t *aad,
3693 uint8_t *result,
3694 size_t *max_result_len) {
3695 const coap_crypto_aes_ccm_t *ccm;
3696
3697 if (data == NULL)
3698 return 0;
3699
3700 assert(params != NULL);
3701
3702 if (!params) {
3703 return 0;
3704 }
3705
3706 if (!get_cipher_key_size(params->alg, NULL)) {
3707 coap_log_debug("coap_crypto_aead_decrypt: algorithm %d not supported\n",
3708 params->alg);
3709 return 0;
3710 }
3711
3712 ccm = &params->params.aes;
3713
3714 if (data->length < ccm->tag_len) {
3715 coap_log_err("coap_decrypt: invalid tag length\n");
3716 return 0;
3717 }
3718
3719 if (coap_crypto_aead_decrypt_ccm(ccm->key.s, ccm->key.length,
3720 ccm->nonce, 15 - ccm->l,
3721 aad ? aad->s : NULL, aad ? aad->length : 0,
3722 data->s, data->length,
3723 result, *max_result_len, max_result_len,
3724 ccm->tag_len) != 0) {
3725 coap_log_debug("coap_crypto_aead_decrypt: decryption failed\n");
3726 return 0;
3727 }
3728
3729 return 1;
3730}
3731
3732int
3734 coap_bin_const_t *key,
3735 coap_bin_const_t *data,
3736 coap_bin_const_t **hmac) {
3737 coap_crypto_md_type_t md_type;
3738 size_t mac_len;
3740
3741 assert(key);
3742 assert(data);
3743 assert(hmac);
3744
3745 if (!get_hmac_params(hmac_alg, &md_type, &mac_len)) {
3746 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3747 return 0;
3748 }
3749
3750 dummy = coap_new_binary(mac_len);
3751 if (dummy == NULL)
3752 return 0;
3753
3754 if (coap_crypto_hmac_compute(md_type, key->s, key->length,
3755 data->s, data->length,
3756 dummy->s, mac_len, NULL) != 0) {
3757 coap_log_debug("coap_crypto_hmac: computation failed\n");
3759 return 0;
3760 }
3761
3762 *hmac = (coap_bin_const_t *)dummy;
3763 return 1;
3764}
3765
3766#endif /* COAP_OSCORE_SUPPORT */
3767
3768#else /* ! COAP_WITH_LIBMBEDTLS && ! COAP_WITH_LIBMBEDTLS_OSCORE*/
3769
3770#ifdef __clang__
3771/* Make compilers happy that do not like empty modules. As this function is
3772 * never used, we ignore -Wunused-function at the end of compiling this file
3773 */
3774#pragma GCC diagnostic ignored "-Wunused-function"
3775#endif
3776static inline void
3777dummy(void) {
3778}
3779
3780#endif /* ! COAP_WITH_LIBMBEDTLS */
static size_t strnlen(const char *s, size_t maxlen)
A length-safe strlen() fake.
Definition coap_debug.c:183
static void dummy(void)
#define COAP_SERVER_SUPPORT
#define PRIuS
#define PRIx32
#define PRIdS
const char * coap_socket_strerror(void)
Definition coap_io.c:963
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:31
@ COAP_NACK_TLS_FAILED
Definition coap_io.h:68
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
@ COAP_LAYER_TLS
Library specific build wrapper for coap_internal.h.
static void dummy(void)
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:258
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition coap_notls.c:370
ssize_t coap_tls_read(coap_session_t *session COAP_UNUSED, uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:442
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition coap_notls.c:365
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:384
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition coap_notls.c:304
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:402
int coap_dtls_context_load_pki_trust_store(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:274
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:297
ssize_t coap_dtls_send(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:353
ssize_t coap_tls_write(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:430
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:349
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:266
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:379
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:327
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:345
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:322
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:421
#define NULL
Definition coap_option.h:30
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:149
int coap_prng_lkd(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition coap_prng.c:190
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:5268
int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len)
Parses and interprets a CoAP datagram with context ctx.
Definition coap_net.c:3141
void coap_ticks(coap_tick_t *t)
Returns the current value of an internal tick counter.
Definition coap_time.c:90
int coap_crypto_hmac(cose_hmac_alg_t hmac_alg, coap_bin_const_t *key, coap_bin_const_t *data, coap_bin_const_t **hmac)
Create a HMAC hash of the provided data.
int coap_crypto_aead_decrypt(const coap_crypto_param_t *params, coap_bin_const_t *data, coap_bin_const_t *aad, uint8_t *result, size_t *max_result_len)
Decrypt the provided encrypted data into plaintext.
int coap_crypto_aead_encrypt(const coap_crypto_param_t *params, coap_bin_const_t *data, coap_bin_const_t *aad, uint8_t *result, size_t *max_result_len)
Encrypt the provided plaintext data.
int coap_crypto_hash(cose_alg_t alg, const coap_bin_const_t *data, coap_bin_const_t **hash)
Create a hash of the provided data.
int coap_crypto_check_hkdf_alg(cose_hkdf_alg_t hkdf_alg)
Check whether the defined hkdf algorithm is supported by the underlying crypto library.
int coap_crypto_check_cipher_alg(cose_alg_t alg)
Check whether the defined cipher algorithm is supported by the underlying crypto library.
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *coap_session)
Get the current client's PSK identity.
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:109
#define COAP_DTLS_RETRANSMIT_MS
int coap_dtls_define_issue(coap_define_issue_key_t type, coap_define_issue_fail_t fail, coap_dtls_key_t *key, const coap_dtls_role_t role, int ret)
Report PKI DEFINE type issue.
Definition coap_dtls.c:165
void coap_dtls_thread_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:118
int coap_dtls_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
#define COAP_DTLS_CID_LENGTH
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition coap_notls.c:360
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:113
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
void coap_dtls_map_key_type_to_define(const coap_dtls_pki_t *setup_data, coap_dtls_key_t *key)
Map the PKI key definitions to the new DEFINE format.
Definition coap_dtls.c:26
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
#define COAP_DTLS_RETRANSMIT_TOTAL_MS
@ COAP_DEFINE_KEY_PRIVATE
@ COAP_DEFINE_KEY_ROOT_CA
@ COAP_DEFINE_KEY_CA
@ COAP_DEFINE_KEY_PUBLIC
@ COAP_DEFINE_FAIL_NONE
@ COAP_DEFINE_FAIL_NOT_SUPPORTED
@ COAP_DEFINE_FAIL_BAD
coap_tls_version_t * coap_get_tls_library_version(void)
Determine the type and version of the underlying (D)TLS library.
Definition coap_notls.c:101
struct coap_dtls_key_t coap_dtls_key_t
The structure that holds the PKI key information.
coap_dtls_role_t
Definition coap_dtls.h:48
struct coap_dtls_spsk_info_t coap_dtls_spsk_info_t
The structure that holds the Server Pre-Shared Key and Identity Hint information.
coap_tls_library_t
Definition coap_dtls.h:74
struct coap_dtls_pki_t coap_dtls_pki_t
Definition coap_dtls.h:36
@ COAP_PKI_KEY_DEF_PKCS11
The PKI key type is PKCS11 (pkcs11:...).
Definition coap_dtls.h:249
@ COAP_PKI_KEY_DEF_DER_BUF
The PKI key type is DER buffer (ASN.1).
Definition coap_dtls.h:246
@ COAP_PKI_KEY_DEF_PEM_BUF
The PKI key type is PEM buffer.
Definition coap_dtls.h:240
@ COAP_PKI_KEY_DEF_PEM
The PKI key type is PEM file.
Definition coap_dtls.h:238
@ COAP_PKI_KEY_DEF_ENGINE
The PKI key type is to be passed to ENGINE.
Definition coap_dtls.h:255
@ COAP_PKI_KEY_DEF_RPK_BUF
The PKI key type is RPK in buffer.
Definition coap_dtls.h:242
@ COAP_PKI_KEY_DEF_DER
The PKI key type is DER file.
Definition coap_dtls.h:244
@ COAP_PKI_KEY_DEF_PKCS11_RPK
The PKI key type is PKCS11 w/ RPK (pkcs11:...).
Definition coap_dtls.h:252
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:50
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition coap_dtls.h:49
@ COAP_PKI_KEY_DEFINE
The individual PKI key types are Definable.
Definition coap_dtls.h:176
@ COAP_TLS_LIBRARY_MBEDTLS
Using Mbed TLS library.
Definition coap_dtls.h:79
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:41
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:43
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:47
#define coap_lock_callback_ret(r, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:126
#define coap_log_emerg(...)
Definition coap_debug.h:87
coap_log_t
Logging type.
Definition coap_debug.h:56
coap_log_t coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition coap_notls.c:317
#define coap_dtls_log(level,...)
Logging function.
Definition coap_debug.h:306
void coap_dtls_set_log_level(coap_log_t level)
Sets the (D)TLS logging level to the specified level.
Definition coap_notls.c:312
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:114
#define coap_log_warn(...)
Definition coap_debug.h:108
#define coap_log_err(...)
Definition coap_debug.h:102
@ COAP_LOG_INFO
Definition coap_debug.h:63
@ COAP_LOG_EMERG
Definition coap_debug.h:57
@ COAP_LOG_NOTICE
Definition coap_debug.h:62
@ COAP_LOG_DEBUG
Definition coap_debug.h:64
@ COAP_LOG_ALERT
Definition coap_debug.h:58
@ COAP_LOG_CRIT
Definition coap_debug.h:59
@ COAP_LOG_ERR
Definition coap_debug.h:60
@ COAP_LOG_WARN
Definition coap_debug.h:61
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
int cose_get_hmac_alg_for_hkdf(cose_hkdf_alg_t hkdf_alg, cose_hmac_alg_t *hmac_alg)
cose_hkdf_alg_t
cose_hmac_alg_t
cose_alg_t
@ COSE_HMAC_ALG_HMAC384_384
@ COSE_HMAC_ALG_HMAC256_256
@ COSE_HMAC_ALG_HMAC512_512
@ COSE_ALGORITHM_SHA_256_256
@ COSE_ALGORITHM_SHA_1
@ COSE_ALGORITHM_AES_CCM_16_64_128
@ COSE_ALGORITHM_SHA_512
@ COSE_ALGORITHM_AES_CCM_16_64_256
coap_proto_t
CoAP protocol types Note: coap_layers_coap[] needs updating if extended.
Definition coap_pdu.h:234
@ COAP_PROTO_DTLS
Definition coap_pdu.h:237
@ COAP_PROTO_TLS
Definition coap_pdu.h:239
@ COAP_PROTO_WSS
Definition coap_pdu.h:241
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Refresh the session's current Identity Hint (PSK).
int coap_session_refresh_psk_key(coap_session_t *session, const coap_bin_const_t *psk_key)
Refresh the session's current pre-shared key (PSK).
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
int coap_session_refresh_psk_identity(coap_session_t *session, const coap_bin_const_t *psk_identity)
Refresh the session's current pre-shared identity (PSK).
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
#define COAP_PROTO_NOT_RELIABLE(p)
@ COAP_SESSION_TYPE_CLIENT
client-side
@ COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_NONE
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:81
coap_bin_const_t * coap_new_bin_const(const uint8_t *data, size_t size)
Take the specified byte array (text) and create a coap_bin_const_t * Returns a new const binary objec...
Definition coap_str.c:119
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:114
int coap_dtls_cid_is_supported(void)
Check whether (D)TLS CID is available.
Definition coap_notls.c:86
int coap_dtls_psk_is_supported(void)
Check whether (D)TLS PSK is available.
Definition coap_notls.c:50
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_oscore_is_supported(void)
Check whether OSCORE is available.
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_dtls_pki_is_supported(void)
Check whether (D)TLS PKI is available.
Definition coap_notls.c:59
int coap_dtls_rpk_is_supported(void)
Check whether (D)TLS RPK is available.
Definition coap_notls.c:77
int coap_dtls_pkcs11_is_supported(void)
Check whether (D)TLS PKCS11 is available.
Definition coap_notls.c:68
#define COAP_UNUSED
Definition libcoap.h:74
coap_address_t remote
remote address and port
Definition coap_io.h:58
CoAP binary data definition with const data.
Definition coap_str.h:65
size_t length
length of binary data
Definition coap_str.h:66
const uint8_t * s
read-only binary data
Definition coap_str.h:67
CoAP binary data definition.
Definition coap_str.h:57
The CoAP stack's global state is stored in a coap_context_t object.
The structure that holds the AES Crypto information.
size_t l
The number of bytes in the length field.
const uint8_t * nonce
must be exactly 15 - l bytes
coap_crypto_key_t key
The Key to use.
size_t tag_len
The size of the Tag.
The common structure that holds the Crypto information.
union coap_crypto_param_t::@013342365277111013141357350166222244241273034362 params
coap_crypto_aes_ccm_t aes
Used if AES type encryption.
cose_alg_t alg
The COSE algorith to use.
The structure used for defining the Client PSK setup data to be used.
Definition coap_dtls.h:414
uint8_t use_cid
Set to 1 if DTLS Connection ID is to be used.
Definition coap_dtls.h:421
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:441
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition coap_dtls.h:437
uint8_t ec_jpake
Set to COAP_DTLS_CPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:419
The structure that holds the PKI key information.
Definition coap_dtls.h:283
coap_pki_key_define_t define
for definable type keys
Definition coap_dtls.h:290
union coap_dtls_key_t::@063257166335312256117260270312367251270130034073 key
coap_pki_key_t key_type
key format type
Definition coap_dtls.h:284
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:316
uint8_t allow_no_crl
1 ignore if CRL not there
Definition coap_dtls.h:330
void * cn_call_back_arg
Passed in to the CN callback function.
Definition coap_dtls.h:355
uint8_t allow_short_rsa_length
1 if small RSA keysizes are allowed
Definition coap_dtls.h:333
uint8_t cert_chain_validation
1 if to check cert_chain_verify_depth
Definition coap_dtls.h:327
uint8_t allow_bad_md_hash
1 if unsupported MD hashes are allowed
Definition coap_dtls.h:332
uint8_t use_cid
1 if DTLS Connection ID is to be used (Client only, server always enabled) if supported
Definition coap_dtls.h:337
uint8_t check_cert_revocation
1 if revocation checks wanted
Definition coap_dtls.h:329
uint8_t cert_chain_verify_depth
recommended depth is 3
Definition coap_dtls.h:328
uint8_t allow_expired_certs
1 if expired certs are allowed
Definition coap_dtls.h:326
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:321
uint8_t allow_self_signed
1 if self-signed certs are allowed.
Definition coap_dtls.h:324
coap_dtls_cn_callback_t validate_cn_call_back
CN check callback function.
Definition coap_dtls.h:354
uint8_t allow_expired_crl
1 if expired crl is allowed
Definition coap_dtls.h:331
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition coap_dtls.h:334
uint8_t check_common_ca
1 if peer cert is to be signed by the same CA as the local cert
Definition coap_dtls.h:322
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition coap_dtls.h:454
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:505
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition coap_dtls.h:526
void * id_call_back_arg
Passed in to the Identity callback function.
Definition coap_dtls.h:527
uint8_t ec_jpake
Set to COAP_DTLS_SPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:510
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
coap_const_char_ptr_t public_cert
define: Public Cert
Definition coap_dtls.h:265
coap_const_char_ptr_t private_key
define: Private Key
Definition coap_dtls.h:266
coap_const_char_ptr_t ca
define: Common CA Certificate
Definition coap_dtls.h:264
size_t public_cert_len
define Public Cert length (if needed)
Definition coap_dtls.h:268
size_t ca_len
define CA Cert length (if needed)
Definition coap_dtls.h:267
coap_pki_define_t private_key_def
define: Private Key type definition
Definition coap_dtls.h:272
size_t private_key_len
define Private Key length (if needed)
Definition coap_dtls.h:269
coap_pki_define_t ca_def
define: Common CA type definition
Definition coap_dtls.h:270
coap_pki_define_t public_cert_def
define: Public Cert type definition
Definition coap_dtls.h:271
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
unsigned int dtls_timeout_count
dtls setup retry counter
coap_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationship with peer
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
int dtls_event
Tracking any (D)TLS events on this session.
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
coap_session_type_t type
client or server side socket
coap_context_t * context
session's context
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
coap_socket_flags_t flags
1 or more of COAP_SOCKET* flag values
The structure used for returning the underlying (D)TLS library information.
Definition coap_dtls.h:87
uint64_t built_version
(D)TLS Built against Library Version
Definition coap_dtls.h:90
coap_tls_library_t type
Library type.
Definition coap_dtls.h:89
uint64_t version
(D)TLS runtime Library Version
Definition coap_dtls.h:88
const char * s_byte
signed char ptr
Definition coap_str.h:84
const uint8_t * u_byte
unsigned char ptr
Definition coap_str.h:85