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