libcoap 4.3.5rc1
Loading...
Searching...
No Matches
coap_mbedtls.c
Go to the documentation of this file.
1/*
2 * coap_mbedtls.c -- Mbed TLS Datagram Transport Layer Support for libcoap
3 *
4 * Copyright (C) 2019-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
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)
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 coap_dtls_key_t key;
509 int ret;
510 int done_private_key = 0;
511 int done_public_cert = 0;
512 uint8_t *buffer;
513 size_t length;
514
515 /* Map over to the new define format to save code duplication */
516 coap_dtls_map_key_type_to_define(setup_data, &key);
517
518 assert(key.key_type == COAP_PKI_KEY_DEFINE);
519
520 /*
521 * Configure the Private Key
522 */
523 if (key.key.define.private_key.u_byte &&
524 key.key.define.private_key.u_byte[0]) {
525 switch (key.key.define.private_key_def) {
526 case COAP_PKI_KEY_DEF_DER: /* define private key */
527 /* Fall Through */
528 case COAP_PKI_KEY_DEF_PEM: /* define private key */
529#if defined(MBEDTLS_FS_IO)
530 mbedtls_pk_init(private_key);
531#ifdef MBEDTLS_2_X_COMPAT
532 ret = mbedtls_pk_parse_keyfile(private_key,
533 key.key.define.private_key.s_byte, NULL);
534#else
535 ret = mbedtls_pk_parse_keyfile(private_key,
537 NULL, coap_rng, (void *)&m_env->ctr_drbg);
538#endif /* MBEDTLS_2_X_COMPAT */
539 if (ret < 0) {
542 &key, role, ret);
543 }
544 done_private_key = 1;
545 break;
546#else /* ! MBEDTLS_FS_IO */
549 &key, role, -1);
550#endif /* ! MBEDTLS_FS_IO */
551 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
552 mbedtls_pk_init(private_key);
553 length = key.key.define.private_key_len;
554 if (key.key.define.private_key.u_byte[length-1] != '\000') {
555 /* Need to allocate memory to add in NULL terminator */
556 buffer = mbedtls_malloc(length + 1);
557 if (!buffer) {
558 coap_log_err("mbedtls_malloc failed\n");
559 return 0;
560 }
561 memcpy(buffer, key.key.define.private_key.u_byte, length);
562 buffer[length] = '\000';
563 length++;
564#ifdef MBEDTLS_2_X_COMPAT
565 ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
566#else
567 ret = mbedtls_pk_parse_key(private_key, buffer, length,
568 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
569#endif /* MBEDTLS_2_X_COMPAT */
570 mbedtls_free(buffer);
571 } else {
572#ifdef MBEDTLS_2_X_COMPAT
573 ret = mbedtls_pk_parse_key(private_key,
575 key.key.define.private_key_len, NULL, 0);
576#else
577 ret = mbedtls_pk_parse_key(private_key,
580 NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
581#endif /* MBEDTLS_2_X_COMPAT */
582 }
583 if (ret < 0) {
586 &key, role, ret);
587 }
588 done_private_key = 1;
589 break;
590 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
591 mbedtls_pk_init(private_key);
592#ifdef MBEDTLS_2_X_COMPAT
593 ret = mbedtls_pk_parse_key(private_key,
595 key.key.define.private_key_len, NULL, 0);
596#else
597 ret = mbedtls_pk_parse_key(private_key,
599 key.key.define.private_key_len, NULL, 0, coap_rng,
600 (void *)&m_env->ctr_drbg);
601#endif /* MBEDTLS_2_X_COMPAT */
602 if (ret < 0) {
605 &key, role, ret);
606 }
607 done_private_key = 1;
608 break;
609 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
610 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
611 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
612 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
613 default:
616 &key, role, -1);
617 }
618 } else if (role == COAP_DTLS_ROLE_SERVER ||
620 key.key.define.public_cert.u_byte[0])) {
623 &key, role, -1);
624 }
625
626 /*
627 * Configure the Public Certificate / Key
628 */
629 if (key.key.define.public_cert.u_byte &&
630 key.key.define.public_cert.u_byte[0]) {
631 switch (key.key.define.public_cert_def) {
632 case COAP_PKI_KEY_DEF_DER: /* define public cert */
633 /* Fall Through */
634 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
635#if defined(MBEDTLS_FS_IO)
636 mbedtls_x509_crt_init(public_cert);
637 ret = mbedtls_x509_crt_parse_file(public_cert,
639 if (ret < 0) {
642 &key, role, ret);
643 }
644 done_public_cert = 1;
645 break;
646#else /* ! MBEDTLS_FS_IO */
649 &key, role, -1);
650#endif /* ! MBEDTLS_FS_IO */
651 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
652 mbedtls_x509_crt_init(public_cert);
653
654 length = key.key.define.public_cert_len;
655 if (key.key.define.public_cert.u_byte[length-1] != '\000') {
656 /* Need to allocate memory to add in NULL terminator */
657 buffer = mbedtls_malloc(length + 1);
658 if (!buffer) {
659 coap_log_err("mbedtls_malloc failed\n");
660 return 0;
661 }
662 memcpy(buffer, key.key.define.public_cert.u_byte, length);
663 buffer[length] = '\000';
664 length++;
665 ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
666 mbedtls_free(buffer);
667 } else {
668 ret = mbedtls_x509_crt_parse(public_cert,
671 }
672 if (ret < 0) {
675 &key, role, ret);
676 }
677 done_public_cert = 1;
678 break;
679 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
682 &key, role, -1);
683 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
684 mbedtls_x509_crt_init(public_cert);
685 ret = mbedtls_x509_crt_parse(public_cert,
688 if (ret < 0) {
691 &key, role, ret);
692 }
693 done_public_cert = 1;
694 break;
695 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
696 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
697 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
698 default:
701 &key, role, -1);
702 }
703 } else if (role == COAP_DTLS_ROLE_SERVER ||
705 key.key.define.private_key.u_byte[0])) {
708 &key, role, -1);
709 }
710
711 if (done_private_key && done_public_cert) {
712 ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
713 if (ret < 0) {
714 coap_log_err("mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
715 -ret, get_error_string(ret));
716 return 0;
717 }
718 }
719
720 /*
721 * Configure the CA
722 */
723 if (setup_data->check_common_ca && key.key.define.ca.u_byte &&
724 key.key.define.ca.u_byte[0]) {
725 switch (key.key.define.ca_def) {
726 case COAP_PKI_KEY_DEF_DER: /* define ca */
727 /* Fall Through */
729#if defined(MBEDTLS_FS_IO)
730 mbedtls_x509_crt_init(cacert);
731 ret = mbedtls_x509_crt_parse_file(cacert,
732 key.key.define.ca.s_byte);
733 if (ret < 0) {
736 &key, role, ret);
737 }
738 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
739#else /* ! MBEDTLS_FS_IO */
742 &key, role, -1);
743#endif /* ! MBEDTLS_FS_IO */
744 break;
745 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
746 mbedtls_x509_crt_init(cacert);
747 length = key.key.define.ca_len;
748 if (key.key.define.ca.u_byte[length-1] != '\000') {
749 /* Need to allocate memory to add in NULL terminator */
750 buffer = mbedtls_malloc(length + 1);
751 if (!buffer) {
752 coap_log_err("mbedtls_malloc failed\n");
753 return 0;
754 }
755 memcpy(buffer, key.key.define.ca.u_byte, length);
756 buffer[length] = '\000';
757 length++;
758 ret = mbedtls_x509_crt_parse(cacert, buffer, length);
759 mbedtls_free(buffer);
760 } else {
761 ret = mbedtls_x509_crt_parse(cacert,
762 key.key.define.ca.u_byte,
763 key.key.define.ca_len);
764 }
765 if (ret < 0) {
768 &key, role, ret);
769 }
770 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
771 break;
772 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
775 &key, role, -1);
776 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
777 mbedtls_x509_crt_init(cacert);
778 ret = mbedtls_x509_crt_parse(cacert,
779 key.key.define.ca.u_byte,
780 key.key.define.ca_len);
781 if (ret < 0) {
784 &key, role, ret);
785 }
786 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
787 break;
788 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
789 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
790 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
791 default:
794 &key, role, -1);
795 }
796 }
797
798 /* Add in any root CA definitons */
799
800#if defined(MBEDTLS_FS_IO)
801 if (m_context->root_ca_file) {
802 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
803 if (ret < 0) {
807 &key, role, ret);
808 }
809 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
810 }
811 if (m_context->root_ca_path) {
812 ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_path);
813 if (ret < 0) {
817 &key, role, ret);
818 }
819 mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
820 }
821#else /* ! MBEDTLS_FS_IO */
822 (void)m_context;
825 &key, role, -1);
826#endif /* ! MBEDTLS_FS_IO */
827
828#if defined(MBEDTLS_SSL_SRV_C)
829 mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
830 setup_data->check_common_ca ?
831 MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
832 MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
833#endif
834 mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
835 MBEDTLS_SSL_VERIFY_REQUIRED :
836 MBEDTLS_SSL_VERIFY_NONE);
837 /*
838 * Verify Peer.
839 * Need to do all checking, even if setup_data->verify_peer_cert is not set
840 */
841 mbedtls_ssl_conf_verify(&m_env->conf,
842 cert_verify_callback_mbedtls, c_session);
843
844 return 1;
845}
846
847#if defined(MBEDTLS_SSL_SRV_C)
848/*
849 * PKI SNI callback.
850 */
851static int
852pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
853 const unsigned char *uname, size_t name_len) {
854 unsigned int i;
855 coap_dtls_pki_t sni_setup_data;
856 coap_session_t *c_session = (coap_session_t *)p_info;
857 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
858 coap_mbedtls_context_t *m_context =
859 (coap_mbedtls_context_t *)c_session->context->dtls_context;
860 char *name;
861
862 name = mbedtls_malloc(name_len+1);
863 if (!name)
864 return -1;
865
866 memcpy(name, uname, name_len);
867 name[name_len] = '\000';
868
869 /* Is this a cached entry? */
870 for (i = 0; i < m_context->pki_sni_count; i++) {
871 if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
872 break;
873 }
874 }
875 if (i == m_context->pki_sni_count) {
876 /*
877 * New PKI SNI request
878 */
879 coap_dtls_key_t *new_entry;
880 pki_sni_entry *pki_sni_entry_list;
881
882 new_entry =
883 m_context->setup_data.validate_sni_call_back(name,
884 m_context->setup_data.sni_call_back_arg);
885 if (!new_entry) {
886 mbedtls_free(name);
887 return -1;
888 }
889
890 pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
891 (i+1)*sizeof(pki_sni_entry));
892
893 if (pki_sni_entry_list == NULL) {
894 mbedtls_free(name);
895 return -1;
896 }
897 m_context->pki_sni_entry_list = pki_sni_entry_list;
898 memset(&m_context->pki_sni_entry_list[i], 0,
899 sizeof(m_context->pki_sni_entry_list[i]));
900 m_context->pki_sni_entry_list[i].sni = name;
901 m_context->pki_sni_entry_list[i].pki_key = *new_entry;
902 sni_setup_data = m_context->setup_data;
903 sni_setup_data.pki_key = *new_entry;
904 if (setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
905 &m_context->pki_sni_entry_list[i].public_cert,
906 &m_context->pki_sni_entry_list[i].private_key,
907 m_env,
908 m_context,
909 c_session,
910 &sni_setup_data, COAP_DTLS_ROLE_SERVER) < 0) {
911 mbedtls_free(name);
912 return -1;
913 }
914 /* name has been absorbed into pki_sni_entry_list[].sni entry */
915 m_context->pki_sni_count++;
916 } else {
917 mbedtls_free(name);
918 }
919
920 mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
921 NULL);
922 return mbedtls_ssl_set_hs_own_cert(ssl,
923 &m_context->pki_sni_entry_list[i].public_cert,
924 &m_context->pki_sni_entry_list[i].private_key);
925}
926
927#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
928/*
929 * PSK SNI callback.
930 */
931static int
932psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
933 const unsigned char *uname, size_t name_len) {
934 unsigned int i;
935 coap_session_t *c_session = (coap_session_t *)p_info;
936 coap_mbedtls_context_t *m_context =
937 (coap_mbedtls_context_t *)c_session->context->dtls_context;
938 char *name;
939
940 name = mbedtls_malloc(name_len+1);
941 if (!name)
942 return -1;
943
944 memcpy(name, uname, name_len);
945 name[name_len] = '\000';
946
947 /* Is this a cached entry? */
948 for (i = 0; i < m_context->psk_sni_count; i++) {
949 if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
950 break;
951 }
952 }
953 if (i == m_context->psk_sni_count) {
954 /*
955 * New PSK SNI request
956 */
957 const coap_dtls_spsk_info_t *new_entry;
958 psk_sni_entry *psk_sni_entry_list;
959
960 new_entry =
962 c_session,
964 if (!new_entry) {
965 mbedtls_free(name);
966 return -1;
967 }
968
969 psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
970 (i+1)*sizeof(psk_sni_entry));
971
972 if (psk_sni_entry_list == NULL) {
973 mbedtls_free(name);
974 return -1;
975 }
976 m_context->psk_sni_entry_list = psk_sni_entry_list;
977 m_context->psk_sni_entry_list[i].sni = name;
978 m_context->psk_sni_entry_list[i].psk_info = *new_entry;
979 /* name has been absorbed into psk_sni_entry_list[].sni entry */
980 m_context->psk_sni_count++;
981 } else {
982 mbedtls_free(name);
983 }
984
986 &m_context->psk_sni_entry_list[i].psk_info.hint);
988 &m_context->psk_sni_entry_list[i].psk_info.key);
989 return mbedtls_ssl_set_hs_psk(ssl,
990 m_context->psk_sni_entry_list[i].psk_info.key.s,
991 m_context->psk_sni_entry_list[i].psk_info.key.length);
992}
993#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
994
995static int
996setup_server_ssl_session(coap_session_t *c_session,
997 coap_mbedtls_env_t *m_env) {
998 coap_mbedtls_context_t *m_context =
999 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1000 int ret = 0;
1001 m_context->psk_pki_enabled |= IS_SERVER;
1002
1003 mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
1004 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1005 MBEDTLS_SSL_IS_SERVER,
1006 c_session->proto == COAP_PROTO_DTLS ?
1007 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1008 MBEDTLS_SSL_TRANSPORT_STREAM,
1009 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1010 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1011 -ret, get_error_string(ret));
1012 goto fail;
1013 }
1014
1015 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1016
1017#if defined(MBEDTLS_SSL_PROTO_DTLS)
1018 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1019 COAP_DTLS_RETRANSMIT_TOTAL_MS);
1020#endif /* MBEDTLS_SSL_PROTO_DTLS */
1021
1022 if (m_context->psk_pki_enabled & IS_PSK) {
1023#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1024 mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
1026 mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
1027 }
1028#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1029 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1030#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1031 }
1032
1033 if (m_context->psk_pki_enabled & IS_PKI) {
1034 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1035 &m_env->private_key, m_env, m_context,
1036 c_session, &m_context->setup_data,
1038 if (ret < 0) {
1039 coap_log_err("PKI setup failed\n");
1040 return ret;
1041 }
1042 if (m_context->setup_data.validate_sni_call_back) {
1043 mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1044 }
1045 }
1046
1047 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1048 mbedtls_ctr_drbg_random,
1049 &m_env->ctr_drbg)) != 0) {
1050 coap_log_err("mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1051 -ret, get_error_string(ret));
1052 goto fail;
1053 }
1054
1055#if defined(MBEDTLS_SSL_PROTO_DTLS)
1056 mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1057 mbedtls_ssl_cookie_check,
1058 &m_env->cookie_ctx);
1059#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1060 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1061#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1062#endif /* MBEDTLS_SSL_PROTO_DTLS */
1063#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1064 /*
1065 * Configure CID max length.
1066 *
1067 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1068 * to use RFC9146 extension ID of 54, rather than the draft version -05
1069 * value of 254.
1070 */
1071 mbedtls_ssl_conf_cid(&m_env->conf, COAP_DTLS_CID_LENGTH, MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1072#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1073fail:
1074 return ret;
1075}
1076#endif /* MBEDTLS_SSL_SRV_C */
1077
1078#if COAP_CLIENT_SUPPORT
1079static int *psk_ciphers = NULL;
1080static int *pki_ciphers = NULL;
1081static int processed_ciphers = 0;
1082
1083#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1084static int
1085coap_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info) {
1086#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1087 switch (info->key_exchange) {
1088 case MBEDTLS_KEY_EXCHANGE_PSK:
1089 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
1090 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
1091 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1092 return 1;
1093 case MBEDTLS_KEY_EXCHANGE_NONE:
1094 case MBEDTLS_KEY_EXCHANGE_RSA:
1095 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
1096 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1097 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1098 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
1099 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
1100 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1101 default:
1102 return 0;
1103 }
1104#else /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1105 return mbedtls_ssl_ciphersuite_uses_psk(info);
1106#endif /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1107}
1108#endif /* defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) */
1109
1110static void
1111set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) {
1112 if (!processed_ciphers) {
1113 const int *list = mbedtls_ssl_list_ciphersuites();
1114 const int *base = list;
1115 int *psk_list;
1116 int *pki_list;
1117 int psk_count = 1; /* account for empty terminator */
1118 int pki_count = 1;
1119
1120 while (*list) {
1121 const mbedtls_ssl_ciphersuite_t *cur =
1122 mbedtls_ssl_ciphersuite_from_id(*list);
1123
1124#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1125 if (cur) {
1126 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1127 /* Minimum of TLS1.2 required - skip */
1128 }
1129#else
1130 if (cur) {
1131 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1132 /* Minimum of TLS1.2 required - skip */
1133 }
1134#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1135#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1136 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1137 psk_count++;
1138 }
1139#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1140 else {
1141 pki_count++;
1142 }
1143 }
1144 list++;
1145 }
1146 list = base;
1147
1148 psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1149 if (psk_ciphers == NULL) {
1150 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1151 return;
1152 }
1153 pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1154 if (pki_ciphers == NULL) {
1155 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1156 mbedtls_free(psk_ciphers);
1157 psk_ciphers = NULL;
1158 return;
1159 }
1160
1161 psk_list = psk_ciphers;
1162 pki_list = pki_ciphers;
1163
1164 while (*list) {
1165 const mbedtls_ssl_ciphersuite_t *cur =
1166 mbedtls_ssl_ciphersuite_from_id(*list);
1167#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1168 if (cur) {
1169 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1170 /* Minimum of TLS1.2 required - skip */
1171 }
1172#else
1173 if (cur) {
1174 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1175 /* Minimum of TLS1.2 required - skip */
1176 }
1177#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1178#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1179 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1180 *psk_list = *list;
1181 psk_list++;
1182 }
1183#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1184 else {
1185 *pki_list = *list;
1186 pki_list++;
1187 }
1188 }
1189 list++;
1190 }
1191 /* zero terminate */
1192 *psk_list = 0;
1193 *pki_list = 0;
1194 processed_ciphers = 1;
1195 }
1196 mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers);
1197}
1198
1199static int
1200setup_client_ssl_session(coap_session_t *c_session,
1201 coap_mbedtls_env_t *m_env) {
1202 int ret;
1203
1204 coap_mbedtls_context_t *m_context =
1205 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1206
1207 m_context->psk_pki_enabled |= IS_CLIENT;
1208
1209 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1210 MBEDTLS_SSL_IS_CLIENT,
1211 c_session->proto == COAP_PROTO_DTLS ?
1212 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1213 MBEDTLS_SSL_TRANSPORT_STREAM,
1214 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1215 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1216 -ret, get_error_string(ret));
1217 goto fail;
1218 }
1219
1220#if defined(MBEDTLS_SSL_PROTO_DTLS)
1221 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1222 COAP_DTLS_RETRANSMIT_TOTAL_MS);
1223#endif /* MBEDTLS_SSL_PROTO_DTLS */
1224
1225 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1226 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1227
1228 if (m_context->psk_pki_enabled & IS_PSK) {
1229#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1230 const coap_bin_const_t *psk_key;
1231 const coap_bin_const_t *psk_identity;
1232
1233 coap_log_info("Setting PSK key\n");
1234
1235 psk_key = coap_get_session_client_psk_key(c_session);
1236 psk_identity = coap_get_session_client_psk_identity(c_session);
1237 if (psk_key == NULL || psk_identity == NULL) {
1238 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1239 goto fail;
1240 }
1241
1242 if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1243 psk_key->length, psk_identity->s,
1244 psk_identity->length)) != 0) {
1245 coap_log_err("mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1246 -ret, get_error_string(ret));
1247 goto fail;
1248 }
1249 if (c_session->cpsk_setup_data.client_sni) {
1250 if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1251 c_session->cpsk_setup_data.client_sni)) != 0) {
1252 coap_log_err("mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1253 -ret, get_error_string(ret));
1254 goto fail;
1255 }
1256 }
1257 /* Identity Hint currently not supported in Mbed TLS so code removed */
1258
1259 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1260#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1261 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1262#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1263 } else if ((m_context->psk_pki_enabled & IS_PKI) ||
1264 (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1265 /*
1266 * If neither PSK or PKI have been set up, use PKI basics.
1267 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1268 */
1269 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1270 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1271 &m_env->private_key, m_env, m_context,
1272 c_session, &m_context->setup_data,
1274 if (ret < 0) {
1275 coap_log_err("PKI setup failed\n");
1276 return ret;
1277 }
1278#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1279 if (c_session->proto == COAP_PROTO_TLS ||
1280 c_session->proto == COAP_PROTO_WSS) {
1281 static const char *alpn_list[] = { "coap", NULL };
1282
1283 ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1284 if (ret != 0) {
1285 coap_log_err("ALPN setup failed %d)\n", ret);
1286 }
1287 }
1288#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1289 if (m_context->setup_data.client_sni) {
1290 mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1291 }
1292#if defined(MBEDTLS_SSL_PROTO_DTLS)
1293#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1294 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1295#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1296#endif /* MBEDTLS_SSL_PROTO_DTLS */
1297 set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1298 }
1299 return 0;
1300
1301fail:
1302 return ret;
1303}
1304#endif /* COAP_CLIENT_SUPPORT */
1305
1306static void
1307mbedtls_cleanup(coap_mbedtls_env_t *m_env) {
1308 if (!m_env) {
1309 return;
1310 }
1311
1312 mbedtls_x509_crt_free(&m_env->cacert);
1313 mbedtls_x509_crt_free(&m_env->public_cert);
1314 mbedtls_pk_free(&m_env->private_key);
1315 mbedtls_entropy_free(&m_env->entropy);
1316 mbedtls_ssl_config_free(&m_env->conf);
1317 mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1318 mbedtls_ssl_free(&m_env->ssl);
1319 mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1320}
1321
1322static void
1323coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1324 if (m_env) {
1325 if (!m_env->sent_alert)
1326 mbedtls_ssl_close_notify(&m_env->ssl);
1327 mbedtls_cleanup(m_env);
1328 mbedtls_free(m_env);
1329 }
1330}
1331
1332#if COAP_MAX_LOGGING_LEVEL > 0
1333static const char *
1334report_mbedtls_alert(unsigned char alert) {
1335 switch (alert) {
1336 case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC:
1337 return ": Bad Record MAC";
1338 case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE:
1339 return ": Handshake failure";
1340 case MBEDTLS_SSL_ALERT_MSG_NO_CERT:
1341 return ": No Certificate provided";
1342 case MBEDTLS_SSL_ALERT_MSG_BAD_CERT:
1343 return ": Certificate is bad";
1344 case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN:
1345 return ": Certificate is unknown";
1346 case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA:
1347 return ": CA is unknown";
1348 case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED:
1349 return ": Access was denied";
1350 case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR:
1351 return ": Decrypt error";
1352 default:
1353 return "";
1354 }
1355}
1356#endif /* COAP_MAX_LOGGING_LEVEL */
1357
1358/*
1359 * return -1 failure
1360 * 0 not completed
1361 * 1 established
1362 */
1363static int
1364do_mbedtls_handshake(coap_session_t *c_session,
1365 coap_mbedtls_env_t *m_env) {
1366 int ret;
1367 int alert;
1368
1369 ret = mbedtls_ssl_handshake(&m_env->ssl);
1370 switch (ret) {
1371 case 0:
1372 m_env->established = 1;
1373 coap_log_debug("* %s: Mbed TLS established\n",
1374 coap_session_str(c_session));
1375 ret = 1;
1376 break;
1377 case MBEDTLS_ERR_SSL_WANT_READ:
1378 case MBEDTLS_ERR_SSL_WANT_WRITE:
1379 errno = EAGAIN;
1380 ret = 0;
1381 break;
1382 case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1383 coap_log_debug("hello verification requested\n");
1384 goto reset;
1385 case MBEDTLS_ERR_SSL_INVALID_MAC:
1386 goto fail;
1387#ifdef MBEDTLS_2_X_COMPAT
1388 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
1389#else /* ! MBEDTLS_2_X_COMPAT */
1390 case MBEDTLS_ERR_SSL_DECODE_ERROR:
1391#endif /* ! MBEDTLS_2_X_COMPAT */
1392 goto fail;
1393 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1394 alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1395 goto fail_alert;
1396#ifdef MBEDTLS_2_X_COMPAT
1397 case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1398 case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1399 alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1400 goto fail_alert;
1401#endif /* MBEDTLS_2_X_COMPAT */
1402 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1403 goto fail;
1404 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1405 if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1406 coap_log_warn("***%s: Alert '%d'%s\n",
1407 coap_session_str(c_session), m_env->ssl.in_msg[1],
1408 report_mbedtls_alert(m_env->ssl.in_msg[1]));
1409 /* Fall through */
1410 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1411 case MBEDTLS_ERR_SSL_CONN_EOF:
1412 case MBEDTLS_ERR_NET_CONN_RESET:
1414 ret = -1;
1415 break;
1416 default:
1417 coap_log_warn("do_mbedtls_handshake: session establish "
1418 "returned -0x%x: '%s'\n",
1419 -ret, get_error_string(ret));
1420 ret = -1;
1421 break;
1422 }
1423 return ret;
1424
1425fail_alert:
1426 mbedtls_ssl_send_alert_message(&m_env->ssl,
1427 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1428 alert);
1429 m_env->sent_alert = 1;
1430fail:
1431 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1432 coap_log_warn("do_mbedtls_handshake: session establish "
1433 "returned '%s'\n",
1434 get_error_string(ret));
1435reset:
1436 mbedtls_ssl_session_reset(&m_env->ssl);
1437 return -1;
1438}
1439
1440static void
1441mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1442 const char *file COAP_UNUSED,
1443 int line COAP_UNUSED, const char *str) {
1444
1445 coap_log_t coap_level = COAP_LOG_DEBUG;
1446 /*
1447 * 0 No debug
1448 * 1 Error
1449 * 2 State change
1450 * 3 Informational
1451 * 4 Verbose
1452 */
1453 switch (level) {
1454 case 0:
1455 coap_level = COAP_LOG_EMERG;
1456 break;
1457 case 1:
1458 coap_level = COAP_LOG_WARN;
1459 break;
1460 case 2:
1461 coap_level = COAP_LOG_NOTICE;
1462 break;
1463 case 3:
1464 coap_level = COAP_LOG_INFO;
1465 break;
1466 case 4:
1467 default:
1468 coap_level = COAP_LOG_DEBUG;
1469 break;
1470 }
1471 coap_dtls_log(coap_level, "%s", str);
1472}
1473
1474#if !COAP_DISABLE_TCP
1475/*
1476 * strm
1477 * return +ve data amount
1478 * 0 no more
1479 * -ve Mbed TLS error
1480 */
1481static int
1482coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
1483 int ret = MBEDTLS_ERR_SSL_CONN_EOF;
1484 coap_session_t *c_session = (coap_session_t *)ctx;
1485
1486 if (out != NULL) {
1487 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
1488 /* Translate layer returns into what MbedTLS expects */
1489 if (ret == -1) {
1490 if (errno == ECONNRESET) {
1491 /* graceful shutdown */
1492 ret = MBEDTLS_ERR_SSL_CONN_EOF;
1493 } else {
1494 ret = MBEDTLS_ERR_NET_RECV_FAILED;
1495 }
1496 } else if (ret == 0) {
1497 errno = EAGAIN;
1498 ret = MBEDTLS_ERR_SSL_WANT_READ;
1499 }
1500 }
1501 return ret;
1502}
1503
1504/*
1505 * strm
1506 * return +ve data amount
1507 * 0 no more
1508 * -ve Mbed TLS error
1509 */
1510static int
1511coap_sock_write(void *context, const unsigned char *in, size_t inl) {
1512 int ret = 0;
1513 coap_session_t *c_session = (coap_session_t *)context;
1514
1515 ret = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
1516 (const uint8_t *)in,
1517 inl);
1518 /* Translate layer what returns into what MbedTLS expects */
1519 if (ret < 0) {
1520 if ((c_session->state == COAP_SESSION_STATE_CSM ||
1521 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
1522 (errno == EPIPE || errno == ECONNRESET)) {
1523 /*
1524 * Need to handle a TCP timing window where an agent continues with
1525 * the sending of the next handshake or a CSM.
1526 * However, the peer does not like a certificate and so sends a
1527 * fatal alert and closes the TCP session.
1528 * The sending of the next handshake or CSM may get terminated because
1529 * of the closed TCP session, but there is still an outstanding alert
1530 * to be read in and reported on.
1531 * In this case, pretend that sending the info was fine so that the
1532 * alert can be read (which effectively is what happens with DTLS).
1533 */
1534 ret = inl;
1535 } else {
1536#ifdef _WIN32
1537 int lasterror = WSAGetLastError();
1538
1539 if (lasterror == WSAEWOULDBLOCK) {
1540 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1541 } else if (lasterror == WSAECONNRESET) {
1542 ret = MBEDTLS_ERR_NET_CONN_RESET;
1543 }
1544#else
1545 if (errno == EAGAIN || errno == EINTR) {
1546 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1547 } else if (errno == EPIPE || errno == ECONNRESET) {
1548 ret = MBEDTLS_ERR_NET_CONN_RESET;
1549 }
1550#endif
1551 else {
1552 ret = MBEDTLS_ERR_NET_SEND_FAILED;
1553 }
1554 coap_log_debug("* %s: failed to send %zd bytes (%s) state %d\n",
1555 coap_session_str(c_session), inl, coap_socket_strerror(),
1556 c_session->state);
1557 }
1558 }
1559 if (ret == 0) {
1560 errno = EAGAIN;
1561 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1562 }
1563 return ret;
1564}
1565#endif /* !COAP_DISABLE_TCP */
1566
1567static coap_mbedtls_env_t *
1568coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1569 coap_dtls_role_t role,
1570 coap_proto_t proto) {
1571 int ret = 0;
1572 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1573
1574 if (m_env)
1575 return m_env;
1576
1577 m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1578 if (!m_env) {
1579 return NULL;
1580 }
1581 memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1582
1583 mbedtls_ssl_init(&m_env->ssl);
1584 mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1585 mbedtls_ssl_config_init(&m_env->conf);
1586 mbedtls_entropy_init(&m_env->entropy);
1587
1588#if defined(MBEDTLS_PSA_CRYPTO_C)
1589 psa_crypto_init();
1590#endif /* MBEDTLS_PSA_CRYPTO_C */
1591
1592#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1593 mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1594#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1595 if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1596 mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1597 coap_log_err("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1598 -ret, get_error_string(ret));
1599 goto fail;
1600 }
1601
1602 if (role == COAP_DTLS_ROLE_CLIENT) {
1603#if COAP_CLIENT_SUPPORT
1604 if (setup_client_ssl_session(c_session, m_env) != 0) {
1605 goto fail;
1606 }
1607#else /* !COAP_CLIENT_SUPPORT */
1608 goto fail;
1609#endif /* !COAP_CLIENT_SUPPORT */
1610 } else if (role == COAP_DTLS_ROLE_SERVER) {
1611#if defined(MBEDTLS_SSL_SRV_C)
1612 if (setup_server_ssl_session(c_session, m_env) != 0) {
1613 goto fail;
1614 }
1615#else /* ! MBEDTLS_SSL_SRV_C */
1616 goto fail;
1617#endif /* ! MBEDTLS_SSL_SRV_C */
1618 } else {
1619 goto fail;
1620 }
1621
1622#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1623 mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1624#else
1625 mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1626 MBEDTLS_SSL_MINOR_VERSION_3);
1627#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1628
1629 if (mbedtls_ssl_setup(&m_env->ssl, &m_env->conf) != 0) {
1630 goto fail;
1631 }
1632 if (proto == COAP_PROTO_DTLS) {
1633 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1634 coap_dgram_read, NULL);
1635#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1636 if (role != COAP_DTLS_ROLE_CLIENT &&
1637 COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
1638 u_char cid[COAP_DTLS_CID_LENGTH];
1639 /*
1640 * Enable server DTLS CID support.
1641 *
1642 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1643 * to use RFC9146 extension ID of 54, rather than the draft version -05
1644 * value of 254.
1645 */
1646 coap_prng(cid, sizeof(cid));
1647 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, cid,
1648 sizeof(cid));
1649 }
1650#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1651 }
1652#if !COAP_DISABLE_TCP
1653 else {
1654 assert(proto == COAP_PROTO_TLS);
1655 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
1656 coap_sock_read, NULL);
1657 }
1658#endif /* ! COAP_DISABLE_TCP */
1659 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1660 mbedtls_timing_set_delay,
1661 mbedtls_timing_get_delay);
1662
1663 mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1664 return m_env;
1665
1666fail:
1667 if (m_env) {
1668 mbedtls_free(m_env);
1669 }
1670 return NULL;
1671}
1672
1673int
1675#if defined(MBEDTLS_SSL_PROTO_DTLS)
1676 return 1;
1677#else /* !MBEDTLS_SSL_PROTO_DTLS */
1678 static int reported = 0;
1679 if (!reported) {
1680 reported = 1;
1681 coap_log_emerg("libcoap not compiled for DTLS with Mbed TLS"
1682 " - update Mbed TLS to include DTLS\n");
1683 }
1684 return 0;
1685#endif /* !MBEDTLS_SSL_PROTO_DTLS */
1686}
1687
1688int
1690#if !COAP_DISABLE_TCP
1691 return 1;
1692#else /* COAP_DISABLE_TCP */
1693 return 0;
1694#endif /* COAP_DISABLE_TCP */
1695}
1696
1697/*
1698 * return 0 failed
1699 * 1 passed
1700 */
1701int
1703 return 1;
1704}
1705
1706/*
1707 * return 0 failed
1708 * 1 passed
1709 */
1710int
1712 return 1;
1713}
1714
1715/*
1716 * return 0 failed
1717 * 1 passed
1718 */
1719int
1721 return 0;
1722}
1723
1724/*
1725 * return 0 failed
1726 * 1 passed
1727 */
1728int
1730 return 0;
1731}
1732
1733void *
1735 coap_mbedtls_context_t *m_context;
1736 (void)c_context;
1737
1738 m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
1739 if (m_context) {
1740 memset(m_context, 0, sizeof(coap_mbedtls_context_t));
1741 }
1742 return m_context;
1743}
1744
1745#if COAP_SERVER_SUPPORT
1746/*
1747 * return 0 failed
1748 * 1 passed
1749 */
1750int
1752 coap_dtls_spsk_t *setup_data
1753 ) {
1754 coap_mbedtls_context_t *m_context =
1755 ((coap_mbedtls_context_t *)c_context->dtls_context);
1756
1757#if !defined(MBEDTLS_SSL_SRV_C)
1758 coap_log_emerg("coap_context_set_spsk:"
1759 " libcoap not compiled for Server Mode for Mbed TLS"
1760 " - update Mbed TLS to include Server Mode\n");
1761 return 0;
1762#endif /* !MBEDTLS_SSL_SRV_C */
1763 if (!m_context || !setup_data)
1764 return 0;
1765
1766 m_context->psk_pki_enabled |= IS_PSK;
1767 return 1;
1768}
1769#endif /* COAP_SERVER_SUPPORT */
1770
1771#if COAP_CLIENT_SUPPORT
1772/*
1773 * return 0 failed
1774 * 1 passed
1775 */
1776int
1778 coap_dtls_cpsk_t *setup_data
1779 ) {
1780#if !defined(MBEDTLS_SSL_CLI_C)
1781 (void)c_context;
1782 (void)setup_data;
1783
1784 coap_log_emerg("coap_context_set_cpsk:"
1785 " libcoap not compiled for Client Mode for Mbed TLS"
1786 " - update Mbed TLS to include Client Mode\n");
1787 return 0;
1788#else /* MBEDTLS_SSL_CLI_C */
1789 coap_mbedtls_context_t *m_context =
1790 ((coap_mbedtls_context_t *)c_context->dtls_context);
1791
1792 if (!m_context || !setup_data)
1793 return 0;
1794
1795 if (setup_data->validate_ih_call_back) {
1796 coap_log_warn("CoAP Client with Mbed TLS does not support Identity Hint selection\n");
1797 }
1798 m_context->psk_pki_enabled |= IS_PSK;
1799 return 1;
1800#endif /* MBEDTLS_SSL_CLI_C */
1801}
1802#endif /* COAP_CLIENT_SUPPORT */
1803
1804int
1806 const coap_dtls_pki_t *setup_data,
1807 const coap_dtls_role_t role COAP_UNUSED) {
1808 coap_mbedtls_context_t *m_context =
1809 ((coap_mbedtls_context_t *)c_context->dtls_context);
1810
1811 m_context->setup_data = *setup_data;
1812 if (!m_context->setup_data.verify_peer_cert) {
1813 /* Needs to be clear so that no CA DNs are transmitted */
1814 m_context->setup_data.check_common_ca = 0;
1815 /* Allow all of these but warn if issue */
1816 m_context->setup_data.allow_self_signed = 1;
1817 m_context->setup_data.allow_expired_certs = 1;
1818 m_context->setup_data.cert_chain_validation = 1;
1819 m_context->setup_data.cert_chain_verify_depth = 10;
1820 m_context->setup_data.check_cert_revocation = 1;
1821 m_context->setup_data.allow_no_crl = 1;
1822 m_context->setup_data.allow_expired_crl = 1;
1823 m_context->setup_data.allow_bad_md_hash = 1;
1824 m_context->setup_data.allow_short_rsa_length = 1;
1825 }
1826 m_context->psk_pki_enabled |= IS_PKI;
1827 return 1;
1828}
1829
1830int
1832 const char *ca_file,
1833 const char *ca_path) {
1834 coap_mbedtls_context_t *m_context =
1835 ((coap_mbedtls_context_t *)c_context->dtls_context);
1836
1837 if (!m_context) {
1838 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
1839 "not set up\n");
1840 return 0;
1841 }
1842
1843 if (ca_file == NULL && ca_path == NULL) {
1844 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
1845 "not defined\n");
1846 return 0;
1847 }
1848 if (m_context->root_ca_file) {
1849 mbedtls_free(m_context->root_ca_file);
1850 m_context->root_ca_file = NULL;
1851 }
1852
1853 if (ca_file) {
1854 m_context->root_ca_file = mbedtls_strdup(ca_file);
1855 }
1856
1857 if (m_context->root_ca_path) {
1858 mbedtls_free(m_context->root_ca_path);
1859 m_context->root_ca_path = NULL;
1860 }
1861
1862 if (ca_path) {
1863 m_context->root_ca_path = mbedtls_strdup(ca_path);
1864 }
1865 return 1;
1866}
1867
1868int
1870 coap_mbedtls_context_t *m_context =
1871 ((coap_mbedtls_context_t *)c_context->dtls_context);
1872 return m_context->psk_pki_enabled ? 1 : 0;
1873}
1874
1875void
1876coap_dtls_free_context(void *dtls_context) {
1877 coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
1878 unsigned int i;
1879
1880 for (i = 0; i < m_context->pki_sni_count; i++) {
1881 mbedtls_free(m_context->pki_sni_entry_list[i].sni);
1882
1883 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
1884
1885 mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
1886
1887 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
1888 }
1889 if (m_context->pki_sni_entry_list)
1890 mbedtls_free(m_context->pki_sni_entry_list);
1891
1892 for (i = 0; i < m_context->psk_sni_count; i++) {
1893 mbedtls_free(m_context->psk_sni_entry_list[i].sni);
1894 }
1895 if (m_context->psk_sni_entry_list)
1896 mbedtls_free(m_context->psk_sni_entry_list);
1897
1898 if (m_context->root_ca_path)
1899 mbedtls_free(m_context->root_ca_path);
1900 if (m_context->root_ca_file)
1901 mbedtls_free(m_context->root_ca_file);
1902
1903 mbedtls_free(m_context);
1904}
1905
1906#if COAP_CLIENT_SUPPORT
1907void *
1909#if !defined(MBEDTLS_SSL_CLI_C)
1910 (void)c_session;
1911 coap_log_emerg("coap_dtls_new_client_session:"
1912 " libcoap not compiled for Client Mode for Mbed TLS"
1913 " - update Mbed TLS to include Client Mode\n");
1914 return NULL;
1915#else /* MBEDTLS_SSL_CLI_C */
1916 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
1919 int ret;
1920
1921 if (m_env) {
1922 coap_tick_t now;
1923#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1924 if (COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
1925 /*
1926 * Enable passive DTLS CID support.
1927 *
1928 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1929 * to use RFC9146 extension ID of 54, rather than the draft version -05
1930 * value of 254.
1931 */
1932 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, NULL, 0);
1933 }
1934#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1935 coap_ticks(&now);
1936 m_env->last_timeout = now;
1937 ret = do_mbedtls_handshake(c_session, m_env);
1938 if (ret == -1) {
1939 coap_dtls_free_mbedtls_env(m_env);
1940 return NULL;
1941 }
1942 }
1943 return m_env;
1944#endif /* MBEDTLS_SSL_CLI_C */
1945}
1946#endif /* COAP_CLIENT_SUPPORT */
1947
1948#if COAP_SERVER_SUPPORT
1949void *
1951#if !defined(MBEDTLS_SSL_SRV_C)
1952 (void)c_session;
1953 coap_log_emerg("coap_dtls_new_server_session:"
1954 " libcoap not compiled for Server Mode for Mbed TLS"
1955 " - update Mbed TLS to include Server Mode\n");
1956 return NULL;
1957#else /* MBEDTLS_SSL_SRV_C */
1958 coap_mbedtls_env_t *m_env =
1959 (coap_mbedtls_env_t *)c_session->tls;
1960 if (m_env) {
1961#if defined(MBEDTLS_SSL_PROTO_DTLS)
1962#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1963 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1964#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1965#endif /* MBEDTLS_SSL_PROTO_DTLS */
1966 }
1967 return m_env;
1968#endif /* MBEDTLS_SSL_SRV_C */
1969}
1970#endif /* COAP_SERVER_SUPPORT */
1971
1972void
1974 if (c_session && c_session->context && c_session->tls) {
1975 coap_dtls_free_mbedtls_env(c_session->tls);
1976 c_session->tls = NULL;
1978 }
1979 return;
1980}
1981
1982void
1984#if defined(MBEDTLS_SSL_PROTO_DTLS)
1985 coap_mbedtls_env_t *m_env =
1986 (coap_mbedtls_env_t *)c_session->tls;
1987 if (m_env) {
1988#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1989 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1990#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1991 }
1992#else /* ! MBEDTLS_SSL_PROTO_DTLS */
1993 (void)c_session;
1994#endif /* MBEDTLS_SSL_PROTO_DTLS */
1995}
1996
1997ssize_t
1999 const uint8_t *data, size_t data_len) {
2000 int ret;
2001 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2002
2003 assert(m_env != NULL);
2004
2005 if (!m_env) {
2006 return -1;
2007 }
2008 c_session->dtls_event = -1;
2009 if (m_env->established) {
2010 ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char *) data, data_len);
2011 if (ret <= 0) {
2012 switch (ret) {
2013 case MBEDTLS_ERR_SSL_WANT_READ:
2014 case MBEDTLS_ERR_SSL_WANT_WRITE:
2015 ret = 0;
2016 break;
2017 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2019 ret = -1;
2020 break;
2021 default:
2022 coap_log_warn("coap_dtls_send: "
2023 "returned -0x%x: '%s'\n",
2024 -ret, get_error_string(ret));
2025 ret = -1;
2026 break;
2027 }
2028 if (ret == -1) {
2029 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2030 }
2031 }
2032 } else {
2033 ret = do_mbedtls_handshake(c_session, m_env);
2034 if (ret == 1) {
2035 /* Just connected, so send the data */
2036 return coap_dtls_send(c_session, data, data_len);
2037 }
2038 ret = -1;
2039 }
2040
2041 if (c_session->dtls_event >= 0) {
2042 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2043 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2044 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2045 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2046 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2048 ret = -1;
2049 }
2050 }
2051 if (ret > 0) {
2052 if (ret == (ssize_t)data_len)
2053 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2054 coap_session_str(c_session), ret);
2055 else
2056 coap_log_debug("* %s: dtls: sent %4d of %4zd bytes\n",
2057 coap_session_str(c_session), ret, data_len);
2058 }
2059 return ret;
2060}
2061
2062int
2064 return 0;
2065}
2066
2068coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2069 return 0;
2070}
2071
2074 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2075 int ret = mbedtls_timing_get_delay(&m_env->timer);
2076 unsigned int scalar = 1 << m_env->retry_scalar;
2077
2078 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2079 switch (ret) {
2080 case 0:
2081 /* int_ms has not timed out */
2082 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2083 /* Need to indicate remaining timeout time */
2084 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2085 }
2086 m_env->last_timeout = now;
2087 /* This may cause a minor extra delay */
2088 return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2089 case 1:
2090 /* int_ms has timed out, but not fin_ms */
2091 /*
2092 * Need to make sure that we do not do this too frequently
2093 */
2094 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2095 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2096 }
2097
2098 /* Reset for the next time */
2099 m_env->last_timeout = now;
2100 return now;
2101 case 2:
2102 /* fin_ms has timed out - timed out - one final try */
2103 return now;
2104 default:
2105 break;
2106 }
2107
2108 return 0;
2109}
2110
2111/*
2112 * return 1 timed out
2113 * 0 still timing out
2114 */
2115int
2117 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2118
2119 assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2120 m_env->retry_scalar++;
2121 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2122 (do_mbedtls_handshake(c_session, m_env) < 0)) {
2123 /* Too many retries */
2125 return 1;
2126 }
2127 return 0;
2128}
2129
2130/*
2131 * return +ve data amount
2132 * 0 no more
2133 * -1 error
2134 */
2135int
2137 const uint8_t *data,
2138 size_t data_len) {
2139 int ret = 1;
2140
2141 c_session->dtls_event = -1;
2142 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2143 coap_ssl_t *ssl_data;
2144
2145 assert(m_env != NULL);
2146
2147 ssl_data = &m_env->coap_ssl_data;
2148 if (ssl_data->pdu_len) {
2149 coap_log_err("** %s: Previous data not read %u bytes\n",
2150 coap_session_str(c_session), ssl_data->pdu_len);
2151 }
2152 ssl_data->pdu = data;
2153 ssl_data->pdu_len = (unsigned)data_len;
2154
2155 if (m_env->established) {
2156#if COAP_CONSTRAINED_STACK
2157 /* pdu protected by mutex m_dtls_recv */
2158 static uint8_t pdu[COAP_RXBUFFER_SIZE];
2159#else /* ! COAP_CONSTRAINED_STACK */
2160 uint8_t pdu[COAP_RXBUFFER_SIZE];
2161#endif /* ! COAP_CONSTRAINED_STACK */
2162
2163#if COAP_CONSTRAINED_STACK
2164 coap_mutex_lock(&m_dtls_recv);
2165#endif /* COAP_CONSTRAINED_STACK */
2166
2167 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2169 c_session);
2170 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2171 }
2172
2173 ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2174 if (ret > 0) {
2175 ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2176#if COAP_CONSTRAINED_STACK
2177 coap_mutex_unlock(&m_dtls_recv);
2178#endif /* COAP_CONSTRAINED_STACK */
2179 goto finish;
2180 }
2181 switch (ret) {
2182 case 0:
2183 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2184 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2186 break;
2187 case MBEDTLS_ERR_SSL_WANT_READ:
2188 break;
2189 default:
2190 coap_log_warn("coap_dtls_receive: "
2191 "returned -0x%x: '%s' (length %zd)\n",
2192 -ret, get_error_string(ret), data_len);
2193 break;
2194 }
2195#if COAP_CONSTRAINED_STACK
2196 coap_mutex_unlock(&m_dtls_recv);
2197#endif /* COAP_CONSTRAINED_STACK */
2198 ret = -1;
2199 } else {
2200 ret = do_mbedtls_handshake(c_session, m_env);
2201 if (ret == 1) {
2202 /* Just connected, so send the data */
2203 coap_session_connected(c_session);
2204 } else {
2205 if (ssl_data->pdu_len) {
2206 /* Do the handshake again incase of internal timeout */
2207 ret = do_mbedtls_handshake(c_session, m_env);
2208 if (ret == 1) {
2209 /* Just connected, so send the data */
2210 coap_session_connected(c_session);
2211 }
2212 }
2213 ret = -1;
2214 }
2215 }
2216 if (c_session->dtls_event >= 0) {
2217 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2218 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2219 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2220 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2221 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2223 ssl_data = NULL;
2224 ret = -1;
2225 }
2226 }
2227finish:
2228 if (ssl_data && ssl_data->pdu_len) {
2229 /* pdu data is held on stack which will not stay there */
2230 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2231 ssl_data->pdu_len = 0;
2232 ssl_data->pdu = NULL;
2233 }
2234 if (ret > 0) {
2235 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2236 coap_session_str(c_session), ret);
2237 }
2238 return ret;
2239}
2240
2241#if COAP_SERVER_SUPPORT
2242/*
2243 * return -1 failure
2244 * 0 not completed
2245 * 1 client hello seen
2246 */
2247int
2249 const uint8_t *data,
2250 size_t data_len) {
2251#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2252 (void)c_session;
2253 (void)data;
2254 (void)data_len;
2255 coap_log_emerg("coap_dtls_hello:"
2256 " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2257 " - update Mbed TLS to include DTLS and Server Mode\n");
2258 return -1;
2259#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2260 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2261 coap_ssl_t *ssl_data;
2262 int ret;
2263
2264 if (!m_env) {
2265 m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2267 if (m_env) {
2268 c_session->tls = m_env;
2269 } else {
2270 /* error should have already been reported */
2271 return -1;
2272 }
2273 }
2274
2275 if ((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2276 (unsigned char *)&c_session->addr_info.remote,
2277 sizeof(c_session->addr_info.remote))) != 0) {
2278 coap_log_err("mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2279 -ret, get_error_string(ret));
2280 return -1;
2281 }
2282
2283 ssl_data = &m_env->coap_ssl_data;
2284 if (ssl_data->pdu_len) {
2285 coap_log_err("** %s: Previous data not read %u bytes\n",
2286 coap_session_str(c_session), ssl_data->pdu_len);
2287 }
2288 ssl_data->pdu = data;
2289 ssl_data->pdu_len = (unsigned)data_len;
2290
2291 ret = do_mbedtls_handshake(c_session, m_env);
2292 if (ret == 0 || m_env->seen_client_hello) {
2293 /* The test for seen_client_hello gives the ability to setup a new
2294 c_session to continue the do_mbedtls_handshake past the client hello
2295 and safely allow updating of the m_env and separately
2296 letting a new session cleanly start up.
2297 */
2298 m_env->seen_client_hello = 0;
2299 ret = 1;
2300 } else {
2301 ret = 0;
2302 }
2303
2304 if (ssl_data->pdu_len) {
2305 /* pdu data is held on stack which will not stay there */
2306 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2307 ssl_data->pdu_len = 0;
2308 ssl_data->pdu = NULL;
2309 }
2310 return ret;
2311#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2312}
2313#endif /* COAP_SERVER_SUPPORT */
2314
2315unsigned int
2317 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2318 int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2319
2320 if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2321 return 13 + 8 + 8;
2322 }
2323 return expansion;
2324}
2325
2326#if !COAP_DISABLE_TCP
2327#if COAP_CLIENT_SUPPORT
2328void *
2330#if !defined(MBEDTLS_SSL_CLI_C)
2331 (void)c_session;
2332 *connected = 0;
2333 coap_log_emerg("coap_tls_new_client_session:"
2334 " libcoap not compiled for Client Mode for Mbed TLS"
2335 " - update Mbed TLS to include Client Mode\n");
2336 return NULL;
2337#else /* MBEDTLS_SSL_CLI_C */
2338 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2341 int ret;
2342 coap_tick_t now;
2343 coap_ticks(&now);
2344
2345 if (!m_env)
2346 return NULL;
2347
2348 m_env->last_timeout = now;
2349 c_session->tls = m_env;
2350 ret = do_mbedtls_handshake(c_session, m_env);
2351 if (ret == 1) {
2353 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2354 }
2355 return m_env;
2356#endif /* MBEDTLS_SSL_CLI_C */
2357}
2358#endif /* COAP_CLIENT_SUPPORT */
2359
2360#if COAP_SERVER_SUPPORT
2361void *
2363#if !defined(MBEDTLS_SSL_SRV_C)
2364 (void)c_session;
2365 (void)connected;
2366
2367 coap_log_emerg("coap_tls_new_server_session:"
2368 " libcoap not compiled for Server Mode for Mbed TLS"
2369 " - update Mbed TLS to include Server Mode\n");
2370 return NULL;
2371#else /* MBEDTLS_SSL_SRV_C */
2372 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2375 int ret;
2376
2377 if (!m_env)
2378 return NULL;
2379
2380 c_session->tls = m_env;
2381 ret = do_mbedtls_handshake(c_session, m_env);
2382 if (ret == 1) {
2384 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2385 }
2386 return m_env;
2387#endif /* MBEDTLS_SSL_SRV_C */
2388}
2389#endif /* COAP_SERVER_SUPPORT */
2390
2391void
2393 coap_dtls_free_session(c_session);
2394 return;
2395}
2396
2397/*
2398 * strm
2399 * return +ve Number of bytes written.
2400 * -1 Error (error in errno).
2401 */
2402ssize_t
2403coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2404 size_t data_len) {
2405 int ret = 0;
2406 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2407 size_t amount_sent = 0;
2408
2409 assert(m_env != NULL);
2410
2411 if (!m_env) {
2412 errno = ENXIO;
2413 return -1;
2414 }
2415 c_session->dtls_event = -1;
2416 if (m_env->established) {
2417 while (amount_sent < data_len) {
2418 ret = mbedtls_ssl_write(&m_env->ssl, &data[amount_sent],
2419 data_len - amount_sent);
2420 if (ret <= 0) {
2421 switch (ret) {
2422 case MBEDTLS_ERR_SSL_WANT_READ:
2423 case MBEDTLS_ERR_SSL_WANT_WRITE:
2424 if (amount_sent)
2425 ret = amount_sent;
2426 else
2427 ret = 0;
2428 c_session->sock.flags |= COAP_SOCKET_WANT_WRITE;
2429 break;
2430 case MBEDTLS_ERR_NET_CONN_RESET:
2431 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2433 break;
2434 default:
2435 coap_log_warn("coap_tls_write: "
2436 "returned -0x%x: '%s'\n",
2437 -ret, get_error_string(ret));
2438 ret = -1;
2439 break;
2440 }
2441 if (ret == -1) {
2442 coap_log_warn("coap_tls_write: cannot send PDU\n");
2443 }
2444 break;
2445 }
2446 amount_sent += ret;
2447 }
2448 } else {
2449 ret = do_mbedtls_handshake(c_session, m_env);
2450 if (ret == 1) {
2452 c_session);
2453 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2454 } else {
2455 ret = -1;
2456 }
2457 }
2458
2459 if (c_session->dtls_event >= 0) {
2460 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2461 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2462 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2463 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2464 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2466 ret = -1;
2467 }
2468 }
2469 if (ret > 0) {
2470 if (ret == (ssize_t)data_len)
2471 coap_log_debug("* %s: tls: sent %4d bytes\n",
2472 coap_session_str(c_session), ret);
2473 else
2474 coap_log_debug("* %s: tls: sent %4d of %4zd bytes\n",
2475 coap_session_str(c_session), ret, data_len);
2476 }
2477 return ret;
2478}
2479
2480/*
2481 * strm
2482 * return >=0 Number of bytes read.
2483 * -1 Error (error in errno).
2484 */
2485ssize_t
2486coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
2487 int ret = -1;
2488
2489 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2490
2491 if (!m_env) {
2492 errno = ENXIO;
2493 return -1;
2494 }
2495
2496 c_session->dtls_event = -1;
2497
2498 if (!m_env->established && !m_env->sent_alert) {
2499 ret = do_mbedtls_handshake(c_session, m_env);
2500 if (ret == 1) {
2502 c_session);
2503 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2504 }
2505 }
2506
2507 if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
2508 ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
2509 if (ret <= 0) {
2510 switch (ret) {
2511 case 0:
2512 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2514 ret = -1;
2515 break;
2516 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2517 /* Stop the sending of an alert on closedown */
2518 m_env->sent_alert = 1;
2520 break;
2521 case MBEDTLS_ERR_SSL_WANT_READ:
2522 errno = EAGAIN;
2523 ret = 0;
2524 break;
2525 default:
2526 coap_log_warn("coap_tls_read: "
2527 "returned -0x%x: '%s' (length %zd)\n",
2528 -ret, get_error_string(ret), data_len);
2529 ret = -1;
2530 break;
2531 }
2532 } else if (ret < (int)data_len) {
2533 c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
2534 }
2535 }
2536
2537 if (c_session->dtls_event >= 0) {
2538 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2539 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2540 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2541 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2542 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2544 ret = -1;
2545 }
2546 }
2547 if (ret > 0) {
2548 coap_log_debug("* %s: tls: recv %4d bytes\n",
2549 coap_session_str(c_session), ret);
2550 }
2551 return ret;
2552}
2553#endif /* !COAP_DISABLE_TCP */
2554
2555void
2556coap_dtls_startup(void) {
2557}
2558
2559void
2560coap_dtls_shutdown(void) {
2561#if COAP_CLIENT_SUPPORT
2562 mbedtls_free(psk_ciphers);
2563 mbedtls_free(pki_ciphers);
2564 psk_ciphers = NULL;
2565 pki_ciphers = NULL;
2566 processed_ciphers = 0;
2567#endif /* COAP_CLIENT_SUPPORT */
2569}
2570
2571void *
2572coap_dtls_get_tls(const coap_session_t *c_session,
2573 coap_tls_library_t *tls_lib) {
2574 if (tls_lib)
2575 *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
2576 if (c_session && c_session->tls) {
2577 coap_mbedtls_env_t *m_env;
2578
2579 /* To get around const issue */
2580 memcpy(&m_env, &c_session->tls, sizeof(m_env));
2581
2582 return (void *)&m_env->ssl;
2583 }
2584 return NULL;
2585}
2586
2587static coap_log_t keep_log_level = COAP_LOG_EMERG;
2588
2589void
2591#if !defined(ESPIDF_VERSION)
2592 int use_level;
2593 /*
2594 * Mbed TLS debug levels filter
2595 * 0 No debug
2596 * 1 Error
2597 * 2 State change
2598 * 3 Informational
2599 * 4 Verbose
2600 */
2601 switch ((int)level) {
2602 case COAP_LOG_EMERG:
2603 use_level = 0;
2604 break;
2605 case COAP_LOG_ALERT:
2606 case COAP_LOG_CRIT:
2607 case COAP_LOG_ERR:
2608 case COAP_LOG_WARN:
2609 use_level = 1;
2610 break;
2611 case COAP_LOG_NOTICE:
2612 use_level = 2;
2613 break;
2614 case COAP_LOG_INFO:
2615 use_level = 3;
2616 break;
2617 case COAP_LOG_DEBUG:
2618 default:
2619 use_level = 4;
2620 break;
2621 }
2622 mbedtls_debug_set_threshold(use_level);
2623#endif /* !ESPIDF_VERSION) */
2624 keep_log_level = level;
2625}
2626
2629 return keep_log_level;
2630}
2631
2634 static coap_tls_version_t version;
2635 version.version = mbedtls_version_get_number();
2636 version.built_version = MBEDTLS_VERSION_NUMBER;
2638 return &version;
2639}
2640
2641#if COAP_SERVER_SUPPORT
2643coap_digest_setup(void) {
2644 mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
2645
2646 if (digest_ctx) {
2647 mbedtls_sha256_init(digest_ctx);
2648#ifdef MBEDTLS_2_X_COMPAT
2649 if (mbedtls_sha256_starts_ret(digest_ctx, 0) != 0) {
2650#else
2651 if (mbedtls_sha256_starts(digest_ctx, 0) != 0) {
2652#endif /* MBEDTLS_2_X_COMPAT */
2653 coap_digest_free(digest_ctx);
2654 return NULL;
2655 }
2656 }
2657 return digest_ctx;
2658}
2659
2660void
2662 mbedtls_sha256_free(digest_ctx);
2663 mbedtls_free(digest_ctx);
2664}
2665
2666int
2668 const uint8_t *data,
2669 size_t data_len) {
2670#ifdef MBEDTLS_2_X_COMPAT
2671 int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
2672#else
2673 int ret = mbedtls_sha256_update(digest_ctx, data, data_len);
2674#endif /* MBEDTLS_2_X_COMPAT */
2675
2676 return ret == 0;
2677}
2678
2679int
2681 coap_digest_t *digest_buffer) {
2682#ifdef MBEDTLS_2_X_COMPAT
2683 int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t *)digest_buffer);
2684#else
2685 int ret = mbedtls_sha256_finish(digest_ctx, (uint8_t *)digest_buffer);
2686#endif /* MBEDTLS_2_X_COMPAT */
2687
2688 coap_digest_free(digest_ctx);
2689 return ret == 0;
2690}
2691#endif /* COAP_SERVER_SUPPORT */
2692
2693#include <mbedtls/cipher.h>
2694#include <mbedtls/md.h>
2695
2696#ifndef MBEDTLS_CIPHER_MODE_AEAD
2697#error need MBEDTLS_CIPHER_MODE_AEAD, please enable MBEDTLS_CCM_C
2698#endif /* MBEDTLS_CIPHER_MODE_AEAD */
2699
2700#ifdef MBEDTLS_ERROR_C
2701#include <mbedtls/error.h>
2702#endif /* MBEDTLS_ERROR_C */
2703
2704#ifdef MBEDTLS_ERROR_C
2705#define C(Func) \
2706 do { \
2707 int c_tmp = (int)(Func); \
2708 if (c_tmp != 0) { \
2709 char error_buf[64]; \
2710 mbedtls_strerror(c_tmp, error_buf, sizeof(error_buf)); \
2711 coap_log_err("mbedtls: -0x%04x: %s\n", -c_tmp, error_buf); \
2712 goto error; \
2713 } \
2714 } while (0);
2715#else /* !MBEDTLS_ERROR_C */
2716#define C(Func) \
2717 do { \
2718 int c_tmp = (int)(Func); \
2719 if (c_tmp != 0) { \
2720 coap_log_err("mbedtls: %d\n", tmp); \
2721 goto error; \
2722 } \
2723 } while (0);
2724#endif /* !MBEDTLS_ERROR_C */
2725
2726#if COAP_WS_SUPPORT
2727/*
2728 * The struct hash_algs and the function get_hash_alg() are used to
2729 * determine which hash type to use for creating the required hash object.
2730 */
2731static struct hash_algs {
2732 cose_alg_t alg;
2733 mbedtls_md_type_t hash_type;
2734 size_t hash_size;
2735} hashs[] = {
2736 {COSE_ALGORITHM_SHA_1, MBEDTLS_MD_SHA1, 20},
2737 {COSE_ALGORITHM_SHA_256_256, MBEDTLS_MD_SHA256, 32},
2738 {COSE_ALGORITHM_SHA_512, MBEDTLS_MD_SHA512, 64},
2739};
2740
2741static mbedtls_md_type_t
2742get_hash_alg(cose_alg_t alg, size_t *hash_len) {
2743 size_t idx;
2744
2745 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
2746 if (hashs[idx].alg == alg) {
2747 *hash_len = hashs[idx].hash_size;
2748 return hashs[idx].hash_type;
2749 }
2750 }
2751 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
2752 return MBEDTLS_MD_NONE;
2753}
2754
2755int
2757 const coap_bin_const_t *data,
2758 coap_bin_const_t **hash) {
2759 mbedtls_md_context_t ctx;
2760 int ret = 0;
2761 const mbedtls_md_info_t *md_info;
2762 unsigned int len;
2763 coap_binary_t *dummy = NULL;
2764 size_t hash_length;
2765 mbedtls_md_type_t dig_type = get_hash_alg(alg, &hash_length);
2766
2767 if (dig_type == MBEDTLS_MD_NONE) {
2768 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
2769 return 0;
2770 }
2771 md_info = mbedtls_md_info_from_type(dig_type);
2772
2773 len = mbedtls_md_get_size(md_info);
2774 if (len == 0) {
2775 return 0;
2776 }
2777
2778 mbedtls_md_init(&ctx);
2779 C(mbedtls_md_setup(&ctx, md_info, 0));
2780
2781 C(mbedtls_md_starts(&ctx));
2782 C(mbedtls_md_update(&ctx, (const unsigned char *)data->s, data->length));
2783 dummy = coap_new_binary(len);
2784 if (dummy == NULL)
2785 goto error;
2786 C(mbedtls_md_finish(&ctx, dummy->s));
2787
2788 *hash = (coap_bin_const_t *)dummy;
2789 ret = 1;
2790error:
2791 mbedtls_md_free(&ctx);
2792 return ret;
2793}
2794#endif /* COAP_WS_SUPPORT */
2795
2796#if COAP_OSCORE_SUPPORT
2797int
2799 return 1;
2800}
2801
2802/*
2803 * The struct cipher_algs and the function get_cipher_alg() are used to
2804 * determine which cipher type to use for creating the required cipher
2805 * suite object.
2806 */
2807static struct cipher_algs {
2808 cose_alg_t alg;
2809 mbedtls_cipher_type_t cipher_type;
2810} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, MBEDTLS_CIPHER_AES_128_CCM},
2811 {COSE_ALGORITHM_AES_CCM_16_64_256, MBEDTLS_CIPHER_AES_256_CCM}
2812};
2813
2814static mbedtls_cipher_type_t
2815get_cipher_alg(cose_alg_t alg) {
2816 size_t idx;
2817
2818 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
2819 if (ciphers[idx].alg == alg)
2820 return ciphers[idx].cipher_type;
2821 }
2822 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
2823 return 0;
2824}
2825
2826/*
2827 * The struct hmac_algs and the function get_hmac_alg() are used to
2828 * determine which hmac type to use for creating the required hmac
2829 * suite object.
2830 */
2831static struct hmac_algs {
2832 cose_hmac_alg_t hmac_alg;
2833 mbedtls_md_type_t hmac_type;
2834} hmacs[] = {
2835 {COSE_HMAC_ALG_HMAC256_256, MBEDTLS_MD_SHA256},
2836 {COSE_HMAC_ALG_HMAC384_384, MBEDTLS_MD_SHA384},
2837 {COSE_HMAC_ALG_HMAC512_512, MBEDTLS_MD_SHA512},
2838};
2839
2840static mbedtls_md_type_t
2841get_hmac_alg(cose_hmac_alg_t hmac_alg) {
2842 size_t idx;
2843
2844 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
2845 if (hmacs[idx].hmac_alg == hmac_alg)
2846 return hmacs[idx].hmac_type;
2847 }
2848 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
2849 return 0;
2850}
2851
2852int
2854 return get_cipher_alg(alg) != 0;
2855}
2856
2857int
2859 cose_hmac_alg_t hmac_alg;
2860
2861 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
2862 return 0;
2863 return get_hmac_alg(hmac_alg) != 0;
2864}
2865
2870static int
2871setup_cipher_context(mbedtls_cipher_context_t *ctx,
2872 cose_alg_t coap_alg,
2873 const uint8_t *key_data,
2874 size_t key_length,
2875 mbedtls_operation_t mode) {
2876 const mbedtls_cipher_info_t *cipher_info;
2877 mbedtls_cipher_type_t cipher_type;
2878 uint8_t key[COAP_CRYPTO_MAX_KEY_SIZE]; /* buffer for normalizing the key
2879 according to its key length */
2880 int klen;
2881 memset(key, 0, sizeof(key));
2882
2883 if ((cipher_type = get_cipher_alg(coap_alg)) == 0) {
2884 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
2885 coap_alg);
2886 return 0;
2887 }
2888 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
2889 if (!cipher_info) {
2890 coap_log_crit("coap_crypto_encrypt: cannot get cipher info\n");
2891 return 0;
2892 }
2893
2894 mbedtls_cipher_init(ctx);
2895
2896 C(mbedtls_cipher_setup(ctx, cipher_info));
2897 klen = mbedtls_cipher_get_key_bitlen(ctx);
2898 if ((klen > (int)(sizeof(key) * 8)) || (key_length > sizeof(key))) {
2899 coap_log_crit("coap_crypto: cannot set key\n");
2900 goto error;
2901 }
2902 memcpy(key, key_data, key_length);
2903 C(mbedtls_cipher_setkey(ctx, key, klen, mode));
2904
2905 /* On success, the cipher context is released by the caller. */
2906 return 1;
2907error:
2908 mbedtls_cipher_free(ctx);
2909 return 0;
2910}
2911
2912int
2914 coap_bin_const_t *data,
2915 coap_bin_const_t *aad,
2916 uint8_t *result,
2917 size_t *max_result_len) {
2918 mbedtls_cipher_context_t ctx;
2919 const coap_crypto_aes_ccm_t *ccm;
2920#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2921 unsigned char tag[16];
2922#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
2923 int ret = 0;
2924 size_t result_len = *max_result_len;
2925 coap_bin_const_t laad;
2926
2927 if (data == NULL)
2928 return 0;
2929
2930 assert(params != NULL);
2931
2932 if (!params) {
2933 return 0;
2934 }
2935 ccm = &params->params.aes;
2936
2937 if (!setup_cipher_context(&ctx,
2938 params->alg,
2939 ccm->key.s,
2940 ccm->key.length,
2941 MBEDTLS_ENCRYPT)) {
2942 return 0;
2943 }
2944
2945 if (aad) {
2946 laad = *aad;
2947 } else {
2948 laad.s = NULL;
2949 laad.length = 0;
2950 }
2951
2952#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
2953 C(mbedtls_cipher_auth_encrypt(&ctx,
2954 ccm->nonce,
2955 15 - ccm->l, /* iv */
2956 laad.s,
2957 laad.length, /* ad */
2958 data->s,
2959 data->length, /* input */
2960 result,
2961 &result_len, /* output */
2962 tag,
2963 ccm->tag_len /* tag */
2964 ));
2965 /* check if buffer is sufficient to hold tag */
2966 if ((result_len + ccm->tag_len) > *max_result_len) {
2967 coap_log_err("coap_encrypt: buffer too small\n");
2968 goto error;
2969 }
2970 /* append tag to result */
2971 memcpy(result + result_len, tag, ccm->tag_len);
2972 *max_result_len = result_len + ccm->tag_len;
2973 ret = 1;
2974#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
2975 C(mbedtls_cipher_auth_encrypt_ext(&ctx,
2976 ccm->nonce,
2977 15 - ccm->l, /* iv */
2978 laad.s,
2979 laad.length, /* ad */
2980 data->s,
2981 data->length, /* input */
2982 result,
2983 result_len,
2984 &result_len, /* output */
2985 ccm->tag_len /* tag */
2986 ));
2987 *max_result_len = result_len;
2988 ret = 1;
2989#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
2990
2991error:
2992 mbedtls_cipher_free(&ctx);
2993 return ret;
2994}
2995
2996int
2998 coap_bin_const_t *data,
2999 coap_bin_const_t *aad,
3000 uint8_t *result,
3001 size_t *max_result_len) {
3002 mbedtls_cipher_context_t ctx;
3003 const coap_crypto_aes_ccm_t *ccm;
3004#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3005 const unsigned char *tag;
3006#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
3007 int ret = 0;
3008 size_t result_len = *max_result_len;
3009 coap_bin_const_t laad;
3010
3011 if (data == NULL)
3012 return 0;
3013
3014 assert(params != NULL);
3015
3016 if (!params) {
3017 return 0;
3018 }
3019
3020 ccm = &params->params.aes;
3021
3022 if (!setup_cipher_context(&ctx,
3023 params->alg,
3024 ccm->key.s,
3025 ccm->key.length,
3026 MBEDTLS_DECRYPT)) {
3027 return 0;
3028 }
3029
3030 if (data->length < ccm->tag_len) {
3031 coap_log_err("coap_decrypt: invalid tag length\n");
3032 goto error;
3033 }
3034
3035 if (aad) {
3036 laad = *aad;
3037 } else {
3038 laad.s = NULL;
3039 laad.length = 0;
3040 }
3041
3042#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3043 tag = data->s + data->length - ccm->tag_len;
3044 C(mbedtls_cipher_auth_decrypt(&ctx,
3045 ccm->nonce,
3046 15 - ccm->l, /* iv */
3047 laad.s,
3048 laad.length, /* ad */
3049 data->s,
3050 data->length - ccm->tag_len, /* input */
3051 result,
3052 &result_len, /* output */
3053 tag,
3054 ccm->tag_len /* tag */
3055 ));
3056#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3057 C(mbedtls_cipher_auth_decrypt_ext(&ctx,
3058 ccm->nonce,
3059 15 - ccm->l, /* iv */
3060 laad.s,
3061 laad.length, /* ad */
3062 data->s,
3063 // data->length - ccm->tag_len, /* input */
3064 data->length, /* input */
3065 result,
3066 result_len,
3067 &result_len, /* output */
3068 ccm->tag_len /* tag */
3069 ));
3070#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3071
3072 *max_result_len = result_len;
3073 ret = 1;
3074error:
3075 mbedtls_cipher_free(&ctx);
3076 return ret;
3077}
3078
3079int
3081 coap_bin_const_t *key,
3082 coap_bin_const_t *data,
3083 coap_bin_const_t **hmac) {
3084 mbedtls_md_context_t ctx;
3085 int ret = 0;
3086 const int use_hmac = 1;
3087 const mbedtls_md_info_t *md_info;
3088 mbedtls_md_type_t mac_algo;
3089 unsigned int len;
3090 coap_binary_t *dummy = NULL;
3091
3092 assert(key);
3093 assert(data);
3094 assert(hmac);
3095
3096 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3097 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3098 return 0;
3099 }
3100 md_info = mbedtls_md_info_from_type(mac_algo);
3101
3102 len = mbedtls_md_get_size(md_info);
3103 if (len == 0) {
3104 return 0;
3105 }
3106
3107 mbedtls_md_init(&ctx);
3108 C(mbedtls_md_setup(&ctx, md_info, use_hmac));
3109
3110 C(mbedtls_md_hmac_starts(&ctx, key->s, key->length));
3111 C(mbedtls_md_hmac_update(&ctx, (const unsigned char *)data->s, data->length));
3112 dummy = coap_new_binary(len);
3113 if (dummy == NULL)
3114 goto error;
3115 C(mbedtls_md_hmac_finish(&ctx, dummy->s));
3116
3117 *hmac = (coap_bin_const_t *)dummy;
3118 ret = 1;
3119error:
3120 mbedtls_md_free(&ctx);
3121 return ret;
3122}
3123
3124#endif /* COAP_OSCORE_SUPPORT */
3125
3126#else /* !COAP_WITH_LIBMBEDTLS */
3127
3128#ifdef __clang__
3129/* Make compilers happy that do not like empty modules. As this function is
3130 * never used, we ignore -Wunused-function at the end of compiling this file
3131 */
3132#pragma GCC diagnostic ignored "-Wunused-function"
3133#endif
3134static inline void
3135dummy(void) {
3136}
3137
3138#endif /* COAP_WITH_LIBMBEDTLS */
#define COAP_SERVER_SUPPORT
#define PRIx32
const char * coap_socket_strerror(void)
Definition coap_io.c:1835
#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
Library specific build wrapper for coap_internal.h.
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:90
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition coap_notls.c:206
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:278
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition coap_notls.c:201
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:220
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition coap_notls.c:135
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:238
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:124
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:189
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:266
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:185
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:98
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:215
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:163
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:181
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:158
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:257
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_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4253
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:2422
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:308
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:131
int coap_dtls_define_issue(coap_define_issue_key_t type, coap_define_issue_fail_t fail, coap_dtls_key_t *key, const coap_dtls_role_t role, int ret)
Report PKI DEFINE type issue.
Definition coap_dtls.c:165
void * coap_dtls_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:196
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:143
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
void coap_dtls_map_key_type_to_define(const coap_dtls_pki_t *setup_data, coap_dtls_key_t *key)
Map the PKI key definitions to the new DEFINE format.
Definition coap_dtls.c:26
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
@ COAP_DEFINE_KEY_PRIVATE
@ COAP_DEFINE_KEY_ROOT_CA
@ COAP_DEFINE_KEY_CA
@ COAP_DEFINE_KEY_PUBLIC
@ COAP_DEFINE_FAIL_NONE
@ COAP_DEFINE_FAIL_NOT_SUPPORTED
@ COAP_DEFINE_FAIL_BAD
coap_tls_version_t * coap_get_tls_library_version(void)
Determine the type and version of the underlying (D)TLS library.
Definition coap_notls.c:82
int coap_dtls_psk_is_supported(void)
Check whether (D)TLS PSK is available.
Definition coap_notls.c:50
coap_dtls_role_t
Definition coap_dtls.h:44
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_dtls_pki_is_supported(void)
Check whether (D)TLS PKI is available.
Definition coap_notls.c:59
int coap_dtls_rpk_is_supported(void)
Check whether (D)TLS RPK is available.
Definition coap_notls.c:77
coap_tls_library_t
Definition coap_dtls.h:112
int coap_dtls_pkcs11_is_supported(void)
Check whether (D)TLS PKCS11 is available.
Definition coap_notls.c:68
@ COAP_PKI_KEY_DEF_PKCS11
The PKI key type is PKCS11 (pkcs11:...).
Definition coap_dtls.h:287
@ COAP_PKI_KEY_DEF_DER_BUF
The PKI key type is DER buffer (ASN.1).
Definition coap_dtls.h:284
@ COAP_PKI_KEY_DEF_PEM_BUF
The PKI key type is PEM buffer.
Definition coap_dtls.h:278
@ COAP_PKI_KEY_DEF_PEM
The PKI key type is PEM file.
Definition coap_dtls.h:276
@ COAP_PKI_KEY_DEF_ENGINE
The PKI key type is to be passed to ENGINE.
Definition coap_dtls.h:293
@ COAP_PKI_KEY_DEF_RPK_BUF
The PKI key type is RPK in buffer.
Definition coap_dtls.h:280
@ COAP_PKI_KEY_DEF_DER
The PKI key type is DER file.
Definition coap_dtls.h:282
@ COAP_PKI_KEY_DEF_PKCS11_RPK
The PKI key type is PKCS11 w/ RPK (pkcs11:...).
Definition coap_dtls.h:290
@ 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_DEFINE
The individual PKI key types are Definable.
Definition coap_dtls.h:214
@ COAP_TLS_LIBRARY_MBEDTLS
Using Mbed TLS library.
Definition coap_dtls.h:117
@ 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:153
#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:148
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)
cose_hkdf_alg_t
cose_hmac_alg_t
cose_alg_t
@ COSE_HMAC_ALG_HMAC384_384
@ COSE_HMAC_ALG_HMAC256_256
@ COSE_HMAC_ALG_HMAC512_512
@ COSE_ALGORITHM_SHA_256_256
@ COSE_ALGORITHM_SHA_1
@ COSE_ALGORITHM_AES_CCM_16_64_128
@ COSE_ALGORITHM_SHA_512
@ COSE_ALGORITHM_AES_CCM_16_64_256
int coap_oscore_is_supported(void)
Check whether OSCORE is available.
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.
int coap_session_refresh_psk_identity(coap_session_t *session, const coap_bin_const_t *psk_identity)
Refresh the session's current pre-shared identity (PSK).
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
#define COAP_PROTO_NOT_RELIABLE(p)
@ COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_NONE
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
#define COAP_UNUSED
Definition libcoap.h:70
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:448
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:472
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition coap_dtls.h:468
The structure that holds the PKI key information.
Definition coap_dtls.h:321
coap_pki_key_define_t define
for definable type keys
Definition coap_dtls.h:328
union coap_dtls_key_t::@3 key
coap_pki_key_t key_type
key format type
Definition coap_dtls.h:322
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:354
void * cn_call_back_arg
Passed in to the CN callback function.
Definition coap_dtls.h:390
uint8_t allow_short_rsa_length
1 if small RSA keysizes are allowed
Definition coap_dtls.h:371
uint8_t cert_chain_validation
1 if to check cert_chain_verify_depth
Definition coap_dtls.h:365
uint8_t allow_bad_md_hash
1 if unsupported MD hashes are allowed
Definition coap_dtls.h:370
uint8_t check_cert_revocation
1 if revocation checks wanted
Definition coap_dtls.h:367
uint8_t cert_chain_verify_depth
recommended depth is 3
Definition coap_dtls.h:366
uint8_t allow_expired_certs
1 if expired certs are allowed
Definition coap_dtls.h:364
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:359
uint8_t allow_self_signed
1 if self-signed certs are allowed.
Definition coap_dtls.h:362
coap_dtls_cn_callback_t validate_cn_call_back
CN check callback function.
Definition coap_dtls.h:389
uint8_t allow_expired_crl
1 if expired crl is allowed
Definition coap_dtls.h:369
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:360
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition coap_dtls.h:484
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:535
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition coap_dtls.h:562
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition coap_dtls.h:554
void * id_call_back_arg
Passed in to the Identity callback function.
Definition coap_dtls.h:555
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition coap_dtls.h:563
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
coap_const_char_ptr_t public_cert
define: Public Cert
Definition coap_dtls.h:303
coap_const_char_ptr_t private_key
define: Private Key
Definition coap_dtls.h:304
coap_const_char_ptr_t ca
define: Common CA Certificate
Definition coap_dtls.h:302
size_t public_cert_len
define Public Cert length (if needed)
Definition coap_dtls.h:306
size_t ca_len
define CA Cert length (if needed)
Definition coap_dtls.h:305
coap_pki_define_t private_key_def
define: Private Key type definition
Definition coap_dtls.h:310
size_t private_key_len
define Private Key length (if needed)
Definition coap_dtls.h:307
coap_pki_define_t ca_def
define: Common CA type definition
Definition coap_dtls.h:308
coap_pki_define_t public_cert_def
define: Public Cert type definition
Definition coap_dtls.h:309
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:125
uint64_t built_version
(D)TLS Built against Library Version
Definition coap_dtls.h:128
coap_tls_library_t type
Library type.
Definition coap_dtls.h:127
uint64_t version
(D)TLS runtime Library Version
Definition coap_dtls.h:126
const char * s_byte
signed char ptr
Definition coap_str.h:73
const uint8_t * u_byte
unsigned char ptr
Definition coap_str.h:74