libcoap 4.3.5-develop-5a5330d
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 if (m_context->root_ca_file || m_context->root_ca_path ||
951 m_context->trust_store_defined) {
952 /* No FS to read these files */
955 &key, role, -1);
956 }
957#endif /* ! MBEDTLS_FS_IO */
958
959#if defined(MBEDTLS_SSL_SRV_C)
960 mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
961 setup_data->check_common_ca ?
962 MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
963 MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
964#endif
965 mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
966 MBEDTLS_SSL_VERIFY_REQUIRED :
967 MBEDTLS_SSL_VERIFY_NONE);
968 /*
969 * Verify Peer.
970 * Need to do all checking, even if setup_data->verify_peer_cert is not set
971 */
972 mbedtls_ssl_conf_verify(&m_env->conf,
973 cert_verify_callback_mbedtls, c_session);
974
975 return 1;
976}
977
978#if defined(MBEDTLS_SSL_SRV_C)
979/*
980 * PKI SNI callback.
981 */
982static int
983pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
984 const unsigned char *uname, size_t name_len) {
985 unsigned int i;
986 coap_dtls_pki_t sni_setup_data;
987 coap_session_t *c_session = (coap_session_t *)p_info;
988 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
989 coap_mbedtls_context_t *m_context =
990 (coap_mbedtls_context_t *)c_session->context->dtls_context;
991 char *name;
992
993 name = mbedtls_malloc(name_len+1);
994 if (!name)
995 return -1;
996
997 memcpy(name, uname, name_len);
998 name[name_len] = '\000';
999
1000 /* Is this a cached entry? */
1001 for (i = 0; i < m_context->pki_sni_count; i++) {
1002 if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
1003 break;
1004 }
1005 }
1006 if (i == m_context->pki_sni_count) {
1007 /*
1008 * New PKI SNI request
1009 */
1010 coap_dtls_key_t *new_entry;
1011 pki_sni_entry *pki_sni_entry_list;
1012
1013 coap_lock_callback_ret(new_entry,
1014 m_context->setup_data.validate_sni_call_back(name,
1015 m_context->setup_data.sni_call_back_arg));
1016 if (!new_entry) {
1017 mbedtls_free(name);
1018 return -1;
1019 }
1020
1021 pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
1022 (i+1)*sizeof(pki_sni_entry));
1023
1024 if (pki_sni_entry_list == NULL) {
1025 mbedtls_free(name);
1026 return -1;
1027 }
1028 m_context->pki_sni_entry_list = pki_sni_entry_list;
1029 memset(&m_context->pki_sni_entry_list[i], 0,
1030 sizeof(m_context->pki_sni_entry_list[i]));
1031 m_context->pki_sni_entry_list[i].sni = name;
1032 m_context->pki_sni_entry_list[i].pki_key = *new_entry;
1033 sni_setup_data = m_context->setup_data;
1034 sni_setup_data.pki_key = *new_entry;
1035 if (setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
1036 &m_context->pki_sni_entry_list[i].public_cert,
1037 &m_context->pki_sni_entry_list[i].private_key,
1038 m_env,
1039 m_context,
1040 c_session,
1041 &sni_setup_data, COAP_DTLS_ROLE_SERVER) < 0) {
1042 mbedtls_free(name);
1043 return -1;
1044 }
1045 /* name has been absorbed into pki_sni_entry_list[].sni entry */
1046 m_context->pki_sni_count++;
1047 } else {
1048 mbedtls_free(name);
1049 }
1050
1051 mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
1052 NULL);
1053 return mbedtls_ssl_set_hs_own_cert(ssl,
1054 &m_context->pki_sni_entry_list[i].public_cert,
1055 &m_context->pki_sni_entry_list[i].private_key);
1056}
1057
1058#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1059/*
1060 * PSK SNI callback.
1061 */
1062static int
1063psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
1064 const unsigned char *uname, size_t name_len) {
1065 unsigned int i;
1066 coap_session_t *c_session = (coap_session_t *)p_info;
1067 coap_mbedtls_context_t *m_context =
1068 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1069 char *name;
1070
1071 name = mbedtls_malloc(name_len+1);
1072 if (!name)
1073 return -1;
1074
1075 memcpy(name, uname, name_len);
1076 name[name_len] = '\000';
1077
1078 /* Is this a cached entry? */
1079 for (i = 0; i < m_context->psk_sni_count; i++) {
1080 if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
1081 break;
1082 }
1083 }
1084 if (i == m_context->psk_sni_count) {
1085 /*
1086 * New PSK SNI request
1087 */
1088 const coap_dtls_spsk_info_t *new_entry;
1089 psk_sni_entry *psk_sni_entry_list;
1090
1091 coap_lock_callback_ret(new_entry,
1093 c_session,
1095 if (!new_entry) {
1096 mbedtls_free(name);
1097 return -1;
1098 }
1099
1100 psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
1101 (i+1)*sizeof(psk_sni_entry));
1102
1103 if (psk_sni_entry_list == NULL) {
1104 mbedtls_free(name);
1105 return -1;
1106 }
1107 m_context->psk_sni_entry_list = psk_sni_entry_list;
1108 m_context->psk_sni_entry_list[i].sni = name;
1109 m_context->psk_sni_entry_list[i].psk_info = *new_entry;
1110 /* name has been absorbed into psk_sni_entry_list[].sni entry */
1111 m_context->psk_sni_count++;
1112 } else {
1113 mbedtls_free(name);
1114 }
1115
1117 &m_context->psk_sni_entry_list[i].psk_info.hint);
1119 &m_context->psk_sni_entry_list[i].psk_info.key);
1120 return mbedtls_ssl_set_hs_psk(ssl,
1121 m_context->psk_sni_entry_list[i].psk_info.key.s,
1122 m_context->psk_sni_entry_list[i].psk_info.key.length);
1123}
1124#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1125
1126static int
1127setup_server_ssl_session(coap_session_t *c_session,
1128 coap_mbedtls_env_t *m_env) {
1129 coap_mbedtls_context_t *m_context =
1130 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1131 int ret = 0;
1132 m_context->psk_pki_enabled |= IS_SERVER;
1133
1134 mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
1135 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1136 MBEDTLS_SSL_IS_SERVER,
1137 c_session->proto == COAP_PROTO_DTLS ?
1138 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1139 MBEDTLS_SSL_TRANSPORT_STREAM,
1140 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1141 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1142 -ret, get_error_string(ret));
1143 goto fail;
1144 }
1145
1146 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1147
1148#if defined(MBEDTLS_SSL_PROTO_DTLS)
1149 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1150 COAP_DTLS_RETRANSMIT_TOTAL_MS);
1151#endif /* MBEDTLS_SSL_PROTO_DTLS */
1152
1153 if (m_context->psk_pki_enabled & IS_PSK) {
1154#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1155 mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
1157 mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
1158 }
1159#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1160 m_env->ec_jpake = c_session->context->spsk_setup_data.ec_jpake;
1161#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1162#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1163 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1164#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1165 }
1166
1167 if (m_context->psk_pki_enabled & IS_PKI) {
1168 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1169 &m_env->private_key, m_env, m_context,
1170 c_session, &m_context->setup_data,
1172 if (ret < 0) {
1173 coap_log_err("PKI setup failed\n");
1174 return ret;
1175 }
1176 if (m_context->setup_data.validate_sni_call_back) {
1177 mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1178 }
1179 }
1180
1181 if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1182 mbedtls_ctr_drbg_random,
1183 &m_env->ctr_drbg)) != 0) {
1184 coap_log_err("mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1185 -ret, get_error_string(ret));
1186 goto fail;
1187 }
1188
1189#if defined(MBEDTLS_SSL_PROTO_DTLS)
1190 mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1191 mbedtls_ssl_cookie_check,
1192 &m_env->cookie_ctx);
1193#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1194 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1195#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1196#endif /* MBEDTLS_SSL_PROTO_DTLS */
1197#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1198 /*
1199 * Configure CID max length.
1200 *
1201 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1202 * to use RFC9146 extension ID of 54, rather than the draft version -05
1203 * value of 254.
1204 */
1205 mbedtls_ssl_conf_cid(&m_env->conf, COAP_DTLS_CID_LENGTH, MBEDTLS_SSL_UNEXPECTED_CID_IGNORE);
1206#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1207fail:
1208 return ret;
1209}
1210#endif /* MBEDTLS_SSL_SRV_C */
1211
1212#if COAP_CLIENT_SUPPORT
1213static int *psk_ciphers = NULL;
1214static int *pki_ciphers = NULL;
1215static int *ecjpake_ciphers = NULL;
1216static int processed_ciphers = 0;
1217
1218#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1219static int
1220coap_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info) {
1221#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1222 switch (info->key_exchange) {
1223 case MBEDTLS_KEY_EXCHANGE_PSK:
1224 case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
1225 case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
1226 case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
1227 return 1;
1228 case MBEDTLS_KEY_EXCHANGE_NONE:
1229 case MBEDTLS_KEY_EXCHANGE_RSA:
1230 case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
1231 case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
1232 case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
1233 case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
1234 case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
1235 case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
1236 default:
1237 return 0;
1238 }
1239#else /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1240 return mbedtls_ssl_ciphersuite_uses_psk(info);
1241#endif /* MBEDTLS_VERSION_NUMBER < 0x03060000 */
1242}
1243#endif /* defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) */
1244
1245static void
1246set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method) {
1247 if (!processed_ciphers) {
1248 const int *list = mbedtls_ssl_list_ciphersuites();
1249 const int *base = list;
1250 int *psk_list;
1251 int *pki_list;
1252#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1253 int *ecjpake_list;
1254 int ecjpake_count = 1;
1255#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1256 int psk_count = 1; /* account for empty terminator */
1257 int pki_count = 1;
1258
1259 while (*list) {
1260 const mbedtls_ssl_ciphersuite_t *cur =
1261 mbedtls_ssl_ciphersuite_from_id(*list);
1262
1263 if (cur) {
1264#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1265 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1266 /* Minimum of TLS1.2 required - skip */
1267 }
1268#else
1269 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1270 /* Minimum of TLS1.2 required - skip */
1271 }
1272#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1273#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1274 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1275 ecjpake_count++;
1276 }
1277#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1278#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1279 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1280 psk_count++;
1281 pki_count++;
1282 }
1283#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1284#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1285 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1286 psk_count++;
1287 }
1288#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1289 else {
1290 pki_count++;
1291 }
1292 }
1293 list++;
1294 }
1295 list = base;
1296
1297 psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1298 if (psk_ciphers == NULL) {
1299 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1300 return;
1301 }
1302 pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1303 if (pki_ciphers == NULL) {
1304 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1305 mbedtls_free(psk_ciphers);
1306 psk_ciphers = NULL;
1307 return;
1308 }
1309#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1310 ecjpake_ciphers = mbedtls_malloc(ecjpake_count * sizeof(ecjpake_ciphers[0]));
1311 if (ecjpake_ciphers == NULL) {
1312 coap_log_err("set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1313 mbedtls_free(psk_ciphers);
1314 mbedtls_free(pki_ciphers);
1315 psk_ciphers = NULL;
1316 pki_ciphers = NULL;
1317 return;
1318 }
1319#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1320
1321 psk_list = psk_ciphers;
1322 pki_list = pki_ciphers;
1323#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1324 ecjpake_list = ecjpake_ciphers;
1325#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1326
1327 while (*list) {
1328 const mbedtls_ssl_ciphersuite_t *cur =
1329 mbedtls_ssl_ciphersuite_from_id(*list);
1330 if (cur) {
1331#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1332 if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1333 /* Minimum of TLS1.2 required - skip */
1334 }
1335#else
1336 if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1337 /* Minimum of TLS1.2 required - skip */
1338 }
1339#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1340#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1341 else if (cur->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1342 *ecjpake_list = *list;
1343 ecjpake_list++;
1344 }
1345#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1346#if MBEDTLS_VERSION_NUMBER >= 0x03060000
1347 else if (cur->min_tls_version >= MBEDTLS_SSL_VERSION_TLS1_3) {
1348 *psk_list = *list;
1349 psk_list++;
1350 *pki_list = *list;
1351 pki_list++;
1352 }
1353#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
1354#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1355 else if (coap_ssl_ciphersuite_uses_psk(cur)) {
1356 *psk_list = *list;
1357 psk_list++;
1358 }
1359#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1360 else {
1361 *pki_list = *list;
1362 pki_list++;
1363 }
1364 }
1365 list++;
1366 }
1367 /* zero terminate */
1368 *psk_list = 0;
1369 *pki_list = 0;
1370 processed_ciphers = 1;
1371 }
1372 switch (method) {
1373 case COAP_ENC_PSK:
1374 mbedtls_ssl_conf_ciphersuites(conf, psk_ciphers);
1375 break;
1376 case COAP_ENC_PKI:
1377 mbedtls_ssl_conf_ciphersuites(conf, pki_ciphers);
1378 break;
1379 case COAP_ENC_ECJPAKE:
1380 mbedtls_ssl_conf_ciphersuites(conf, ecjpake_ciphers);
1381 break;
1382 default:
1383 assert(0);
1384 break;
1385 }
1386}
1387
1388static int
1389setup_client_ssl_session(coap_session_t *c_session,
1390 coap_mbedtls_env_t *m_env) {
1391 int ret;
1392
1393 coap_mbedtls_context_t *m_context =
1394 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1395
1396 m_context->psk_pki_enabled |= IS_CLIENT;
1397
1398 if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1399 MBEDTLS_SSL_IS_CLIENT,
1400 c_session->proto == COAP_PROTO_DTLS ?
1401 MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1402 MBEDTLS_SSL_TRANSPORT_STREAM,
1403 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1404 coap_log_err("mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1405 -ret, get_error_string(ret));
1406 goto fail;
1407 }
1408
1409#if defined(MBEDTLS_SSL_PROTO_DTLS)
1410 mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1411 COAP_DTLS_RETRANSMIT_TOTAL_MS);
1412#endif /* MBEDTLS_SSL_PROTO_DTLS */
1413
1414 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1415 mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1416
1417 if (m_context->psk_pki_enabled & IS_PSK) {
1418#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1419 const coap_bin_const_t *psk_key;
1420 const coap_bin_const_t *psk_identity;
1421
1422 coap_log_info("Setting PSK key\n");
1423
1424 psk_key = coap_get_session_client_psk_key(c_session);
1425 psk_identity = coap_get_session_client_psk_identity(c_session);
1426 if (psk_key == NULL || psk_identity == NULL) {
1427 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1428 goto fail;
1429 }
1430
1431 if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1432 psk_key->length, psk_identity->s,
1433 psk_identity->length)) != 0) {
1434 coap_log_err("mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1435 -ret, get_error_string(ret));
1436 goto fail;
1437 }
1438 if (c_session->cpsk_setup_data.client_sni) {
1439 if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1440 c_session->cpsk_setup_data.client_sni)) != 0) {
1441 coap_log_err("mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1442 -ret, get_error_string(ret));
1443 goto fail;
1444 }
1445 }
1446 /* Identity Hint currently not supported in Mbed TLS so code removed */
1447
1448#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1449 if (c_session->cpsk_setup_data.ec_jpake) {
1450 m_env->ec_jpake = 1;
1451 set_ciphersuites(&m_env->conf, COAP_ENC_ECJPAKE);
1452#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1453 mbedtls_ssl_conf_max_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1454#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1455 } else {
1456 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1457 }
1458#else /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1459 set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1460#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1461#else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1462 coap_log_warn("PSK not enabled in Mbed TLS library\n");
1463#endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1464 } else if ((m_context->psk_pki_enabled & IS_PKI) ||
1465 (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1466 /*
1467 * If neither PSK or PKI have been set up, use PKI basics.
1468 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1469 */
1470 coap_dtls_pki_t *setup_data = &m_context->setup_data;
1471
1472 if (!(m_context->psk_pki_enabled & IS_PKI)) {
1473 /* PKI not defined - set up some defaults */
1474 setup_data->verify_peer_cert = 1;
1475 setup_data->check_common_ca = 0;
1476 setup_data->allow_self_signed = 1;
1477 setup_data->allow_expired_certs = 1;
1478 setup_data->cert_chain_validation = 1;
1479 setup_data->cert_chain_verify_depth = 2;
1480 setup_data->check_cert_revocation = 1;
1481 setup_data->allow_no_crl = 1;
1482 setup_data->allow_expired_crl = 1;
1483 setup_data->is_rpk_not_cert = 0;
1484 setup_data->use_cid = 0;
1485 }
1486 mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1487 ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1488 &m_env->private_key, m_env, m_context,
1489 c_session, setup_data,
1491 if (ret < 0) {
1492 coap_log_err("PKI setup failed\n");
1493 return ret;
1494 }
1495#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1496 if (c_session->proto == COAP_PROTO_TLS ||
1497 c_session->proto == COAP_PROTO_WSS) {
1498 static const char *alpn_list[] = { "coap", NULL };
1499
1500 ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1501 if (ret != 0) {
1502 coap_log_err("ALPN setup failed %d)\n", ret);
1503 }
1504 }
1505#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1506 mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1507#if defined(MBEDTLS_SSL_PROTO_DTLS)
1508#if MBEDTLS_VERSION_NUMBER >= 0x02100100
1509 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1510#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1511#endif /* MBEDTLS_SSL_PROTO_DTLS */
1512 set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1513 }
1514 return 0;
1515
1516fail:
1517 return ret;
1518}
1519#endif /* COAP_CLIENT_SUPPORT */
1520
1521static void
1522mbedtls_cleanup(coap_mbedtls_env_t *m_env) {
1523 if (!m_env) {
1524 return;
1525 }
1526
1527 mbedtls_x509_crt_free(&m_env->cacert);
1528 mbedtls_x509_crt_free(&m_env->public_cert);
1529 mbedtls_pk_free(&m_env->private_key);
1530 mbedtls_entropy_free(&m_env->entropy);
1531 mbedtls_ssl_config_free(&m_env->conf);
1532 mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1533 mbedtls_ssl_free(&m_env->ssl);
1534 mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1535}
1536
1537static void
1538coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1539 if (m_env) {
1540 if (!m_env->sent_alert)
1541 mbedtls_ssl_close_notify(&m_env->ssl);
1542 mbedtls_cleanup(m_env);
1543 mbedtls_free(m_env);
1544 }
1545}
1546
1547#if COAP_MAX_LOGGING_LEVEL > 0
1548static const char *
1549report_mbedtls_alert(unsigned char alert) {
1550 switch (alert) {
1551 case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC:
1552 return ": Bad Record MAC";
1553 case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE:
1554 return ": Handshake failure";
1555 case MBEDTLS_SSL_ALERT_MSG_NO_CERT:
1556 return ": No Certificate provided";
1557 case MBEDTLS_SSL_ALERT_MSG_BAD_CERT:
1558 return ": Certificate is bad";
1559 case MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN:
1560 return ": Certificate is unknown";
1561 case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA:
1562 return ": CA is unknown";
1563 case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED:
1564 return ": Access was denied";
1565 case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR:
1566 return ": Decrypt error";
1567 default:
1568 return "";
1569 }
1570}
1571#endif /* COAP_MAX_LOGGING_LEVEL */
1572
1573/*
1574 * return -1 failure
1575 * 0 not completed
1576 * 1 established
1577 */
1578static int
1579do_mbedtls_handshake(coap_session_t *c_session,
1580 coap_mbedtls_env_t *m_env) {
1581 int ret;
1582 int alert;
1583
1584 ret = mbedtls_ssl_handshake(&m_env->ssl);
1585 switch (ret) {
1586 case 0:
1587 m_env->established = 1;
1588 coap_log_debug("* %s: Mbed TLS established\n",
1589 coap_session_str(c_session));
1590 ret = 1;
1591#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1592#if COAP_CLIENT_SUPPORT
1593 if (c_session->type == COAP_SESSION_TYPE_CLIENT &&
1594 c_session->proto == COAP_PROTO_DTLS) {
1595 coap_mbedtls_context_t *m_context;
1596
1597 m_context = (coap_mbedtls_context_t *)c_session->context->dtls_context;
1598 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
1599 m_context->setup_data.use_cid) {
1600 unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX];
1601 int enabled;
1602 size_t peer_cid_len;
1603
1604 /* See whether CID was negotiated */
1605 if (mbedtls_ssl_get_peer_cid(&m_env->ssl, &enabled, peer_cid, &peer_cid_len) == 0 &&
1606 enabled == MBEDTLS_SSL_CID_ENABLED) {
1607 c_session->negotiated_cid = 1;
1608 } else {
1609 coap_log_info("** %s: CID was not negotiated\n", coap_session_str(c_session));
1610 c_session->negotiated_cid = 0;
1611 }
1612 }
1613 }
1614#endif /* COAP_CLIENT_SUPPORT */
1615#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1616 break;
1617 case MBEDTLS_ERR_SSL_WANT_READ:
1618 case MBEDTLS_ERR_SSL_WANT_WRITE:
1619 if (m_env->ssl.state == MBEDTLS_SSL_SERVER_HELLO
1620#if MBEDTLS_VERSION_NUMBER >= 0x03030000
1621 || m_env->ssl.state == MBEDTLS_SSL_NEW_SESSION_TICKET
1622#endif /* MBEDTLS_VERSION_NUMBER >= 0x03030000 */
1623 ) {
1624 if (++m_env->server_hello_cnt > 10) {
1625 /* retried this too many times */
1626 goto fail;
1627 }
1628 }
1629 errno = EAGAIN;
1630 ret = 0;
1631 break;
1632 case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1633 coap_log_debug("hello verification requested\n");
1634 goto reset;
1635 case MBEDTLS_ERR_SSL_INVALID_MAC:
1636 goto fail;
1637#ifdef MBEDTLS_2_X_COMPAT
1638 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
1639#else /* ! MBEDTLS_2_X_COMPAT */
1640 case MBEDTLS_ERR_SSL_DECODE_ERROR:
1641#endif /* ! MBEDTLS_2_X_COMPAT */
1642 goto fail;
1643 case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1644 alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1645 goto fail_alert;
1646#ifdef MBEDTLS_2_X_COMPAT
1647 case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1648 case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1649 alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1650 goto fail_alert;
1651#endif /* MBEDTLS_2_X_COMPAT */
1652 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1653 goto fail;
1654 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1655 if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1656 coap_log_warn("***%s: Alert '%d'%s\n",
1657 coap_session_str(c_session), m_env->ssl.in_msg[1],
1658 report_mbedtls_alert(m_env->ssl.in_msg[1]));
1659 /* Fall through */
1660 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1661 case MBEDTLS_ERR_SSL_CONN_EOF:
1662 case MBEDTLS_ERR_NET_CONN_RESET:
1664 ret = -1;
1665 break;
1666 default:
1667 coap_log_warn("do_mbedtls_handshake: session establish "
1668 "returned -0x%x: '%s'\n",
1669 -ret, get_error_string(ret));
1670 ret = -1;
1671 break;
1672 }
1673 return ret;
1674
1675fail_alert:
1676 mbedtls_ssl_send_alert_message(&m_env->ssl,
1677 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1678 alert);
1679 m_env->sent_alert = 1;
1680fail:
1681 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1682 coap_log_warn("do_mbedtls_handshake: session establish "
1683 "returned '%s'\n",
1684 get_error_string(ret));
1685reset:
1686 mbedtls_ssl_session_reset(&m_env->ssl);
1687#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1688 if (m_env->ec_jpake) {
1689 const coap_bin_const_t *psk_key;
1690
1691#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
1692 if (c_session->type == COAP_SESSION_TYPE_CLIENT) {
1693 psk_key = coap_get_session_client_psk_key(c_session);
1694 } else {
1695 psk_key = coap_get_session_server_psk_key(c_session);
1696 }
1697#elif COAP_CLIENT_SUPPORT
1698 psk_key = coap_get_session_client_psk_key(c_session);
1699#else /* COAP_SERVER_SUPPORT */
1700 psk_key = coap_get_session_server_psk_key(c_session);
1701#endif /* COAP_SERVER_SUPPORT */
1702 if (psk_key) {
1703 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
1704 }
1705 }
1706#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1707 return -1;
1708}
1709
1710static void
1711mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1712 const char *file COAP_UNUSED,
1713 int line COAP_UNUSED, const char *str) {
1714
1715 coap_log_t coap_level = COAP_LOG_DEBUG;
1716 /*
1717 * 0 No debug
1718 * 1 Error
1719 * 2 State change
1720 * 3 Informational
1721 * 4 Verbose
1722 */
1723 switch (level) {
1724 case 0:
1725 coap_level = COAP_LOG_EMERG;
1726 break;
1727 case 1:
1728 coap_level = COAP_LOG_WARN;
1729 break;
1730 case 2:
1731 coap_level = COAP_LOG_NOTICE;
1732 break;
1733 case 3:
1734 coap_level = COAP_LOG_INFO;
1735 break;
1736 case 4:
1737 default:
1738 coap_level = COAP_LOG_DEBUG;
1739 break;
1740 }
1741 coap_dtls_log(coap_level, "%s", str);
1742}
1743
1744#if !COAP_DISABLE_TCP
1745/*
1746 * strm
1747 * return +ve data amount
1748 * 0 no more
1749 * -ve Mbed TLS error
1750 */
1751static int
1752coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
1753 int ret = MBEDTLS_ERR_SSL_CONN_EOF;
1754 coap_session_t *c_session = (coap_session_t *)ctx;
1755
1756 if (out != NULL) {
1757 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
1758 /* Translate layer returns into what MbedTLS expects */
1759 if (ret == -1) {
1760 if (errno == ECONNRESET) {
1761 /* graceful shutdown */
1762 ret = MBEDTLS_ERR_SSL_CONN_EOF;
1763 } else {
1764 ret = MBEDTLS_ERR_NET_RECV_FAILED;
1765 }
1766 } else if (ret == 0) {
1767 errno = EAGAIN;
1768 ret = MBEDTLS_ERR_SSL_WANT_READ;
1769 }
1770 }
1771 return ret;
1772}
1773
1774/*
1775 * strm
1776 * return +ve data amount
1777 * 0 no more
1778 * -ve Mbed TLS error
1779 */
1780static int
1781coap_sock_write(void *context, const unsigned char *in, size_t inl) {
1782 int ret = 0;
1783 coap_session_t *c_session = (coap_session_t *)context;
1784
1785 ret = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
1786 (const uint8_t *)in,
1787 inl);
1788 /* Translate layer what returns into what MbedTLS expects */
1789 if (ret < 0) {
1790 if ((c_session->state == COAP_SESSION_STATE_CSM ||
1791 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
1792 (errno == EPIPE || errno == ECONNRESET)) {
1793 /*
1794 * Need to handle a TCP timing window where an agent continues with
1795 * the sending of the next handshake or a CSM.
1796 * However, the peer does not like a certificate and so sends a
1797 * fatal alert and closes the TCP session.
1798 * The sending of the next handshake or CSM may get terminated because
1799 * of the closed TCP session, but there is still an outstanding alert
1800 * to be read in and reported on.
1801 * In this case, pretend that sending the info was fine so that the
1802 * alert can be read (which effectively is what happens with DTLS).
1803 */
1804 ret = inl;
1805 } else {
1806#ifdef _WIN32
1807 int lasterror = WSAGetLastError();
1808
1809 if (lasterror == WSAEWOULDBLOCK) {
1810 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1811 } else if (lasterror == WSAECONNRESET) {
1812 ret = MBEDTLS_ERR_NET_CONN_RESET;
1813 }
1814#else
1815 if (errno == EAGAIN || errno == EINTR) {
1816 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1817 } else if (errno == EPIPE || errno == ECONNRESET) {
1818 ret = MBEDTLS_ERR_NET_CONN_RESET;
1819 }
1820#endif
1821 else {
1822 ret = MBEDTLS_ERR_NET_SEND_FAILED;
1823 }
1824 coap_log_debug("* %s: failed to send %zd bytes (%s) state %d\n",
1825 coap_session_str(c_session), inl, coap_socket_strerror(),
1826 c_session->state);
1827 }
1828 }
1829 if (ret == 0) {
1830 errno = EAGAIN;
1831 ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1832 }
1833 return ret;
1834}
1835#endif /* !COAP_DISABLE_TCP */
1836
1837static coap_mbedtls_env_t *
1838coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1839 coap_dtls_role_t role,
1840 coap_proto_t proto) {
1841 int ret = 0;
1842 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1843
1844 if (m_env)
1845 return m_env;
1846
1847 m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1848 if (!m_env) {
1849 return NULL;
1850 }
1851 memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1852
1853 mbedtls_ssl_init(&m_env->ssl);
1854 mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1855 mbedtls_ssl_config_init(&m_env->conf);
1856 mbedtls_entropy_init(&m_env->entropy);
1857
1858#if defined(MBEDTLS_PSA_CRYPTO_C)
1859 psa_crypto_init();
1860#endif /* MBEDTLS_PSA_CRYPTO_C */
1861
1862#if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1863 mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1864#endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1865 if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1866 mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1867 if (ret != MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) {
1868 coap_log_info("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1869 -ret, get_error_string(ret));
1870 goto fail;
1871 }
1872 coap_log_err("mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1873 -ret, get_error_string(ret));
1874 }
1875
1876 if (role == COAP_DTLS_ROLE_CLIENT) {
1877#if COAP_CLIENT_SUPPORT
1878 if (setup_client_ssl_session(c_session, m_env) != 0) {
1879 goto fail;
1880 }
1881#else /* !COAP_CLIENT_SUPPORT */
1882 goto fail;
1883#endif /* !COAP_CLIENT_SUPPORT */
1884 } else if (role == COAP_DTLS_ROLE_SERVER) {
1885#if defined(MBEDTLS_SSL_SRV_C)
1886 if (setup_server_ssl_session(c_session, m_env) != 0) {
1887 goto fail;
1888 }
1889#else /* ! MBEDTLS_SSL_SRV_C */
1890 goto fail;
1891#endif /* ! MBEDTLS_SSL_SRV_C */
1892 } else {
1893 goto fail;
1894 }
1895
1896#if MBEDTLS_VERSION_NUMBER >= 0x03020000
1897 mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1898#else
1899 mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1900 MBEDTLS_SSL_MINOR_VERSION_3);
1901#endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1902
1903 if (mbedtls_ssl_setup(&m_env->ssl, &m_env->conf) != 0) {
1904 goto fail;
1905 }
1906 if (proto == COAP_PROTO_DTLS) {
1907 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1908 coap_dgram_read, NULL);
1909#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
1910 if (COAP_PROTO_NOT_RELIABLE(c_session->proto)) {
1911 if (role == COAP_DTLS_ROLE_CLIENT) {
1912#if COAP_CLIENT_SUPPORT
1913 coap_mbedtls_context_t *m_context =
1914 (coap_mbedtls_context_t *)c_session->context->dtls_context;
1915
1916 if ((m_context->psk_pki_enabled & IS_PSK && c_session->cpsk_setup_data.use_cid) ||
1917 m_context->setup_data.use_cid) {
1918 /*
1919 * Enable passive DTLS CID support.
1920 *
1921 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1922 * to use RFC9146 extension ID of 54, rather than the draft version -05
1923 * value of 254.
1924 */
1925 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, NULL, 0);
1926 }
1927#endif /* COAP_CLIENT_SUPPORT */
1928 } else {
1929#if COAP_SERVER_SUPPORT
1930 uint8_t cid[COAP_DTLS_CID_LENGTH];
1931 /*
1932 * Enable server DTLS CID support.
1933 *
1934 * Note: Set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT to 0 (the default)
1935 * to use RFC9146 extension ID of 54, rather than the draft version -05
1936 * value of 254.
1937 */
1938 coap_prng_lkd(cid, sizeof(cid));
1939 mbedtls_ssl_set_cid(&m_env->ssl, MBEDTLS_SSL_CID_ENABLED, cid,
1940 sizeof(cid));
1941 c_session->client_cid = coap_new_bin_const(cid, sizeof(cid));
1942#endif /* COAP_SERVER_SUPPORT */
1943 }
1944 }
1945#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1946 }
1947#if !COAP_DISABLE_TCP
1948 else {
1949 assert(proto == COAP_PROTO_TLS);
1950 mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
1951 coap_sock_read, NULL);
1952 }
1953#endif /* ! COAP_DISABLE_TCP */
1954#ifdef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
1955 coap_mbedtls_context_t *m_context =
1956 ((coap_mbedtls_context_t *)c_session->context->dtls_context);
1957 if ((m_context->psk_pki_enabled & IS_PSK) &&
1958 m_env->ec_jpake) {
1959 const coap_bin_const_t *psk_key;
1960
1961#if COAP_CLIENT_SUPPORT && COAP_SERVER_SUPPORT
1962 if (role == COAP_DTLS_ROLE_CLIENT) {
1963 psk_key = coap_get_session_client_psk_key(c_session);
1964 } else {
1965 psk_key = coap_get_session_server_psk_key(c_session);
1966 }
1967#elif COAP_CLIENT_SUPPORT
1968 psk_key = coap_get_session_client_psk_key(c_session);
1969#else /* COAP_SERVER_SUPPORT */
1970 psk_key = coap_get_session_server_psk_key(c_session);
1971#endif /* COAP_SERVER_SUPPORT */
1972 mbedtls_ssl_set_hs_ecjpake_password(&m_env->ssl, psk_key->s, psk_key->length);
1973 }
1974#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1975#ifdef __ZEPHYR__
1976 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1977 zephyr_timing_set_delay,
1978 zephyr_timing_get_delay);
1979#else
1980 mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1981 mbedtls_timing_set_delay,
1982 mbedtls_timing_get_delay);
1983#endif
1984
1985 mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1986 return m_env;
1987
1988fail:
1989 if (m_env) {
1990 mbedtls_free(m_env);
1991 }
1992 return NULL;
1993}
1994
1995int
1997#if defined(MBEDTLS_SSL_PROTO_DTLS)
1998 return 1;
1999#else /* !MBEDTLS_SSL_PROTO_DTLS */
2000 static int reported = 0;
2001 if (!reported) {
2002 reported = 1;
2003 coap_log_emerg("libcoap not compiled for DTLS with Mbed TLS"
2004 " - update Mbed TLS to include DTLS\n");
2005 }
2006 return 0;
2007#endif /* !MBEDTLS_SSL_PROTO_DTLS */
2008}
2009
2010int
2012#if !COAP_DISABLE_TCP
2013 return 1;
2014#else /* COAP_DISABLE_TCP */
2015 return 0;
2016#endif /* COAP_DISABLE_TCP */
2017}
2018
2019/*
2020 * return 0 failed
2021 * 1 passed
2022 */
2023int
2025 return 1;
2026}
2027
2028/*
2029 * return 0 failed
2030 * 1 passed
2031 */
2032int
2034 return 1;
2035}
2036
2037/*
2038 * return 0 failed
2039 * 1 passed
2040 */
2041int
2043 return 0;
2044}
2045
2046/*
2047 * return 0 failed
2048 * 1 passed
2049 */
2050int
2052 return 0;
2053}
2054
2055/*
2056 * return 0 failed
2057 * 1 passed
2058 */
2059int
2061#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2062 return 1;
2063#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2064 return 0;
2065#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2066}
2067
2068#if COAP_CLIENT_SUPPORT
2069int
2070coap_dtls_set_cid_tuple_change(coap_context_t *c_context, uint8_t every) {
2071#ifdef MBEDTLS_SSL_DTLS_CONNECTION_ID
2072 c_context->testing_cids = every;
2073 return 1;
2074#else /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2075 (void)c_context;
2076 (void)every;
2077 return 0;
2078#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2079}
2080#endif /* COAP_CLIENT_SUPPORT */
2081
2082void *
2084 coap_mbedtls_context_t *m_context;
2085 (void)c_context;
2086
2087 m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
2088 if (m_context) {
2089 memset(m_context, 0, sizeof(coap_mbedtls_context_t));
2090 }
2091 return m_context;
2092}
2093
2094#if COAP_SERVER_SUPPORT
2095/*
2096 * return 0 failed
2097 * 1 passed
2098 */
2099int
2101 coap_dtls_spsk_t *setup_data
2102 ) {
2103 coap_mbedtls_context_t *m_context =
2104 ((coap_mbedtls_context_t *)c_context->dtls_context);
2105
2106#if !defined(MBEDTLS_SSL_SRV_C)
2107 coap_log_emerg("coap_context_set_spsk:"
2108 " libcoap not compiled for Server Mode for Mbed TLS"
2109 " - update Mbed TLS to include Server Mode\n");
2110 return 0;
2111#endif /* !MBEDTLS_SSL_SRV_C */
2112 if (!m_context || !setup_data)
2113 return 0;
2114
2115 if (setup_data->ec_jpake) {
2116#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2117 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2118#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2119 }
2120 m_context->psk_pki_enabled |= IS_PSK;
2121 return 1;
2122}
2123#endif /* COAP_SERVER_SUPPORT */
2124
2125#if COAP_CLIENT_SUPPORT
2126/*
2127 * return 0 failed
2128 * 1 passed
2129 */
2130int
2132 coap_dtls_cpsk_t *setup_data
2133 ) {
2134#if !defined(MBEDTLS_SSL_CLI_C)
2135 (void)c_context;
2136 (void)setup_data;
2137
2138 coap_log_emerg("coap_context_set_cpsk:"
2139 " libcoap not compiled for Client Mode for Mbed TLS"
2140 " - update Mbed TLS to include Client Mode\n");
2141 return 0;
2142#else /* MBEDTLS_SSL_CLI_C */
2143 coap_mbedtls_context_t *m_context =
2144 ((coap_mbedtls_context_t *)c_context->dtls_context);
2145
2146 if (!m_context || !setup_data)
2147 return 0;
2148
2149 if (setup_data->validate_ih_call_back) {
2150 coap_log_warn("CoAP Client with Mbed TLS does not support Identity Hint selection\n");
2151 }
2152 if (setup_data->ec_jpake) {
2153#ifndef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
2154 coap_log_warn("Mbed TLS not compiled for EC-JPAKE support\n");
2155#endif /* ! MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2156 }
2157 if (setup_data->use_cid) {
2158#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2159 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2160#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2161 }
2162 m_context->psk_pki_enabled |= IS_PSK;
2163 return 1;
2164#endif /* MBEDTLS_SSL_CLI_C */
2165}
2166#endif /* COAP_CLIENT_SUPPORT */
2167
2168int
2170 const coap_dtls_pki_t *setup_data,
2171 const coap_dtls_role_t role COAP_UNUSED) {
2172 coap_mbedtls_context_t *m_context =
2173 ((coap_mbedtls_context_t *)c_context->dtls_context);
2174
2175 m_context->setup_data = *setup_data;
2176 if (!m_context->setup_data.verify_peer_cert) {
2177 /* Needs to be clear so that no CA DNs are transmitted */
2178 m_context->setup_data.check_common_ca = 0;
2179 /* Allow all of these but warn if issue */
2180 m_context->setup_data.allow_self_signed = 1;
2181 m_context->setup_data.allow_expired_certs = 1;
2182 m_context->setup_data.cert_chain_validation = 1;
2183 m_context->setup_data.cert_chain_verify_depth = 10;
2184 m_context->setup_data.check_cert_revocation = 1;
2185 m_context->setup_data.allow_no_crl = 1;
2186 m_context->setup_data.allow_expired_crl = 1;
2187 m_context->setup_data.allow_bad_md_hash = 1;
2188 m_context->setup_data.allow_short_rsa_length = 1;
2189 }
2190 m_context->psk_pki_enabled |= IS_PKI;
2191 if (setup_data->use_cid) {
2192#ifndef MBEDTLS_SSL_DTLS_CONNECTION_ID
2193 coap_log_warn("Mbed TLS not compiled for Connection-ID support\n");
2194#endif /* ! MBEDTLS_SSL_DTLS_CONNECTION_ID */
2195 }
2196 return 1;
2197}
2198
2199int
2201 const char *ca_file,
2202 const char *ca_path) {
2203 coap_mbedtls_context_t *m_context =
2204 ((coap_mbedtls_context_t *)c_context->dtls_context);
2205
2206 if (!m_context) {
2207 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
2208 "not set up\n");
2209 return 0;
2210 }
2211
2212 if (ca_file == NULL && ca_path == NULL) {
2213 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
2214 "not defined\n");
2215 return 0;
2216 }
2217 if (m_context->root_ca_file) {
2218 mbedtls_free(m_context->root_ca_file);
2219 m_context->root_ca_file = NULL;
2220 }
2221
2222 if (ca_file) {
2223 m_context->root_ca_file = mbedtls_strdup(ca_file);
2224 }
2225
2226 if (m_context->root_ca_path) {
2227 mbedtls_free(m_context->root_ca_path);
2228 m_context->root_ca_path = NULL;
2229 }
2230
2231 if (ca_path) {
2232 m_context->root_ca_path = mbedtls_strdup(ca_path);
2233 }
2234 return 1;
2235}
2236
2237/*
2238 * return 0 failed
2239 * 1 passed
2240 */
2241int
2243 coap_mbedtls_context_t *m_context =
2244 ((coap_mbedtls_context_t *)c_context->dtls_context);
2245
2246 if (!m_context) {
2247 coap_log_warn("coap_context_load_pki_trust_store: (D)TLS environment "
2248 "not set up\n");
2249 return 0;
2250 }
2251 m_context->trust_store_defined = 1;
2252
2253 /* No proper support for this in MbedTLS at this point */
2254 return 1;
2255}
2256
2257
2258int
2260 coap_mbedtls_context_t *m_context =
2261 ((coap_mbedtls_context_t *)c_context->dtls_context);
2262 return m_context->psk_pki_enabled ? 1 : 0;
2263}
2264
2265void
2266coap_dtls_free_context(void *dtls_context) {
2267 coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
2268 unsigned int i;
2269
2270 for (i = 0; i < m_context->pki_sni_count; i++) {
2271 mbedtls_free(m_context->pki_sni_entry_list[i].sni);
2272
2273 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
2274
2275 mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
2276
2277 mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
2278 }
2279 if (m_context->pki_sni_entry_list)
2280 mbedtls_free(m_context->pki_sni_entry_list);
2281
2282 for (i = 0; i < m_context->psk_sni_count; i++) {
2283 mbedtls_free(m_context->psk_sni_entry_list[i].sni);
2284 }
2285 if (m_context->psk_sni_entry_list)
2286 mbedtls_free(m_context->psk_sni_entry_list);
2287
2288 if (m_context->root_ca_path)
2289 mbedtls_free(m_context->root_ca_path);
2290 if (m_context->root_ca_file)
2291 mbedtls_free(m_context->root_ca_file);
2292
2293 mbedtls_free(m_context);
2294}
2295
2296#if COAP_CLIENT_SUPPORT
2297void *
2299#if !defined(MBEDTLS_SSL_CLI_C)
2300 (void)c_session;
2301 coap_log_emerg("coap_dtls_new_client_session:"
2302 " libcoap not compiled for Client Mode for Mbed TLS"
2303 " - update Mbed TLS to include Client Mode\n");
2304 return NULL;
2305#else /* MBEDTLS_SSL_CLI_C */
2306 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2309 int ret;
2310
2311 if (m_env) {
2312 coap_tick_t now;
2313
2314 coap_ticks(&now);
2315 m_env->last_timeout = now;
2316 ret = do_mbedtls_handshake(c_session, m_env);
2317 if (ret == -1) {
2318 coap_dtls_free_mbedtls_env(m_env);
2319 return NULL;
2320 }
2321 }
2322 return m_env;
2323#endif /* MBEDTLS_SSL_CLI_C */
2324}
2325#endif /* COAP_CLIENT_SUPPORT */
2326
2327#if COAP_SERVER_SUPPORT
2328void *
2330#if !defined(MBEDTLS_SSL_SRV_C)
2331 (void)c_session;
2332 coap_log_emerg("coap_dtls_new_server_session:"
2333 " libcoap not compiled for Server Mode for Mbed TLS"
2334 " - update Mbed TLS to include Server Mode\n");
2335 return NULL;
2336#else /* MBEDTLS_SSL_SRV_C */
2337 coap_mbedtls_env_t *m_env =
2338 (coap_mbedtls_env_t *)c_session->tls;
2339 if (m_env) {
2340#if defined(MBEDTLS_SSL_PROTO_DTLS)
2341#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2342 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2343#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2344#endif /* MBEDTLS_SSL_PROTO_DTLS */
2345 }
2346 return m_env;
2347#endif /* MBEDTLS_SSL_SRV_C */
2348}
2349#endif /* COAP_SERVER_SUPPORT */
2350
2351void
2353 if (c_session && c_session->context && c_session->tls) {
2354 coap_dtls_free_mbedtls_env(c_session->tls);
2355 c_session->tls = NULL;
2357 }
2358 return;
2359}
2360
2361void
2363#if defined(MBEDTLS_SSL_PROTO_DTLS)
2364 coap_mbedtls_env_t *m_env =
2365 (coap_mbedtls_env_t *)c_session->tls;
2366 if (m_env) {
2367#if MBEDTLS_VERSION_NUMBER >= 0x02100100
2368 mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
2369#endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
2370 }
2371#else /* ! MBEDTLS_SSL_PROTO_DTLS */
2372 (void)c_session;
2373#endif /* MBEDTLS_SSL_PROTO_DTLS */
2374}
2375
2376ssize_t
2378 const uint8_t *data, size_t data_len) {
2379 int ret;
2380 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2381
2382 assert(m_env != NULL);
2383
2384 if (!m_env) {
2385 return -1;
2386 }
2387 c_session->dtls_event = -1;
2388 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2389 coap_session_str(c_session), (int)data_len);
2390 if (m_env->established) {
2391 ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char *) data, data_len);
2392 if (ret <= 0) {
2393 switch (ret) {
2394 case MBEDTLS_ERR_SSL_WANT_READ:
2395 case MBEDTLS_ERR_SSL_WANT_WRITE:
2396 ret = 0;
2397 break;
2398 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2400 ret = -1;
2401 break;
2402 default:
2403 coap_log_warn("coap_dtls_send: "
2404 "returned -0x%x: '%s'\n",
2405 -ret, get_error_string(ret));
2406 ret = -1;
2407 break;
2408 }
2409 if (ret == -1) {
2410 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2411 }
2412 }
2413 } else {
2414 ret = do_mbedtls_handshake(c_session, m_env);
2415 if (ret == 1) {
2416 /* Just connected, so send the data */
2417 return coap_dtls_send(c_session, data, data_len);
2418 }
2419 ret = -1;
2420 }
2421
2422 if (c_session->dtls_event >= 0) {
2423 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2424 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2425 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2426 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2427 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2429 ret = -1;
2430 }
2431 }
2432 return ret;
2433}
2434
2435int
2437 return 0;
2438}
2439
2441coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2442 return 0;
2443}
2444
2447 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2448#ifdef __ZEPHYR__
2449 int ret = zephyr_timing_get_delay(&m_env->timer);
2450#else
2451 int ret = mbedtls_timing_get_delay(&m_env->timer);
2452#endif
2453 unsigned int scalar = 1 << m_env->retry_scalar;
2454
2455 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2456 switch (ret) {
2457 case 0:
2458 /* int_ms has not timed out */
2459 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2460 /* Need to indicate remaining timeout time */
2461 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2462 }
2463 m_env->last_timeout = now;
2464 /* This may cause a minor extra delay */
2465 return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2466 case 1:
2467 /* int_ms has timed out, but not fin_ms */
2468 /*
2469 * Need to make sure that we do not do this too frequently
2470 */
2471 if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
2472 return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
2473 }
2474
2475 /* Reset for the next time */
2476 m_env->last_timeout = now;
2477 return now;
2478 case 2:
2479 /* fin_ms has timed out - timed out - one final try */
2480 return now;
2481 default:
2482 break;
2483 }
2484
2485 return 0;
2486}
2487
2488/*
2489 * return 1 timed out
2490 * 0 still timing out
2491 */
2492int
2494 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2495
2496 assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2497 m_env->retry_scalar++;
2498 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2499 (do_mbedtls_handshake(c_session, m_env) < 0)) {
2500 /* Too many retries */
2502 return 1;
2503 }
2504 return 0;
2505}
2506
2507/*
2508 * return +ve data amount
2509 * 0 no more
2510 * -1 error
2511 */
2512int
2514 const uint8_t *data,
2515 size_t data_len) {
2516 int ret = 1;
2517
2518 c_session->dtls_event = -1;
2519 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2520 coap_ssl_t *ssl_data;
2521
2522 assert(m_env != NULL);
2523
2524 ssl_data = &m_env->coap_ssl_data;
2525 if (ssl_data->pdu_len) {
2526 coap_log_err("** %s: Previous data not read %u bytes\n",
2527 coap_session_str(c_session), ssl_data->pdu_len);
2528 }
2529 ssl_data->pdu = data;
2530 ssl_data->pdu_len = (unsigned)data_len;
2531
2532 if (m_env->established) {
2533#if COAP_CONSTRAINED_STACK
2534 /* pdu can be protected by global_lock if needed */
2535 static uint8_t pdu[COAP_RXBUFFER_SIZE];
2536#else /* ! COAP_CONSTRAINED_STACK */
2537 uint8_t pdu[COAP_RXBUFFER_SIZE];
2538#endif /* ! COAP_CONSTRAINED_STACK */
2539
2540 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2542 c_session);
2543 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2544 }
2545
2546 ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2547 if (ret > 0) {
2548 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2549 coap_session_str(c_session), ret);
2550 ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2551 goto finish;
2552 }
2553 switch (ret) {
2554 case 0:
2555 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2556 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2558 break;
2559 case MBEDTLS_ERR_SSL_WANT_READ:
2560 break;
2561 default:
2562 coap_log_warn("coap_dtls_receive: "
2563 "returned -0x%x: '%s' (length %zd)\n",
2564 -ret, get_error_string(ret), data_len);
2565 break;
2566 }
2567 ret = -1;
2568 } else {
2569 ret = do_mbedtls_handshake(c_session, m_env);
2570 if (ret == 1) {
2571 /* Just connected, so send the data */
2572 coap_session_connected(c_session);
2573 } else {
2574 if (ssl_data->pdu_len) {
2575 /* Do the handshake again incase of internal timeout */
2576 ret = do_mbedtls_handshake(c_session, m_env);
2577 if (ret == 1) {
2578 /* Just connected, so send the data */
2579 coap_session_connected(c_session);
2580 }
2581 }
2582 ret = -1;
2583 }
2584 }
2585 if (c_session->dtls_event >= 0) {
2586 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2587 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2588 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2589 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2590 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2592 ssl_data = NULL;
2593 ret = -1;
2594 }
2595 }
2596finish:
2597 if (ssl_data && ssl_data->pdu_len) {
2598 /* pdu data is held on stack which will not stay there */
2599 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2600 ssl_data->pdu_len = 0;
2601 ssl_data->pdu = NULL;
2602 }
2603 return ret;
2604}
2605
2606#if COAP_SERVER_SUPPORT
2607/*
2608 * return -1 failure
2609 * 0 not completed
2610 * 1 client hello seen
2611 */
2612int
2614 const uint8_t *data,
2615 size_t data_len) {
2616#if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2617 (void)c_session;
2618 (void)data;
2619 (void)data_len;
2620 coap_log_emerg("coap_dtls_hello:"
2621 " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2622 " - update Mbed TLS to include DTLS and Server Mode\n");
2623 return -1;
2624#else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2625 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2626 coap_ssl_t *ssl_data;
2627 int ret;
2628
2629 if (!m_env) {
2630 m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2632 if (m_env) {
2633 c_session->tls = m_env;
2634 } else {
2635 /* error should have already been reported */
2636 return -1;
2637 }
2638 }
2639
2640 if ((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2641 (unsigned char *)&c_session->addr_info.remote,
2642 sizeof(c_session->addr_info.remote))) != 0) {
2643 coap_log_err("mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2644 -ret, get_error_string(ret));
2645 return -1;
2646 }
2647
2648 ssl_data = &m_env->coap_ssl_data;
2649 if (ssl_data->pdu_len) {
2650 coap_log_err("** %s: Previous data not read %u bytes\n",
2651 coap_session_str(c_session), ssl_data->pdu_len);
2652 }
2653 ssl_data->pdu = data;
2654 ssl_data->pdu_len = (unsigned)data_len;
2655
2656 ret = do_mbedtls_handshake(c_session, m_env);
2657 if (ret == 0 || m_env->seen_client_hello) {
2658 /* The test for seen_client_hello gives the ability to setup a new
2659 c_session to continue the do_mbedtls_handshake past the client hello
2660 and safely allow updating of the m_env and separately
2661 letting a new session cleanly start up.
2662 */
2663 m_env->seen_client_hello = 0;
2664 ret = 1;
2665 } else {
2666 ret = 0;
2667 }
2668
2669 if (ssl_data->pdu_len) {
2670 /* pdu data is held on stack which will not stay there */
2671 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2672 ssl_data->pdu_len = 0;
2673 ssl_data->pdu = NULL;
2674 }
2675 return ret;
2676#endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2677}
2678#endif /* COAP_SERVER_SUPPORT */
2679
2680unsigned int
2682 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2683 int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2684
2685 if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2686 return 13 + 8 + 8;
2687 }
2688 return expansion;
2689}
2690
2691#if !COAP_DISABLE_TCP
2692#if COAP_CLIENT_SUPPORT
2693void *
2695#if !defined(MBEDTLS_SSL_CLI_C)
2696 (void)c_session;
2697 *connected = 0;
2698 coap_log_emerg("coap_tls_new_client_session:"
2699 " libcoap not compiled for Client Mode for Mbed TLS"
2700 " - update Mbed TLS to include Client Mode\n");
2701 return NULL;
2702#else /* MBEDTLS_SSL_CLI_C */
2703 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2706 int ret;
2707 coap_tick_t now;
2708 coap_ticks(&now);
2709
2710 if (!m_env)
2711 return NULL;
2712
2713 m_env->last_timeout = now;
2714 c_session->tls = m_env;
2715 ret = do_mbedtls_handshake(c_session, m_env);
2716 if (ret == 1) {
2718 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2719 }
2720 return m_env;
2721#endif /* MBEDTLS_SSL_CLI_C */
2722}
2723#endif /* COAP_CLIENT_SUPPORT */
2724
2725#if COAP_SERVER_SUPPORT
2726void *
2728#if !defined(MBEDTLS_SSL_SRV_C)
2729 (void)c_session;
2730 (void)connected;
2731
2732 coap_log_emerg("coap_tls_new_server_session:"
2733 " libcoap not compiled for Server Mode for Mbed TLS"
2734 " - update Mbed TLS to include Server Mode\n");
2735 return NULL;
2736#else /* MBEDTLS_SSL_SRV_C */
2737 coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2740 int ret;
2741
2742 if (!m_env)
2743 return NULL;
2744
2745 c_session->tls = m_env;
2746 ret = do_mbedtls_handshake(c_session, m_env);
2747 if (ret == 1) {
2749 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2750 }
2751 return m_env;
2752#endif /* MBEDTLS_SSL_SRV_C */
2753}
2754#endif /* COAP_SERVER_SUPPORT */
2755
2756void
2758 coap_dtls_free_session(c_session);
2759 return;
2760}
2761
2762/*
2763 * strm
2764 * return +ve Number of bytes written.
2765 * -1 Error (error in errno).
2766 */
2767ssize_t
2768coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2769 size_t data_len) {
2770 int ret = 0;
2771 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2772 size_t amount_sent = 0;
2773
2774 assert(m_env != NULL);
2775
2776 if (!m_env) {
2777 errno = ENXIO;
2778 return -1;
2779 }
2780 c_session->dtls_event = -1;
2781 if (m_env->established) {
2782 while (amount_sent < data_len) {
2783 ret = mbedtls_ssl_write(&m_env->ssl, &data[amount_sent],
2784 data_len - amount_sent);
2785 if (ret <= 0) {
2786 switch (ret) {
2787 case MBEDTLS_ERR_SSL_WANT_READ:
2788 case MBEDTLS_ERR_SSL_WANT_WRITE:
2789 if (amount_sent)
2790 ret = amount_sent;
2791 else
2792 ret = 0;
2793 c_session->sock.flags |= COAP_SOCKET_WANT_WRITE;
2794 break;
2795 case MBEDTLS_ERR_NET_CONN_RESET:
2796 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2798 break;
2799 default:
2800 coap_log_warn("coap_tls_write: "
2801 "returned -0x%x: '%s'\n",
2802 -ret, get_error_string(ret));
2803 ret = -1;
2804 break;
2805 }
2806 if (ret == -1) {
2807 coap_log_warn("coap_tls_write: cannot send PDU\n");
2808 }
2809 break;
2810 }
2811 amount_sent += ret;
2812 }
2813 } else {
2814 ret = do_mbedtls_handshake(c_session, m_env);
2815 if (ret == 1) {
2817 c_session);
2818 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2819 } else {
2820 ret = -1;
2821 }
2822 }
2823
2824 if (c_session->dtls_event >= 0) {
2825 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2826 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2827 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2828 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2829 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2831 ret = -1;
2832 }
2833 }
2834 if (ret > 0) {
2835 if (ret == (ssize_t)data_len)
2836 coap_log_debug("* %s: tls: sent %4d bytes\n",
2837 coap_session_str(c_session), ret);
2838 else
2839 coap_log_debug("* %s: tls: sent %4d of %4zd bytes\n",
2840 coap_session_str(c_session), ret, data_len);
2841 }
2842 return ret;
2843}
2844
2845/*
2846 * strm
2847 * return >=0 Number of bytes read.
2848 * -1 Error (error in errno).
2849 */
2850ssize_t
2851coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
2852 int ret = -1;
2853
2854 coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2855
2856 if (!m_env) {
2857 errno = ENXIO;
2858 return -1;
2859 }
2860
2861 c_session->dtls_event = -1;
2862
2863 if (!m_env->established && !m_env->sent_alert) {
2864 ret = do_mbedtls_handshake(c_session, m_env);
2865 if (ret == 1) {
2867 c_session);
2868 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2869 }
2870 }
2871
2872 if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
2873 ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
2874 if (ret <= 0) {
2875 switch (ret) {
2876 case 0:
2877 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2879 ret = -1;
2880 break;
2881 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2882 /* Stop the sending of an alert on closedown */
2883 m_env->sent_alert = 1;
2885 break;
2886#if MBEDTLS_VERSION_NUMBER >= 0x03060000
2887 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
2888#endif /* MBEDTLS_VERSION_NUMBER >= 0x03060000 */
2889 case MBEDTLS_ERR_SSL_WANT_READ:
2890 errno = EAGAIN;
2891 ret = 0;
2892 break;
2893 default:
2894 coap_log_warn("coap_tls_read: "
2895 "returned -0x%x: '%s' (length %zd)\n",
2896 -ret, get_error_string(ret), data_len);
2897 ret = -1;
2898 break;
2899 }
2900 } else if (ret < (int)data_len) {
2901 c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
2902 }
2903 }
2904
2905 if (c_session->dtls_event >= 0) {
2906 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2907 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2908 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2909 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2910 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2912 ret = -1;
2913 }
2914 }
2915 if (ret > 0) {
2916 coap_log_debug("* %s: tls: recv %4d bytes\n",
2917 coap_session_str(c_session), ret);
2918 }
2919 return ret;
2920}
2921#endif /* !COAP_DISABLE_TCP */
2922
2923void
2924coap_dtls_startup(void) {
2925}
2926
2927void
2928coap_dtls_shutdown(void) {
2929#if COAP_CLIENT_SUPPORT
2930 mbedtls_free(psk_ciphers);
2931 mbedtls_free(pki_ciphers);
2932 mbedtls_free(ecjpake_ciphers);
2933 psk_ciphers = NULL;
2934 pki_ciphers = NULL;
2935 ecjpake_ciphers = NULL;
2936 processed_ciphers = 0;
2937#endif /* COAP_CLIENT_SUPPORT */
2939}
2940
2941void *
2942coap_dtls_get_tls(const coap_session_t *c_session,
2943 coap_tls_library_t *tls_lib) {
2944 if (tls_lib)
2945 *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
2946 if (c_session && c_session->tls) {
2947 coap_mbedtls_env_t *m_env;
2948
2949 /* To get around const issue */
2950 memcpy(&m_env, &c_session->tls, sizeof(m_env));
2951
2952 return (void *)&m_env->ssl;
2953 }
2954 return NULL;
2955}
2956
2957static coap_log_t keep_log_level = COAP_LOG_EMERG;
2958
2959void
2961#if !defined(ESPIDF_VERSION)
2962 int use_level;
2963 /*
2964 * Mbed TLS debug levels filter
2965 * 0 No debug
2966 * 1 Error
2967 * 2 State change
2968 * 3 Informational
2969 * 4 Verbose
2970 */
2971 switch ((int)level) {
2972 case COAP_LOG_EMERG:
2973 use_level = 0;
2974 break;
2975 case COAP_LOG_ALERT:
2976 case COAP_LOG_CRIT:
2977 case COAP_LOG_ERR:
2978 case COAP_LOG_WARN:
2979 use_level = 1;
2980 break;
2981 case COAP_LOG_NOTICE:
2982 use_level = 2;
2983 break;
2984 case COAP_LOG_INFO:
2985 use_level = 3;
2986 break;
2987 case COAP_LOG_DEBUG:
2988 default:
2989 use_level = 4;
2990 break;
2991 }
2992 mbedtls_debug_set_threshold(use_level);
2993#endif /* !ESPIDF_VERSION) */
2994 keep_log_level = level;
2995}
2996
2999 return keep_log_level;
3000}
3001
3004 static coap_tls_version_t version;
3005 version.version = mbedtls_version_get_number();
3006 version.built_version = MBEDTLS_VERSION_NUMBER;
3008 return &version;
3009}
3010
3011#if COAP_SERVER_SUPPORT
3013coap_digest_setup(void) {
3014 mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
3015
3016 if (digest_ctx) {
3017 mbedtls_sha256_init(digest_ctx);
3018#ifdef MBEDTLS_2_X_COMPAT
3019 if (mbedtls_sha256_starts_ret(digest_ctx, 0) != 0) {
3020#else
3021 if (mbedtls_sha256_starts(digest_ctx, 0) != 0) {
3022#endif /* MBEDTLS_2_X_COMPAT */
3023 coap_digest_free(digest_ctx);
3024 return NULL;
3025 }
3026 }
3027 return digest_ctx;
3028}
3029
3030void
3032 if (digest_ctx) {
3033 mbedtls_sha256_free(digest_ctx);
3034 mbedtls_free(digest_ctx);
3035 }
3036}
3037
3038int
3040 const uint8_t *data,
3041 size_t data_len) {
3042#ifdef MBEDTLS_2_X_COMPAT
3043 int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
3044#else
3045 int ret = mbedtls_sha256_update(digest_ctx, data, data_len);
3046#endif /* MBEDTLS_2_X_COMPAT */
3047
3048 return ret == 0;
3049}
3050
3051int
3053 coap_digest_t *digest_buffer) {
3054#ifdef MBEDTLS_2_X_COMPAT
3055 int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t *)digest_buffer);
3056#else
3057 int ret = mbedtls_sha256_finish(digest_ctx, (uint8_t *)digest_buffer);
3058#endif /* MBEDTLS_2_X_COMPAT */
3059
3060 coap_digest_free(digest_ctx);
3061 return ret == 0;
3062}
3063#endif /* COAP_SERVER_SUPPORT */
3064
3065#include <mbedtls/cipher.h>
3066#include <mbedtls/md.h>
3067
3068#ifndef MBEDTLS_CIPHER_MODE_AEAD
3069#error need MBEDTLS_CIPHER_MODE_AEAD, please enable MBEDTLS_CCM_C
3070#endif /* MBEDTLS_CIPHER_MODE_AEAD */
3071
3072#ifdef MBEDTLS_ERROR_C
3073#include <mbedtls/error.h>
3074#endif /* MBEDTLS_ERROR_C */
3075
3076#ifdef MBEDTLS_ERROR_C
3077#define C(Func) \
3078 do { \
3079 int c_tmp = (int)(Func); \
3080 if (c_tmp != 0) { \
3081 char error_buf[64]; \
3082 mbedtls_strerror(c_tmp, error_buf, sizeof(error_buf)); \
3083 coap_log_err("mbedtls: -0x%04x: %s\n", -c_tmp, error_buf); \
3084 goto error; \
3085 } \
3086 } while (0);
3087#else /* !MBEDTLS_ERROR_C */
3088#define C(Func) \
3089 do { \
3090 int c_tmp = (int)(Func); \
3091 if (c_tmp != 0) { \
3092 coap_log_err("mbedtls: %d\n", tmp); \
3093 goto error; \
3094 } \
3095 } while (0);
3096#endif /* !MBEDTLS_ERROR_C */
3097
3098#if COAP_WS_SUPPORT
3099/*
3100 * The struct hash_algs and the function get_hash_alg() are used to
3101 * determine which hash type to use for creating the required hash object.
3102 */
3103static struct hash_algs {
3104 cose_alg_t alg;
3105 mbedtls_md_type_t hash_type;
3106 size_t hash_size;
3107} hashs[] = {
3108 {COSE_ALGORITHM_SHA_1, MBEDTLS_MD_SHA1, 20},
3109 {COSE_ALGORITHM_SHA_256_256, MBEDTLS_MD_SHA256, 32},
3110 {COSE_ALGORITHM_SHA_512, MBEDTLS_MD_SHA512, 64},
3111};
3112
3113static mbedtls_md_type_t
3114get_hash_alg(cose_alg_t alg, size_t *hash_len) {
3115 size_t idx;
3116
3117 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
3118 if (hashs[idx].alg == alg) {
3119 *hash_len = hashs[idx].hash_size;
3120 return hashs[idx].hash_type;
3121 }
3122 }
3123 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
3124 return MBEDTLS_MD_NONE;
3125}
3126
3127int
3129 const coap_bin_const_t *data,
3130 coap_bin_const_t **hash) {
3131 mbedtls_md_context_t ctx;
3132 int ret = 0;
3133 const mbedtls_md_info_t *md_info;
3134 unsigned int len;
3135 coap_binary_t *dummy = NULL;
3136 size_t hash_length;
3137 mbedtls_md_type_t dig_type = get_hash_alg(alg, &hash_length);
3138
3139 if (dig_type == MBEDTLS_MD_NONE) {
3140 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3141 return 0;
3142 }
3143 md_info = mbedtls_md_info_from_type(dig_type);
3144
3145 len = mbedtls_md_get_size(md_info);
3146 if (len == 0) {
3147 return 0;
3148 }
3149
3150 mbedtls_md_init(&ctx);
3151 C(mbedtls_md_setup(&ctx, md_info, 0));
3152
3153 C(mbedtls_md_starts(&ctx));
3154 C(mbedtls_md_update(&ctx, (const unsigned char *)data->s, data->length));
3155 dummy = coap_new_binary(len);
3156 if (dummy == NULL)
3157 goto error;
3158 C(mbedtls_md_finish(&ctx, dummy->s));
3159
3160 *hash = (coap_bin_const_t *)dummy;
3161 ret = 1;
3162error:
3163 mbedtls_md_free(&ctx);
3164 return ret;
3165}
3166#endif /* COAP_WS_SUPPORT */
3167
3168#if COAP_OSCORE_SUPPORT
3169int
3171 return 1;
3172}
3173
3174/*
3175 * The struct cipher_algs and the function get_cipher_alg() are used to
3176 * determine which cipher type to use for creating the required cipher
3177 * suite object.
3178 */
3179static struct cipher_algs {
3180 cose_alg_t alg;
3181 mbedtls_cipher_type_t cipher_type;
3182} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, MBEDTLS_CIPHER_AES_128_CCM},
3183 {COSE_ALGORITHM_AES_CCM_16_64_256, MBEDTLS_CIPHER_AES_256_CCM}
3184};
3185
3186static mbedtls_cipher_type_t
3187get_cipher_alg(cose_alg_t alg) {
3188 size_t idx;
3189
3190 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
3191 if (ciphers[idx].alg == alg)
3192 return ciphers[idx].cipher_type;
3193 }
3194 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
3195 return 0;
3196}
3197
3198/*
3199 * The struct hmac_algs and the function get_hmac_alg() are used to
3200 * determine which hmac type to use for creating the required hmac
3201 * suite object.
3202 */
3203static struct hmac_algs {
3204 cose_hmac_alg_t hmac_alg;
3205 mbedtls_md_type_t hmac_type;
3206} hmacs[] = {
3207 {COSE_HMAC_ALG_HMAC256_256, MBEDTLS_MD_SHA256},
3208 {COSE_HMAC_ALG_HMAC384_384, MBEDTLS_MD_SHA384},
3209 {COSE_HMAC_ALG_HMAC512_512, MBEDTLS_MD_SHA512},
3210};
3211
3212static mbedtls_md_type_t
3213get_hmac_alg(cose_hmac_alg_t hmac_alg) {
3214 size_t idx;
3215
3216 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
3217 if (hmacs[idx].hmac_alg == hmac_alg)
3218 return hmacs[idx].hmac_type;
3219 }
3220 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
3221 return 0;
3222}
3223
3224int
3226 return get_cipher_alg(alg) != 0;
3227}
3228
3229int
3231 cose_hmac_alg_t hmac_alg;
3232
3233 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3234 return 0;
3235 return get_hmac_alg(hmac_alg) != 0;
3236}
3237
3242static int
3243setup_cipher_context(mbedtls_cipher_context_t *ctx,
3244 cose_alg_t coap_alg,
3245 const uint8_t *key_data,
3246 size_t key_length,
3247 mbedtls_operation_t mode) {
3248 const mbedtls_cipher_info_t *cipher_info;
3249 mbedtls_cipher_type_t cipher_type;
3250 uint8_t key[COAP_CRYPTO_MAX_KEY_SIZE]; /* buffer for normalizing the key
3251 according to its key length */
3252 int klen;
3253 memset(key, 0, sizeof(key));
3254
3255 if ((cipher_type = get_cipher_alg(coap_alg)) == 0) {
3256 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
3257 coap_alg);
3258 return 0;
3259 }
3260 cipher_info = mbedtls_cipher_info_from_type(cipher_type);
3261 if (!cipher_info) {
3262 coap_log_crit("coap_crypto_encrypt: cannot get cipher info\n");
3263 return 0;
3264 }
3265
3266 mbedtls_cipher_init(ctx);
3267
3268 C(mbedtls_cipher_setup(ctx, cipher_info));
3269 klen = mbedtls_cipher_get_key_bitlen(ctx);
3270 if ((klen > (int)(sizeof(key) * 8)) || (key_length > sizeof(key))) {
3271 coap_log_crit("coap_crypto: cannot set key\n");
3272 goto error;
3273 }
3274 memcpy(key, key_data, key_length);
3275 C(mbedtls_cipher_setkey(ctx, key, klen, mode));
3276
3277 /* On success, the cipher context is released by the caller. */
3278 return 1;
3279error:
3280 mbedtls_cipher_free(ctx);
3281 return 0;
3282}
3283
3284int
3286 coap_bin_const_t *data,
3287 coap_bin_const_t *aad,
3288 uint8_t *result,
3289 size_t *max_result_len) {
3290 mbedtls_cipher_context_t ctx;
3291 const coap_crypto_aes_ccm_t *ccm;
3292#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3293 unsigned char tag[16];
3294#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
3295 int ret = 0;
3296 size_t result_len = *max_result_len;
3297 coap_bin_const_t laad;
3298
3299 if (data == NULL)
3300 return 0;
3301
3302 assert(params != NULL);
3303
3304 if (!params) {
3305 return 0;
3306 }
3307 ccm = &params->params.aes;
3308
3309 if (!setup_cipher_context(&ctx,
3310 params->alg,
3311 ccm->key.s,
3312 ccm->key.length,
3313 MBEDTLS_ENCRYPT)) {
3314 return 0;
3315 }
3316
3317 if (aad) {
3318 laad = *aad;
3319 } else {
3320 laad.s = NULL;
3321 laad.length = 0;
3322 }
3323
3324#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3325 C(mbedtls_cipher_auth_encrypt(&ctx,
3326 ccm->nonce,
3327 15 - ccm->l, /* iv */
3328 laad.s,
3329 laad.length, /* ad */
3330 data->s,
3331 data->length, /* input */
3332 result,
3333 &result_len, /* output */
3334 tag,
3335 ccm->tag_len /* tag */
3336 ));
3337 /* check if buffer is sufficient to hold tag */
3338 if ((result_len + ccm->tag_len) > *max_result_len) {
3339 coap_log_err("coap_encrypt: buffer too small\n");
3340 goto error;
3341 }
3342 /* append tag to result */
3343 memcpy(result + result_len, tag, ccm->tag_len);
3344 *max_result_len = result_len + ccm->tag_len;
3345 ret = 1;
3346#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3347 C(mbedtls_cipher_auth_encrypt_ext(&ctx,
3348 ccm->nonce,
3349 15 - ccm->l, /* iv */
3350 laad.s,
3351 laad.length, /* ad */
3352 data->s,
3353 data->length, /* input */
3354 result,
3355 result_len,
3356 &result_len, /* output */
3357 ccm->tag_len /* tag */
3358 ));
3359 *max_result_len = result_len;
3360 ret = 1;
3361#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3362
3363error:
3364 mbedtls_cipher_free(&ctx);
3365 return ret;
3366}
3367
3368int
3370 coap_bin_const_t *data,
3371 coap_bin_const_t *aad,
3372 uint8_t *result,
3373 size_t *max_result_len) {
3374 mbedtls_cipher_context_t ctx;
3375 const coap_crypto_aes_ccm_t *ccm;
3376#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3377 const unsigned char *tag;
3378#endif /* MBEDTLS_VERSION_NUMBER < 0x02150000 */
3379 int ret = 0;
3380 size_t result_len = *max_result_len;
3381 coap_bin_const_t laad;
3382
3383 if (data == NULL)
3384 return 0;
3385
3386 assert(params != NULL);
3387
3388 if (!params) {
3389 return 0;
3390 }
3391
3392 ccm = &params->params.aes;
3393
3394 if (!setup_cipher_context(&ctx,
3395 params->alg,
3396 ccm->key.s,
3397 ccm->key.length,
3398 MBEDTLS_DECRYPT)) {
3399 return 0;
3400 }
3401
3402 if (data->length < ccm->tag_len) {
3403 coap_log_err("coap_decrypt: invalid tag length\n");
3404 goto error;
3405 }
3406
3407 if (aad) {
3408 laad = *aad;
3409 } else {
3410 laad.s = NULL;
3411 laad.length = 0;
3412 }
3413
3414#if (MBEDTLS_VERSION_NUMBER < 0x02150000)
3415 tag = data->s + data->length - ccm->tag_len;
3416 C(mbedtls_cipher_auth_decrypt(&ctx,
3417 ccm->nonce,
3418 15 - ccm->l, /* iv */
3419 laad.s,
3420 laad.length, /* ad */
3421 data->s,
3422 data->length - ccm->tag_len, /* input */
3423 result,
3424 &result_len, /* output */
3425 tag,
3426 ccm->tag_len /* tag */
3427 ));
3428#else /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3429 C(mbedtls_cipher_auth_decrypt_ext(&ctx,
3430 ccm->nonce,
3431 15 - ccm->l, /* iv */
3432 laad.s,
3433 laad.length, /* ad */
3434 data->s,
3435 // data->length - ccm->tag_len, /* input */
3436 data->length, /* input */
3437 result,
3438 result_len,
3439 &result_len, /* output */
3440 ccm->tag_len /* tag */
3441 ));
3442#endif /* MBEDTLS_VERSION_NUMBER >= 0x02150000 */
3443
3444 *max_result_len = result_len;
3445 ret = 1;
3446error:
3447 mbedtls_cipher_free(&ctx);
3448 return ret;
3449}
3450
3451int
3453 coap_bin_const_t *key,
3454 coap_bin_const_t *data,
3455 coap_bin_const_t **hmac) {
3456 mbedtls_md_context_t ctx;
3457 int ret = 0;
3458 const int use_hmac = 1;
3459 const mbedtls_md_info_t *md_info;
3460 mbedtls_md_type_t mac_algo;
3461 unsigned int len;
3462 coap_binary_t *dummy = NULL;
3463
3464 assert(key);
3465 assert(data);
3466 assert(hmac);
3467
3468 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3469 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3470 return 0;
3471 }
3472 md_info = mbedtls_md_info_from_type(mac_algo);
3473
3474 len = mbedtls_md_get_size(md_info);
3475 if (len == 0) {
3476 return 0;
3477 }
3478
3479 mbedtls_md_init(&ctx);
3480 C(mbedtls_md_setup(&ctx, md_info, use_hmac));
3481
3482 C(mbedtls_md_hmac_starts(&ctx, key->s, key->length));
3483 C(mbedtls_md_hmac_update(&ctx, (const unsigned char *)data->s, data->length));
3484 dummy = coap_new_binary(len);
3485 if (dummy == NULL)
3486 goto error;
3487 C(mbedtls_md_hmac_finish(&ctx, dummy->s));
3488
3489 *hmac = (coap_bin_const_t *)dummy;
3490 ret = 1;
3491error:
3492 mbedtls_md_free(&ctx);
3493 return ret;
3494}
3495
3496#endif /* COAP_OSCORE_SUPPORT */
3497
3498#else /* ! COAP_WITH_LIBMBEDTLS */
3499
3500#ifdef __clang__
3501/* Make compilers happy that do not like empty modules. As this function is
3502 * never used, we ignore -Wunused-function at the end of compiling this file
3503 */
3504#pragma GCC diagnostic ignored "-Wunused-function"
3505#endif
3506static inline void
3507dummy(void) {
3508}
3509
3510#endif /* ! COAP_WITH_LIBMBEDTLS */
#define COAP_SERVER_SUPPORT
#define PRIx32
const char * coap_socket_strerror(void)
Definition coap_io.c:847
#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:4963
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:2911
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 Note: coap_layers_coap[] needs updating if extended.
Definition coap_pdu.h:318
@ COAP_PROTO_DTLS
Definition coap_pdu.h:321
@ COAP_PROTO_TLS
Definition coap_pdu.h:323
@ COAP_PROTO_WSS
Definition coap_pdu.h:325
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