libcoap 4.3.5-develop-3035cfd
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 if (*flags == 0)
682 return 0;
683
684 cn = get_san_or_cn_from_cert(crt);
685
686 if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
687 if (setup_data->allow_expired_certs) {
688 *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
689 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
690 coap_session_str(c_session),
691 "The certificate has expired", cn ? cn : "?", depth);
692 }
693 }
694 if (*flags & MBEDTLS_X509_BADCERT_FUTURE) {
695 if (setup_data->allow_expired_certs) {
696 *flags &= ~MBEDTLS_X509_BADCERT_FUTURE;
697 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
698 coap_session_str(c_session),
699 "The certificate has a future date", cn ? cn : "?", depth);
700 }
701 }
702 if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) {
703 if (setup_data->allow_bad_md_hash) {
704 *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD;
705 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
706 coap_session_str(c_session),
707 "The certificate has a bad MD hash", cn ? cn : "?", depth);
708 }
709 }
710 if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) {
711 if (setup_data->allow_short_rsa_length) {
712 *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY;
713 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
714 coap_session_str(c_session),
715 "The certificate has a short RSA length", cn ? cn : "?", depth);
716 }
717 }
718 if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
719 uint32_t lflags;
720 int self_signed = !mbedtls_x509_crt_verify(crt, crt, NULL, NULL, &lflags,
721 self_signed_cert_verify_callback_mbedtls,
722 data);
723 if (self_signed && depth == 0) {
724 if (setup_data->allow_self_signed &&
725 !setup_data->check_common_ca) {
726 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
727 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
728 coap_session_str(c_session),
729 "Self-signed",
730 cn ? cn : "?", depth);
731 }
732 } else if (self_signed) {
733 if (!setup_data->verify_peer_cert) {
734 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
735 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
736 coap_session_str(c_session),
737 "Self-signed", cn ? cn : "?", depth);
738 }
739 } else {
740 if (!setup_data->verify_peer_cert) {
741 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
742 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
743 coap_session_str(c_session),
744 "The certificate's CA is not trusted", cn ? cn : "?", depth);
745 }
746 }
747 }
748 if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) {
749 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
750 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
751 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
752 coap_session_str(c_session),
753 "The certificate's CRL has expired", cn ? cn : "?", depth);
754 } else if (!setup_data->check_cert_revocation) {
755 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
756 }
757 }
758 if (*flags & MBEDTLS_X509_BADCRL_FUTURE) {
759 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
760 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
761 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
762 coap_session_str(c_session),
763 "The certificate's CRL has a future date", cn ? cn : "?", depth);
764 } else if (!setup_data->check_cert_revocation) {
765 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
766 }
767 }
768 if (setup_data->cert_chain_validation &&
769 depth > (setup_data->cert_chain_verify_depth + 1)) {
770 *flags |= MBEDTLS_X509_BADCERT_OTHER;
771 coap_log_warn(" %s: %s: '%s' depth %d\n",
772 coap_session_str(c_session),
773 "The certificate's verify depth is too long",
774 cn ? cn : "?", depth);
775 }
776
777 if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
778 *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
779 }
780 if (setup_data->validate_cn_call_back) {
781 int ret;
782
784 setup_data->validate_cn_call_back(cn,
785 crt->raw.p,
786 crt->raw.len,
787 c_session,
788 depth,
789 *flags == 0,
790 setup_data->cn_call_back_arg));
791 if (!ret) {
792 *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
793 }
794 }
795 if (*flags != 0) {
796 char buf[128];
797 char *tcp;
798 int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
799
800 if (ret >= 0) {
801 tcp = strchr(buf, '\n');
802 while (tcp) {
803 *tcp = '\000';
804 coap_log_warn(" %s: %s: issue 0x%" PRIx32 ": '%s' depth %d\n",
805 coap_session_str(c_session),
806 buf, *flags, cn ? cn : "?", depth);
807 tcp = strchr(tcp+1, '\n');
808 }
809 } else {
810 coap_log_err("mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n",
811 -ret, get_error_string(ret));
812 }
813 }
814
815 if (cn)
816 mbedtls_free(cn);
817
818 return 0;
819}
820
821static int
822setup_pki_credentials(mbedtls_x509_crt *cacert,
823 mbedtls_x509_crt *public_cert,
824 mbedtls_pk_context *private_key,
825 coap_mbedtls_env_t *m_env,
826 coap_mbedtls_context_t *m_context,
827 coap_session_t *c_session,
828 coap_dtls_pki_t *setup_data,
829 coap_dtls_role_t role) {
830 coap_dtls_key_t key;
831 int ret;
832 int done_private_key = 0;
833 int done_public_cert = 0;
834 uint8_t *buffer;
835 size_t length;
836
837 /* Map over to the new define format to save code duplication */
838 coap_dtls_map_key_type_to_define(setup_data, &key);
839
840 assert(key.key_type == COAP_PKI_KEY_DEFINE);
841
842 /*
843 * Configure the Private Key
844 */
845 if (key.key.define.private_key.u_byte &&
846 key.key.define.private_key.u_byte[0]) {
847 switch (key.key.define.private_key_def) {
848 case COAP_PKI_KEY_DEF_DER: /* define private key */
849 /* Fall Through */
850 case COAP_PKI_KEY_DEF_PEM: /* define private key */
851#if defined(MBEDTLS_FS_IO)
852 mbedtls_pk_init(private_key);
853#if COAP_USE_PSA_CRYPTO
854 ret = mbedtls_pk_parse_keyfile(private_key,
856#elif defined(MBEDTLS_2_X_COMPAT)
857 ret = mbedtls_pk_parse_keyfile(private_key,
859#else
860 ret = mbedtls_pk_parse_keyfile(private_key,
862 NULL, coap_rng, (void *)&m_env->ctr_drbg);
863#endif
864 if (ret < 0) {
867 &key, role, ret);
868 }
869 done_private_key = 1;
870 break;
871#else /* ! MBEDTLS_FS_IO */
874 &key, role, -1);
875#endif /* ! MBEDTLS_FS_IO */
876 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
877 mbedtls_pk_init(private_key);
878 length = key.key.define.private_key_len;
879 if (key.key.define.private_key.u_byte[length-1] != '\000') {
880 /* Need to allocate memory to add in NULL terminator */
881 buffer = mbedtls_malloc(length + 1);
882 if (!buffer) {
883 coap_log_err("mbedtls_malloc failed\n");
884 return 0;
885 }
886 memcpy(buffer, key.key.define.private_key.u_byte, length);
887 buffer[length] = '\000';
888 length++;
889#if COAP_USE_PSA_CRYPTO
890 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
891#elif defined(MBEDTLS_2_X_COMPAT)
892 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
893#else
894 ret = mbedtls_pk_parse_key(private_key, buffer, length,
895 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
896#endif
897 mbedtls_free(buffer);
898 } else {
899#if COAP_USE_PSA_CRYPTO
900 ret = mbedtls_pk_parse_key(private_key,
903#elif defined(MBEDTLS_2_X_COMPAT)
904 ret = mbedtls_pk_parse_key(private_key,
907#else
908 ret = mbedtls_pk_parse_key(private_key,
911 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
912#endif
913 }
914 if (ret < 0) {
917 &key, role, ret);
918 }
919 done_private_key = 1;
920 break;
921 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
922 mbedtls_pk_init(private_key);
923#if COAP_USE_PSA_CRYPTO
924 ret = mbedtls_pk_parse_key(private_key,
927#elif defined(MBEDTLS_2_X_COMPAT)
928 ret = mbedtls_pk_parse_key(private_key,
931#else
932 ret = mbedtls_pk_parse_key(private_key,
934 key.key.define.private_key_len, NULL, 0, coap_rng,
935 (void *)&m_env->ctr_drbg);
936#endif
937 if (ret < 0) {
940 &key, role, ret);
941 }
942 done_private_key = 1;
943 break;
944 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
945 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
946 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
947 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
948 default:
951 &key, role, -1);
952 }
953 } else if (role == COAP_DTLS_ROLE_SERVER ||
955 key.key.define.public_cert.u_byte[0])) {
958 &key, role, -1);
959 }
960
961 /*
962 * Configure the Public Certificate / Key
963 */
964 if (key.key.define.public_cert.u_byte &&
965 key.key.define.public_cert.u_byte[0]) {
966 switch (key.key.define.public_cert_def) {
967 case COAP_PKI_KEY_DEF_DER: /* define public cert */
968 /* Fall Through */
969 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
970#if defined(MBEDTLS_FS_IO)
971 mbedtls_x509_crt_init(public_cert);
972 ret = mbedtls_x509_crt_parse_file(public_cert,
974 if (ret < 0) {
977 &key, role, ret);
978 }
979 done_public_cert = 1;
980 break;
981#else /* ! MBEDTLS_FS_IO */
984 &key, role, -1);
985#endif /* ! MBEDTLS_FS_IO */
986 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
987 mbedtls_x509_crt_init(public_cert);
988
989 length = key.key.define.public_cert_len;
990 if (key.key.define.public_cert.u_byte[length-1] != '\000') {
991 /* Need to allocate memory to add in NULL terminator */
992 buffer = mbedtls_malloc(length + 1);
993 if (!buffer) {
994 coap_log_err("mbedtls_malloc failed\n");
995 return 0;
996 }
997 memcpy(buffer, key.key.define.public_cert.u_byte, length);
998 buffer[length] = '\000';
999 length++;
1000 ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
1001 mbedtls_free(buffer);
1002 } else {
1003 ret = mbedtls_x509_crt_parse(public_cert,
1006 }
1007 if (ret < 0) {
1010 &key, role, ret);
1011 }
1012 done_public_cert = 1;
1013 break;
1014 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
1017 &key, role, -1);
1018 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
1019 mbedtls_x509_crt_init(public_cert);
1020 ret = mbedtls_x509_crt_parse(public_cert,
1023 if (ret < 0) {
1026 &key, role, ret);
1027 }
1028 done_public_cert = 1;
1029 break;
1030 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
1031 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
1032 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
1033 default:
1036 &key, role, -1);
1037 }
1038 } else if (role == COAP_DTLS_ROLE_SERVER ||
1040 key.key.define.private_key.u_byte[0])) {
1043 &key, role, -1);
1044 }
1045
1046 if (done_private_key && done_public_cert) {
1047 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
1048 if (ret < 0) {
1049 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
1050 -ret, get_error_string(ret));
1051 return 0;
1052 }
1053 }
1054
1055 /*
1056 * Configure the CA
1057 */
1058 if (
1059 key.key.define.ca.u_byte &&
1060 key.key.define.ca.u_byte[0]) {
1061 switch (key.key.define.ca_def) {
1062 case COAP_PKI_KEY_DEF_DER: /* define ca */
1063 /* Fall Through */
1065#if defined(MBEDTLS_FS_IO)
1066 mbedtls_x509_crt_init(cacert);
1067 ret = mbedtls_x509_crt_parse_file(cacert,
1068 key.key.define.ca.s_byte);
1069 if (ret < 0) {
1072 &key, role, ret);
1073 }
1074 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1075#else /* ! MBEDTLS_FS_IO */
1078 &key, role, -1);
1079#endif /* ! MBEDTLS_FS_IO */
1080 break;
1081 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
1082 mbedtls_x509_crt_init(cacert);
1083 length = key.key.define.ca_len;
1084 if (key.key.define.ca.u_byte[length-1] != '\000') {
1085 /* Need to allocate memory to add in NULL terminator */
1086 buffer = mbedtls_malloc(length + 1);
1087 if (!buffer) {
1088 coap_log_err("mbedtls_malloc failed\n");
1089 return 0;
1090 }
1091 memcpy(buffer, key.key.define.ca.u_byte, length);
1092 buffer[length] = '\000';
1093 length++;
1094 ret = mbedtls_x509_crt_parse(cacert, buffer, length);
1095 mbedtls_free(buffer);
1096 } else {
1097 ret = mbedtls_x509_crt_parse(cacert,
1098 key.key.define.ca.u_byte,
1099 key.key.define.ca_len);
1100 }
1101 if (ret < 0) {
1104 &key, role, ret);
1105 }
1106 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1107 break;
1108 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
1111 &key, role, -1);
1112 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
1113 mbedtls_x509_crt_init(cacert);
1114 ret = mbedtls_x509_crt_parse(cacert,
1115 key.key.define.ca.u_byte,
1116 key.key.define.ca_len);
1117 if (ret < 0) {
1120 &key, role, ret);
1121 }
1122 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1123 break;
1124 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
1125 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
1126 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
1127 default:
1130 &key, role, -1);
1131 }
1132 }
1133
1134 /* Add in any root CA definitons */
1135
1136#if defined(MBEDTLS_FS_IO)
1137 if (m_context->root_ca_file) {
1138 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
1139 if (ret < 0) {
1143 &key, role, ret);
1144 }
1145 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1146 }
1147 if (m_context->root_ca_path) {
1148 ret = mbedtls_x509_crt_parse_path(cacert, m_context->root_ca_path);
1149 if (ret < 0) {
1153 &key, role, ret);
1154 }
1155 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1156 }
1157#if MBEDTLS_VERSION_NUMBER >= 0x04000000
1158 if (m_context->trust_store_defined)
1159#else /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1160 if (m_context->trust_store_defined ||
1161 (role == COAP_DTLS_ROLE_CLIENT && !m_context->setup_data.verify_peer_cert))
1162#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1163 {
1164 /* Until Trust Store is implemented in MbedTLS */
1165 const char *trust_list[] = {
1166 "/etc/ssl/ca-bundle.pem",
1167 "/etc/ssl/certs/ca-certificates.crt",
1168 "/etc/pki/tls/cert.pem",
1169 "/usr/local/share/certs/ca-root-nss.crt",
1170 "/etc/ssl/cert.pem"
1171 };
1172 static const char *trust_file_found = NULL;
1173 static int trust_file_done = 0;
1174 unsigned int i;
1175
1176 if (trust_file_found) {
1177 ret = mbedtls_x509_crt_parse_file(cacert, trust_file_found);
1178 if (ret >= 0) {
1179 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1180 } else {
1181 coap_log_warn("Unable to load trusted root CAs (%s)\n",
1182 trust_file_found);
1183 }
1184 } else if (!trust_file_done) {
1185 trust_file_done = 1;
1186 for (i = 0; i < sizeof(trust_list)/sizeof(trust_list[0]); i++) {
1187 ret = mbedtls_x509_crt_parse_file(cacert, trust_list[i]);
1188 if (ret >= 0) {
1189 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
1190 trust_file_found = trust_list[i];
1191 break;
1192 }
1193 }
1194 if (i == sizeof(trust_list)/sizeof(trust_list[0])) {
1195 coap_log_warn("Unable to load trusted root CAs\n");
1196 }
1197 }
1198 }
1199#else /* ! MBEDTLS_FS_IO */
1200 if (m_context->root_ca_file || m_context->root_ca_path ||
1201 m_context->trust_store_defined) {
1202 /* No FS to read these files */
1205 &key, role, -1);
1206 }
1207#endif /* ! MBEDTLS_FS_IO */
1208
1209#if defined(MBEDTLS_SSL_SRV_C)
1210 mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
1211 setup_data->check_common_ca ?
1212 MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
1213 MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
1214#endif
1215 mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
1216 MBEDTLS_SSL_VERIFY_REQUIRED :
1217 MBEDTLS_SSL_VERIFY_NONE);
1218 /*
1219 * Verify Peer.
1220 * Need to do all checking, even if setup_data->verify_peer_cert is not set
1221 */
1222 mbedtls_ssl_conf_verify(&m_env->conf,
1223 cert_verify_callback_mbedtls, c_session);
1224
1225 return 1;
1226}
1227
1228#if defined(MBEDTLS_SSL_SRV_C)
1229/*
1230 * PKI SNI callback.
1231 */
1232static int
1233pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
1234 const unsigned char *uname, size_t name_len) {
1235 unsigned int i;
1236 coap_dtls_pki_t sni_setup_data;
1237 coap_session_t *c_session = (coap_session_t *)p_info;
1238 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1239 coap_mbedtls_context_t *m_context =
1240 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1241 char *name;
1242
1243 name = mbedtls_malloc(name_len+1);
1244 if (!name)
1245 return -1;
1246
1247 memcpy(name, uname, name_len);
1248 name[name_len] = '\000';
1249
1250 /* Is this a cached entry? */
1251 for (i = 0; i < m_context->pki_sni_count; i++) {
1252 if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
1253 break;
1254 }
1255 }
1256 if (i == m_context->pki_sni_count) {
1257 /*
1258 * New PKI SNI request
1259 */
1260 coap_dtls_key_t *new_entry;
1261 pki_sni_entry *pki_sni_entry_list;
1262
1263 coap_lock_callback_ret(new_entry,
1264 m_context->setup_data.validate_sni_call_back(name,
1265 m_context->setup_data.sni_call_back_arg));
1266 if (!new_entry) {
1267 mbedtls_free(name);
1268 return -1;
1269 }
1270
1271 pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
1272 (i+1)*sizeof(pki_sni_entry));
1273
1274 if (pki_sni_entry_list == NULL) {
1275 mbedtls_free(name);
1276 return -1;
1277 }
1278 m_context->pki_sni_entry_list = pki_sni_entry_list;
1279 memset(&m_context->pki_sni_entry_list[i], 0,
1280 sizeof(m_context->pki_sni_entry_list[i]));
1281 m_context->pki_sni_entry_list[i].sni = name;
1282 m_context->pki_sni_entry_list[i].pki_key = *new_entry;
1283 sni_setup_data = m_context->setup_data;
1284 sni_setup_data.pki_key = *new_entry;
1285 if (setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
1286 &m_context->pki_sni_entry_list[i].public_cert,
1287 &m_context->pki_sni_entry_list[i].private_key,
1288 m_env,
1289 m_context,
1290 c_session,
1291 &sni_setup_data, COAP_DTLS_ROLE_SERVER) < 0) {
1292 mbedtls_free(name);
1293 return -1;
1294 }
1295 /* name has been absorbed into pki_sni_entry_list[].sni entry */
1296 m_context->pki_sni_count++;
1297 } else {
1298 mbedtls_free(name);
1299 }
1300
1301 mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
1302 NULL);
1303 return mbedtls_ssl_set_hs_own_cert(ssl,
1304 &m_context->pki_sni_entry_list[i].public_cert,
1305 &m_context->pki_sni_entry_list[i].private_key);
1306}
1307
1308#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1309/*
1310 * PSK SNI callback.
1311 */
1312static int
1313psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
1314 const unsigned char *uname, size_t name_len) {
1315 unsigned int i;
1316 coap_session_t *c_session = (coap_session_t *)p_info;
1317 coap_mbedtls_context_t *m_context =
1318 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1319 char *name;
1320
1321 name = mbedtls_malloc(name_len+1);
1322 if (!name)
1323 return -1;
1324
1325 memcpy(name, uname, name_len);
1326 name[name_len] = '\000';
1327
1328 /* Is this a cached entry? */
1329 for (i = 0; i < m_context->psk_sni_count; i++) {
1330 if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
1331 break;
1332 }
1333 }
1334 if (i == m_context->psk_sni_count) {
1335 /*
1336 * New PSK SNI request
1337 */
1338 const coap_dtls_spsk_info_t *new_entry;
1339 psk_sni_entry *psk_sni_entry_list;
1340
1341 coap_lock_callback_ret(new_entry,
1342 c_session->context->spsk_setup_data.validate_sni_call_back(name,
1343 c_session,
1344 c_session->context->spsk_setup_data.sni_call_back_arg));
1345 if (!new_entry) {
1346 mbedtls_free(name);
1347 return -1;
1348 }
1349
1350 psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
1351 (i+1)*sizeof(psk_sni_entry));
1352
1353 if (psk_sni_entry_list == NULL) {
1354 mbedtls_free(name);
1355 return -1;
1356 }
1357 m_context->psk_sni_entry_list = psk_sni_entry_list;
1358 m_context->psk_sni_entry_list[i].sni = name;
1359 m_context->psk_sni_entry_list[i].psk_info = *new_entry;
1360 /* name has been absorbed into psk_sni_entry_list[].sni entry */
1361 m_context->psk_sni_count++;
1362 } else {
1363 mbedtls_free(name);
1364 }
1365
1367 &m_context->psk_sni_entry_list[i].psk_info.hint);
1369 &m_context->psk_sni_entry_list[i].psk_info.key);
1370#if MBEDTLS_VERSION_NUMBER >= 0x04000000
1371 (void)ssl;
1372 return 0;
1373#else /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1374 return mbedtls_ssl_set_hs_psk(ssl,
1375 m_context->psk_sni_entry_list[i].psk_info.key.s,
1376 m_context->psk_sni_entry_list[i].psk_info.key.length);
1377#endif /* MBEDTLS_VERSION_NUMBER < 0x04000000 */
1378}
1379#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1380
1381static int
1382setup_server_ssl_session(coap_session_t *c_session,
1383 coap_mbedtls_env_t *m_env) {
1384 coap_mbedtls_context_t *m_context =
1385 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1386 int ret = 0;
1387 m_context->psk_pki_enabled |= IS_SERVER;
1388
1389 mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
1390 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1391 MBEDTLS_SSL_IS_SERVER,
1392 c_session->proto == COAP_PROTO_DTLS ?
1393 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1394 MBEDTLS_SSL_TRANSPORT_STREAM,
1395 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1396 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1397 -ret, get_error_string(ret));
1398 goto fail;
1399 }
1400
1401#if !COAP_USE_PSA_CRYPTO
1402 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1403#endif /* !COAP_USE_PSA_CRYPTO */
1404
1405#if defined(MBEDTLS_SSL_PROTO_DTLS)
1406 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1408#endif /* MBEDTLS_SSL_PROTO_DTLS */
1409
1410 if (m_context->psk_pki_enabled & IS_PSK) {
1411#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1412 mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
1413 if (c_session->context->spsk_setup_data.validate_sni_call_back) {
1414 mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
1415 }
1416#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1417 m_env->ec_jpake = c_session->context->spsk_setup_data.ec_jpake;
1418#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1419#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1420 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1421#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1422 }
1423
1424 if (m_context->psk_pki_enabled & IS_PKI) {
1425 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1426 &m_env->private_key, m_env, m_context,
1427 c_session, &m_context->setup_data,
1429 if (ret < 0) {
1430 coap_log_err("PKI setup failed\n");
1431 return ret;
1432 }
1433 if (m_context->setup_data.validate_sni_call_back) {
1434 mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1435 }
1436 }
1437
1438#if COAP_USE_PSA_CRYPTO
1439 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx)) != 0) {
1440#else /* !COAP_USE_PSA_CRYPTO */
1441 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1442 mbedtls_ctr_drbg_random,
1443 &m_env->ctr_drbg)) != 0) {
1444#endif /* !COAP_USE_PSA_CRYPTO */
1445 coap_log_err("mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1446 -ret, get_error_string(ret));
1447 goto fail;
1448 }
1449
1450#if defined(MBEDTLS_SSL_PROTO_DTLS)
1451 mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1452 mbedtls_ssl_cookie_check,
1453 &m_env->cookie_ctx);
1454#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1455 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1456#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1457#endif /* MBEDTLS_SSL_PROTO_DTLS */
1458#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1459 /*
1460 * Configure CID max length.
1461 *
1462 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1463 * to use RFC9146 extension ID of 54, rather than the draft version -05
1464 * value of 254.
1465 */
1466 mbedtls_ssl_conf_cid(&m_env->conf, COAP_DTLS_CID_LENGTH, MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1467#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1468fail:
1469 return ret;
1470}
1471#endif /* MBEDTLS_SSL_SRV_C */
1472
1473#if COAP_CLIENT_SUPPORT
1474static int *psk_ciphers = NULL;
1475static int *pki_ciphers = NULL;
1476static int *ecjpake_ciphers = NULL;
1477static int processed_ciphers = 0;
1478
1479#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1480static int
1481coap_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info) {
1482#if COAP_USE_PSA_CRYPTO
1483 switch (info->key_exchange) {
1484 case MBEDTLS_KEY_EXCHANGE_PSK:
1485 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1486 return 1;
1487 case MBEDTLS_KEY_EXCHANGE_NONE:
1488 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1489 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1490 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1491 default:
1492 return 0;
1493 }
1494#elif MBEDTLS_VERSION_NUMBER >= 0x03060000
1495 switch (info->key_exchange) {
1496 case MBEDTLS_KEY_EXCHANGE_PSK:
1497 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
1498 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
1499 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1500 return 1;
1501 case MBEDTLS_KEY_EXCHANGE_NONE:
1502 case MBEDTLS_KEY_EXCHANGE_RSA:
1503 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
1504 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1505 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1506 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
1507 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
1508 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1509 default:
1510 return 0;
1511 }
1512#else /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1513 return mbedtls_ssl_ciphersuite_uses_psk(info);
1514#endif /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1515}
1516#endif /* defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) */
1517
1518static void
1519set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) {
1520 if (!processed_ciphers) {
1521 const int *list = mbedtls_ssl_list_ciphersuites();
1522 const int *base = list;
1523 int *psk_list;
1524 int *pki_list;
1525#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1526 int *ecjpake_list;
1527 int ecjpake_count = 1;
1528#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1529 int psk_count = 1; /* account for empty terminator */
1530 int pki_count = 1;
1531
1532 while (*list) {
1533 const mbedtls_ssl_ciphersuite_t *cur =
1534 mbedtls_ssl_ciphersuite_from_id(*list);
1535
1536 if (cur) {
1537#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1538 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1539 /* Minimum of TLS1.2 required - skip */
1540 }
1541#else
1542 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1543 /* Minimum of TLS1.2 required - skip */
1544 }
1545#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1546#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1547 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1548 ecjpake_count++;
1549 }
1550#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1551#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1552 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1553 psk_count++;
1554 pki_count++;
1555 }
1556#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1557#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1558 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1559 psk_count++;
1560 }
1561#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1562 else {
1563 pki_count++;
1564 }
1565 }
1566 list++;
1567 }
1568 list = base;
1569
1570 psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1571 if (psk_ciphers == NULL) {
1572 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1573 return;
1574 }
1575 pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1576 if (pki_ciphers == NULL) {
1577 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1578 mbedtls_free(psk_ciphers);
1579 psk_ciphers = NULL;
1580 return;
1581 }
1582#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1583 ecjpake_ciphers = mbedtls_malloc(ecjpake_count * sizeof(ecjpake_ciphers[0]));
1584 if (ecjpake_ciphers == NULL) {
1585 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1586 mbedtls_free(psk_ciphers);
1587 mbedtls_free(pki_ciphers);
1588 psk_ciphers = NULL;
1589 pki_ciphers = NULL;
1590 return;
1591 }
1592#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1593
1594 psk_list = psk_ciphers;
1595 pki_list = pki_ciphers;
1596#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1597 ecjpake_list = ecjpake_ciphers;
1598#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1599
1600 while (*list) {
1601 const mbedtls_ssl_ciphersuite_t *cur =
1602 mbedtls_ssl_ciphersuite_from_id(*list);
1603 if (cur) {
1604#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1605 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1606 /* Minimum of TLS1.2 required - skip */
1607 }
1608#else
1609 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1610 /* Minimum of TLS1.2 required - skip */
1611 }
1612#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1613#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1614 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1615 *ecjpake_list = *list;
1616 ecjpake_list++;
1617 }
1618#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1619#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1620 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1621 *psk_list = *list;
1622 psk_list++;
1623 *pki_list = *list;
1624 pki_list++;
1625 }
1626#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1627#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1628 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1629 *psk_list = *list;
1630 psk_list++;
1631 }
1632#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1633 else {
1634 *pki_list = *list;
1635 pki_list++;
1636 }
1637 }
1638 list++;
1639 }
1640 /* zero terminate */
1641 *psk_list = 0;
1642 *pki_list = 0;
1643 processed_ciphers = 1;
1644 }
1645 switch (method) {
1646 case COAP_ENC_PSK:
1647 mbedtls_ssl_conf_ciphersuites(conf, psk_ciphers);
1648 break;
1649 case COAP_ENC_PKI:
1650 mbedtls_ssl_conf_ciphersuites(conf, pki_ciphers);
1651 break;
1652 case COAP_ENC_ECJPAKE:
1653 mbedtls_ssl_conf_ciphersuites(conf, ecjpake_ciphers);
1654 break;
1655 default:
1656 assert(0);
1657 break;
1658 }
1659}
1660
1661static int
1662setup_client_ssl_session(coap_session_t *c_session,
1663 coap_mbedtls_env_t *m_env) {
1664 int ret;
1665
1666 coap_mbedtls_context_t *m_context =
1667 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1668
1669 m_context->psk_pki_enabled |= IS_CLIENT;
1670
1671 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1672 MBEDTLS_SSL_IS_CLIENT,
1673 c_session->proto == COAP_PROTO_DTLS ?
1674 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1675 MBEDTLS_SSL_TRANSPORT_STREAM,
1676 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1677 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1678 -ret, get_error_string(ret));
1679 goto fail;
1680 }
1681
1682#if defined(MBEDTLS_SSL_PROTO_DTLS)
1683 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1685#endif /* MBEDTLS_SSL_PROTO_DTLS */
1686
1687 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1688#if !COAP_USE_PSA_CRYPTO
1689 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1690#endif /* !COAP_USE_PSA_CRYPTO */
1691
1692 if (m_context->psk_pki_enabled & IS_PSK) {
1693#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1694 const coap_bin_const_t *psk_key;
1695 const coap_bin_const_t *psk_identity;
1696
1697 coap_log_info("Setting PSK key\n");
1698
1699 psk_key = coap_get_session_client_psk_key(c_session);
1700 psk_identity = coap_get_session_client_psk_identity(c_session);
1701 if (psk_key == NULL || psk_identity == NULL) {
1702 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1703 goto fail;
1704 }
1705
1706 if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1707 psk_key->length, psk_identity->s,
1708 psk_identity->length)) != 0) {
1709 coap_log_err("mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1710 -ret, get_error_string(ret));
1711 goto fail;
1712 }
1713 if (c_session->cpsk_setup_data.client_sni) {
1714 if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1715 c_session->cpsk_setup_data.client_sni)) != 0) {
1716 coap_log_err("mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1717 -ret, get_error_string(ret));
1718 goto fail;
1719 }
1720 }
1721 /* Identity Hint currently not supported in Mbed TLS so code removed */
1722
1723#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1724 if (c_session->cpsk_setup_data.ec_jpake) {
1725 m_env->ec_jpake = 1;
1726 set_ciphersuites(&m_env->conf, COAP_ENC_ECJPAKE);
1727#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1728 mbedtls_ssl_conf_max_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1729#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1730 } else {
1731 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1732 }
1733#else /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1734 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1735#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1736#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1737 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1738#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1739 } else if ((m_context->psk_pki_enabled & IS_PKI) ||
1740 (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1741 /*
1742 * If neither PSK or PKI have been set up, use PKI basics.
1743 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1744 */
1745 coap_dtls_pki_t *setup_data = &m_context->setup_data;
1746
1747 if (!(m_context->psk_pki_enabled & IS_PKI)) {
1748 /* PKI not defined - set up some defaults */
1749 setup_data->verify_peer_cert = 1;
1750 setup_data->check_common_ca = 0;
1751 setup_data->allow_self_signed = 1;
1752 setup_data->allow_expired_certs = 1;
1753 setup_data->cert_chain_validation = 1;
1754 setup_data->cert_chain_verify_depth = 2;
1755 setup_data->check_cert_revocation = 1;
1756 setup_data->allow_no_crl = 1;
1757 setup_data->allow_expired_crl = 1;
1758 setup_data->is_rpk_not_cert = 0;
1759 setup_data->use_cid = 0;
1760 }
1761 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1762 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1763 &m_env->private_key, m_env, m_context,
1764 c_session, setup_data,
1766 if (ret < 0) {
1767 coap_log_err("PKI setup failed\n");
1768 return ret;
1769 }
1770#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1771 if (c_session->proto == COAP_PROTO_TLS ||
1772 c_session->proto == COAP_PROTO_WSS) {
1773 static const char *alpn_list[] = { "coap", NULL };
1774
1775 ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1776 if (ret != 0) {
1777 coap_log_err("ALPN setup failed %d)\n", ret);
1778 }
1779 }
1780#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1781 mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1782#if defined(MBEDTLS_SSL_PROTO_DTLS)
1783#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1784 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1785#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1786#endif /* MBEDTLS_SSL_PROTO_DTLS */
1787 set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1788 }
1789 return 0;
1790
1791fail:
1792 return ret;
1793}
1794#endif /* COAP_CLIENT_SUPPORT */
1795
1796static void
1797mbedtls_cleanup(coap_mbedtls_env_t *m_env) {
1798 if (!m_env) {
1799 return;
1800 }
1801
1802 mbedtls_x509_crt_free(&m_env->cacert);
1803 mbedtls_x509_crt_free(&m_env->public_cert);
1804 mbedtls_pk_free(&m_env->private_key);
1805#if !COAP_USE_PSA_CRYPTO
1806 mbedtls_entropy_free(&m_env->entropy);
1807 mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1808#endif /* !COAP_USE_PSA_CRYPTO */
1809 mbedtls_ssl_config_free(&m_env->conf);
1810 mbedtls_ssl_free(&m_env->ssl);
1811 mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1812}
1813
1814static void
1815coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1816 if (m_env) {
1817 if (!m_env->sent_alert)
1818 mbedtls_ssl_close_notify(&m_env->ssl);
1819 mbedtls_cleanup(m_env);
1820 mbedtls_free(m_env);
1821 }
1822}
1823
1824#if COAP_MAX_LOGGING_LEVEL > 0
1825static const char *
1826report_mbedtls_alert(unsigned char alert) {
1827 switch (alert) {
1828 case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC:
1829 return ": Bad Record MAC";
1830 case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE:
1831 return ": Handshake failure";
1832 case MBEDTLS_SSL_ALERT_MSG_NO_CERT:
1833 return ": No Certificate provided";
1834 case MBEDTLS_SSL_ALERT_MSG_BAD_CERT:
1835 return ": Certificate is bad";
1836 case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN:
1837 return ": Certificate is unknown";
1838 case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA:
1839 return ": CA is unknown";
1840 case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED:
1841 return ": Access was denied";
1842 case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR:
1843 return ": Decrypt error";
1844 default:
1845 return "";
1846 }
1847}
1848#endif /* COAP_MAX_LOGGING_LEVEL */
1849
1850/*
1851 * return -1 failure
1852 * 0 not completed
1853 * 1 established
1854 */
1855static int
1856do_mbedtls_handshake(coap_session_t *c_session,
1857 coap_mbedtls_env_t *m_env) {
1858 int ret;
1859 int alert;
1860
1861 ret = mbedtls_ssl_handshake(&m_env->ssl);
1862 switch (ret) {
1863 case 0:
1864 m_env->established = 1;
1865 coap_log_debug("* %s: Mbed TLS established\n",
1866 coap_session_str(c_session));
1867 ret = 1;
1868#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1869#if COAP_CLIENT_SUPPORT
1870 if (c_session->type == COAP_SESSION_TYPE_CLIENT &&
1871 c_session->proto == COAP_PROTO_DTLS) {
1872 coap_mbedtls_context_t *m_context;
1873
1874 m_context = (coap_mbedtls_context_t *)c_session->context->dtls_context;
1875 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
1876 m_context->setup_data.use_cid) {
1877 unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
1878 int enabled;
1879 size_t peer_cid_len;
1880
1881 /* See whether CID was negotiated */
1882 if (mbedtls_ssl_get_peer_cid(&m_env->ssl, &enabled, peer_cid, &peer_cid_len) == 0 &&
1883 enabled == MBEDTLS_SSL_CID_ENABLED) {
1884 c_session->negotiated_cid = 1;
1885 } else {
1886 coap_log_info("** %s: CID was not negotiated\n", coap_session_str(c_session));
1887 c_session->negotiated_cid = 0;
1888 }
1889 }
1890 }
1891#endif /* COAP_CLIENT_SUPPORT */
1892#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1893 break;
1894 case MBEDTLS_ERR_SSL_WANT_READ:
1895 case MBEDTLS_ERR_SSL_WANT_WRITE:
1896 if (m_env->ssl.state == MBEDTLS_SSL_SERVER_HELLO
1897#if MBEDTLS_VERSION_NUMBER >= 0x03030000
1898 || m_env->ssl.state == MBEDTLS_SSL_NEW_SESSION_TICKET
1899#endif /* MBEDTLS_VERSION_NUMBER >= 0x03030000 */
1900 ) {
1901 if (++m_env->server_hello_cnt > 10) {
1902 /* retried this too many times */
1903 goto fail;
1904 }
1905 }
1906 errno = EAGAIN;
1907 ret = 0;
1908 break;
1909 case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1910 coap_log_debug("hello verification requested\n");
1911 goto reset;
1912 case MBEDTLS_ERR_SSL_INVALID_MAC:
1913 goto fail;
1914#ifdef MBEDTLS_2_X_COMPAT
1915 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
1916#else /* ! MBEDTLS_2_X_COMPAT */
1917 case MBEDTLS_ERR_SSL_DECODE_ERROR:
1918#endif /* ! MBEDTLS_2_X_COMPAT */
1919 goto fail;
1920 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1921 alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1922 goto fail_alert;
1923#ifdef MBEDTLS_2_X_COMPAT
1924 case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1925 case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1926 alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1927 goto fail_alert;
1928#endif /* MBEDTLS_2_X_COMPAT */
1929 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1930 goto fail;
1931 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1932 if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1933 coap_log_warn("***%s: Alert '%d'%s\n",
1934 coap_session_str(c_session), m_env->ssl.in_msg[1],
1935 report_mbedtls_alert(m_env->ssl.in_msg[1]));
1936 /* Fall through */
1937 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1938 case MBEDTLS_ERR_SSL_CONN_EOF:
1939 case MBEDTLS_ERR_NET_CONN_RESET:
1941 ret = -1;
1942 break;
1943 default:
1944 coap_log_warn("do_mbedtls_handshake: session establish "
1945 "returned -0x%x: '%s'\n",
1946 -ret, get_error_string(ret));
1947 ret = -1;
1948 break;
1949 }
1950 return ret;
1951
1952fail_alert:
1953 mbedtls_ssl_send_alert_message(&m_env->ssl,
1954 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1955 alert);
1956 m_env->sent_alert = 1;
1957fail:
1958 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1959 coap_log_warn("do_mbedtls_handshake: session establish "
1960 "returned '%s'\n",
1961 get_error_string(ret));
1962reset:
1963 mbedtls_ssl_session_reset(&m_env->ssl);
1964#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1965 if (m_env->ec_jpake) {
1966 const coap_bin_const_t *psk_key;
1967
1968#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
1969 if (c_session->type == COAP_SESSION_TYPE_CLIENT) {
1970 psk_key = coap_get_session_client_psk_key(c_session);
1971 } else {
1972 psk_key = coap_get_session_server_psk_key(c_session);
1973 }
1974#elif COAP_CLIENT_SUPPORT
1975 psk_key = coap_get_session_client_psk_key(c_session);
1976#else /* COAP_SERVER_SUPPORT */
1977 psk_key = coap_get_session_server_psk_key(c_session);
1978#endif /* COAP_SERVER_SUPPORT */
1979 if (psk_key) {
1980 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
1981 }
1982 }
1983#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1984 return -1;
1985}
1986
1987static void
1988mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1989 const char *file COAP_UNUSED,
1990 int line COAP_UNUSED, const char *str) {
1991
1992 coap_log_t coap_level = COAP_LOG_DEBUG;
1993 /*
1994 * 0 No debug
1995 * 1 Error
1996 * 2 State change
1997 * 3 Informational
1998 * 4 Verbose
1999 */
2000 switch (level) {
2001 case 0:
2002 coap_level = COAP_LOG_EMERG;
2003 break;
2004 case 1:
2005 coap_level = COAP_LOG_WARN;
2006 break;
2007 case 2:
2008 coap_level = COAP_LOG_NOTICE;
2009 break;
2010 case 3:
2011 coap_level = COAP_LOG_INFO;
2012 break;
2013 case 4:
2014 default:
2015 coap_level = COAP_LOG_DEBUG;
2016 break;
2017 }
2018 coap_dtls_log(coap_level, "%s", str);
2019}
2020
2021#if !COAP_DISABLE_TCP
2022/*
2023 * strm
2024 * return +ve data amount
2025 * 0 no more
2026 * -ve Mbed TLS error
2027 */
2028static int
2029coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
2030 int ret = MBEDTLS_ERR_SSL_CONN_EOF;
2031 coap_session_t *c_session = (coap_session_t *)ctx;
2032
2033 if (out != NULL) {
2034 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
2035 /* Translate layer returns into what MbedTLS expects */
2036 if (ret == -1) {
2037 if (errno == ECONNRESET) {
2038 /* graceful shutdown */
2039 ret = MBEDTLS_ERR_SSL_CONN_EOF;
2040 } else {
2041 ret = MBEDTLS_ERR_NET_RECV_FAILED;
2042 }
2043 } else if (ret == 0) {
2044 errno = EAGAIN;
2045 ret = MBEDTLS_ERR_SSL_WANT_READ;
2046 }
2047 }
2048 return ret;
2049}
2050
2051/*
2052 * strm
2053 * return +ve data amount
2054 * 0 no more
2055 * -ve Mbed TLS error
2056 */
2057static int
2058coap_sock_write(void *context, const unsigned char *in, size_t inl) {
2059 int ret = 0;
2060 coap_session_t *c_session = (coap_session_t *)context;
2061
2062 ret = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
2063 (const uint8_t *)in,
2064 inl);
2065 /* Translate layer what returns into what MbedTLS expects */
2066 if (ret < 0) {
2067 if ((c_session->state == COAP_SESSION_STATE_CSM ||
2068 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
2069 (errno == EPIPE || errno == ECONNRESET)) {
2070 /*
2071 * Need to handle a TCP timing window where an agent continues with
2072 * the sending of the next handshake or a CSM.
2073 * However, the peer does not like a certificate and so sends a
2074 * fatal alert and closes the TCP session.
2075 * The sending of the next handshake or CSM may get terminated because
2076 * of the closed TCP session, but there is still an outstanding alert
2077 * to be read in and reported on.
2078 * In this case, pretend that sending the info was fine so that the
2079 * alert can be read (which effectively is what happens with DTLS).
2080 */
2081 ret = inl;
2082 } else {
2083#ifdef _WIN32
2084 int lasterror = WSAGetLastError();
2085
2086 if (lasterror == WSAEWOULDBLOCK) {
2087 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2088 } else if (lasterror == WSAECONNRESET) {
2089 ret = MBEDTLS_ERR_NET_CONN_RESET;
2090 }
2091#else
2092 if (errno == EAGAIN || errno == EINTR) {
2093 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2094 } else if (errno == EPIPE || errno == ECONNRESET) {
2095 ret = MBEDTLS_ERR_NET_CONN_RESET;
2096 }
2097#endif
2098 else {
2099 ret = MBEDTLS_ERR_NET_SEND_FAILED;
2100 }
2101 coap_log_debug("* %s: failed to send %" PRIdS " bytes (%s) state %d\n",
2102 coap_session_str(c_session), inl, coap_socket_strerror(),
2103 c_session->state);
2104 }
2105 }
2106 if (ret == 0) {
2107 errno = EAGAIN;
2108 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
2109 }
2110 return ret;
2111}
2112#endif /* !COAP_DISABLE_TCP */
2113
2114static coap_mbedtls_env_t *
2115coap_dtls_new_mbedtls_env(coap_session_t *c_session,
2116 coap_dtls_role_t role,
2117 coap_proto_t proto) {
2118#if !COAP_USE_PSA_CRYPTO
2119 int ret = 0;
2120#endif /* !COAP_USE_PSA_CRYPTO */
2121 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2122
2123 if (m_env)
2124 return m_env;
2125
2126 m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
2127 if (!m_env) {
2128 return NULL;
2129 }
2130 memset(m_env, 0, sizeof(coap_mbedtls_env_t));
2131
2132 mbedtls_ssl_init(&m_env->ssl);
2133#if !COAP_USE_PSA_CRYPTO
2134 mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
2135 mbedtls_entropy_init(&m_env->entropy);
2136#endif /* !COAP_USE_PSA_CRYPTO */
2137 mbedtls_ssl_config_init(&m_env->conf);
2138
2139#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
2140 mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
2141#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
2142
2143#if !COAP_USE_PSA_CRYPTO
2144 if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
2145 mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
2146 if (ret != MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) {
2147 coap_log_info("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
2148 -ret, get_error_string(ret));
2149 goto fail;
2150 }
2151 coap_log_err("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
2152 -ret, get_error_string(ret));
2153 }
2154#endif /* !COAP_USE_PSA_CRYPTO */
2155
2156 if (role == COAP_DTLS_ROLE_CLIENT) {
2157#if COAP_CLIENT_SUPPORT
2158 if (setup_client_ssl_session(c_session, m_env) != 0) {
2159 goto fail;
2160 }
2161#else /* !COAP_CLIENT_SUPPORT */
2162 goto fail;
2163#endif /* !COAP_CLIENT_SUPPORT */
2164 } else if (role == COAP_DTLS_ROLE_SERVER) {
2165#if defined(MBEDTLS_SSL_SRV_C)
2166 if (setup_server_ssl_session(c_session, m_env) != 0) {
2167 goto fail;
2168 }
2169#else /* ! MBEDTLS_SSL_SRV_C */
2170 goto fail;
2171#endif /* ! MBEDTLS_SSL_SRV_C */
2172 } else {
2173 goto fail;
2174 }
2175
2176#if MBEDTLS_VERSION_NUMBER >= 0x03020000
2177 mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
2178#else
2179 mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
2180 MBEDTLS_SSL_MINOR_VERSION_3);
2181#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
2182
2183 if (mbedtls_ssl_setup(&m_env->ssl, &m_env->conf) != 0) {
2184 goto fail;
2185 }
2186 if (proto == COAP_PROTO_DTLS) {
2187 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
2188 coap_dgram_read, NULL);
2189#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2190 if (COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
2191 if (role == COAP_DTLS_ROLE_CLIENT) {
2192#if COAP_CLIENT_SUPPORT
2193 coap_mbedtls_context_t *m_context =
2194 (coap_mbedtls_context_t *)c_session->context->dtls_context;
2195
2196 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
2197 m_context->setup_data.use_cid) {
2198 /*
2199 * Enable passive DTLS CID support.
2200 *
2201 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
2202 * to use RFC9146 extension ID of 54, rather than the draft version -05
2203 * value of 254.
2204 */
2205 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, NULL, 0);
2206 }
2207#endif /* COAP_CLIENT_SUPPORT */
2208 } else {
2209#if COAP_SERVER_SUPPORT
2210 uint8_t cid[COAP_DTLS_CID_LENGTH];
2211 /*
2212 * Enable server DTLS CID support.
2213 *
2214 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
2215 * to use RFC9146 extension ID of 54, rather than the draft version -05
2216 * value of 254.
2217 */
2218 coap_prng_lkd(cid, sizeof(cid));
2219 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, cid,
2220 sizeof(cid));
2221 c_session->client_cid = coap_new_bin_const(cid, sizeof(cid));
2222#endif /* COAP_SERVER_SUPPORT */
2223 }
2224 }
2225#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2226 }
2227#if !COAP_DISABLE_TCP
2228 else {
2229 assert(proto == COAP_PROTO_TLS);
2230 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
2231 coap_sock_read, NULL);
2232 }
2233#endif /* ! COAP_DISABLE_TCP */
2234#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2235 coap_mbedtls_context_t *m_context =
2236 ((coap_mbedtls_context_t *)c_session->context->dtls_context);
2237 if ((m_context->psk_pki_enabled & IS_PSK) &&
2238 m_env->ec_jpake) {
2239 const coap_bin_const_t *psk_key;
2240
2241#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
2242 if (role == COAP_DTLS_ROLE_CLIENT) {
2243 psk_key = coap_get_session_client_psk_key(c_session);
2244 } else {
2245 psk_key = coap_get_session_server_psk_key(c_session);
2246 }
2247#elif COAP_CLIENT_SUPPORT
2248 psk_key = coap_get_session_client_psk_key(c_session);
2249#else /* COAP_SERVER_SUPPORT */
2250 psk_key = coap_get_session_server_psk_key(c_session);
2251#endif /* COAP_SERVER_SUPPORT */
2252 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
2253 }
2254#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2255#ifdef __ZEPHYR__
2256 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
2257 zephyr_timing_set_delay,
2258 zephyr_timing_get_delay);
2259#else
2260 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
2261 mbedtls_timing_set_delay,
2262 mbedtls_timing_get_delay);
2263#endif
2264
2265 mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
2266 return m_env;
2267
2268fail:
2269 if (m_env) {
2270 mbedtls_free(m_env);
2271 }
2272 return NULL;
2273}
2274
2275int
2277#if defined(MBEDTLS_SSL_PROTO_DTLS)
2278 return 1;
2279#else /* !MBEDTLS_SSL_PROTO_DTLS */
2280 static int reported = 0;
2281 if (!reported) {
2282 reported = 1;
2283 coap_log_emerg("libcoap not compiled for DTLS with Mbed TLS"
2284 " - update Mbed TLS to include DTLS\n");
2285 }
2286 return 0;
2287#endif /* !MBEDTLS_SSL_PROTO_DTLS */
2288}
2289
2290int
2292#if !COAP_DISABLE_TCP
2293 return 1;
2294#else /* COAP_DISABLE_TCP */
2295 return 0;
2296#endif /* COAP_DISABLE_TCP */
2297}
2298
2299/*
2300 * return 0 failed
2301 * 1 passed
2302 */
2303int
2305 return 1;
2306}
2307
2308/*
2309 * return 0 failed
2310 * 1 passed
2311 */
2312int
2314 return 1;
2315}
2316
2317/*
2318 * return 0 failed
2319 * 1 passed
2320 */
2321int
2323 return 0;
2324}
2325
2326/*
2327 * return 0 failed
2328 * 1 passed
2329 */
2330int
2332 return 0;
2333}
2334
2335/*
2336 * return 0 failed
2337 * 1 passed
2338 */
2339int
2341#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2342 return 1;
2343#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2344 return 0;
2345#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2346}
2347
2348#if COAP_CLIENT_SUPPORT
2349int
2350coap_dtls_set_cid_tuple_change(coap_context_t *c_context, uint8_t every) {
2351#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2352 c_context->testing_cids = every;
2353 return 1;
2354#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2355 (void)c_context;
2356 (void)every;
2357 return 0;
2358#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2359}
2360#endif /* COAP_CLIENT_SUPPORT */
2361
2362void *
2364 coap_mbedtls_context_t *m_context;
2365 (void)c_context;
2366
2367 m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
2368 if (m_context) {
2369 memset(m_context, 0, sizeof(coap_mbedtls_context_t));
2370 }
2371 return m_context;
2372}
2373
2374#if COAP_SERVER_SUPPORT
2375/*
2376 * return 0 failed
2377 * 1 passed
2378 */
2379int
2380coap_dtls_context_set_spsk(coap_context_t *c_context,
2381 coap_dtls_spsk_t *setup_data
2382 ) {
2383 coap_mbedtls_context_t *m_context =
2384 ((coap_mbedtls_context_t *)c_context->dtls_context);
2385
2386#if !defined(MBEDTLS_SSL_SRV_C)
2387 coap_log_emerg("coap_context_set_spsk:"
2388 " libcoap not compiled for Server Mode for Mbed TLS"
2389 " - update Mbed TLS to include Server Mode\n");
2390 return 0;
2391#endif /* !MBEDTLS_SSL_SRV_C */
2392 if (!m_context || !setup_data)
2393 return 0;
2394
2395 if (setup_data->ec_jpake) {
2396#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2397 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2398#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2399 }
2400 m_context->psk_pki_enabled |= IS_PSK;
2401 return 1;
2402}
2403#endif /* COAP_SERVER_SUPPORT */
2404
2405#if COAP_CLIENT_SUPPORT
2406/*
2407 * return 0 failed
2408 * 1 passed
2409 */
2410int
2411coap_dtls_context_set_cpsk(coap_context_t *c_context,
2412 coap_dtls_cpsk_t *setup_data
2413 ) {
2414#if !defined(MBEDTLS_SSL_CLI_C)
2415 (void)c_context;
2416 (void)setup_data;
2417
2418 coap_log_emerg("coap_context_set_cpsk:"
2419 " libcoap not compiled for Client Mode for Mbed TLS"
2420 " - update Mbed TLS to include Client Mode\n");
2421 return 0;
2422#else /* MBEDTLS_SSL_CLI_C */
2423 coap_mbedtls_context_t *m_context =
2424 ((coap_mbedtls_context_t *)c_context->dtls_context);
2425
2426 if (!m_context || !setup_data)
2427 return 0;
2428
2429 if (setup_data->validate_ih_call_back) {
2430 coap_log_warn("CoAP Client with Mbed TLS does not support Identity Hint selection\n");
2431 }
2432 if (setup_data->ec_jpake) {
2433#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2434 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2435#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2436 }
2437 if (setup_data->use_cid) {
2438#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2439 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2440#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2441 }
2442 m_context->psk_pki_enabled |= IS_PSK;
2443 return 1;
2444#endif /* MBEDTLS_SSL_CLI_C */
2445}
2446#endif /* COAP_CLIENT_SUPPORT */
2447
2448int
2450 const coap_dtls_pki_t *setup_data,
2451 const coap_dtls_role_t role COAP_UNUSED) {
2452 coap_mbedtls_context_t *m_context =
2453 ((coap_mbedtls_context_t *)c_context->dtls_context);
2454
2455 m_context->setup_data = *setup_data;
2456 if (!m_context->setup_data.verify_peer_cert) {
2457 /* Needs to be clear so that no CA DNs are transmitted */
2458 m_context->setup_data.check_common_ca = 0;
2459 /* Allow all of these but warn if issue */
2460 m_context->setup_data.allow_self_signed = 1;
2461 m_context->setup_data.allow_expired_certs = 1;
2462 m_context->setup_data.cert_chain_validation = 1;
2463 m_context->setup_data.cert_chain_verify_depth = 10;
2464 m_context->setup_data.check_cert_revocation = 1;
2465 m_context->setup_data.allow_no_crl = 1;
2466 m_context->setup_data.allow_expired_crl = 1;
2467 m_context->setup_data.allow_bad_md_hash = 1;
2468 m_context->setup_data.allow_short_rsa_length = 1;
2469 }
2470 m_context->psk_pki_enabled |= IS_PKI;
2471 if (setup_data->use_cid) {
2472#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2473 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2474#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2475 }
2476 return 1;
2477}
2478
2479int
2481 const char *ca_file,
2482 const char *ca_path) {
2483 coap_mbedtls_context_t *m_context =
2484 ((coap_mbedtls_context_t *)c_context->dtls_context);
2485
2486 if (!m_context) {
2487 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
2488 "not set up\n");
2489 return 0;
2490 }
2491
2492 if (ca_file == NULL && ca_path == NULL) {
2493 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
2494 "not defined\n");
2495 return 0;
2496 }
2497 if (m_context->root_ca_file) {
2498 mbedtls_free(m_context->root_ca_file);
2499 m_context->root_ca_file = NULL;
2500 }
2501
2502 if (ca_file) {
2503 m_context->root_ca_file = mbedtls_strdup(ca_file);
2504 }
2505
2506 if (m_context->root_ca_path) {
2507 mbedtls_free(m_context->root_ca_path);
2508 m_context->root_ca_path = NULL;
2509 }
2510
2511 if (ca_path) {
2512 m_context->root_ca_path = mbedtls_strdup(ca_path);
2513 }
2514 return 1;
2515}
2516
2517/*
2518 * return 0 failed
2519 * 1 passed
2520 */
2521int
2523 coap_mbedtls_context_t *m_context =
2524 ((coap_mbedtls_context_t *)c_context->dtls_context);
2525
2526 if (!m_context) {
2527 coap_log_warn("coap_context_load_pki_trust_store: (D)TLS environment "
2528 "not set up\n");
2529 return 0;
2530 }
2531 m_context->trust_store_defined = 1;
2532
2533 /* No proper support for this in MbedTLS at this point */
2534 return 1;
2535}
2536
2537
2538int
2540 coap_mbedtls_context_t *m_context =
2541 ((coap_mbedtls_context_t *)c_context->dtls_context);
2542 return m_context->psk_pki_enabled ? 1 : 0;
2543}
2544
2545void
2546coap_dtls_free_context(void *dtls_context) {
2547 coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
2548 unsigned int i;
2549
2550 for (i = 0; i < m_context->pki_sni_count; i++) {
2551 mbedtls_free(m_context->pki_sni_entry_list[i].sni);
2552
2553 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
2554
2555 mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
2556
2557 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
2558 }
2559 if (m_context->pki_sni_entry_list)
2560 mbedtls_free(m_context->pki_sni_entry_list);
2561
2562 for (i = 0; i < m_context->psk_sni_count; i++) {
2563 mbedtls_free(m_context->psk_sni_entry_list[i].sni);
2564 }
2565 if (m_context->psk_sni_entry_list)
2566 mbedtls_free(m_context->psk_sni_entry_list);
2567
2568 if (m_context->root_ca_path)
2569 mbedtls_free(m_context->root_ca_path);
2570 if (m_context->root_ca_file)
2571 mbedtls_free(m_context->root_ca_file);
2572
2573 mbedtls_free(m_context);
2574}
2575
2576#if COAP_CLIENT_SUPPORT
2577void *
2578coap_dtls_new_client_session(coap_session_t *c_session) {
2579#if !defined(MBEDTLS_SSL_CLI_C)
2580 (void)c_session;
2581 coap_log_emerg("coap_dtls_new_client_session:"
2582 " libcoap not compiled for Client Mode for Mbed TLS"
2583 " - update Mbed TLS to include Client Mode\n");
2584 return NULL;
2585#else /* MBEDTLS_SSL_CLI_C */
2586 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2589 int ret;
2590
2591 if (m_env) {
2592 coap_tick_t now;
2593
2594 coap_ticks(&now);
2595 m_env->last_timeout = now;
2596 ret = do_mbedtls_handshake(c_session, m_env);
2597 if (ret == -1) {
2598 coap_dtls_free_mbedtls_env(m_env);
2599 return NULL;
2600 }
2601 }
2602 return m_env;
2603#endif /* MBEDTLS_SSL_CLI_C */
2604}
2605#endif /* COAP_CLIENT_SUPPORT */
2606
2607#if COAP_SERVER_SUPPORT
2608void *
2609coap_dtls_new_server_session(coap_session_t *c_session) {
2610#if !defined(MBEDTLS_SSL_SRV_C)
2611 (void)c_session;
2612 coap_log_emerg("coap_dtls_new_server_session:"
2613 " libcoap not compiled for Server Mode for Mbed TLS"
2614 " - update Mbed TLS to include Server Mode\n");
2615 return NULL;
2616#else /* MBEDTLS_SSL_SRV_C */
2617 coap_mbedtls_env_t *m_env =
2618 (coap_mbedtls_env_t *)c_session->tls;
2619 if (m_env) {
2620#if defined(MBEDTLS_SSL_PROTO_DTLS)
2621#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2622 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2623#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2624#endif /* MBEDTLS_SSL_PROTO_DTLS */
2625 }
2626 return m_env;
2627#endif /* MBEDTLS_SSL_SRV_C */
2628}
2629#endif /* COAP_SERVER_SUPPORT */
2630
2631void
2633 if (c_session && c_session->context && c_session->tls) {
2634 coap_dtls_free_mbedtls_env(c_session->tls);
2635 c_session->tls = NULL;
2637 }
2638 return;
2639}
2640
2641void
2643#if defined(MBEDTLS_SSL_PROTO_DTLS)
2644 coap_mbedtls_env_t *m_env =
2645 (coap_mbedtls_env_t *)c_session->tls;
2646 if (m_env) {
2647#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2648 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2649#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2650 }
2651#else /* ! MBEDTLS_SSL_PROTO_DTLS */
2652 (void)c_session;
2653#endif /* MBEDTLS_SSL_PROTO_DTLS */
2654}
2655
2656ssize_t
2658 const uint8_t *data, size_t data_len) {
2659 int ret;
2660 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2661
2662 assert(m_env != NULL);
2663
2664 if (!m_env) {
2665 return -1;
2666 }
2667 c_session->dtls_event = -1;
2668 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2669 coap_session_str(c_session), (int)data_len);
2670 if (m_env->established) {
2671 ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char *) data, data_len);
2672 if (ret <= 0) {
2673 switch (ret) {
2674 case MBEDTLS_ERR_SSL_WANT_READ:
2675 case MBEDTLS_ERR_SSL_WANT_WRITE:
2676 ret = 0;
2677 break;
2678 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2680 ret = -1;
2681 break;
2682 default:
2683 coap_log_warn("coap_dtls_send: "
2684 "returned -0x%x: '%s'\n",
2685 -ret, get_error_string(ret));
2686 ret = -1;
2687 break;
2688 }
2689 if (ret == -1) {
2690 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2691 }
2692 }
2693 } else {
2694 ret = do_mbedtls_handshake(c_session, m_env);
2695 if (ret == 1) {
2696 /* Just connected, so send the data */
2697 return coap_dtls_send(c_session, data, data_len);
2698 }
2699 ret = -1;
2700 }
2701
2702 if (c_session->dtls_event >= 0) {
2703 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2704 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2705 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2706 ret = -1;
2707 }
2708 }
2709 return ret;
2710}
2711
2712int
2714 return 0;
2715}
2716
2718coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2719 return 0;
2720}
2721
2724 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2725#ifdef __ZEPHYR__
2726 int ret = zephyr_timing_get_delay(&m_env->timer);
2727#else
2728 int ret = mbedtls_timing_get_delay(&m_env->timer);
2729#endif
2730 unsigned int scalar = 1 << m_env->retry_scalar;
2731
2732 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2733 switch (ret) {
2734 case 0:
2735 /* int_ms has not timed out */
2736 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2737 /* Need to indicate remaining timeout time */
2738 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2739 }
2740 m_env->last_timeout = now;
2741 /* This may cause a minor extra delay */
2742 return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2743 case 1:
2744 /* int_ms has timed out, but not fin_ms */
2745 /*
2746 * Need to make sure that we do not do this too frequently
2747 */
2748 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2749 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2750 }
2751
2752 /* Reset for the next time */
2753 m_env->last_timeout = now;
2754 return now;
2755 case 2:
2756 /* fin_ms has timed out - timed out - one final try */
2757 return now;
2758 default:
2759 break;
2760 }
2761
2762 return 0;
2763}
2764
2765/*
2766 * return 1 timed out
2767 * 0 still timing out
2768 */
2769int
2771 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2772
2773 assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2774 m_env->retry_scalar++;
2775 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2776 (do_mbedtls_handshake(c_session, m_env) < 0)) {
2777 /* Too many retries */
2779 return 1;
2780 }
2781 return 0;
2782}
2783
2784/*
2785 * return +ve data amount
2786 * 0 no more
2787 * -1 error
2788 */
2789int
2791 const uint8_t *data,
2792 size_t data_len) {
2793 int ret = 1;
2794
2795 c_session->dtls_event = -1;
2796 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2797 coap_ssl_t *ssl_data;
2798
2799 assert(m_env != NULL);
2800
2801 ssl_data = &m_env->coap_ssl_data;
2802 if (ssl_data->pdu_len) {
2803 coap_log_err("** %s: Previous data not read %u bytes\n",
2804 coap_session_str(c_session), ssl_data->pdu_len);
2805 }
2806 ssl_data->pdu = data;
2807 ssl_data->pdu_len = (unsigned)data_len;
2808
2809 if (m_env->established) {
2810#if COAP_CONSTRAINED_STACK
2811 /* pdu can be protected by global_lock if needed */
2812 static uint8_t pdu[COAP_RXBUFFER_SIZE];
2813#else /* ! COAP_CONSTRAINED_STACK */
2814 uint8_t pdu[COAP_RXBUFFER_SIZE];
2815#endif /* ! COAP_CONSTRAINED_STACK */
2816
2817 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2819 c_session);
2820 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2821 }
2822
2823 ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2824 if (ret > 0) {
2825 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2826 coap_session_str(c_session), ret);
2827 ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2828 if (!c_session->tls) {
2829 /* Possible there was a DTLS error */
2830 ssl_data = NULL;
2831 }
2832 goto finish;
2833 }
2834 switch (ret) {
2835 case 0:
2836 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2837 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2839 break;
2840 case MBEDTLS_ERR_SSL_WANT_READ:
2841 break;
2842 default:
2843 coap_log_warn("coap_dtls_receive: "
2844 "returned -0x%x: '%s' (length %" PRIdS ")\n",
2845 -ret, get_error_string(ret), data_len);
2846 break;
2847 }
2848 ret = -1;
2849 } else {
2850 ret = do_mbedtls_handshake(c_session, m_env);
2851 if (ret == 1) {
2852 /* Just connected, so send the data */
2853 coap_session_connected(c_session);
2854 } else {
2855 if (ssl_data->pdu_len) {
2856 /* Do the handshake again incase of internal timeout */
2857 ret = do_mbedtls_handshake(c_session, m_env);
2858 if (ret == 1) {
2859 /* Just connected, so send the data */
2860 coap_session_connected(c_session);
2861 }
2862 }
2863 ret = -1;
2864 }
2865 }
2866 if (c_session->dtls_event >= 0) {
2867 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2868 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2869 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2871 ssl_data = NULL;
2872 ret = -1;
2873 }
2874 }
2875finish:
2876 if (ssl_data && ssl_data->pdu_len) {
2877 /* pdu data is held on stack which will not stay there */
2878 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2879 ssl_data->pdu_len = 0;
2880 ssl_data->pdu = NULL;
2881 }
2882 return ret;
2883}
2884
2885#if COAP_SERVER_SUPPORT
2886/*
2887 * return -1 failure
2888 * 0 not completed
2889 * 1 client hello seen
2890 */
2891int
2892coap_dtls_hello(coap_session_t *c_session,
2893 const uint8_t *data,
2894 size_t data_len) {
2895#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2896 (void)c_session;
2897 (void)data;
2898 (void)data_len;
2899 coap_log_emerg("coap_dtls_hello:"
2900 " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2901 " - update Mbed TLS to include DTLS and Server Mode\n");
2902 return -1;
2903#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2904 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2905 coap_ssl_t *ssl_data;
2906 int ret;
2907
2908 if (!m_env) {
2909 m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2911 if (m_env) {
2912 c_session->tls = m_env;
2913 } else {
2914 /* error should have already been reported */
2915 return -1;
2916 }
2917 }
2918
2919 if ((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2920 (unsigned char *)&c_session->addr_info.remote,
2921 sizeof(c_session->addr_info.remote))) != 0) {
2922 coap_log_err("mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2923 -ret, get_error_string(ret));
2924 return -1;
2925 }
2926
2927 ssl_data = &m_env->coap_ssl_data;
2928 if (ssl_data->pdu_len) {
2929 coap_log_err("** %s: Previous data not read %u bytes\n",
2930 coap_session_str(c_session), ssl_data->pdu_len);
2931 }
2932 ssl_data->pdu = data;
2933 ssl_data->pdu_len = (unsigned)data_len;
2934
2935 ret = do_mbedtls_handshake(c_session, m_env);
2936 if (ret == 0 || m_env->seen_client_hello) {
2937 /* The test for seen_client_hello gives the ability to setup a new
2938 c_session to continue the do_mbedtls_handshake past the client hello
2939 and safely allow updating of the m_env and separately
2940 letting a new session cleanly start up.
2941 */
2942 m_env->seen_client_hello = 0;
2943 ret = 1;
2944 } else {
2945 ret = 0;
2946 }
2947
2948 if (ssl_data->pdu_len) {
2949 /* pdu data is held on stack which will not stay there */
2950 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2951 ssl_data->pdu_len = 0;
2952 ssl_data->pdu = NULL;
2953 }
2954 return ret;
2955#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2956}
2957#endif /* COAP_SERVER_SUPPORT */
2958
2959unsigned int
2961 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2962 int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2963
2964 if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2965 return 13 + 8 + 8;
2966 }
2967 return expansion;
2968}
2969
2970#if !COAP_DISABLE_TCP
2971#if COAP_CLIENT_SUPPORT
2972void *
2973coap_tls_new_client_session(coap_session_t *c_session) {
2974#if !defined(MBEDTLS_SSL_CLI_C)
2975 (void)c_session;
2976 *connected = 0;
2977 coap_log_emerg("coap_tls_new_client_session:"
2978 " libcoap not compiled for Client Mode for Mbed TLS"
2979 " - update Mbed TLS to include Client Mode\n");
2980 return NULL;
2981#else /* MBEDTLS_SSL_CLI_C */
2982 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2985 int ret;
2986 coap_tick_t now;
2987 coap_ticks(&now);
2988
2989 if (!m_env)
2990 return NULL;
2991
2992 m_env->last_timeout = now;
2993 c_session->tls = m_env;
2994 ret = do_mbedtls_handshake(c_session, m_env);
2995 if (ret == 1) {
2997 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2998 }
2999 return m_env;
3000#endif /* MBEDTLS_SSL_CLI_C */
3001}
3002#endif /* COAP_CLIENT_SUPPORT */
3003
3004#if COAP_SERVER_SUPPORT
3005void *
3006coap_tls_new_server_session(coap_session_t *c_session) {
3007#if !defined(MBEDTLS_SSL_SRV_C)
3008 (void)c_session;
3009 (void)connected;
3010
3011 coap_log_emerg("coap_tls_new_server_session:"
3012 " libcoap not compiled for Server Mode for Mbed TLS"
3013 " - update Mbed TLS to include Server Mode\n");
3014 return NULL;
3015#else /* MBEDTLS_SSL_SRV_C */
3016 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
3019 int ret;
3020
3021 if (!m_env)
3022 return NULL;
3023
3024 c_session->tls = m_env;
3025 ret = do_mbedtls_handshake(c_session, m_env);
3026 if (ret == 1) {
3028 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
3029 }
3030 return m_env;
3031#endif /* MBEDTLS_SSL_SRV_C */
3032}
3033#endif /* COAP_SERVER_SUPPORT */
3034
3035void
3037 coap_dtls_free_session(c_session);
3038 return;
3039}
3040
3041/*
3042 * strm
3043 * return +ve Number of bytes written.
3044 * -1 Error (error in errno).
3045 */
3046ssize_t
3047coap_tls_write(coap_session_t *c_session, const uint8_t *data,
3048 size_t data_len) {
3049 int ret = 0;
3050 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
3051 size_t amount_sent = 0;
3052
3053 assert(m_env != NULL);
3054
3055 if (!m_env) {
3056 errno = ENXIO;
3057 return -1;
3058 }
3059 c_session->dtls_event = -1;
3060 if (m_env->established) {
3061 while (amount_sent < data_len) {
3062 ret = mbedtls_ssl_write(&m_env->ssl, &data[amount_sent],
3063 data_len - amount_sent);
3064 if (ret <= 0) {
3065 switch (ret) {
3066 case MBEDTLS_ERR_SSL_WANT_READ:
3067 case MBEDTLS_ERR_SSL_WANT_WRITE:
3068 if (amount_sent)
3069 ret = amount_sent;
3070 else
3071 ret = 0;
3072 c_session->sock.flags |= COAP_SOCKET_WANT_WRITE;
3073 break;
3074 case MBEDTLS_ERR_NET_CONN_RESET:
3075 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
3077 break;
3078 default:
3079 coap_log_warn("coap_tls_write: "
3080 "returned -0x%x: '%s'\n",
3081 -ret, get_error_string(ret));
3082 ret = -1;
3083 break;
3084 }
3085 if (ret == -1) {
3086 coap_log_warn("coap_tls_write: cannot send PDU\n");
3087 }
3088 break;
3089 }
3090 amount_sent += ret;
3091 }
3092 } else {
3093 ret = do_mbedtls_handshake(c_session, m_env);
3094 if (ret == 1) {
3096 c_session);
3097 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
3098 } else {
3099 ret = -1;
3100 }
3101 }
3102
3103 if (c_session->dtls_event >= 0) {
3104 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
3105 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
3106 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
3107 ret = -1;
3108 }
3109 }
3110 if (ret > 0) {
3111 if (ret == (ssize_t)data_len)
3112 coap_log_debug("* %s: tls: sent %4d bytes\n",
3113 coap_session_str(c_session), ret);
3114 else
3115 coap_log_debug("* %s: tls: sent %4d of %4" PRIdS " bytes\n",
3116 coap_session_str(c_session), ret, data_len);
3117 }
3118 return ret;
3119}
3120
3121/*
3122 * strm
3123 * return >=0 Number of bytes read.
3124 * -1 Error (error in errno).
3125 */
3126ssize_t
3127coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
3128 int ret = -1;
3129
3130 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
3131
3132 if (!m_env) {
3133 errno = ENXIO;
3134 return -1;
3135 }
3136
3137 c_session->dtls_event = -1;
3138
3139 if (!m_env->established && !m_env->sent_alert) {
3140 ret = do_mbedtls_handshake(c_session, m_env);
3141 if (ret == 1) {
3143 c_session);
3144 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
3145 }
3146 }
3147
3148 if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
3149 ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
3150 if (ret <= 0) {
3151 switch (ret) {
3152 case 0:
3153 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
3155 ret = -1;
3156 break;
3157 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
3158 /* Stop the sending of an alert on closedown */
3159 m_env->sent_alert = 1;
3161 break;
3162#if MBEDTLS_VERSION_NUMBER >= 0x03060000
3163 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
3164#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
3165 case MBEDTLS_ERR_SSL_WANT_READ:
3166 errno = EAGAIN;
3167 ret = 0;
3168 break;
3169 default:
3170 coap_log_warn("coap_tls_read: "
3171 "returned -0x%x: '%s' (length %" PRIdS ")\n",
3172 -ret, get_error_string(ret), data_len);
3173 ret = -1;
3174 break;
3175 }
3176 } else if (ret < (int)data_len) {
3177 c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
3178 }
3179 }
3180
3181 if (c_session->dtls_event >= 0) {
3182 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
3183 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
3184 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
3186 ret = -1;
3187 }
3188 }
3189 if (ret > 0) {
3190 coap_log_debug("* %s: tls: recv %4d bytes\n",
3191 coap_session_str(c_session), ret);
3192 }
3193 return ret;
3194}
3195#endif /* !COAP_DISABLE_TCP */
3196
3197void
3198coap_dtls_startup(void) {
3199#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
3200 psa_crypto_init();
3201#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
3202}
3203
3204void
3205coap_dtls_shutdown(void) {
3206#if COAP_CLIENT_SUPPORT
3207 mbedtls_free(psk_ciphers);
3208 mbedtls_free(pki_ciphers);
3209 mbedtls_free(ecjpake_ciphers);
3210 psk_ciphers = NULL;
3211 pki_ciphers = NULL;
3212 ecjpake_ciphers = NULL;
3213 processed_ciphers = 0;
3214#endif /* COAP_CLIENT_SUPPORT */
3216#if COAP_USE_PSA_CRYPTO || defined(MBEDTLS_PSA_CRYPTO_C)
3217 mbedtls_psa_crypto_free();
3218#endif /* COAP_USE_PSA_CRYPTO || MBEDTLS_PSA_CRYPTO_C */
3219}
3220
3221
3222void *
3223coap_dtls_get_tls(const coap_session_t *c_session,
3224 coap_tls_library_t *tls_lib) {
3225 if (tls_lib)
3226 *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
3227 if (c_session && c_session->tls) {
3228 coap_mbedtls_env_t *m_env;
3229
3230 /* To get around const issue */
3231 memcpy(&m_env, &c_session->tls, sizeof(m_env));
3232
3233 return (void *)&m_env->ssl;
3234 }
3235 return NULL;
3236}
3237
3238static coap_log_t keep_log_level = COAP_LOG_EMERG;
3239
3240void
3242#if !defined(ESPIDF_VERSION)
3243 int use_level;
3244 /*
3245 * Mbed TLS debug levels filter
3246 * 0 No debug
3247 * 1 Error
3248 * 2 State change
3249 * 3 Informational
3250 * 4 Verbose
3251 */
3252 switch ((int)level) {
3253 case COAP_LOG_EMERG:
3254 use_level = 0;
3255 break;
3256 case COAP_LOG_ALERT:
3257 case COAP_LOG_CRIT:
3258 case COAP_LOG_ERR:
3259 case COAP_LOG_WARN:
3260 use_level = 1;
3261 break;
3262 case COAP_LOG_NOTICE:
3263 use_level = 2;
3264 break;
3265 case COAP_LOG_INFO:
3266 use_level = 3;
3267 break;
3268 case COAP_LOG_DEBUG:
3269 default:
3270 use_level = 4;
3271 break;
3272 }
3273 mbedtls_debug_set_threshold(use_level);
3274#endif /* !ESPIDF_VERSION) */
3275 keep_log_level = level;
3276}
3277
3280 return keep_log_level;
3281}
3282
3283#endif /* COAP_WITH_LIBMBEDTLS */
3284
3285#if COAP_WITH_LIBMBEDTLS || COAP_WITH_LIBMBEDTLS_OSCORE
3286
3287#if COAP_SERVER_SUPPORT
3288coap_digest_ctx_t *
3289coap_digest_setup(void) {
3290 coap_crypto_sha256_ctx_t *digest_ctx = mbedtls_malloc(sizeof(coap_crypto_sha256_ctx_t));
3291
3292 if (digest_ctx) {
3293 if (coap_crypto_sha256_init(digest_ctx) != 0) {
3294 coap_digest_free(digest_ctx);
3295 return NULL;
3296 }
3297 }
3298 return digest_ctx;
3299}
3300
3301void
3302coap_digest_free(coap_digest_ctx_t *digest_ctx) {
3303 if (digest_ctx) {
3304 coap_crypto_sha256_free(digest_ctx);
3305 mbedtls_free(digest_ctx);
3306 }
3307}
3308
3309int
3310coap_digest_update(coap_digest_ctx_t *digest_ctx,
3311 const uint8_t *data,
3312 size_t data_len) {
3313 return coap_crypto_sha256_update(digest_ctx, data, data_len) == 0;
3314}
3315
3316int
3317coap_digest_final(coap_digest_ctx_t *digest_ctx,
3318 coap_digest_t *digest_buffer) {
3319 int ret = coap_crypto_sha256_finish(digest_ctx, (uint8_t *)digest_buffer) == 0;
3320 coap_digest_free(digest_ctx);
3321 return ret;
3322}
3323#endif /* COAP_SERVER_SUPPORT */
3324
3325#if COAP_WS_SUPPORT
3326int
3328 const coap_bin_const_t *data,
3329 coap_bin_const_t **hash) {
3330 coap_crypto_md_type_t md_type;
3331 size_t hash_len;
3332
3333 switch ((int)alg) {
3335 md_type = COAP_CRYPTO_MD_SHA1;
3336 break;
3338 md_type = COAP_CRYPTO_MD_SHA256;
3339 break;
3341 md_type = COAP_CRYPTO_MD_SHA512;
3342 break;
3343 default:
3344 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3345 return 0;
3346 }
3347
3348 hash_len = coap_crypto_hash_size(md_type);
3349 if (hash_len == 0)
3350 return 0;
3351
3352 coap_binary_t *dummy = coap_new_binary(hash_len);
3353 if (dummy == NULL)
3354 return 0;
3355
3356 if (coap_crypto_hash_compute(md_type, data->s, data->length,
3357 dummy->s, hash_len, NULL) != 0) {
3359 return 0;
3360 }
3361
3362 *hash = (coap_bin_const_t *)dummy;
3363 return 1;
3364}
3365#endif /* COAP_WS_SUPPORT */
3366
3367/* HMAC Functions */
3368
3369#if COAP_OSCORE_SUPPORT
3370static int
3371coap_crypto_hmac_compute(coap_crypto_md_type_t md_type,
3372 const uint8_t *key, size_t key_len,
3373 const uint8_t *input, size_t ilen,
3374 uint8_t *output, size_t output_size,
3375 size_t *output_len) {
3376#if COAP_USE_PSA_CRYPTO
3377 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3378 psa_key_id_t key_id;
3379 psa_algorithm_t psa_alg = PSA_ALG_HMAC(md_type);
3380 size_t mac_len;
3381 psa_status_t status;
3382
3383 psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
3384 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
3385 psa_set_key_algorithm(&attributes, psa_alg);
3386
3387 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3388 return -1;
3389 }
3390
3391 status = psa_mac_compute(key_id, psa_alg, input, ilen,
3392 output, output_size, &mac_len);
3393 psa_destroy_key(key_id);
3394
3395 if (output_len)
3396 *output_len = mac_len;
3397 return (status == PSA_SUCCESS) ? 0 : -1;
3398#else
3399 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
3400 if (!md_info)
3401 return -1;
3402 size_t mac_size = mbedtls_md_get_size(md_info);
3403 if (mac_size > output_size)
3404 return -1;
3405 if (output_len)
3406 *output_len = mac_size;
3407 return mbedtls_md_hmac(md_info, key, key_len, input, ilen, output);
3408#endif
3409}
3410
3411/* AEAD (AES-CCM) Functions */
3412
3413static int
3414coap_crypto_aead_encrypt_ccm(const uint8_t *key, size_t key_len,
3415 const uint8_t *nonce, size_t nonce_len,
3416 const uint8_t *aad, size_t aad_len,
3417 const uint8_t *plaintext, size_t plaintext_len,
3418 uint8_t *ciphertext, size_t ciphertext_size,
3419 size_t *ciphertext_len, size_t tag_len) {
3420#if COAP_USE_PSA_CRYPTO
3421 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3422 psa_key_id_t key_id;
3423 psa_algorithm_t psa_alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_len);
3424 size_t output_len;
3425 psa_status_t status;
3426
3427 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
3428 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
3429 psa_set_key_algorithm(&attributes, psa_alg);
3430 psa_set_key_bits(&attributes, key_len * 8);
3431
3432 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3433 return -1;
3434 }
3435
3436 status = psa_aead_encrypt(key_id, psa_alg,
3437 nonce, nonce_len,
3438 aad, aad_len,
3439 plaintext, plaintext_len,
3440 ciphertext, ciphertext_size, &output_len);
3441 psa_destroy_key(key_id);
3442
3443 if (ciphertext_len)
3444 *ciphertext_len = output_len;
3445 return (status == PSA_SUCCESS) ? 0 : -1;
3446#else
3447 mbedtls_cipher_context_t ctx;
3448 const mbedtls_cipher_info_t *cipher_info;
3449 mbedtls_cipher_type_t cipher_type;
3450 int ret = -1;
3451 size_t result_len = ciphertext_size;
3452
3453 if (key_len == 16) {
3454 cipher_type = MBEDTLS_CIPHER_AES_128_CCM;
3455 } else if (key_len == 32) {
3456 cipher_type = MBEDTLS_CIPHER_AES_256_CCM;
3457 } else {
3458 return -1;
3459 }
3460
3461 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
3462 if (!cipher_info)
3463 return -1;
3464
3465 mbedtls_cipher_init(&ctx);
3466 if (mbedtls_cipher_setup(&ctx, cipher_info) != 0)
3467 goto cleanup;
3468 if (mbedtls_cipher_setkey(&ctx, key, key_len * 8, MBEDTLS_ENCRYPT) != 0)
3469 goto cleanup;
3470
3471#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3472 {
3473 unsigned char tag[16];
3474 if (mbedtls_cipher_auth_encrypt(&ctx,
3475 nonce, nonce_len,
3476 aad, aad_len,
3477 plaintext, plaintext_len,
3478 ciphertext, &result_len,
3479 tag, tag_len) != 0) {
3480 goto cleanup;
3481 }
3482 if ((result_len + tag_len) > ciphertext_size)
3483 goto cleanup;
3484 memcpy(ciphertext + result_len, tag, tag_len);
3485 result_len += tag_len;
3486 }
3487#else
3488 if (mbedtls_cipher_auth_encrypt_ext(&ctx,
3489 nonce, nonce_len,
3490 aad, aad_len,
3491 plaintext, plaintext_len,
3492 ciphertext, ciphertext_size,
3493 &result_len, tag_len) != 0) {
3494 goto cleanup;
3495 }
3496#endif
3497
3498 if (ciphertext_len)
3499 *ciphertext_len = result_len;
3500 ret = 0;
3501
3502cleanup:
3503 mbedtls_cipher_free(&ctx);
3504 return ret;
3505#endif
3506}
3507
3508static int
3509coap_crypto_aead_decrypt_ccm(const uint8_t *key, size_t key_len,
3510 const uint8_t *nonce, size_t nonce_len,
3511 const uint8_t *aad, size_t aad_len,
3512 const uint8_t *ciphertext, size_t ciphertext_len,
3513 uint8_t *plaintext, size_t plaintext_size,
3514 size_t *plaintext_len, size_t tag_len) {
3515#if COAP_USE_PSA_CRYPTO
3516 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3517 psa_key_id_t key_id;
3518 psa_algorithm_t psa_alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, tag_len);
3519 size_t output_len;
3520 psa_status_t status;
3521
3522 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
3523 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
3524 psa_set_key_algorithm(&attributes, psa_alg);
3525 psa_set_key_bits(&attributes, key_len * 8);
3526
3527 if (psa_import_key(&attributes, key, key_len, &key_id) != PSA_SUCCESS) {
3528 return -1;
3529 }
3530
3531 status = psa_aead_decrypt(key_id, psa_alg,
3532 nonce, nonce_len,
3533 aad, aad_len,
3534 ciphertext, ciphertext_len,
3535 plaintext, plaintext_size, &output_len);
3536 psa_destroy_key(key_id);
3537
3538 if (plaintext_len)
3539 *plaintext_len = output_len;
3540 return (status == PSA_SUCCESS) ? 0 : -1;
3541#else
3542 mbedtls_cipher_context_t ctx;
3543 const mbedtls_cipher_info_t *cipher_info;
3544 mbedtls_cipher_type_t cipher_type;
3545 int ret = -1;
3546 size_t result_len = plaintext_size;
3547
3548 if (key_len == 16) {
3549 cipher_type = MBEDTLS_CIPHER_AES_128_CCM;
3550 } else if (key_len == 32) {
3551 cipher_type = MBEDTLS_CIPHER_AES_256_CCM;
3552 } else {
3553 return -1;
3554 }
3555
3556 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
3557 if (!cipher_info)
3558 return -1;
3559
3560 mbedtls_cipher_init(&ctx);
3561 if (mbedtls_cipher_setup(&ctx, cipher_info) != 0)
3562 goto cleanup;
3563 if (mbedtls_cipher_setkey(&ctx, key, key_len * 8, MBEDTLS_DECRYPT) != 0)
3564 goto cleanup;
3565
3566#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3567 {
3568 const unsigned char *tag = ciphertext + ciphertext_len - tag_len;
3569 if (mbedtls_cipher_auth_decrypt(&ctx,
3570 nonce, nonce_len,
3571 aad, aad_len,
3572 ciphertext, ciphertext_len - tag_len,
3573 plaintext, &result_len,
3574 tag, tag_len) != 0) {
3575 goto cleanup;
3576 }
3577 }
3578#else
3579 if (mbedtls_cipher_auth_decrypt_ext(&ctx,
3580 nonce, nonce_len,
3581 aad, aad_len,
3582 ciphertext, ciphertext_len,
3583 plaintext, plaintext_size,
3584 &result_len, tag_len) != 0) {
3585 goto cleanup;
3586 }
3587#endif
3588
3589 if (plaintext_len)
3590 *plaintext_len = result_len;
3591 ret = 0;
3592
3593cleanup:
3594 mbedtls_cipher_free(&ctx);
3595 return ret;
3596#endif
3597}
3598
3599/* End of Crypto Abstraction Functions */
3600
3601int
3603 return 1;
3604}
3605
3606/*
3607 * Helper to check if COSE cipher algorithm is supported and get key size.
3608 */
3609static int
3610get_cipher_key_size(cose_alg_t alg, size_t *key_size) {
3611 switch ((int)alg) {
3613 if (key_size)
3614 *key_size = 16;
3615 return 1;
3617 if (key_size)
3618 *key_size = 32;
3619 return 1;
3620 default:
3621 coap_log_debug("get_cipher_key_size: COSE cipher %d not supported\n", alg);
3622 return 0;
3623 }
3624}
3625
3626/*
3627 * Helper to get HMAC algorithm parameters from COSE HMAC algorithm.
3628 */
3629static int
3630get_hmac_params(cose_hmac_alg_t hmac_alg,
3631 coap_crypto_md_type_t *md_type,
3632 size_t *mac_len) {
3633 switch ((int)hmac_alg) {
3635 if (md_type)
3636 *md_type = COAP_CRYPTO_MD_SHA256;
3637 if (mac_len)
3638 *mac_len = 32;
3639 return 1;
3641 if (md_type)
3642 *md_type = COAP_CRYPTO_MD_SHA384;
3643 if (mac_len)
3644 *mac_len = 48;
3645 return 1;
3647 if (md_type)
3648 *md_type = COAP_CRYPTO_MD_SHA512;
3649 if (mac_len)
3650 *mac_len = 64;
3651 return 1;
3652 default:
3653 coap_log_debug("get_hmac_params: COSE HMAC %d not supported\n", hmac_alg);
3654 return 0;
3655 }
3656}
3657
3658int
3660 return get_cipher_key_size(alg, NULL);
3661}
3662
3663int
3665 cose_hmac_alg_t hmac_alg;
3666
3667 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3668 return 0;
3669 return get_hmac_params(hmac_alg, NULL, NULL);
3670}
3671
3672int
3674 coap_bin_const_t *data,
3675 coap_bin_const_t *aad,
3676 uint8_t *result,
3677 size_t *max_result_len) {
3678 const coap_crypto_aes_ccm_t *ccm;
3679
3680 if (data == NULL)
3681 return 0;
3682
3683 assert(params != NULL);
3684
3685 if (!params) {
3686 return 0;
3687 }
3688
3689 if (!get_cipher_key_size(params->alg, NULL)) {
3690 coap_log_debug("coap_crypto_aead_encrypt: algorithm %d not supported\n",
3691 params->alg);
3692 return 0;
3693 }
3694
3695 ccm = &params->params.aes;
3696
3697 if (coap_crypto_aead_encrypt_ccm(ccm->key.s, ccm->key.length,
3698 ccm->nonce, 15 - ccm->l,
3699 aad ? aad->s : NULL, aad ? aad->length : 0,
3700 data->s, data->length,
3701 result, *max_result_len, max_result_len,
3702 ccm->tag_len) != 0) {
3703 coap_log_debug("coap_crypto_aead_encrypt: encryption failed\n");
3704 return 0;
3705 }
3706
3707 return 1;
3708}
3709
3710int
3712 coap_bin_const_t *data,
3713 coap_bin_const_t *aad,
3714 uint8_t *result,
3715 size_t *max_result_len) {
3716 const coap_crypto_aes_ccm_t *ccm;
3717
3718 if (data == NULL)
3719 return 0;
3720
3721 assert(params != NULL);
3722
3723 if (!params) {
3724 return 0;
3725 }
3726
3727 if (!get_cipher_key_size(params->alg, NULL)) {
3728 coap_log_debug("coap_crypto_aead_decrypt: algorithm %d not supported\n",
3729 params->alg);
3730 return 0;
3731 }
3732
3733 ccm = &params->params.aes;
3734
3735 if (data->length < ccm->tag_len) {
3736 coap_log_err("coap_decrypt: invalid tag length\n");
3737 return 0;
3738 }
3739
3740 if (coap_crypto_aead_decrypt_ccm(ccm->key.s, ccm->key.length,
3741 ccm->nonce, 15 - ccm->l,
3742 aad ? aad->s : NULL, aad ? aad->length : 0,
3743 data->s, data->length,
3744 result, *max_result_len, max_result_len,
3745 ccm->tag_len) != 0) {
3746 coap_log_debug("coap_crypto_aead_decrypt: decryption failed\n");
3747 return 0;
3748 }
3749
3750 return 1;
3751}
3752
3753int
3755 coap_bin_const_t *key,
3756 coap_bin_const_t *data,
3757 coap_bin_const_t **hmac) {
3758 coap_crypto_md_type_t md_type;
3759 size_t mac_len;
3761
3762 assert(key);
3763 assert(data);
3764 assert(hmac);
3765
3766 if (!get_hmac_params(hmac_alg, &md_type, &mac_len)) {
3767 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3768 return 0;
3769 }
3770
3771 dummy = coap_new_binary(mac_len);
3772 if (dummy == NULL)
3773 return 0;
3774
3775 if (coap_crypto_hmac_compute(md_type, key->s, key->length,
3776 data->s, data->length,
3777 dummy->s, mac_len, NULL) != 0) {
3778 coap_log_debug("coap_crypto_hmac: computation failed\n");
3780 return 0;
3781 }
3782
3783 *hmac = (coap_bin_const_t *)dummy;
3784 return 1;
3785}
3786
3787#endif /* COAP_OSCORE_SUPPORT */
3788
3789#else /* ! COAP_WITH_LIBMBEDTLS && ! COAP_WITH_LIBMBEDTLS_OSCORE*/
3790
3791#ifdef __clang__
3792/* Make compilers happy that do not like empty modules. As this function is
3793 * never used, we ignore -Wunused-function at the end of compiling this file
3794 */
3795#pragma GCC diagnostic ignored "-Wunused-function"
3796#endif
3797static inline void
3798dummy(void) {
3799}
3800
3801#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::@333167206175014220336146062237255042022130316354 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::@277120043107012316223314156332370064264045135231 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