libcoap 4.3.4-develop-758a341
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-2024 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
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
35#include "coap3/coap_internal.h"
36
37#ifdef COAP_WITH_LIBMBEDTLS
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/entropy.h>
69#include <mbedtls/ctr_drbg.h>
70#include <mbedtls/error.h>
71#include <mbedtls/timing.h>
72#include <mbedtls/ssl_cookie.h>
73#include <mbedtls/oid.h>
74#include <mbedtls/debug.h>
75#include <mbedtls/sha256.h>
76#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
77#include <mbedtls/esp_debug.h>
78#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
79#if defined(MBEDTLS_PSA_CRYPTO_C)
80#include <psa/crypto.h>
81#endif /* MBEDTLS_PSA_CRYPTO_C */
82
83#define mbedtls_malloc(a) malloc(a)
84#define mbedtls_realloc(a,b) realloc(a,b)
85#define mbedtls_strdup(a) strdup(a)
86#define mbedtls_strndup(a,b) strndup(a,b)
87
88#ifndef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
89/* definition changed in later mbedtls code versions */
90#ifdef MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED
91#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
92#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
93#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
94
95#if ! COAP_SERVER_SUPPORT
96#undef MBEDTLS_SSL_SRV_C
97#endif /* ! COAP_SERVER_SUPPORT */
98#if ! COAP_CLIENT_SUPPORT
99#undef MBEDTLS_SSL_CLI_C
100#endif /* ! COAP_CLIENT_SUPPORT */
101
102#ifdef _WIN32
103#define strcasecmp _stricmp
104#endif
105
106#define IS_PSK (1 << 0)
107#define IS_PKI (1 << 1)
108#define IS_CLIENT (1 << 6)
109#define IS_SERVER (1 << 7)
110
111typedef struct coap_ssl_t {
112 const uint8_t *pdu;
113 unsigned pdu_len;
114 unsigned peekmode;
115} coap_ssl_t;
116
117/*
118 * This structure encapsulates the Mbed TLS session object.
119 * It handles both TLS and DTLS.
120 * c_session->tls points to this.
121 */
122typedef struct coap_mbedtls_env_t {
123 mbedtls_ssl_context ssl;
124 mbedtls_entropy_context entropy;
125 mbedtls_ctr_drbg_context ctr_drbg;
126 mbedtls_ssl_config conf;
127 mbedtls_timing_delay_context timer;
128 mbedtls_x509_crt cacert;
129 mbedtls_x509_crt public_cert;
130 mbedtls_pk_context private_key;
131 mbedtls_ssl_cookie_ctx cookie_ctx;
132 /* If not set, need to do do_mbedtls_handshake */
133 int established;
134 int sent_alert;
135 int seen_client_hello;
136 coap_tick_t last_timeout;
137 unsigned int retry_scalar;
138 coap_ssl_t coap_ssl_data;
139} coap_mbedtls_env_t;
140
141typedef struct pki_sni_entry {
142 char *sni;
143 coap_dtls_key_t pki_key;
144 mbedtls_x509_crt cacert;
145 mbedtls_x509_crt public_cert;
146 mbedtls_pk_context private_key;
147} pki_sni_entry;
148
149typedef struct psk_sni_entry {
150 char *sni;
151 coap_dtls_spsk_info_t psk_info;
152} psk_sni_entry;
153
154typedef struct coap_mbedtls_context_t {
155 coap_dtls_pki_t setup_data;
156 size_t pki_sni_count;
157 pki_sni_entry *pki_sni_entry_list;
158 size_t psk_sni_count;
159 psk_sni_entry *psk_sni_entry_list;
160 char *root_ca_file;
161 char *root_ca_path;
162 int psk_pki_enabled;
163} coap_mbedtls_context_t;
164
165typedef enum coap_enc_method_t {
166 COAP_ENC_PSK,
167 COAP_ENC_PKI,
168} coap_enc_method_t;
169
170#ifndef MBEDTLS_2_X_COMPAT
171/*
172 * mbedtls_ callback functions expect 0 on success, -ve on failure.
173 */
174static int
175coap_rng(void *ctx COAP_UNUSED, unsigned char *buf, size_t len) {
176 return coap_prng(buf, len) ? 0 : MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED;
177}
178#endif /* MBEDTLS_2_X_COMPAT */
179
180static int
181coap_dgram_read(void *ctx, unsigned char *out, size_t outl) {
182 ssize_t ret = 0;
183 coap_session_t *c_session = (coap_session_t *)ctx;
184 coap_ssl_t *data;
185
186 if (!c_session->tls) {
187 errno = EAGAIN;
188 return MBEDTLS_ERR_SSL_WANT_READ;
189 }
190 data = &((coap_mbedtls_env_t *)c_session->tls)->coap_ssl_data;
191
192 if (out != NULL) {
193 if (data->pdu_len > 0) {
194 if (outl < data->pdu_len) {
195 memcpy(out, data->pdu, outl);
196 ret = outl;
197 data->pdu += outl;
198 data->pdu_len -= outl;
199 } else {
200 memcpy(out, data->pdu, data->pdu_len);
201 ret = data->pdu_len;
202 if (!data->peekmode) {
203 data->pdu_len = 0;
204 data->pdu = NULL;
205 }
206 }
207 } else {
208 ret = MBEDTLS_ERR_SSL_WANT_READ;
209 errno = EAGAIN;
210 }
211 }
212 return ret;
213}
214
215/*
216 * return +ve data amount
217 * 0 no more
218 * -ve Mbed TLS error
219 */
220/* callback function given to mbedtls for sending data over socket */
221static int
222coap_dgram_write(void *ctx, const unsigned char *send_buffer,
223 size_t send_buffer_length) {
224 ssize_t result = -1;
225 coap_session_t *c_session = (coap_session_t *)ctx;
226
227 if (c_session) {
228 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
229
230 if (!coap_netif_available(c_session)
231#if COAP_SERVER_SUPPORT
232 && c_session->endpoint == NULL
233#endif /* COAP_SERVER_SUPPORT */
234 ) {
235 /* socket was closed on client due to error */
236 errno = ECONNRESET;
237 return -1;
238 }
239 result = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
240 send_buffer, send_buffer_length);
241 if (result != (ssize_t)send_buffer_length) {
242 coap_log_warn("coap_netif_dgrm_write failed (%zd != %zu)\n",
243 result, send_buffer_length);
244 result = 0;
245 } else if (m_env) {
246 coap_tick_t now;
247 coap_ticks(&now);
248 m_env->last_timeout = now;
249 }
250 } else {
251 result = 0;
252 }
253 return result;
254}
255
256#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && defined(MBEDTLS_SSL_SRV_C)
257/*
258 * Server side PSK callback
259 */
260static int
261psk_server_callback(void *p_info, mbedtls_ssl_context *ssl,
262 const unsigned char *identity, size_t identity_len) {
263 coap_session_t *c_session = (coap_session_t *)p_info;
264 coap_dtls_spsk_t *setup_data;
265 coap_mbedtls_env_t *m_env;
266 coap_bin_const_t lidentity;
267 const coap_bin_const_t *psk_key;
268
269 if (c_session == NULL)
270 return -1;
271
272 /* Track the Identity being used */
273 lidentity.s = identity ? (const uint8_t *)identity : (const uint8_t *)"";
274 lidentity.length = identity ? identity_len : 0;
275 coap_session_refresh_psk_identity(c_session, &lidentity);
276
277 coap_log_debug("got psk_identity: '%.*s'\n",
278 (int)lidentity.length, (const char *)lidentity.s);
279
280 m_env = (coap_mbedtls_env_t *)c_session->tls;
281 setup_data = &c_session->context->spsk_setup_data;
282
283 if (setup_data->validate_id_call_back) {
284 psk_key = setup_data->validate_id_call_back(&lidentity,
285 c_session,
286 setup_data->id_call_back_arg);
287
288 coap_session_refresh_psk_key(c_session, psk_key);
289 } else {
290 psk_key = coap_get_session_server_psk_key(c_session);
291 }
292
293 if (psk_key == NULL)
294 return -1;
295 mbedtls_ssl_set_hs_psk(ssl, psk_key->s, psk_key->length);
296 m_env->seen_client_hello = 1;
297 return 0;
298}
299#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED && MBEDTLS_SSL_SRV_C */
300
301static char *
302get_san_or_cn_from_cert(mbedtls_x509_crt *crt) {
303 if (crt) {
304 const mbedtls_asn1_named_data *cn_data;
305
306 if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
307 mbedtls_asn1_sequence *seq = &crt->subject_alt_names;
308 while (seq && seq->buf.p == NULL) {
309 seq = seq->next;
310 }
311 if (seq) {
312 /* Return the Subject Alt Name */
313 return mbedtls_strndup((const char *)seq->buf.p,
314 seq->buf.len);
315 }
316 }
317
318 cn_data = mbedtls_asn1_find_named_data(&crt->subject,
319 MBEDTLS_OID_AT_CN,
320 MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN));
321 if (cn_data) {
322 /* Return the Common Name */
323 return mbedtls_strndup((const char *)cn_data->val.p,
324 cn_data->val.len);
325 }
326 }
327 return NULL;
328}
329
330#if COAP_MAX_LOGGING_LEVEL > 0
331static char *
332get_error_string(int ret) {
333 static char buf[128] = {0};
334 mbedtls_strerror(ret, buf, sizeof(buf)-1);
335 return buf;
336}
337#endif /* COAP_MAX_LOGGING_LEVEL */
338
339static int
340self_signed_cert_verify_callback_mbedtls(void *data,
341 mbedtls_x509_crt *crt COAP_UNUSED,
342 int depth COAP_UNUSED,
343 uint32_t *flags) {
344 const coap_session_t *c_session = (coap_session_t *)data;
345 const coap_mbedtls_context_t *m_context =
346 (coap_mbedtls_context_t *)c_session->context->dtls_context;
347 const coap_dtls_pki_t *setup_data = &m_context->setup_data;
348
349 if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
350 if (setup_data->allow_expired_certs) {
351 *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
352 }
353 }
354 return 0;
355}
356
357/*
358 * return 0 All OK
359 * -ve Error Code
360 */
361static int
362cert_verify_callback_mbedtls(void *data, mbedtls_x509_crt *crt,
363 int depth, uint32_t *flags) {
364 coap_session_t *c_session = (coap_session_t *)data;
365 coap_mbedtls_context_t *m_context =
366 (coap_mbedtls_context_t *)c_session->context->dtls_context;
367 coap_dtls_pki_t *setup_data = &m_context->setup_data;
368 char *cn = NULL;
369
370 if (*flags == 0)
371 return 0;
372
373 cn = get_san_or_cn_from_cert(crt);
374
375 if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
376 if (setup_data->allow_expired_certs) {
377 *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
378 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
379 coap_session_str(c_session),
380 "The certificate has expired", cn ? cn : "?", depth);
381 }
382 }
383 if (*flags & MBEDTLS_X509_BADCERT_FUTURE) {
384 if (setup_data->allow_expired_certs) {
385 *flags &= ~MBEDTLS_X509_BADCERT_FUTURE;
386 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
387 coap_session_str(c_session),
388 "The certificate has a future date", cn ? cn : "?", depth);
389 }
390 }
391 if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) {
392 if (setup_data->allow_bad_md_hash) {
393 *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD;
394 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
395 coap_session_str(c_session),
396 "The certificate has a bad MD hash", cn ? cn : "?", depth);
397 }
398 }
399 if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) {
400 if (setup_data->allow_short_rsa_length) {
401 *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY;
402 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
403 coap_session_str(c_session),
404 "The certificate has a short RSA length", cn ? cn : "?", depth);
405 }
406 }
407 if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
408 uint32_t lflags;
409 int self_signed = !mbedtls_x509_crt_verify(crt, crt, NULL, NULL, &lflags,
410 self_signed_cert_verify_callback_mbedtls,
411 data);
412 if (self_signed && depth == 0) {
413 if (setup_data->allow_self_signed &&
414 !setup_data->check_common_ca) {
415 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
416 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
417 coap_session_str(c_session),
418 "Self-signed",
419 cn ? cn : "?", depth);
420 }
421 } else {
422 if (!setup_data->verify_peer_cert) {
423 *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
424 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
425 coap_session_str(c_session),
426 "The certificate's CA does not match", cn ? cn : "?", depth);
427 }
428 }
429 }
430 if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) {
431 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
432 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
433 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
434 coap_session_str(c_session),
435 "The certificate's CRL has expired", cn ? cn : "?", depth);
436 } else if (!setup_data->check_cert_revocation) {
437 *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
438 }
439 }
440 if (*flags & MBEDTLS_X509_BADCRL_FUTURE) {
441 if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
442 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
443 coap_log_info(" %s: %s: overridden: '%s' depth %d\n",
444 coap_session_str(c_session),
445 "The certificate's CRL has a future date", cn ? cn : "?", depth);
446 } else if (!setup_data->check_cert_revocation) {
447 *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
448 }
449 }
450 if (setup_data->cert_chain_validation &&
451 depth > (setup_data->cert_chain_verify_depth + 1)) {
452 *flags |= MBEDTLS_X509_BADCERT_OTHER;
453 coap_log_warn(" %s: %s: '%s' depth %d\n",
454 coap_session_str(c_session),
455 "The certificate's verify depth is too long",
456 cn ? cn : "?", depth);
457 }
458
459 if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
460 *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
461 }
462 if (setup_data->validate_cn_call_back) {
463 if (!setup_data->validate_cn_call_back(cn,
464 crt->raw.p,
465 crt->raw.len,
466 c_session,
467 depth,
468 *flags == 0,
469 setup_data->cn_call_back_arg)) {
470 *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
471 }
472 }
473 if (*flags != 0) {
474 char buf[128];
475 char *tcp;
476 int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
477
478 if (ret >= 0) {
479 tcp = strchr(buf, '\n');
480 while (tcp) {
481 *tcp = '\000';
482 coap_log_warn(" %s: %s: issue 0x%" PRIx32 ": '%s' depth %d\n",
483 coap_session_str(c_session),
484 buf, *flags, cn ? cn : "?", depth);
485 tcp = strchr(tcp+1, '\n');
486 }
487 } else {
488 coap_log_err("mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n",
489 -ret, get_error_string(ret));
490 }
491 }
492
493 if (cn)
494 mbedtls_free(cn);
495
496 return 0;
497}
498
499static int
500setup_pki_credentials(mbedtls_x509_crt *cacert,
501 mbedtls_x509_crt *public_cert,
502 mbedtls_pk_context *private_key,
503 coap_mbedtls_env_t *m_env,
504 coap_mbedtls_context_t *m_context,
505 coap_session_t *c_session,
506 coap_dtls_pki_t *setup_data,
507 coap_dtls_role_t role) {
508 int ret;
509
510 if (setup_data->is_rpk_not_cert) {
511 coap_log_err("RPK Support not available in Mbed TLS\n");
512 return -1;
513 }
514 switch (setup_data->pki_key.key_type) {
515 case COAP_PKI_KEY_PEM:
516#if defined(MBEDTLS_FS_IO)
517 if (setup_data->pki_key.key.pem.public_cert &&
518 setup_data->pki_key.key.pem.public_cert[0] &&
519 setup_data->pki_key.key.pem.private_key &&
520 setup_data->pki_key.key.pem.private_key[0]) {
521
522 mbedtls_x509_crt_init(public_cert);
523 mbedtls_pk_init(private_key);
524
525 ret = mbedtls_x509_crt_parse_file(public_cert,
526 setup_data->pki_key.key.pem.public_cert);
527 if (ret < 0) {
528 coap_log_err("mbedtls_x509_crt_parse_file returned -0x%x: '%s'\n",
529 -ret, get_error_string(ret));
530 return ret;
531 }
532
533#ifdef MBEDTLS_2_X_COMPAT
534 ret = mbedtls_pk_parse_keyfile(private_key,
535 setup_data->pki_key.key.pem.private_key, NULL);
536#else
537 ret = mbedtls_pk_parse_keyfile(private_key,
538 setup_data->pki_key.key.pem.private_key,
539 NULL, coap_rng, (void *)&m_env->ctr_drbg);
540#endif /* MBEDTLS_2_X_COMPAT */
541 if (ret < 0) {
542 coap_log_err("mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n",
543 -ret, get_error_string(ret));
544 return ret;
545 }
546
547 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
548 if (ret < 0) {
549 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
550 -ret, get_error_string(ret));
551 return ret;
552 }
553 } else if (role == COAP_DTLS_ROLE_SERVER) {
554 coap_log_err("***setup_pki: (D)TLS: No Server Certificate + Private "
555 "Key defined\n");
556 return -1;
557 }
558
559 if (setup_data->pki_key.key.pem.ca_file &&
560 setup_data->pki_key.key.pem.ca_file[0]) {
561 mbedtls_x509_crt_init(cacert);
562 ret = mbedtls_x509_crt_parse_file(cacert,
563 setup_data->pki_key.key.pem.ca_file);
564 if (ret < 0) {
565 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
566 -ret, get_error_string(ret));
567 return ret;
568 }
569 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
570 }
571#else /* ! MBEDTLS_FS_IO */
572 (void)m_context;
573 coap_log_err("mbedtls_x509_crt_parse_file: MBEDTLS_FS_IO not set, so cannot handle files\n");
574#endif /* ! MBEDTLS_FS_IO */
575 break;
577 if (setup_data->pki_key.key.pem_buf.public_cert &&
578 setup_data->pki_key.key.pem_buf.public_cert_len &&
579 setup_data->pki_key.key.pem_buf.private_key &&
580 setup_data->pki_key.key.pem_buf.private_key_len) {
581 uint8_t *buffer;
582 size_t length;
583
584 mbedtls_x509_crt_init(public_cert);
585 mbedtls_pk_init(private_key);
586
587 length = setup_data->pki_key.key.pem_buf.public_cert_len;
588 if (setup_data->pki_key.key.pem_buf.public_cert[length-1] != '\000') {
589 /* Need to allocate memory to add in NULL terminator */
590 buffer = mbedtls_malloc(length + 1);
591 if (!buffer) {
592 coap_log_err("mbedtls_malloc failed\n");
593 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
594 }
595 memcpy(buffer, setup_data->pki_key.key.pem_buf.public_cert, length);
596 buffer[length] = '\000';
597 length++;
598 ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
599 mbedtls_free(buffer);
600 } else {
601 ret = mbedtls_x509_crt_parse(public_cert,
602 setup_data->pki_key.key.pem_buf.public_cert,
603 setup_data->pki_key.key.pem_buf.public_cert_len);
604 }
605 if (ret < 0) {
606 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
607 -ret, get_error_string(ret));
608 return ret;
609 }
610
611 length = setup_data->pki_key.key.pem_buf.private_key_len;
612 if (setup_data->pki_key.key.pem_buf.private_key[length-1] != '\000') {
613 /* Need to allocate memory to add in NULL terminator */
614 buffer = mbedtls_malloc(length + 1);
615 if (!buffer) {
616 coap_log_err("mbedtls_malloc failed\n");
617 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
618 }
619 memcpy(buffer, setup_data->pki_key.key.pem_buf.private_key, length);
620 buffer[length] = '\000';
621 length++;
622#ifdef MBEDTLS_2_X_COMPAT
623 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
624#else
625 ret = mbedtls_pk_parse_key(private_key, buffer, length,
626 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
627#endif /* MBEDTLS_2_X_COMPAT */
628 mbedtls_free(buffer);
629 } else {
630#ifdef MBEDTLS_2_X_COMPAT
631 ret = mbedtls_pk_parse_key(private_key,
632 setup_data->pki_key.key.pem_buf.private_key,
633 setup_data->pki_key.key.pem_buf.private_key_len, NULL, 0);
634#else
635 ret = mbedtls_pk_parse_key(private_key,
636 setup_data->pki_key.key.pem_buf.private_key,
638 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
639#endif /* MBEDTLS_2_X_COMPAT */
640 }
641 if (ret < 0) {
642 coap_log_err("mbedtls_pk_parse_key returned -0x%x: '%s'\n",
643 -ret, get_error_string(ret));
644 return ret;
645 }
646
647 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
648 if (ret < 0) {
649 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
650 -ret, get_error_string(ret));
651 return ret;
652 }
653 } else if (role == COAP_DTLS_ROLE_SERVER) {
654 coap_log_err("***setup_pki: (D)TLS: No Server Certificate + Private "
655 "Key defined\n");
656 return -1;
657 }
658
659 if (setup_data->pki_key.key.pem_buf.ca_cert &&
660 setup_data->pki_key.key.pem_buf.ca_cert_len) {
661 uint8_t *buffer;
662 size_t length;
663
664 mbedtls_x509_crt_init(cacert);
665 length = setup_data->pki_key.key.pem_buf.ca_cert_len;
666 if (setup_data->pki_key.key.pem_buf.ca_cert[length-1] != '\000') {
667 /* Need to allocate memory to add in NULL terminator */
668 buffer = mbedtls_malloc(length + 1);
669 if (!buffer) {
670 coap_log_err("mbedtls_malloc failed\n");
671 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
672 }
673 memcpy(buffer, setup_data->pki_key.key.pem_buf.ca_cert, length);
674 buffer[length] = '\000';
675 length++;
676 ret = mbedtls_x509_crt_parse(cacert, buffer, length);
677 mbedtls_free(buffer);
678 } else {
679 ret = mbedtls_x509_crt_parse(cacert,
680 setup_data->pki_key.key.pem_buf.ca_cert,
681 setup_data->pki_key.key.pem_buf.ca_cert_len);
682 }
683 if (ret < 0) {
684 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
685 -ret, get_error_string(ret));
686 return ret;
687 }
688 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
689 }
690 break;
692 if (setup_data->pki_key.key.asn1.public_cert &&
693 setup_data->pki_key.key.asn1.public_cert_len &&
694 setup_data->pki_key.key.asn1.private_key &&
695 setup_data->pki_key.key.asn1.private_key_len > 0) {
696
697 mbedtls_x509_crt_init(public_cert);
698 mbedtls_pk_init(private_key);
699 ret = mbedtls_x509_crt_parse(public_cert,
700 (const unsigned char *)setup_data->pki_key.key.asn1.public_cert,
701 setup_data->pki_key.key.asn1.public_cert_len);
702 if (ret < 0) {
703 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
704 -ret, get_error_string(ret));
705 return ret;
706 }
707
708#ifdef MBEDTLS_2_X_COMPAT
709 ret = mbedtls_pk_parse_key(private_key,
710 (const unsigned char *)setup_data->pki_key.key.asn1.private_key,
711 setup_data->pki_key.key.asn1.private_key_len, NULL, 0);
712#else
713 ret = mbedtls_pk_parse_key(private_key,
714 (const unsigned char *)setup_data->pki_key.key.asn1.private_key,
715 setup_data->pki_key.key.asn1.private_key_len, NULL, 0, coap_rng,
716 (void *)&m_env->ctr_drbg);
717#endif /* MBEDTLS_2_X_COMPAT */
718 if (ret < 0) {
719 coap_log_err("mbedtls_pk_parse_key returned -0x%x: '%s'\n",
720 -ret, get_error_string(ret));
721 return ret;
722 }
723
724 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
725 if (ret < 0) {
726 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
727 -ret, get_error_string(ret));
728 return ret;
729 }
730 } else if (role == COAP_DTLS_ROLE_SERVER) {
731 coap_log_err("***setup_pki: (D)TLS: No Server Certificate + Private "
732 "Key defined\n");
733 return -1;
734 }
735
736 if (setup_data->pki_key.key.asn1.ca_cert &&
737 setup_data->pki_key.key.asn1.ca_cert_len > 0) {
738 mbedtls_x509_crt_init(cacert);
739 ret = mbedtls_x509_crt_parse(cacert,
740 (const unsigned char *)setup_data->pki_key.key.asn1.ca_cert,
741 setup_data->pki_key.key.asn1.ca_cert_len);
742 if (ret < 0) {
743 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
744 -ret, get_error_string(ret));
745 return ret;
746 }
747 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
748 }
749 break;
750
752 coap_log_err("***setup_pki: (D)TLS: PKCS11 not currently supported\n");
753 return -1;
754
755 default:
756 coap_log_err("***setup_pki: (D)TLS: Unknown key type %d\n",
757 setup_data->pki_key.key_type);
758 return -1;
759 }
760
761#if defined(MBEDTLS_FS_IO)
762 if (m_context->root_ca_file) {
763 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
764 if (ret < 0) {
765 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
766 -ret, get_error_string(ret));
767 return ret;
768 }
769 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
770 }
771 if (m_context->root_ca_path) {
772 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_path);
773 if (ret < 0) {
774 coap_log_err("mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
775 -ret, get_error_string(ret));
776 return ret;
777 }
778 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
779 }
780#else /* ! MBEDTLS_FS_IO */
781 coap_log_err("mbedtls_x509_crt_parse_file: MBEDTLS_FS_IO not set, so cannot handle files\n");
782#endif /* ! MBEDTLS_FS_IO */
783
784#if defined(MBEDTLS_SSL_SRV_C)
785 mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
786 setup_data->check_common_ca ?
787 MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
788 MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
789#endif
790 mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
791 MBEDTLS_SSL_VERIFY_REQUIRED :
792 MBEDTLS_SSL_VERIFY_NONE);
793 /*
794 * Verify Peer.
795 * Need to do all checking, even if setup_data->verify_peer_cert is not set
796 */
797 mbedtls_ssl_conf_verify(&m_env->conf,
798 cert_verify_callback_mbedtls, c_session);
799
800 return 0;
801}
802
803#if defined(MBEDTLS_SSL_SRV_C)
804/*
805 * PKI SNI callback.
806 */
807static int
808pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
809 const unsigned char *uname, size_t name_len) {
810 unsigned int i;
811 coap_dtls_pki_t sni_setup_data;
812 coap_session_t *c_session = (coap_session_t *)p_info;
813 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
814 coap_mbedtls_context_t *m_context =
815 (coap_mbedtls_context_t *)c_session->context->dtls_context;
816 int ret = 0;
817 char *name;
818
819 name = mbedtls_malloc(name_len+1);
820 if (!name)
821 return -1;
822
823 memcpy(name, uname, name_len);
824 name[name_len] = '\000';
825
826 /* Is this a cached entry? */
827 for (i = 0; i < m_context->pki_sni_count; i++) {
828 if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
829 break;
830 }
831 }
832 if (i == m_context->pki_sni_count) {
833 /*
834 * New PKI SNI request
835 */
836 coap_dtls_key_t *new_entry;
837 pki_sni_entry *pki_sni_entry_list;
838
839 new_entry =
840 m_context->setup_data.validate_sni_call_back(name,
841 m_context->setup_data.sni_call_back_arg);
842 if (!new_entry) {
843 mbedtls_free(name);
844 return -1;
845 }
846
847 pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
848 (i+1)*sizeof(pki_sni_entry));
849
850 if (pki_sni_entry_list == NULL) {
851 mbedtls_free(name);
852 return -1;
853 }
854 m_context->pki_sni_entry_list = pki_sni_entry_list;
855 memset(&m_context->pki_sni_entry_list[i], 0,
856 sizeof(m_context->pki_sni_entry_list[i]));
857 m_context->pki_sni_entry_list[i].sni = name;
858 m_context->pki_sni_entry_list[i].pki_key = *new_entry;
859 sni_setup_data = m_context->setup_data;
860 sni_setup_data.pki_key = *new_entry;
861 if ((ret = setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
862 &m_context->pki_sni_entry_list[i].public_cert,
863 &m_context->pki_sni_entry_list[i].private_key,
864 m_env,
865 m_context,
866 c_session,
867 &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
868 mbedtls_free(name);
869 return -1;
870 }
871 /* name has been absorbed into pki_sni_entry_list[].sni entry */
872 m_context->pki_sni_count++;
873 } else {
874 mbedtls_free(name);
875 }
876
877 mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
878 NULL);
879 return mbedtls_ssl_set_hs_own_cert(ssl,
880 &m_context->pki_sni_entry_list[i].public_cert,
881 &m_context->pki_sni_entry_list[i].private_key);
882}
883
884#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
885/*
886 * PSK SNI callback.
887 */
888static int
889psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
890 const unsigned char *uname, size_t name_len) {
891 unsigned int i;
892 coap_session_t *c_session = (coap_session_t *)p_info;
893 coap_mbedtls_context_t *m_context =
894 (coap_mbedtls_context_t *)c_session->context->dtls_context;
895 char *name;
896
897 name = mbedtls_malloc(name_len+1);
898 if (!name)
899 return -1;
900
901 memcpy(name, uname, name_len);
902 name[name_len] = '\000';
903
904 /* Is this a cached entry? */
905 for (i = 0; i < m_context->psk_sni_count; i++) {
906 if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
907 break;
908 }
909 }
910 if (i == m_context->psk_sni_count) {
911 /*
912 * New PSK SNI request
913 */
914 const coap_dtls_spsk_info_t *new_entry;
915 psk_sni_entry *psk_sni_entry_list;
916
917 new_entry =
919 c_session,
921 if (!new_entry) {
922 mbedtls_free(name);
923 return -1;
924 }
925
926 psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
927 (i+1)*sizeof(psk_sni_entry));
928
929 if (psk_sni_entry_list == NULL) {
930 mbedtls_free(name);
931 return -1;
932 }
933 m_context->psk_sni_entry_list = psk_sni_entry_list;
934 m_context->psk_sni_entry_list[i].sni = name;
935 m_context->psk_sni_entry_list[i].psk_info = *new_entry;
936 /* name has been absorbed into psk_sni_entry_list[].sni entry */
937 m_context->psk_sni_count++;
938 } else {
939 mbedtls_free(name);
940 }
941
943 &m_context->psk_sni_entry_list[i].psk_info.hint);
945 &m_context->psk_sni_entry_list[i].psk_info.key);
946 return mbedtls_ssl_set_hs_psk(ssl,
947 m_context->psk_sni_entry_list[i].psk_info.key.s,
948 m_context->psk_sni_entry_list[i].psk_info.key.length);
949}
950#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
951
952static int
953setup_server_ssl_session(coap_session_t *c_session,
954 coap_mbedtls_env_t *m_env) {
955 coap_mbedtls_context_t *m_context =
956 (coap_mbedtls_context_t *)c_session->context->dtls_context;
957 int ret = 0;
958 m_context->psk_pki_enabled |= IS_SERVER;
959
960 mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
961 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
962 MBEDTLS_SSL_IS_SERVER,
963 c_session->proto == COAP_PROTO_DTLS ?
964 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
965 MBEDTLS_SSL_TRANSPORT_STREAM,
966 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
967 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
968 -ret, get_error_string(ret));
969 goto fail;
970 }
971
972 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
973
974#if defined(MBEDTLS_SSL_PROTO_DTLS)
975 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
976 COAP_DTLS_RETRANSMIT_TOTAL_MS);
977#endif /* MBEDTLS_SSL_PROTO_DTLS */
978
979 if (m_context->psk_pki_enabled & IS_PSK) {
980#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
981 mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
983 mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
984 }
985#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
986 coap_log_warn("PSK not enabled in Mbed TLS library\n");
987#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
988 }
989
990 if (m_context->psk_pki_enabled & IS_PKI) {
991 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
992 &m_env->private_key, m_env, m_context,
993 c_session, &m_context->setup_data,
995 if (ret < 0) {
996 coap_log_err("PKI setup failed\n");
997 return ret;
998 }
999 if (m_context->setup_data.validate_sni_call_back) {
1000 mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1001 }
1002 }
1003
1004 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1005 mbedtls_ctr_drbg_random,
1006 &m_env->ctr_drbg)) != 0) {
1007 coap_log_err("mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1008 -ret, get_error_string(ret));
1009 goto fail;
1010 }
1011
1012#if defined(MBEDTLS_SSL_PROTO_DTLS)
1013 mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1014 mbedtls_ssl_cookie_check,
1015 &m_env->cookie_ctx);
1016#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1017 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1018#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1019#endif /* MBEDTLS_SSL_PROTO_DTLS */
1020#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1021 /*
1022 * Configure CID max length.
1023 *
1024 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1025 * to use RFC9146 extension ID of 54, rather than the draft version -05
1026 * value of 254.
1027 */
1028 mbedtls_ssl_conf_cid(&m_env->conf, COAP_DTLS_CID_LENGTH, MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1029#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1030fail:
1031 return ret;
1032}
1033#endif /* MBEDTLS_SSL_SRV_C */
1034
1035#if COAP_CLIENT_SUPPORT
1036static int *psk_ciphers = NULL;
1037static int *pki_ciphers = NULL;
1038static int processed_ciphers = 0;
1039
1040static void
1041set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) {
1042 if (!processed_ciphers) {
1043 const int *list = mbedtls_ssl_list_ciphersuites();
1044 const int *base = list;
1045 int *psk_list;
1046 int *pki_list;
1047 int psk_count = 1; /* account for empty terminator */
1048 int pki_count = 1;
1049
1050 while (*list) {
1051 const mbedtls_ssl_ciphersuite_t *cur =
1052 mbedtls_ssl_ciphersuite_from_id(*list);
1053
1054#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1055 if (cur) {
1056 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1057 /* Minimum of TLS1.2 required - skip */
1058 }
1059#else
1060 if (cur) {
1061 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1062 /* Minimum of TLS1.2 required - skip */
1063 }
1064#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1065#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1066 else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1067 psk_count++;
1068 }
1069#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1070 else {
1071 pki_count++;
1072 }
1073 }
1074 list++;
1075 }
1076 list = base;
1077
1078 psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1079 if (psk_ciphers == NULL) {
1080 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1081 return;
1082 }
1083 pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1084 if (pki_ciphers == NULL) {
1085 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1086 mbedtls_free(psk_ciphers);
1087 psk_ciphers = NULL;
1088 return;
1089 }
1090
1091 psk_list = psk_ciphers;
1092 pki_list = pki_ciphers;
1093
1094 while (*list) {
1095 const mbedtls_ssl_ciphersuite_t *cur =
1096 mbedtls_ssl_ciphersuite_from_id(*list);
1097#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1098 if (cur) {
1099 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1100 /* Minimum of TLS1.2 required - skip */
1101 }
1102#else
1103 if (cur) {
1104 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1105 /* Minimum of TLS1.2 required - skip */
1106 }
1107#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1108#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1109 else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1110 *psk_list = *list;
1111 psk_list++;
1112 }
1113#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1114 else {
1115 *pki_list = *list;
1116 pki_list++;
1117 }
1118 }
1119 list++;
1120 }
1121 /* zero terminate */
1122 *psk_list = 0;
1123 *pki_list = 0;
1124 processed_ciphers = 1;
1125 }
1126 mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers);
1127}
1128
1129static int
1130setup_client_ssl_session(coap_session_t *c_session,
1131 coap_mbedtls_env_t *m_env) {
1132 int ret;
1133
1134 coap_mbedtls_context_t *m_context =
1135 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1136
1137 m_context->psk_pki_enabled |= IS_CLIENT;
1138
1139 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1140 MBEDTLS_SSL_IS_CLIENT,
1141 c_session->proto == COAP_PROTO_DTLS ?
1142 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1143 MBEDTLS_SSL_TRANSPORT_STREAM,
1144 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1145 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1146 -ret, get_error_string(ret));
1147 goto fail;
1148 }
1149
1150#if defined(MBEDTLS_SSL_PROTO_DTLS)
1151 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1152 COAP_DTLS_RETRANSMIT_TOTAL_MS);
1153#endif /* MBEDTLS_SSL_PROTO_DTLS */
1154
1155 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1156 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1157
1158 if (m_context->psk_pki_enabled & IS_PSK) {
1159#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1160 const coap_bin_const_t *psk_key;
1161 const coap_bin_const_t *psk_identity;
1162
1163 coap_log_info("Setting PSK key\n");
1164
1165 psk_key = coap_get_session_client_psk_key(c_session);
1166 psk_identity = coap_get_session_client_psk_identity(c_session);
1167 if (psk_key == NULL || psk_identity == NULL) {
1168 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1169 goto fail;
1170 }
1171
1172 if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1173 psk_key->length, psk_identity->s,
1174 psk_identity->length)) != 0) {
1175 coap_log_err("mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1176 -ret, get_error_string(ret));
1177 goto fail;
1178 }
1179 if (c_session->cpsk_setup_data.client_sni) {
1180 if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1181 c_session->cpsk_setup_data.client_sni)) != 0) {
1182 coap_log_err("mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1183 -ret, get_error_string(ret));
1184 goto fail;
1185 }
1186 }
1187 /* Identity Hint currently not supported in Mbed TLS so code removed */
1188
1189 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1190#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1191 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1192#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1193 } else if ((m_context->psk_pki_enabled & IS_PKI) ||
1194 (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1195 /*
1196 * If neither PSK or PKI have been set up, use PKI basics.
1197 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1198 */
1199 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1200 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1201 &m_env->private_key, m_env, m_context,
1202 c_session, &m_context->setup_data,
1204 if (ret < 0) {
1205 coap_log_err("PKI setup failed\n");
1206 return ret;
1207 }
1208#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1209 if (c_session->proto == COAP_PROTO_TLS ||
1210 c_session->proto == COAP_PROTO_WSS) {
1211 static const char *alpn_list[] = { "coap", NULL };
1212
1213 ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1214 if (ret != 0) {
1215 coap_log_err("ALPN setup failed %d)\n", ret);
1216 }
1217 }
1218#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1219 if (m_context->setup_data.client_sni) {
1220 mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1221 }
1222#if defined(MBEDTLS_SSL_PROTO_DTLS)
1223#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1224 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1225#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1226#endif /* MBEDTLS_SSL_PROTO_DTLS */
1227 set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1228 }
1229 return 0;
1230
1231fail:
1232 return ret;
1233}
1234#endif /* COAP_CLIENT_SUPPORT */
1235
1236static void
1237mbedtls_cleanup(coap_mbedtls_env_t *m_env) {
1238 if (!m_env) {
1239 return;
1240 }
1241
1242 mbedtls_x509_crt_free(&m_env->cacert);
1243 mbedtls_x509_crt_free(&m_env->public_cert);
1244 mbedtls_pk_free(&m_env->private_key);
1245 mbedtls_entropy_free(&m_env->entropy);
1246 mbedtls_ssl_config_free(&m_env->conf);
1247 mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1248 mbedtls_ssl_free(&m_env->ssl);
1249 mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1250}
1251
1252static void
1253coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1254 if (m_env) {
1255 if (!m_env->sent_alert)
1256 mbedtls_ssl_close_notify(&m_env->ssl);
1257 mbedtls_cleanup(m_env);
1258 mbedtls_free(m_env);
1259 }
1260}
1261
1262#if COAP_MAX_LOGGING_LEVEL > 0
1263static const char *
1264report_mbedtls_alert(unsigned char alert) {
1265 switch (alert) {
1266 case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC:
1267 return ": Bad Record MAC";
1268 case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE:
1269 return ": Handshake failure";
1270 case MBEDTLS_SSL_ALERT_MSG_NO_CERT:
1271 return ": No Certificate provided";
1272 case MBEDTLS_SSL_ALERT_MSG_BAD_CERT:
1273 return ": Certificate is bad";
1274 case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN:
1275 return ": Certificate is unknown";
1276 case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA:
1277 return ": CA is unknown";
1278 case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED:
1279 return ": Access was denied";
1280 case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR:
1281 return ": Decrypt error";
1282 default:
1283 return "";
1284 }
1285}
1286#endif /* COAP_MAX_LOGGING_LEVEL */
1287
1288/*
1289 * return -1 failure
1290 * 0 not completed
1291 * 1 established
1292 */
1293static int
1294do_mbedtls_handshake(coap_session_t *c_session,
1295 coap_mbedtls_env_t *m_env) {
1296 int ret;
1297 int alert;
1298
1299 ret = mbedtls_ssl_handshake(&m_env->ssl);
1300 switch (ret) {
1301 case 0:
1302 m_env->established = 1;
1303 coap_log_debug("* %s: Mbed TLS established\n",
1304 coap_session_str(c_session));
1305 ret = 1;
1306 break;
1307 case MBEDTLS_ERR_SSL_WANT_READ:
1308 case MBEDTLS_ERR_SSL_WANT_WRITE:
1309 errno = EAGAIN;
1310 ret = 0;
1311 break;
1312 case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1313 coap_log_debug("hello verification requested\n");
1314 goto reset;
1315 case MBEDTLS_ERR_SSL_INVALID_MAC:
1316 goto fail;
1317#ifdef MBEDTLS_2_X_COMPAT
1318 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
1319#else /* ! MBEDTLS_2_X_COMPAT */
1320 case MBEDTLS_ERR_SSL_DECODE_ERROR:
1321#endif /* ! MBEDTLS_2_X_COMPAT */
1322 goto fail;
1323 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1324 alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1325 goto fail_alert;
1326#ifdef MBEDTLS_2_X_COMPAT
1327 case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1328 case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1329 alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1330 goto fail_alert;
1331#endif /* MBEDTLS_2_X_COMPAT */
1332 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1333 goto fail;
1334 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1335 if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1336 coap_log_warn("***%s: Alert '%d'%s\n",
1337 coap_session_str(c_session), m_env->ssl.in_msg[1],
1338 report_mbedtls_alert(m_env->ssl.in_msg[1]));
1339 /* Fall through */
1340 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1341 case MBEDTLS_ERR_SSL_CONN_EOF:
1342 case MBEDTLS_ERR_NET_CONN_RESET:
1344 ret = -1;
1345 break;
1346 default:
1347 coap_log_warn("do_mbedtls_handshake: session establish "
1348 "returned -0x%x: '%s'\n",
1349 -ret, get_error_string(ret));
1350 ret = -1;
1351 break;
1352 }
1353 return ret;
1354
1355fail_alert:
1356 mbedtls_ssl_send_alert_message(&m_env->ssl,
1357 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1358 alert);
1359 m_env->sent_alert = 1;
1360fail:
1361 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1362 coap_log_warn("do_mbedtls_handshake: session establish "
1363 "returned '%s'\n",
1364 get_error_string(ret));
1365reset:
1366 mbedtls_ssl_session_reset(&m_env->ssl);
1367 return -1;
1368}
1369
1370static void
1371mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1372 const char *file COAP_UNUSED,
1373 int line COAP_UNUSED, const char *str) {
1374
1375 coap_log_t coap_level = COAP_LOG_DEBUG;
1376 /*
1377 * 0 No debug
1378 * 1 Error
1379 * 2 State change
1380 * 3 Informational
1381 * 4 Verbose
1382 */
1383 switch (level) {
1384 case 0:
1385 coap_level = COAP_LOG_EMERG;
1386 break;
1387 case 1:
1388 coap_level = COAP_LOG_WARN;
1389 break;
1390 case 2:
1391 coap_level = COAP_LOG_NOTICE;
1392 break;
1393 case 3:
1394 coap_level = COAP_LOG_INFO;
1395 break;
1396 case 4:
1397 default:
1398 coap_level = COAP_LOG_DEBUG;
1399 break;
1400 }
1401 coap_dtls_log(coap_level, "%s", str);
1402}
1403
1404#if !COAP_DISABLE_TCP
1405/*
1406 * strm
1407 * return +ve data amount
1408 * 0 no more
1409 * -ve Mbed TLS error
1410 */
1411static int
1412coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
1413 int ret = MBEDTLS_ERR_SSL_CONN_EOF;
1414 coap_session_t *c_session = (coap_session_t *)ctx;
1415
1416 if (out != NULL) {
1417 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
1418 /* Translate layer returns into what MbedTLS expects */
1419 if (ret == -1) {
1420 if (errno == ECONNRESET) {
1421 /* graceful shutdown */
1422 ret = MBEDTLS_ERR_SSL_CONN_EOF;
1423 } else {
1424 ret = MBEDTLS_ERR_NET_RECV_FAILED;
1425 }
1426 } else if (ret == 0) {
1427 errno = EAGAIN;
1428 ret = MBEDTLS_ERR_SSL_WANT_READ;
1429 }
1430 }
1431 return ret;
1432}
1433
1434/*
1435 * strm
1436 * return +ve data amount
1437 * 0 no more
1438 * -ve Mbed TLS error
1439 */
1440static int
1441coap_sock_write(void *context, const unsigned char *in, size_t inl) {
1442 int ret = 0;
1443 coap_session_t *c_session = (coap_session_t *)context;
1444
1445 ret = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
1446 (const uint8_t *)in,
1447 inl);
1448 /* Translate layer what returns into what MbedTLS expects */
1449 if (ret < 0) {
1450 if ((c_session->state == COAP_SESSION_STATE_CSM ||
1451 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
1452 (errno == EPIPE || errno == ECONNRESET)) {
1453 /*
1454 * Need to handle a TCP timing window where an agent continues with
1455 * the sending of the next handshake or a CSM.
1456 * However, the peer does not like a certificate and so sends a
1457 * fatal alert and closes the TCP session.
1458 * The sending of the next handshake or CSM may get terminated because
1459 * of the closed TCP session, but there is still an outstanding alert
1460 * to be read in and reported on.
1461 * In this case, pretend that sending the info was fine so that the
1462 * alert can be read (which effectively is what happens with DTLS).
1463 */
1464 ret = inl;
1465 } else {
1466#ifdef _WIN32
1467 int lasterror = WSAGetLastError();
1468
1469 if (lasterror == WSAEWOULDBLOCK) {
1470 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1471 } else if (lasterror == WSAECONNRESET) {
1472 ret = MBEDTLS_ERR_NET_CONN_RESET;
1473 }
1474#else
1475 if (errno == EAGAIN || errno == EINTR) {
1476 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1477 } else if (errno == EPIPE || errno == ECONNRESET) {
1478 ret = MBEDTLS_ERR_NET_CONN_RESET;
1479 }
1480#endif
1481 else {
1482 ret = MBEDTLS_ERR_NET_SEND_FAILED;
1483 }
1484 coap_log_debug("* %s: failed to send %zd bytes (%s) state %d\n",
1485 coap_session_str(c_session), inl, coap_socket_strerror(),
1486 c_session->state);
1487 }
1488 }
1489 if (ret == 0) {
1490 errno = EAGAIN;
1491 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1492 }
1493 return ret;
1494}
1495#endif /* !COAP_DISABLE_TCP */
1496
1497static coap_mbedtls_env_t *
1498coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1499 coap_dtls_role_t role,
1500 coap_proto_t proto) {
1501 int ret = 0;
1502 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1503
1504 if (m_env)
1505 return m_env;
1506
1507 m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1508 if (!m_env) {
1509 return NULL;
1510 }
1511 memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1512
1513 mbedtls_ssl_init(&m_env->ssl);
1514 mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1515 mbedtls_ssl_config_init(&m_env->conf);
1516 mbedtls_entropy_init(&m_env->entropy);
1517
1518#if defined(MBEDTLS_PSA_CRYPTO_C)
1519 psa_crypto_init();
1520#endif /* MBEDTLS_PSA_CRYPTO_C */
1521
1522#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1523 mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1524#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1525 if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1526 mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1527 coap_log_err("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1528 -ret, get_error_string(ret));
1529 goto fail;
1530 }
1531
1532 if (role == COAP_DTLS_ROLE_CLIENT) {
1533#if COAP_CLIENT_SUPPORT
1534 if (setup_client_ssl_session(c_session, m_env) != 0) {
1535 goto fail;
1536 }
1537#else /* !COAP_CLIENT_SUPPORT */
1538 goto fail;
1539#endif /* !COAP_CLIENT_SUPPORT */
1540 } else if (role == COAP_DTLS_ROLE_SERVER) {
1541#if defined(MBEDTLS_SSL_SRV_C)
1542 if (setup_server_ssl_session(c_session, m_env) != 0) {
1543 goto fail;
1544 }
1545#else /* ! MBEDTLS_SSL_SRV_C */
1546 goto fail;
1547#endif /* ! MBEDTLS_SSL_SRV_C */
1548 } else {
1549 goto fail;
1550 }
1551
1552#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1553 mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1554#else
1555 mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1556 MBEDTLS_SSL_MINOR_VERSION_3);
1557#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1558
1559 if ((ret = mbedtls_ssl_setup(&m_env->ssl, &m_env->conf)) != 0) {
1560 goto fail;
1561 }
1562 if (proto == COAP_PROTO_DTLS) {
1563 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1564 coap_dgram_read, NULL);
1565#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1566 if (role != COAP_DTLS_ROLE_CLIENT &&
1567 COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
1568 u_char cid[COAP_DTLS_CID_LENGTH];
1569 /*
1570 * Enable server DTLS CID support.
1571 *
1572 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1573 * to use RFC9146 extension ID of 54, rather than the draft version -05
1574 * value of 254.
1575 */
1576 coap_prng(cid, sizeof(cid));
1577 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, cid,
1578 sizeof(cid));
1579 }
1580#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1581 }
1582#if !COAP_DISABLE_TCP
1583 else {
1584 assert(proto == COAP_PROTO_TLS);
1585 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
1586 coap_sock_read, NULL);
1587 }
1588#endif /* ! COAP_DISABLE_TCP */
1589 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1590 mbedtls_timing_set_delay,
1591 mbedtls_timing_get_delay);
1592
1593 mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1594 return m_env;
1595
1596fail:
1597 if (m_env) {
1598 mbedtls_free(m_env);
1599 }
1600 return NULL;
1601}
1602
1603int
1605#if defined(MBEDTLS_SSL_PROTO_DTLS)
1606 return 1;
1607#else /* !MBEDTLS_SSL_PROTO_DTLS */
1608 static int reported = 0;
1609 if (!reported) {
1610 reported = 1;
1611 coap_log_emerg("libcoap not compiled for DTLS with Mbed TLS"
1612 " - update Mbed TLS to include DTLS\n");
1613 }
1614 return 0;
1615#endif /* !MBEDTLS_SSL_PROTO_DTLS */
1616}
1617
1618int
1620#if !COAP_DISABLE_TCP
1621 return 1;
1622#else /* COAP_DISABLE_TCP */
1623 return 0;
1624#endif /* COAP_DISABLE_TCP */
1625}
1626
1627/*
1628 * return 0 failed
1629 * 1 passed
1630 */
1631int
1633 return 1;
1634}
1635
1636/*
1637 * return 0 failed
1638 * 1 passed
1639 */
1640int
1642 return 1;
1643}
1644
1645/*
1646 * return 0 failed
1647 * 1 passed
1648 */
1649int
1651 return 0;
1652}
1653
1654/*
1655 * return 0 failed
1656 * 1 passed
1657 */
1658int
1660 return 0;
1661}
1662
1663void *
1665 coap_mbedtls_context_t *m_context;
1666 (void)c_context;
1667
1668 m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
1669 if (m_context) {
1670 memset(m_context, 0, sizeof(coap_mbedtls_context_t));
1671 }
1672 return m_context;
1673}
1674
1675#if COAP_SERVER_SUPPORT
1676/*
1677 * return 0 failed
1678 * 1 passed
1679 */
1680int
1682 coap_dtls_spsk_t *setup_data
1683 ) {
1684 coap_mbedtls_context_t *m_context =
1685 ((coap_mbedtls_context_t *)c_context->dtls_context);
1686
1687#if !defined(MBEDTLS_SSL_SRV_C)
1688 coap_log_emerg("coap_context_set_spsk:"
1689 " libcoap not compiled for Server Mode for Mbed TLS"
1690 " - update Mbed TLS to include Server Mode\n");
1691 return 0;
1692#endif /* !MBEDTLS_SSL_SRV_C */
1693 if (!m_context || !setup_data)
1694 return 0;
1695
1696 m_context->psk_pki_enabled |= IS_PSK;
1697 return 1;
1698}
1699#endif /* COAP_SERVER_SUPPORT */
1700
1701#if COAP_CLIENT_SUPPORT
1702/*
1703 * return 0 failed
1704 * 1 passed
1705 */
1706int
1708 coap_dtls_cpsk_t *setup_data
1709 ) {
1710#if !defined(MBEDTLS_SSL_CLI_C)
1711 (void)c_context;
1712 (void)setup_data;
1713
1714 coap_log_emerg("coap_context_set_cpsk:"
1715 " libcoap not compiled for Client Mode for Mbed TLS"
1716 " - update Mbed TLS to include Client Mode\n");
1717 return 0;
1718#else /* MBEDTLS_SSL_CLI_C */
1719 coap_mbedtls_context_t *m_context =
1720 ((coap_mbedtls_context_t *)c_context->dtls_context);
1721
1722 if (!m_context || !setup_data)
1723 return 0;
1724
1725 if (setup_data->validate_ih_call_back) {
1726 coap_log_warn("CoAP Client with Mbed TLS does not support Identity Hint selection\n");
1727 }
1728 m_context->psk_pki_enabled |= IS_PSK;
1729 return 1;
1730#endif /* MBEDTLS_SSL_CLI_C */
1731}
1732#endif /* COAP_CLIENT_SUPPORT */
1733
1734int
1736 const coap_dtls_pki_t *setup_data,
1737 const coap_dtls_role_t role COAP_UNUSED) {
1738 coap_mbedtls_context_t *m_context =
1739 ((coap_mbedtls_context_t *)c_context->dtls_context);
1740
1741 m_context->setup_data = *setup_data;
1742 if (!m_context->setup_data.verify_peer_cert) {
1743 /* Needs to be clear so that no CA DNs are transmitted */
1744 m_context->setup_data.check_common_ca = 0;
1745 /* Allow all of these but warn if issue */
1746 m_context->setup_data.allow_self_signed = 1;
1747 m_context->setup_data.allow_expired_certs = 1;
1748 m_context->setup_data.cert_chain_validation = 1;
1749 m_context->setup_data.cert_chain_verify_depth = 10;
1750 m_context->setup_data.check_cert_revocation = 1;
1751 m_context->setup_data.allow_no_crl = 1;
1752 m_context->setup_data.allow_expired_crl = 1;
1753 m_context->setup_data.allow_bad_md_hash = 1;
1754 m_context->setup_data.allow_short_rsa_length = 1;
1755 }
1756 m_context->psk_pki_enabled |= IS_PKI;
1757 return 1;
1758}
1759
1760int
1762 const char *ca_file,
1763 const char *ca_path) {
1764 coap_mbedtls_context_t *m_context =
1765 ((coap_mbedtls_context_t *)c_context->dtls_context);
1766
1767 if (!m_context) {
1768 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
1769 "not set up\n");
1770 return 0;
1771 }
1772
1773 if (ca_file == NULL && ca_path == NULL) {
1774 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
1775 "not defined\n");
1776 return 0;
1777 }
1778 if (m_context->root_ca_file) {
1779 mbedtls_free(m_context->root_ca_file);
1780 m_context->root_ca_file = NULL;
1781 }
1782
1783 if (ca_file) {
1784 m_context->root_ca_file = mbedtls_strdup(ca_file);
1785 }
1786
1787 if (m_context->root_ca_path) {
1788 mbedtls_free(m_context->root_ca_path);
1789 m_context->root_ca_path = NULL;
1790 }
1791
1792 if (ca_path) {
1793 m_context->root_ca_path = mbedtls_strdup(ca_path);
1794 }
1795 return 1;
1796}
1797
1798int
1800 coap_mbedtls_context_t *m_context =
1801 ((coap_mbedtls_context_t *)c_context->dtls_context);
1802 return m_context->psk_pki_enabled ? 1 : 0;
1803}
1804
1805void
1806coap_dtls_free_context(void *dtls_context) {
1807 coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
1808 unsigned int i;
1809
1810 for (i = 0; i < m_context->pki_sni_count; i++) {
1811 mbedtls_free(m_context->pki_sni_entry_list[i].sni);
1812
1813 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
1814
1815 mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
1816
1817 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
1818 }
1819 if (m_context->pki_sni_entry_list)
1820 mbedtls_free(m_context->pki_sni_entry_list);
1821
1822 for (i = 0; i < m_context->psk_sni_count; i++) {
1823 mbedtls_free(m_context->psk_sni_entry_list[i].sni);
1824 }
1825 if (m_context->psk_sni_entry_list)
1826 mbedtls_free(m_context->psk_sni_entry_list);
1827
1828 if (m_context->root_ca_path)
1829 mbedtls_free(m_context->root_ca_path);
1830 if (m_context->root_ca_file)
1831 mbedtls_free(m_context->root_ca_file);
1832
1833 mbedtls_free(m_context);
1834}
1835
1836#if COAP_CLIENT_SUPPORT
1837void *
1839#if !defined(MBEDTLS_SSL_CLI_C)
1840 (void)c_session;
1841 coap_log_emerg("coap_dtls_new_client_session:"
1842 " libcoap not compiled for Client Mode for Mbed TLS"
1843 " - update Mbed TLS to include Client Mode\n");
1844 return NULL;
1845#else /* MBEDTLS_SSL_CLI_C */
1846 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
1849 int ret;
1850
1851 if (m_env) {
1852 coap_tick_t now;
1853#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1854 if (COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
1855 /*
1856 * Enable passive DTLS CID support.
1857 *
1858 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1859 * to use RFC9146 extension ID of 54, rather than the draft version -05
1860 * value of 254.
1861 */
1862 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, NULL, 0);
1863 }
1864#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1865 coap_ticks(&now);
1866 m_env->last_timeout = now;
1867 ret = do_mbedtls_handshake(c_session, m_env);
1868 if (ret == -1) {
1869 coap_dtls_free_mbedtls_env(m_env);
1870 return NULL;
1871 }
1872 }
1873 return m_env;
1874#endif /* MBEDTLS_SSL_CLI_C */
1875}
1876#endif /* COAP_CLIENT_SUPPORT */
1877
1878#if COAP_SERVER_SUPPORT
1879void *
1881#if !defined(MBEDTLS_SSL_SRV_C)
1882 (void)c_session;
1883 coap_log_emerg("coap_dtls_new_server_session:"
1884 " libcoap not compiled for Server Mode for Mbed TLS"
1885 " - update Mbed TLS to include Server Mode\n");
1886 return NULL;
1887#else /* MBEDTLS_SSL_SRV_C */
1888 coap_mbedtls_env_t *m_env =
1889 (coap_mbedtls_env_t *)c_session->tls;
1890 if (m_env) {
1891#if defined(MBEDTLS_SSL_PROTO_DTLS)
1892#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1893 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1894#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1895#endif /* MBEDTLS_SSL_PROTO_DTLS */
1896 }
1897 return m_env;
1898#endif /* MBEDTLS_SSL_SRV_C */
1899}
1900#endif /* COAP_SERVER_SUPPORT */
1901
1902void
1904 if (c_session && c_session->context && c_session->tls) {
1905 coap_dtls_free_mbedtls_env(c_session->tls);
1906 c_session->tls = NULL;
1907 coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session);
1908 }
1909 return;
1910}
1911
1912void
1914#if defined(MBEDTLS_SSL_PROTO_DTLS)
1915 coap_mbedtls_env_t *m_env =
1916 (coap_mbedtls_env_t *)c_session->tls;
1917 if (m_env) {
1918#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1919 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1920#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1921 }
1922#else /* ! MBEDTLS_SSL_PROTO_DTLS */
1923 (void)c_session;
1924#endif /* MBEDTLS_SSL_PROTO_DTLS */
1925}
1926
1927ssize_t
1929 const uint8_t *data, size_t data_len) {
1930 int ret;
1931 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1932
1933 assert(m_env != NULL);
1934
1935 if (!m_env) {
1936 return -1;
1937 }
1938 c_session->dtls_event = -1;
1939 if (m_env->established) {
1940 ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char *) data, data_len);
1941 if (ret <= 0) {
1942 switch (ret) {
1943 case MBEDTLS_ERR_SSL_WANT_READ:
1944 case MBEDTLS_ERR_SSL_WANT_WRITE:
1945 ret = 0;
1946 break;
1947 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1949 ret = -1;
1950 break;
1951 default:
1952 coap_log_warn("coap_dtls_send: "
1953 "returned -0x%x: '%s'\n",
1954 -ret, get_error_string(ret));
1955 ret = -1;
1956 break;
1957 }
1958 if (ret == -1) {
1959 coap_log_warn("coap_dtls_send: cannot send PDU\n");
1960 }
1961 }
1962 } else {
1963 ret = do_mbedtls_handshake(c_session, m_env);
1964 if (ret == 1) {
1965 /* Just connected, so send the data */
1966 return coap_dtls_send(c_session, data, data_len);
1967 }
1968 ret = -1;
1969 }
1970
1971 if (c_session->dtls_event >= 0) {
1972 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1973 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1974 coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1975 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1976 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1978 ret = -1;
1979 }
1980 }
1981 if (ret > 0) {
1982 if (ret == (ssize_t)data_len)
1983 coap_log_debug("* %s: dtls: sent %4d bytes\n",
1984 coap_session_str(c_session), ret);
1985 else
1986 coap_log_debug("* %s: dtls: sent %4d of %4zd bytes\n",
1987 coap_session_str(c_session), ret, data_len);
1988 }
1989 return ret;
1990}
1991
1992int
1994 return 0;
1995}
1996
1998coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
1999 return 0;
2000}
2001
2004 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2005 int ret = mbedtls_timing_get_delay(&m_env->timer);
2006 unsigned int scalar = 1 << m_env->retry_scalar;
2007
2008 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2009 switch (ret) {
2010 case 0:
2011 /* int_ms has not timed out */
2012 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2013 /* Need to indicate remaining timeout time */
2014 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2015 }
2016 m_env->last_timeout = now;
2017 /* This may cause a minor extra delay */
2018 return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2019 case 1:
2020 /* int_ms has timed out, but not fin_ms */
2021 /*
2022 * Need to make sure that we do not do this too frequently
2023 */
2024 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2025 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2026 }
2027
2028 /* Reset for the next time */
2029 m_env->last_timeout = now;
2030 return now;
2031 case 2:
2032 /* fin_ms has timed out - timed out - one final try */
2033 return now;
2034 default:
2035 break;
2036 }
2037
2038 return 0;
2039}
2040
2041/*
2042 * return 1 timed out
2043 * 0 still timing out
2044 */
2045int
2047 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2048
2049 assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2050 m_env->retry_scalar++;
2051 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2052 (do_mbedtls_handshake(c_session, m_env) < 0)) {
2053 /* Too many retries */
2055 return 1;
2056 }
2057 return 0;
2058}
2059
2060/*
2061 * return +ve data amount
2062 * 0 no more
2063 * -1 error
2064 */
2065int
2067 const uint8_t *data,
2068 size_t data_len) {
2069 int ret = 1;
2070
2071 c_session->dtls_event = -1;
2072 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2073 coap_ssl_t *ssl_data;
2074
2075 assert(m_env != NULL);
2076
2077 ssl_data = &m_env->coap_ssl_data;
2078 if (ssl_data->pdu_len) {
2079 coap_log_err("** %s: Previous data not read %u bytes\n",
2080 coap_session_str(c_session), ssl_data->pdu_len);
2081 }
2082 ssl_data->pdu = data;
2083 ssl_data->pdu_len = (unsigned)data_len;
2084
2085 if (m_env->established) {
2086#if COAP_CONSTRAINED_STACK
2087 /* pdu protected by mutex m_dtls_recv */
2088 static uint8_t pdu[COAP_RXBUFFER_SIZE];
2089#else /* ! COAP_CONSTRAINED_STACK */
2090 uint8_t pdu[COAP_RXBUFFER_SIZE];
2091#endif /* ! COAP_CONSTRAINED_STACK */
2092
2093#if COAP_CONSTRAINED_STACK
2094 coap_mutex_lock(&m_dtls_recv);
2095#endif /* COAP_CONSTRAINED_STACK */
2096
2097 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2099 c_session);
2100 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2101 }
2102
2103 ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2104 if (ret > 0) {
2105 ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2106#if COAP_CONSTRAINED_STACK
2107 coap_mutex_unlock(&m_dtls_recv);
2108#endif /* COAP_CONSTRAINED_STACK */
2109 goto finish;
2110 }
2111 switch (ret) {
2112 case 0:
2113 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2114 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2116 break;
2117 case MBEDTLS_ERR_SSL_WANT_READ:
2118 break;
2119 default:
2120 coap_log_warn("coap_dtls_receive: "
2121 "returned -0x%x: '%s' (length %zd)\n",
2122 -ret, get_error_string(ret), data_len);
2123 break;
2124 }
2125#if COAP_CONSTRAINED_STACK
2126 coap_mutex_unlock(&m_dtls_recv);
2127#endif /* COAP_CONSTRAINED_STACK */
2128 ret = -1;
2129 } else {
2130 ret = do_mbedtls_handshake(c_session, m_env);
2131 if (ret == 1) {
2132 /* Just connected, so send the data */
2133 coap_session_connected(c_session);
2134 } else {
2135 if (ssl_data->pdu_len) {
2136 /* Do the handshake again incase of internal timeout */
2137 ret = do_mbedtls_handshake(c_session, m_env);
2138 if (ret == 1) {
2139 /* Just connected, so send the data */
2140 coap_session_connected(c_session);
2141 } else {
2142 ret = -1;
2143 }
2144 }
2145 ret = -1;
2146 }
2147 }
2148 if (c_session->dtls_event >= 0) {
2149 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2150 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2151 coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2152 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2153 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2155 ssl_data = NULL;
2156 ret = -1;
2157 }
2158 }
2159finish:
2160 if (ssl_data && ssl_data->pdu_len) {
2161 /* pdu data is held on stack which will not stay there */
2162 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2163 ssl_data->pdu_len = 0;
2164 ssl_data->pdu = NULL;
2165 }
2166 if (ret > 0) {
2167 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2168 coap_session_str(c_session), ret);
2169 }
2170 return ret;
2171}
2172
2173#if COAP_SERVER_SUPPORT
2174/*
2175 * return -1 failure
2176 * 0 not completed
2177 * 1 client hello seen
2178 */
2179int
2181 const uint8_t *data,
2182 size_t data_len) {
2183#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2184 (void)c_session;
2185 (void)data;
2186 (void)data_len;
2187 coap_log_emerg("coap_dtls_hello:"
2188 " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2189 " - update Mbed TLS to include DTLS and Server Mode\n");
2190 return -1;
2191#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2192 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2193 coap_ssl_t *ssl_data;
2194 int ret;
2195
2196 if (!m_env) {
2197 m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2199 if (m_env) {
2200 c_session->tls = m_env;
2201 } else {
2202 /* error should have already been reported */
2203 return -1;
2204 }
2205 }
2206
2207 if ((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2208 (unsigned char *)&c_session->addr_info.remote,
2209 sizeof(c_session->addr_info.remote))) != 0) {
2210 coap_log_err("mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2211 -ret, get_error_string(ret));
2212 return -1;
2213 }
2214
2215 ssl_data = &m_env->coap_ssl_data;
2216 if (ssl_data->pdu_len) {
2217 coap_log_err("** %s: Previous data not read %u bytes\n",
2218 coap_session_str(c_session), ssl_data->pdu_len);
2219 }
2220 ssl_data->pdu = data;
2221 ssl_data->pdu_len = (unsigned)data_len;
2222
2223 ret = do_mbedtls_handshake(c_session, m_env);
2224 if (ret == 0 || m_env->seen_client_hello) {
2225 /* The test for seen_client_hello gives the ability to setup a new
2226 c_session to continue the do_mbedtls_handshake past the client hello
2227 and safely allow updating of the m_env and separately
2228 letting a new session cleanly start up.
2229 */
2230 m_env->seen_client_hello = 0;
2231 ret = 1;
2232 } else {
2233 ret = 0;
2234 }
2235
2236 if (ssl_data->pdu_len) {
2237 /* pdu data is held on stack which will not stay there */
2238 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2239 ssl_data->pdu_len = 0;
2240 ssl_data->pdu = NULL;
2241 }
2242 return ret;
2243#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2244}
2245#endif /* COAP_SERVER_SUPPORT */
2246
2247unsigned int
2249 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2250 int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2251
2252 if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2253 return 13 + 8 + 8;
2254 }
2255 return expansion;
2256}
2257
2258#if !COAP_DISABLE_TCP
2259#if COAP_CLIENT_SUPPORT
2260void *
2262#if !defined(MBEDTLS_SSL_CLI_C)
2263 (void)c_session;
2264 *connected = 0;
2265 coap_log_emerg("coap_tls_new_client_session:"
2266 " libcoap not compiled for Client Mode for Mbed TLS"
2267 " - update Mbed TLS to include Client Mode\n");
2268 return NULL;
2269#else /* MBEDTLS_SSL_CLI_C */
2270 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2273 int ret;
2274 coap_tick_t now;
2275 coap_ticks(&now);
2276
2277 if (!m_env)
2278 return NULL;
2279
2280 m_env->last_timeout = now;
2281 c_session->tls = m_env;
2282 ret = do_mbedtls_handshake(c_session, m_env);
2283 if (ret == 1) {
2284 coap_handle_event(c_session->context, COAP_EVENT_DTLS_CONNECTED, c_session);
2285 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2286 }
2287 return m_env;
2288#endif /* MBEDTLS_SSL_CLI_C */
2289}
2290#endif /* COAP_CLIENT_SUPPORT */
2291
2292#if COAP_SERVER_SUPPORT
2293void *
2295#if !defined(MBEDTLS_SSL_SRV_C)
2296 (void)c_session;
2297 (void)connected;
2298
2299 coap_log_emerg("coap_tls_new_server_session:"
2300 " libcoap not compiled for Server Mode for Mbed TLS"
2301 " - update Mbed TLS to include Server Mode\n");
2302 return NULL;
2303#else /* MBEDTLS_SSL_SRV_C */
2304 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2307 int ret;
2308
2309 if (!m_env)
2310 return NULL;
2311
2312 c_session->tls = m_env;
2313 ret = do_mbedtls_handshake(c_session, m_env);
2314 if (ret == 1) {
2315 coap_handle_event(c_session->context, COAP_EVENT_DTLS_CONNECTED, c_session);
2316 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2317 }
2318 return m_env;
2319#endif /* MBEDTLS_SSL_SRV_C */
2320}
2321#endif /* COAP_SERVER_SUPPORT */
2322
2323void
2325 coap_dtls_free_session(c_session);
2326 return;
2327}
2328
2329/*
2330 * strm
2331 * return +ve Number of bytes written.
2332 * -1 Error (error in errno).
2333 */
2334ssize_t
2335coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2336 size_t data_len) {
2337 int ret = 0;
2338 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2339 size_t amount_sent = 0;
2340
2341 assert(m_env != NULL);
2342
2343 if (!m_env) {
2344 errno = ENXIO;
2345 return -1;
2346 }
2347 c_session->dtls_event = -1;
2348 if (m_env->established) {
2349 while (amount_sent < data_len) {
2350 ret = mbedtls_ssl_write(&m_env->ssl, &data[amount_sent],
2351 data_len - amount_sent);
2352 if (ret <= 0) {
2353 switch (ret) {
2354 case MBEDTLS_ERR_SSL_WANT_READ:
2355 case MBEDTLS_ERR_SSL_WANT_WRITE:
2356 if (amount_sent)
2357 ret = amount_sent;
2358 else
2359 ret = 0;
2360 c_session->sock.flags |= COAP_SOCKET_WANT_WRITE;
2361 break;
2362 case MBEDTLS_ERR_NET_CONN_RESET:
2363 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2365 break;
2366 default:
2367 coap_log_warn("coap_tls_write: "
2368 "returned -0x%x: '%s'\n",
2369 -ret, get_error_string(ret));
2370 ret = -1;
2371 break;
2372 }
2373 if (ret == -1) {
2374 coap_log_warn("coap_tls_write: cannot send PDU\n");
2375 }
2376 break;
2377 }
2378 amount_sent += ret;
2379 }
2380 } else {
2381 ret = do_mbedtls_handshake(c_session, m_env);
2382 if (ret == 1) {
2384 c_session);
2385 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2386 } else {
2387 ret = -1;
2388 }
2389 }
2390
2391 if (c_session->dtls_event >= 0) {
2392 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2393 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2394 coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2395 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2396 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2398 ret = -1;
2399 }
2400 }
2401 if (ret > 0) {
2402 if (ret == (ssize_t)data_len)
2403 coap_log_debug("* %s: tls: sent %4d bytes\n",
2404 coap_session_str(c_session), ret);
2405 else
2406 coap_log_debug("* %s: tls: sent %4d of %4zd bytes\n",
2407 coap_session_str(c_session), ret, data_len);
2408 }
2409 return ret;
2410}
2411
2412/*
2413 * strm
2414 * return >=0 Number of bytes read.
2415 * -1 Error (error in errno).
2416 */
2417ssize_t
2418coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
2419 int ret = -1;
2420
2421 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2422
2423 if (!m_env) {
2424 errno = ENXIO;
2425 return -1;
2426 }
2427
2428 c_session->dtls_event = -1;
2429
2430 if (!m_env->established && !m_env->sent_alert) {
2431 ret = do_mbedtls_handshake(c_session, m_env);
2432 if (ret == 1) {
2434 c_session);
2435 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2436 }
2437 }
2438
2439 if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
2440 ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
2441 if (ret <= 0) {
2442 switch (ret) {
2443 case 0:
2444 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2446 ret = -1;
2447 break;
2448 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2449 /* Stop the sending of an alert on closedown */
2450 m_env->sent_alert = 1;
2452 break;
2453 case MBEDTLS_ERR_SSL_WANT_READ:
2454 errno = EAGAIN;
2455 ret = 0;
2456 break;
2457 default:
2458 coap_log_warn("coap_tls_read: "
2459 "returned -0x%x: '%s' (length %zd)\n",
2460 -ret, get_error_string(ret), data_len);
2461 ret = -1;
2462 break;
2463 }
2464 } else if (ret < (int)data_len) {
2465 c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
2466 }
2467 }
2468
2469 if (c_session->dtls_event >= 0) {
2470 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2471 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2472 coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2473 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2474 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2476 ret = -1;
2477 }
2478 }
2479 if (ret > 0) {
2480 coap_log_debug("* %s: tls: recv %4d bytes\n",
2481 coap_session_str(c_session), ret);
2482 }
2483 return ret;
2484}
2485#endif /* !COAP_DISABLE_TCP */
2486
2487void
2488coap_dtls_startup(void) {
2489}
2490
2491void
2492coap_dtls_shutdown(void) {
2493#if COAP_CLIENT_SUPPORT
2494 mbedtls_free(psk_ciphers);
2495 mbedtls_free(pki_ciphers);
2496 psk_ciphers = NULL;
2497 pki_ciphers = NULL;
2498 processed_ciphers = 0;
2499#endif /* COAP_CLIENT_SUPPORT */
2501}
2502
2503void *
2504coap_dtls_get_tls(const coap_session_t *c_session,
2505 coap_tls_library_t *tls_lib) {
2506 if (tls_lib)
2507 *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
2508 if (c_session && c_session->tls) {
2509 coap_mbedtls_env_t *m_env;
2510
2511 /* To get around const issue */
2512 memcpy(&m_env, &c_session->tls, sizeof(m_env));
2513
2514 return (void *)&m_env->ssl;
2515 }
2516 return NULL;
2517}
2518
2519static coap_log_t keep_log_level = COAP_LOG_EMERG;
2520
2521void
2523#if !defined(ESPIDF_VERSION)
2524 int use_level;
2525 /*
2526 * Mbed TLS debug levels filter
2527 * 0 No debug
2528 * 1 Error
2529 * 2 State change
2530 * 3 Informational
2531 * 4 Verbose
2532 */
2533 switch ((int)level) {
2534 case COAP_LOG_EMERG:
2535 use_level = 0;
2536 break;
2537 case COAP_LOG_ALERT:
2538 case COAP_LOG_CRIT:
2539 case COAP_LOG_ERR:
2540 case COAP_LOG_WARN:
2541 use_level = 1;
2542 break;
2543 case COAP_LOG_NOTICE:
2544 use_level = 2;
2545 break;
2546 case COAP_LOG_INFO:
2547 use_level = 3;
2548 break;
2549 case COAP_LOG_DEBUG:
2550 default:
2551 use_level = 4;
2552 break;
2553 }
2554 mbedtls_debug_set_threshold(use_level);
2555#endif /* !ESPIDF_VERSION) */
2556 keep_log_level = level;
2557}
2558
2561 return keep_log_level;
2562}
2563
2566 static coap_tls_version_t version;
2567 version.version = mbedtls_version_get_number();
2568 version.built_version = MBEDTLS_VERSION_NUMBER;
2570 return &version;
2571}
2572
2573#if COAP_SERVER_SUPPORT
2575coap_digest_setup(void) {
2576 mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
2577
2578 if (digest_ctx) {
2579 mbedtls_sha256_init(digest_ctx);
2580#ifdef MBEDTLS_2_X_COMPAT
2581 if (mbedtls_sha256_starts_ret(digest_ctx, 0) != 0) {
2582#else
2583 if (mbedtls_sha256_starts(digest_ctx, 0) != 0) {
2584#endif /* MBEDTLS_2_X_COMPAT */
2585 return NULL;
2586 }
2587 }
2588 return digest_ctx;
2589}
2590
2591void
2593 mbedtls_sha256_free(digest_ctx);
2594 mbedtls_free(digest_ctx);
2595}
2596
2597int
2599 const uint8_t *data,
2600 size_t data_len) {
2601#ifdef MBEDTLS_2_X_COMPAT
2602 int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
2603#else
2604 int ret = mbedtls_sha256_update(digest_ctx, data, data_len);
2605#endif /* MBEDTLS_2_X_COMPAT */
2606
2607 return ret == 0;
2608}
2609
2610int
2612 coap_digest_t *digest_buffer) {
2613#ifdef MBEDTLS_2_X_COMPAT
2614 int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t *)digest_buffer);
2615#else
2616 int ret = mbedtls_sha256_finish(digest_ctx, (uint8_t *)digest_buffer);
2617#endif /* MBEDTLS_2_X_COMPAT */
2618
2619 coap_digest_free(digest_ctx);
2620 return ret == 0;
2621}
2622#endif /* COAP_SERVER_SUPPORT */
2623
2624#include <mbedtls/cipher.h>
2625#include <mbedtls/md.h>
2626
2627#ifndef MBEDTLS_CIPHER_MODE_AEAD
2628#error need MBEDTLS_CIPHER_MODE_AEAD, please enable MBEDTLS_CCM_C
2629#endif /* MBEDTLS_CIPHER_MODE_AEAD */
2630
2631#ifdef MBEDTLS_ERROR_C
2632#include <mbedtls/error.h>
2633#endif /* MBEDTLS_ERROR_C */
2634
2635#ifdef MBEDTLS_ERROR_C
2636#define C(Func) \
2637 do { \
2638 int c_tmp = (int)(Func); \
2639 if (c_tmp != 0) { \
2640 char error_buf[64]; \
2641 mbedtls_strerror(c_tmp, error_buf, sizeof(error_buf)); \
2642 coap_log_err("mbedtls: -0x%04x: %s\n", -c_tmp, error_buf); \
2643 goto error; \
2644 } \
2645 } while (0);
2646#else /* !MBEDTLS_ERROR_C */
2647#define C(Func) \
2648 do { \
2649 int c_tmp = (int)(Func); \
2650 if (c_tmp != 0) { \
2651 coap_log_err("mbedtls: %d\n", tmp); \
2652 goto error; \
2653 } \
2654 } while (0);
2655#endif /* !MBEDTLS_ERROR_C */
2656
2657#if COAP_WS_SUPPORT
2658/*
2659 * The struct hash_algs and the function get_hash_alg() are used to
2660 * determine which hash type to use for creating the required hash object.
2661 */
2662static struct hash_algs {
2663 cose_alg_t alg;
2664 mbedtls_md_type_t hash_type;
2665 size_t hash_size;
2666} hashs[] = {
2667 {COSE_ALGORITHM_SHA_1, MBEDTLS_MD_SHA1, 20},
2668 {COSE_ALGORITHM_SHA_256_256, MBEDTLS_MD_SHA256, 32},
2669 {COSE_ALGORITHM_SHA_512, MBEDTLS_MD_SHA512, 64},
2670};
2671
2672static mbedtls_md_type_t
2673get_hash_alg(cose_alg_t alg, size_t *hash_len) {
2674 size_t idx;
2675
2676 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
2677 if (hashs[idx].alg == alg) {
2678 *hash_len = hashs[idx].hash_size;
2679 return hashs[idx].hash_type;
2680 }
2681 }
2682 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
2683 return MBEDTLS_MD_NONE;
2684}
2685
2686int
2688 const coap_bin_const_t *data,
2689 coap_bin_const_t **hash) {
2690 mbedtls_md_context_t ctx;
2691 int ret = 0;
2692 const mbedtls_md_info_t *md_info;
2693 unsigned int len;
2694 coap_binary_t *dummy = NULL;
2695 size_t hash_length;
2696 mbedtls_md_type_t dig_type = get_hash_alg(alg, &hash_length);
2697
2698 if (dig_type == MBEDTLS_MD_NONE) {
2699 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
2700 return 0;
2701 }
2702 md_info = mbedtls_md_info_from_type(dig_type);
2703
2704 len = mbedtls_md_get_size(md_info);
2705 if (len == 0) {
2706 return 0;
2707 }
2708
2709 mbedtls_md_init(&ctx);
2710 C(mbedtls_md_setup(&ctx, md_info, 0));
2711
2712 C(mbedtls_md_starts(&ctx));
2713 C(mbedtls_md_update(&ctx, (const unsigned char *)data->s, data->length));
2714 dummy = coap_new_binary(len);
2715 if (dummy == NULL)
2716 goto error;
2717 C(mbedtls_md_finish(&ctx, dummy->s));
2718
2719 *hash = (coap_bin_const_t *)dummy;
2720 ret = 1;
2721error:
2722 mbedtls_md_free(&ctx);
2723 return ret;
2724}
2725#endif /* COAP_WS_SUPPORT */
2726
2727#if COAP_OSCORE_SUPPORT
2728int
2730 return 1;
2731}
2732
2733/*
2734 * The struct cipher_algs and the function get_cipher_alg() are used to
2735 * determine which cipher type to use for creating the required cipher
2736 * suite object.
2737 */
2738static struct cipher_algs {
2739 cose_alg_t alg;
2740 mbedtls_cipher_type_t cipher_type;
2741} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, MBEDTLS_CIPHER_AES_128_CCM},
2742 {COSE_ALGORITHM_AES_CCM_16_64_256, MBEDTLS_CIPHER_AES_256_CCM}
2743};
2744
2745static mbedtls_cipher_type_t
2746get_cipher_alg(cose_alg_t alg) {
2747 size_t idx;
2748
2749 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
2750 if (ciphers[idx].alg == alg)
2751 return ciphers[idx].cipher_type;
2752 }
2753 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
2754 return 0;
2755}
2756
2757/*
2758 * The struct hmac_algs and the function get_hmac_alg() are used to
2759 * determine which hmac type to use for creating the required hmac
2760 * suite object.
2761 */
2762static struct hmac_algs {
2763 cose_hmac_alg_t hmac_alg;
2764 mbedtls_md_type_t hmac_type;
2765} hmacs[] = {
2766 {COSE_HMAC_ALG_HMAC256_256, MBEDTLS_MD_SHA256},
2767 {COSE_HMAC_ALG_HMAC384_384, MBEDTLS_MD_SHA384},
2768 {COSE_HMAC_ALG_HMAC512_512, MBEDTLS_MD_SHA512},
2769};
2770
2771static mbedtls_md_type_t
2772get_hmac_alg(cose_hmac_alg_t hmac_alg) {
2773 size_t idx;
2774
2775 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
2776 if (hmacs[idx].hmac_alg == hmac_alg)
2777 return hmacs[idx].hmac_type;
2778 }
2779 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
2780 return 0;
2781}
2782
2783int
2785 return get_cipher_alg(alg) != 0;
2786}
2787
2788int
2790 cose_hmac_alg_t hmac_alg;
2791
2792 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
2793 return 0;
2794 return get_hmac_alg(hmac_alg) != 0;
2795}
2796
2801static int
2802setup_cipher_context(mbedtls_cipher_context_t *ctx,
2803 cose_alg_t coap_alg,
2804 const uint8_t *key_data,
2805 size_t key_length,
2806 mbedtls_operation_t mode) {
2807 const mbedtls_cipher_info_t *cipher_info;
2808 mbedtls_cipher_type_t cipher_type;
2809 uint8_t key[COAP_CRYPTO_MAX_KEY_SIZE]; /* buffer for normalizing the key
2810 according to its key length */
2811 int klen;
2812 memset(key, 0, sizeof(key));
2813
2814 if ((cipher_type = get_cipher_alg(coap_alg)) == 0) {
2815 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
2816 coap_alg);
2817 return 0;
2818 }
2819 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
2820 if (!cipher_info) {
2821 coap_log_crit("coap_crypto_encrypt: cannot get cipher info\n");
2822 return 0;
2823 }
2824
2825 mbedtls_cipher_init(ctx);
2826
2827 C(mbedtls_cipher_setup(ctx, cipher_info));
2828 klen = mbedtls_cipher_get_key_bitlen(ctx);
2829 if ((klen > (int)(sizeof(key) * 8)) || (key_length > sizeof(key))) {
2830 coap_log_crit("coap_crypto: cannot set key\n");
2831 goto error;
2832 }
2833 memcpy(key, key_data, key_length);
2834 C(mbedtls_cipher_setkey(ctx, key, klen, mode));
2835
2836 /* On success, the cipher context is released by the caller. */
2837 return 1;
2838error:
2839 mbedtls_cipher_free(ctx);
2840 return 0;
2841}
2842
2843int
2845 coap_bin_const_t *data,
2846 coap_bin_const_t *aad,
2847 uint8_t *result,
2848 size_t *max_result_len) {
2849 mbedtls_cipher_context_t ctx;
2850 const coap_crypto_aes_ccm_t *ccm;
2851#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2852 unsigned char tag[16];
2853#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
2854 int ret = 0;
2855 size_t result_len = *max_result_len;
2856 coap_bin_const_t laad;
2857
2858 if (data == NULL)
2859 return 0;
2860
2861 assert(params != NULL);
2862
2863 if (!params) {
2864 return 0;
2865 }
2866 ccm = &params->params.aes;
2867
2868 if (!setup_cipher_context(&ctx,
2869 params->alg,
2870 ccm->key.s,
2871 ccm->key.length,
2872 MBEDTLS_ENCRYPT)) {
2873 return 0;
2874 }
2875
2876 if (aad) {
2877 laad = *aad;
2878 } else {
2879 laad.s = NULL;
2880 laad.length = 0;
2881 }
2882
2883#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2884 C(mbedtls_cipher_auth_encrypt(&ctx,
2885 ccm->nonce,
2886 15 - ccm->l, /* iv */
2887 laad.s,
2888 laad.length, /* ad */
2889 data->s,
2890 data->length, /* input */
2891 result,
2892 &result_len, /* output */
2893 tag,
2894 ccm->tag_len /* tag */
2895 ));
2896 /* check if buffer is sufficient to hold tag */
2897 if ((result_len + ccm->tag_len) > *max_result_len) {
2898 coap_log_err("coap_encrypt: buffer too small\n");
2899 goto error;
2900 }
2901 /* append tag to result */
2902 memcpy(result + result_len, tag, ccm->tag_len);
2903 *max_result_len = result_len + ccm->tag_len;
2904 ret = 1;
2905#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
2906 C(mbedtls_cipher_auth_encrypt_ext(&ctx,
2907 ccm->nonce,
2908 15 - ccm->l, /* iv */
2909 laad.s,
2910 laad.length, /* ad */
2911 data->s,
2912 data->length, /* input */
2913 result,
2914 result_len,
2915 &result_len, /* output */
2916 ccm->tag_len /* tag */
2917 ));
2918 *max_result_len = result_len;
2919 ret = 1;
2920#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
2921
2922error:
2923 mbedtls_cipher_free(&ctx);
2924 return ret;
2925}
2926
2927int
2929 coap_bin_const_t *data,
2930 coap_bin_const_t *aad,
2931 uint8_t *result,
2932 size_t *max_result_len) {
2933 mbedtls_cipher_context_t ctx;
2934 const coap_crypto_aes_ccm_t *ccm;
2935#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2936 const unsigned char *tag;
2937#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
2938 int ret = 0;
2939 size_t result_len = *max_result_len;
2940 coap_bin_const_t laad;
2941
2942 if (data == NULL)
2943 return 0;
2944
2945 assert(params != NULL);
2946
2947 if (!params) {
2948 return 0;
2949 }
2950
2951 ccm = &params->params.aes;
2952
2953 if (!setup_cipher_context(&ctx,
2954 params->alg,
2955 ccm->key.s,
2956 ccm->key.length,
2957 MBEDTLS_DECRYPT)) {
2958 return 0;
2959 }
2960
2961 if (data->length < ccm->tag_len) {
2962 coap_log_err("coap_decrypt: invalid tag length\n");
2963 goto error;
2964 }
2965
2966 if (aad) {
2967 laad = *aad;
2968 } else {
2969 laad.s = NULL;
2970 laad.length = 0;
2971 }
2972
2973#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2974 tag = data->s + data->length - ccm->tag_len;
2975 C(mbedtls_cipher_auth_decrypt(&ctx,
2976 ccm->nonce,
2977 15 - ccm->l, /* iv */
2978 laad.s,
2979 laad.length, /* ad */
2980 data->s,
2981 data->length - ccm->tag_len, /* input */
2982 result,
2983 &result_len, /* output */
2984 tag,
2985 ccm->tag_len /* tag */
2986 ));
2987#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
2988 C(mbedtls_cipher_auth_decrypt_ext(&ctx,
2989 ccm->nonce,
2990 15 - ccm->l, /* iv */
2991 laad.s,
2992 laad.length, /* ad */
2993 data->s,
2994 // data->length - ccm->tag_len, /* input */
2995 data->length, /* input */
2996 result,
2997 result_len,
2998 &result_len, /* output */
2999 ccm->tag_len /* tag */
3000 ));
3001#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3002
3003 *max_result_len = result_len;
3004 ret = 1;
3005error:
3006 mbedtls_cipher_free(&ctx);
3007 return ret;
3008}
3009
3010int
3012 coap_bin_const_t *key,
3013 coap_bin_const_t *data,
3014 coap_bin_const_t **hmac) {
3015 mbedtls_md_context_t ctx;
3016 int ret = 0;
3017 const int use_hmac = 1;
3018 const mbedtls_md_info_t *md_info;
3019 mbedtls_md_type_t mac_algo;
3020 unsigned int len;
3021 coap_binary_t *dummy = NULL;
3022
3023 assert(key);
3024 assert(data);
3025 assert(hmac);
3026
3027 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3028 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3029 return 0;
3030 }
3031 md_info = mbedtls_md_info_from_type(mac_algo);
3032
3033 len = mbedtls_md_get_size(md_info);
3034 if (len == 0) {
3035 return 0;
3036 }
3037
3038 mbedtls_md_init(&ctx);
3039 C(mbedtls_md_setup(&ctx, md_info, use_hmac));
3040
3041 C(mbedtls_md_hmac_starts(&ctx, key->s, key->length));
3042 C(mbedtls_md_hmac_update(&ctx, (const unsigned char *)data->s, data->length));
3043 dummy = coap_new_binary(len);
3044 if (dummy == NULL)
3045 goto error;
3046 C(mbedtls_md_hmac_finish(&ctx, dummy->s));
3047
3048 *hmac = (coap_bin_const_t *)dummy;
3049 ret = 1;
3050error:
3051 mbedtls_md_free(&ctx);
3052 return ret;
3053}
3054
3055#endif /* COAP_OSCORE_SUPPORT */
3056
3057#else /* !COAP_WITH_LIBMBEDTLS */
3058
3059#ifdef __clang__
3060/* Make compilers happy that do not like empty modules. As this function is
3061 * never used, we ignore -Wunused-function at the end of compiling this file
3062 */
3063#pragma GCC diagnostic ignored "-Wunused-function"
3064#endif
3065static inline void
3066dummy(void) {
3067}
3068
3069#endif /* COAP_WITH_LIBMBEDTLS */
Pulls together all the internal only header files.
#define PRIx32
Definition: coap_internal.h:42
const char * coap_socket_strerror(void)
Definition: coap_io.c:1774
#define COAP_RXBUFFER_SIZE
Definition: coap_io.h:29
@ COAP_NACK_TLS_FAILED
Definition: coap_io.h:73
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
@ COAP_LAYER_TLS
static void dummy(void)
#define coap_mutex_unlock(a)
#define coap_mutex_lock(a)
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:77
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition: coap_notls.c:193
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:265
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition: coap_notls.c:188
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:207
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition: coap_notls.c:122
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:225
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition: coap_notls.c:111
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:176
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:253
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:172
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:85
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:202
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition: coap_notls.c:150
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:168
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition: coap_notls.c:145
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:244
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition: coap_time.h:143
int coap_prng(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition: coap_prng.c:140
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:2285
int coap_handle_event(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:4073
void coap_ticks(coap_tick_t *)
Returns the current value of an internal tick counter.
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.
#define COAP_CRYPTO_MAX_KEY_SIZE
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.
void * coap_tls_new_server_session(coap_session_t *coap_session)
Create a TLS new server-side session.
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *session)
Get the current client's PSK identity.
Definition: coap_net.c:286
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:118
void * coap_dtls_new_client_session(coap_session_t *coap_session)
Create a new client-side session.
void * coap_dtls_new_server_session(coap_session_t *coap_session)
Create a new DTLS server-side session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition: coap_notls.c:183
int coap_dtls_context_set_cpsk(coap_context_t *coap_context, coap_dtls_cpsk_t *setup_data)
Set the DTLS context's default client PSK information.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition: coap_notls.c:130
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
void * coap_tls_new_client_session(coap_session_t *coap_session)
Create a new TLS client-side session.
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
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:69
int coap_dtls_psk_is_supported(void)
Check whether (D)TLS PSK is available.
Definition: coap_notls.c:37
coap_dtls_role_t
Definition: coap_dtls.h:44
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition: coap_notls.c:28
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition: coap_notls.c:23
int coap_dtls_pki_is_supported(void)
Check whether (D)TLS PKI is available.
Definition: coap_notls.c:46
int coap_dtls_rpk_is_supported(void)
Check whether (D)TLS RPK is available.
Definition: coap_notls.c:64
coap_tls_library_t
Definition: coap_dtls.h:93
int coap_dtls_pkcs11_is_supported(void)
Check whether (D)TLS PKCS11 is available.
Definition: coap_notls.c:55
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:46
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition: coap_dtls.h:45
@ COAP_PKI_KEY_PKCS11
The PKI key type is PKCS11 (DER)
Definition: coap_dtls.h:194
@ COAP_PKI_KEY_PEM_BUF
The PKI key type is PEM buffer.
Definition: coap_dtls.h:193
@ COAP_PKI_KEY_PEM
The PKI key type is PEM file.
Definition: coap_dtls.h:191
@ COAP_PKI_KEY_ASN1
The PKI key type is ASN.1 (DER) buffer.
Definition: coap_dtls.h:192
@ COAP_TLS_LIBRARY_MBEDTLS
Using Mbed TLS library.
Definition: coap_dtls.h:98
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition: coap_event.h:39
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition: coap_event.h:41
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition: coap_event.h:45
#define coap_log_debug(...)
Definition: coap_debug.h:120
#define coap_log_emerg(...)
Definition: coap_debug.h:81
coap_log_t
Logging type.
Definition: coap_debug.h:50
coap_log_t coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition: coap_notls.c:140
#define coap_dtls_log(level,...)
Logging function.
Definition: coap_debug.h:300
void coap_dtls_set_log_level(coap_log_t level)
Sets the (D)TLS logging level to the specified level.
Definition: coap_notls.c:135
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition: coap_debug.h:108
#define coap_log_warn(...)
Definition: coap_debug.h:102
#define coap_log_err(...)
Definition: coap_debug.h:96
#define coap_log_crit(...)
Definition: coap_debug.h:90
@ COAP_LOG_INFO
Definition: coap_debug.h:57
@ COAP_LOG_EMERG
Definition: coap_debug.h:51
@ COAP_LOG_NOTICE
Definition: coap_debug.h:56
@ COAP_LOG_DEBUG
Definition: coap_debug.h:58
@ COAP_LOG_ALERT
Definition: coap_debug.h:52
@ COAP_LOG_CRIT
Definition: coap_debug.h:53
@ COAP_LOG_ERR
Definition: coap_debug.h:54
@ COAP_LOG_WARN
Definition: coap_debug.h:55
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)
Definition: oscore_cose.c:179
cose_hkdf_alg_t
Definition: oscore_cose.h:165
cose_hmac_alg_t
Definition: oscore_cose.h:157
cose_alg_t
Definition: oscore_cose.h:126
@ COSE_HMAC_ALG_HMAC384_384
Definition: oscore_cose.h:160
@ COSE_HMAC_ALG_HMAC256_256
Definition: oscore_cose.h:159
@ COSE_HMAC_ALG_HMAC512_512
Definition: oscore_cose.h:161
@ COSE_ALGORITHM_SHA_256_256
Definition: oscore_cose.h:134
@ COSE_ALGORITHM_SHA_1
Definition: oscore_cose.h:136
@ COSE_ALGORITHM_AES_CCM_16_64_128
Definition: oscore_cose.h:145
@ COSE_ALGORITHM_SHA_512
Definition: oscore_cose.h:128
@ COSE_ALGORITHM_AES_CCM_16_64_256
Definition: oscore_cose.h:146
int coap_oscore_is_supported(void)
Check whether OSCORE is available.
Definition: coap_oscore.c:2113
coap_proto_t
CoAP protocol types.
Definition: coap_pdu.h:312
@ COAP_PROTO_DTLS
Definition: coap_pdu.h:315
@ COAP_PROTO_TLS
Definition: coap_pdu.h:317
@ COAP_PROTO_WSS
Definition: coap_pdu.h:319
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.
Definition: coap_session.c:766
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).
#define COAP_PROTO_NOT_RELIABLE(p)
Definition: coap_session.h:37
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:855
@ COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:58
@ COAP_SESSION_STATE_CSM
Definition: coap_session.h:59
@ COAP_SESSION_STATE_NONE
Definition: coap_session.h:56
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:77
#define COAP_UNUSED
Definition: libcoap.h:68
coap_address_t remote
remote address and port
Definition: coap_io.h:56
CoAP binary data definition with const data.
Definition: coap_str.h:64
size_t length
length of binary data
Definition: coap_str.h:65
const uint8_t * s
read-only binary data
Definition: coap_str.h:66
CoAP binary data definition.
Definition: coap_str.h:56
The CoAP stack's global state is stored in a coap_context_t object.
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
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::@2 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:381
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition: coap_dtls.h:405
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition: coap_dtls.h:401
The structure that holds the PKI key information.
Definition: coap_dtls.h:255
coap_pki_key_pem_t pem
for PEM file keys
Definition: coap_dtls.h:258
union coap_dtls_key_t::@3 key
coap_pki_key_pem_buf_t pem_buf
for PEM memory keys
Definition: coap_dtls.h:259
coap_pki_key_t key_type
key format type
Definition: coap_dtls.h:256
coap_pki_key_asn1_t asn1
for ASN.1 (DER) memory keys
Definition: coap_dtls.h:260
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:287
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition: coap_dtls.h:292
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition: coap_dtls.h:305
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:293
coap_dtls_key_t pki_key
PKI key definition.
Definition: coap_dtls.h:344
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:417
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:468
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition: coap_dtls.h:495
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition: coap_dtls.h:487
void * id_call_back_arg
Passed in to the Identity callback function.
Definition: coap_dtls.h:488
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition: coap_dtls.h:496
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
const uint8_t * private_key
ASN1 (DER) Private Key.
Definition: coap_dtls.h:233
size_t public_cert_len
ASN1 Public Cert length.
Definition: coap_dtls.h:235
size_t private_key_len
ASN1 Private Key length.
Definition: coap_dtls.h:236
const uint8_t * ca_cert
ASN1 (DER) Common CA Cert.
Definition: coap_dtls.h:231
size_t ca_cert_len
ASN1 CA Cert length.
Definition: coap_dtls.h:234
const uint8_t * public_cert
ASN1 (DER) Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:232
size_t ca_cert_len
PEM buffer CA Cert length.
Definition: coap_dtls.h:222
const uint8_t * ca_cert
PEM buffer Common CA Cert.
Definition: coap_dtls.h:217
size_t private_key_len
PEM buffer Private Key length.
Definition: coap_dtls.h:224
const uint8_t * private_key
PEM buffer Private Key If RPK and 'EC PRIVATE KEY' this can be used for both the public_cert and priv...
Definition: coap_dtls.h:219
size_t public_cert_len
PEM buffer Public Cert length.
Definition: coap_dtls.h:223
const uint8_t * public_cert
PEM buffer Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:218
const char * ca_file
File location of Common CA (and any intermediates) in PEM format.
Definition: coap_dtls.h:201
const char * public_cert
File location of Public Cert.
Definition: coap_dtls.h:203
const char * private_key
File location of Private Key in PEM format.
Definition: coap_dtls.h:204
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_endpoint_t * endpoint
session's endpoint
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_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:106
uint64_t built_version
(D)TLS Built against Library Version
Definition: coap_dtls.h:109
coap_tls_library_t type
Library type.
Definition: coap_dtls.h:108
uint64_t version
(D)TLS runtime Library Version
Definition: coap_dtls.h:107