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