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