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