libcoap  4.3.1
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-2022 Jon Shallow <supjps-libcoap@jpshallow.com>
5  * 2019 Jitin George <jitin@espressif.com>
6  *
7  * SPDX-License-Identifier: BSD-2-Clause
8  *
9  * This file is part of the CoAP library libcoap. Please see README for terms
10  * of use.
11  */
12 
18 /*
19  * Naming used to prevent confusion between coap sessions, mbedtls sessions etc.
20  * when reading the code.
21  *
22  * c_context A coap_context_t *
23  * c_session A coap_session_t *
24  * m_context A coap_mbedtls_context_t * (held in c_context->dtls_context)
25  * m_env A coap_mbedtls_env_t * (held in c_session->tls)
26  */
27 
28 #include "coap3/coap_internal.h"
29 
30 #ifdef HAVE_MBEDTLS
31 
32 /*
33  * This code can be conditionally compiled to remove some components if
34  * they are not required to make a lighter footprint - all based on how
35  * the mbedtls library has been built. These are not defined within the
36  * libcoap environment.
37  *
38  * MBEDTLS_SSL_SRV_C - defined for server side functionality
39  * MBEDTLS_SSL_CLI_C - defined for client side functionality
40  * MBEDTLS_SSL_PROTO_DTLS - defined for DTLS support
41  * MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED - defined if PSK is to be supported
42  * or MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED - defined if PSK is to be supported
43  *
44  */
45 
46 #include <mbedtls/version.h>
47 
48 /* Keep forward-compatibility with Mbed TLS 3.x */
49 #if (MBEDTLS_VERSION_NUMBER < 0x03000000)
50 #define MBEDTLS_2_X_COMPAT
51 #else /* !(MBEDTLS_VERSION_NUMBER < 0x03000000) */
52 /* Macro wrapper for struct's private members */
53 #ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS
54 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
55 #endif /* MBEDTLS_ALLOW_PRIVATE_ACCESS */
56 #endif /* !(MBEDTLS_VERSION_NUMBER < 0x03000000) */
57 
58 #include <mbedtls/platform.h>
59 #include <mbedtls/net_sockets.h>
60 #include <mbedtls/ssl.h>
61 #include <mbedtls/entropy.h>
62 #include <mbedtls/ctr_drbg.h>
63 #include <mbedtls/error.h>
64 #include <mbedtls/timing.h>
65 #include <mbedtls/ssl_cookie.h>
66 #include <mbedtls/oid.h>
67 #include <mbedtls/debug.h>
68 #include <mbedtls/sha256.h>
69 #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
70 #include <mbedtls/esp_debug.h>
71 #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
72 #include <errno.h>
73 
74 #ifdef HAVE_INTTYPES_H
75 #include <inttypes.h>
76 #else /* ! HAVE_INTTYPES_H */
77 #define PRIx32 "x"
78 #endif /* ! HAVE_INTTYPES_H */
79 
80 #define mbedtls_malloc(a) malloc(a)
81 #define mbedtls_realloc(a,b) realloc(a,b)
82 #define mbedtls_strdup(a) strdup(a)
83 #define mbedtls_strndup(a,b) strndup(a,b)
84 
85 #ifndef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
86 /* definition changed in later mbedtls code versions */
87 #ifdef MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED
88 #define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
89 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
90 #endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
91 
92 #if ! COAP_SERVER_SUPPORT
93 #undef MBEDTLS_SSL_SRV_C
94 #endif /* ! COAP_SERVER_SUPPORT */
95 #if ! COAP_CLIENT_SUPPORT
96 #undef MBEDTLS_SSL_CLI_C
97 #endif /* ! COAP_CLIENT_SUPPORT */
98 
99 #ifdef _WIN32
100 #define strcasecmp _stricmp
101 #endif
102 
103 #define IS_PSK (1 << 0)
104 #define IS_PKI (1 << 1)
105 #define IS_CLIENT (1 << 6)
106 #define IS_SERVER (1 << 7)
107 
108 typedef struct coap_ssl_t {
109  const uint8_t *pdu;
110  unsigned pdu_len;
111  unsigned peekmode;
112 } coap_ssl_t;
113 
114 /*
115  * This structure encapsulates the Mbed TLS session object.
116  * It handles both TLS and DTLS.
117  * c_session->tls points to this.
118  */
119 typedef struct coap_mbedtls_env_t {
120  mbedtls_ssl_context ssl;
121  mbedtls_entropy_context entropy;
122  mbedtls_ctr_drbg_context ctr_drbg;
123  mbedtls_ssl_config conf;
124  mbedtls_timing_delay_context timer;
125  mbedtls_x509_crt cacert;
126  mbedtls_x509_crt public_cert;
127  mbedtls_pk_context private_key;
128  mbedtls_ssl_cookie_ctx cookie_ctx;
129  /* If not set, need to do do_mbedtls_handshake */
130  int established;
131  int sent_alert;
132  int seen_client_hello;
133  coap_tick_t last_timeout;
134  unsigned int retry_scalar;
135  coap_ssl_t coap_ssl_data;
136 } coap_mbedtls_env_t;
137 
138 typedef struct pki_sni_entry {
139  char *sni;
140  coap_dtls_key_t pki_key;
141  mbedtls_x509_crt cacert;
142  mbedtls_x509_crt public_cert;
143  mbedtls_pk_context private_key;
144 } pki_sni_entry;
145 
146 typedef struct psk_sni_entry {
147  char* sni;
148  coap_dtls_spsk_info_t psk_info;
149 } psk_sni_entry;
150 
151 typedef struct coap_mbedtls_context_t {
152  coap_dtls_pki_t setup_data;
153  size_t pki_sni_count;
154  pki_sni_entry *pki_sni_entry_list;
155  size_t psk_sni_count;
156  psk_sni_entry *psk_sni_entry_list;
157  char *root_ca_file;
158  char *root_ca_path;
159  int psk_pki_enabled;
160 } coap_mbedtls_context_t;
161 
162 typedef enum coap_enc_method_t {
163  COAP_ENC_PSK,
164  COAP_ENC_PKI,
165 } coap_enc_method_t;
166 
167 #ifndef MBEDTLS_2_X_COMPAT
168 /*
169  * mbedtls_ callback functions expect 0 on success, -ve on failure.
170  */
171 static int coap_rng(void *ctx COAP_UNUSED, unsigned char *buf, size_t len)
172 {
173  return coap_prng(buf, len) ? 0 : MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED;
174 }
175 #endif /* MBEDTLS_2_X_COMPAT */
176 
177 static int coap_dgram_read(void *ctx, unsigned char *out, size_t outl)
178 {
179  ssize_t ret = 0;
180  coap_session_t *c_session = (coap_session_t *)ctx;
181  coap_ssl_t *data;
182 
183  if (!c_session->tls) {
184  errno = EAGAIN;
185  return MBEDTLS_ERR_SSL_WANT_READ;
186  }
187  data = &((coap_mbedtls_env_t *)c_session->tls)->coap_ssl_data;
188 
189  if (out != NULL) {
190  if (data->pdu_len > 0) {
191  if (outl < data->pdu_len) {
192  memcpy(out, data->pdu, outl);
193  ret = outl;
194  data->pdu += outl;
195  data->pdu_len -= outl;
196  }
197  else {
198  memcpy(out, data->pdu, data->pdu_len);
199  ret = data->pdu_len;
200  if (!data->peekmode) {
201  data->pdu_len = 0;
202  data->pdu = NULL;
203  }
204  }
205  }
206  else {
207  ret = MBEDTLS_ERR_SSL_WANT_READ;
208  errno = EAGAIN;
209  }
210  }
211  return ret;
212 }
213 
214 /*
215  * return +ve data amount
216  * 0 no more
217  * -ve Mbed TLS error
218  */
219 /* callback function given to mbedtls for sending data over socket */
220 static int
221 coap_dgram_write(void *ctx, const unsigned char *send_buffer,
222  size_t send_buffer_length)
223 {
224  ssize_t result = -1;
225  coap_session_t *c_session = (coap_session_t *)ctx;
226 
227  if (c_session) {
228  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
229  result = coap_session_send(c_session, send_buffer, send_buffer_length);
230  if (result != (ssize_t)send_buffer_length) {
231  coap_log(LOG_WARNING, "coap_network_send failed (%zd != %zu)\n",
232  result, send_buffer_length);
233  result = 0;
234  }
235  else if (m_env) {
236  coap_tick_t now;
237  coap_ticks(&now);
238  m_env->last_timeout = now;
239  }
240  } else {
241  result = 0;
242  }
243  return result;
244 }
245 
246 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && defined(MBEDTLS_SSL_SRV_C)
247 /*
248  * Server side PSK callback
249  */
250 static int psk_server_callback(void *p_info, mbedtls_ssl_context *ssl,
251  const unsigned char *identity, size_t identity_len )
252 {
253  coap_session_t *c_session = (coap_session_t *)p_info;
254  coap_dtls_spsk_t *setup_data;
255  coap_mbedtls_env_t *m_env;
256  coap_bin_const_t lidentity;
257  const coap_bin_const_t *psk_key;
258 
259  if (c_session == NULL)
260  return -1;
261 
262  /* Track the Identity being used */
263  lidentity.s = identity ? (const uint8_t*)identity : (const uint8_t*)"";
264  lidentity.length = identity ? identity_len : 0;
265  coap_session_refresh_psk_identity(c_session, &lidentity);
266 
267  coap_log(LOG_DEBUG, "got psk_identity: '%.*s'\n",
268  (int)lidentity.length, (const char *)lidentity.s);
269 
270  m_env = (coap_mbedtls_env_t *)c_session->tls;
271  setup_data = &c_session->context->spsk_setup_data;
272 
273  if (setup_data->validate_id_call_back) {
274  psk_key = setup_data->validate_id_call_back(&lidentity,
275  c_session,
276  setup_data->id_call_back_arg);
277 
278  coap_session_refresh_psk_key(c_session, psk_key);
279  }
280  else {
281  psk_key = coap_get_session_server_psk_key(c_session);
282  }
283 
284  if (psk_key == NULL)
285  return -1;
286  mbedtls_ssl_set_hs_psk(ssl, psk_key->s, psk_key->length);
287  m_env->seen_client_hello = 1;
288  return 0;
289 }
290 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED && MBEDTLS_SSL_SRV_C */
291 
292 static char*
293 get_san_or_cn_from_cert(mbedtls_x509_crt *crt)
294 {
295  if (crt) {
296  const mbedtls_asn1_named_data * cn_data;
297 
298  if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
299  mbedtls_asn1_sequence *seq = &crt->subject_alt_names;
300  while (seq && seq->buf.p == NULL) {
301  seq = seq->next;
302  }
303  if (seq) {
304  /* Return the Subject Alt Name */
305  return mbedtls_strndup((const char *)seq->buf.p,
306  seq->buf.len);
307  }
308  }
309 
310  cn_data = mbedtls_asn1_find_named_data(&crt->subject,
311  MBEDTLS_OID_AT_CN,
312  MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN));
313  if (cn_data) {
314  /* Return the Common Name */
315  return mbedtls_strndup((const char *)cn_data->val.p,
316  cn_data->val.len);
317  }
318  }
319  return NULL;
320 }
321 
322 static char *
323 get_error_string(int ret) {
324  static char buf[128] = {0};
325  mbedtls_strerror(ret, buf, sizeof(buf)-1);
326  return buf;
327 }
328 
329 static int
330 self_signed_cert_verify_callback_mbedtls(void *data,
331  mbedtls_x509_crt *crt COAP_UNUSED,
332  int depth COAP_UNUSED,
333  uint32_t *flags)
334 {
335  const coap_session_t *c_session = (coap_session_t*)data;
336  const coap_mbedtls_context_t *m_context =
337  (coap_mbedtls_context_t *)c_session->context->dtls_context;
338  const coap_dtls_pki_t *setup_data = &m_context->setup_data;
339 
340  if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
341  if (setup_data->allow_expired_certs) {
342  *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
343  }
344  }
345  return 0;
346 }
347 
348 /*
349  * return 0 All OK
350  * -ve Error Code
351  */
352 static int
353 cert_verify_callback_mbedtls(void *data, mbedtls_x509_crt *crt,
354  int depth, uint32_t *flags)
355 {
356  coap_session_t *c_session = (coap_session_t*)data;
357  coap_mbedtls_context_t *m_context =
358  (coap_mbedtls_context_t *)c_session->context->dtls_context;
359  coap_dtls_pki_t *setup_data = &m_context->setup_data;
360  char *cn = NULL;
361 
362  if (*flags == 0)
363  return 0;
364 
365  cn = get_san_or_cn_from_cert(crt);
366 
367  if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
368  if (setup_data->allow_expired_certs) {
369  *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
371  " %s: %s: overridden: '%s' depth %d\n",
372  coap_session_str(c_session),
373  "The certificate has expired", cn ? cn : "?", depth);
374  }
375  }
376  if (*flags & MBEDTLS_X509_BADCERT_FUTURE) {
377  if (setup_data->allow_expired_certs) {
378  *flags &= ~MBEDTLS_X509_BADCERT_FUTURE;
380  " %s: %s: overridden: '%s' depth %d\n",
381  coap_session_str(c_session),
382  "The certificate has a future date", cn ? cn : "?", depth);
383  }
384  }
385  if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) {
386  if (setup_data->allow_bad_md_hash) {
387  *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD;
389  " %s: %s: overridden: '%s' depth %d\n",
390  coap_session_str(c_session),
391  "The certificate has a bad MD hash", cn ? cn : "?", depth);
392  }
393  }
394  if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) {
395  if (setup_data->allow_short_rsa_length) {
396  *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY;
398  " %s: %s: overridden: '%s' depth %d\n",
399  coap_session_str(c_session),
400  "The certificate has a short RSA length", cn ? cn : "?", depth);
401  }
402  }
403  if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
404  uint32_t lflags;
405  int self_signed = !mbedtls_x509_crt_verify(crt, crt, NULL, NULL, &lflags,
406  self_signed_cert_verify_callback_mbedtls,
407  data);
408  if (self_signed && depth == 0) {
409  if (setup_data->allow_self_signed &&
410  !setup_data->check_common_ca) {
411  *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
413  " %s: %s: overridden: '%s' depth %d\n",
414  coap_session_str(c_session),
415  "Self-signed",
416  cn ? cn : "?", depth);
417  }
418  }
419  else {
420  if (!setup_data->verify_peer_cert) {
421  *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
423  " %s: %s: overridden: '%s' depth %d\n",
424  coap_session_str(c_session),
425  "The certificate's CA does not match", cn ? cn : "?", depth);
426  }
427  }
428  }
429  if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) {
430  if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
431  *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
433  " %s: %s: overridden: '%s' depth %d\n",
434  coap_session_str(c_session),
435  "The certificate's CRL has expired", cn ? cn : "?", depth);
436  }
437  else if (!setup_data->check_cert_revocation) {
438  *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
439  }
440  }
441  if (*flags & MBEDTLS_X509_BADCRL_FUTURE) {
442  if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
443  *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
445  " %s: %s: overridden: '%s' depth %d\n",
446  coap_session_str(c_session),
447  "The certificate's CRL has a future date", cn ? cn : "?", depth);
448  }
449  else if (!setup_data->check_cert_revocation) {
450  *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
451  }
452  }
453  if (setup_data->cert_chain_validation &&
454  depth > (setup_data->cert_chain_verify_depth + 1)) {
455  *flags |= MBEDTLS_X509_BADCERT_OTHER;
457  " %s: %s: '%s' depth %d\n",
458  coap_session_str(c_session),
459  "The certificate's verify depth is too long",
460  cn ? cn : "?", depth);
461  }
462 
463  if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
464  *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
465  }
466  if (setup_data->validate_cn_call_back) {
467  if (!setup_data->validate_cn_call_back(cn,
468  crt->raw.p,
469  crt->raw.len,
470  c_session,
471  depth,
472  *flags == 0,
473  setup_data->cn_call_back_arg)) {
474  *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
475  }
476  }
477  if (*flags != 0) {
478  char buf[128];
479  char *tcp;
480  int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
481 
482  if (ret >= 0) {
483  tcp = strchr(buf, '\n');
484  while (tcp) {
485  *tcp = '\000';
487  " %s: %s: issue 0x%" PRIx32 ": '%s' depth %d\n",
488  coap_session_str(c_session),
489  buf, *flags, cn ? cn : "?", depth);
490  tcp = strchr(tcp+1, '\n');
491  }
492  }
493  else {
494  coap_log(LOG_ERR, "mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n",
495  -ret, get_error_string(ret));
496  }
497  }
498 
499  if (cn)
500  mbedtls_free(cn);
501 
502  return 0;
503 }
504 
505 static int
506 setup_pki_credentials(mbedtls_x509_crt *cacert,
507  mbedtls_x509_crt *public_cert,
508  mbedtls_pk_context *private_key,
509  coap_mbedtls_env_t *m_env,
510  coap_mbedtls_context_t *m_context,
511  coap_session_t *c_session,
512  coap_dtls_pki_t *setup_data,
513  coap_dtls_role_t role)
514 {
515  int ret;
516 
517  if (setup_data->is_rpk_not_cert) {
519  "RPK Support not available in Mbed TLS\n");
520  return -1;
521  }
522  switch (setup_data->pki_key.key_type) {
523  case COAP_PKI_KEY_PEM:
524  if (setup_data->pki_key.key.pem.public_cert &&
525  setup_data->pki_key.key.pem.public_cert[0] &&
526  setup_data->pki_key.key.pem.private_key &&
527  setup_data->pki_key.key.pem.private_key[0]) {
528 
529  mbedtls_x509_crt_init(public_cert);
530  mbedtls_pk_init(private_key);
531 
532  ret = mbedtls_x509_crt_parse_file(public_cert,
533  setup_data->pki_key.key.pem.public_cert);
534  if (ret < 0) {
535  coap_log(LOG_ERR, "mbedtls_x509_crt_parse_file returned -0x%x: '%s'\n",
536  -ret, get_error_string(ret));
537  return ret;
538  }
539 
540 #ifdef MBEDTLS_2_X_COMPAT
541  ret = mbedtls_pk_parse_keyfile(private_key,
542  setup_data->pki_key.key.pem.private_key, NULL);
543 #else
544  ret = mbedtls_pk_parse_keyfile(private_key,
545  setup_data->pki_key.key.pem.private_key,
546  NULL, coap_rng, (void *)&m_env->ctr_drbg);
547 #endif /* MBEDTLS_2_X_COMPAT */
548  if (ret < 0) {
549  coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n",
550  -ret, get_error_string(ret));
551  return ret;
552  }
553 
554  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
555  if (ret < 0) {
556  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
557  -ret, get_error_string(ret));
558  return ret;
559  }
560  }
561  else if (role == COAP_DTLS_ROLE_SERVER) {
563  "***setup_pki: (D)TLS: No Server Certificate + Private "
564  "Key defined\n");
565  return -1;
566  }
567 
568  if (setup_data->pki_key.key.pem.ca_file &&
569  setup_data->pki_key.key.pem.ca_file[0]) {
570  mbedtls_x509_crt_init(cacert);
571  ret = mbedtls_x509_crt_parse_file(cacert,
572  setup_data->pki_key.key.pem.ca_file);
573  if (ret < 0) {
574  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
575  -ret, get_error_string(ret));
576  return ret;
577  }
578  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
579  }
580  break;
582  if (setup_data->pki_key.key.pem_buf.public_cert &&
583  setup_data->pki_key.key.pem_buf.public_cert_len &&
584  setup_data->pki_key.key.pem_buf.private_key &&
585  setup_data->pki_key.key.pem_buf.private_key_len) {
586  uint8_t *buffer;
587  size_t length;
588 
589  mbedtls_x509_crt_init(public_cert);
590  mbedtls_pk_init(private_key);
591 
592  length = setup_data->pki_key.key.pem_buf.public_cert_len;
593  if (setup_data->pki_key.key.pem_buf.public_cert[length-1] != '\000') {
594  /* Need to allocate memory to add in NULL terminator */
595  buffer = mbedtls_malloc(length + 1);
596  if (!buffer) {
597  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
598  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
599  }
600  memcpy(buffer, setup_data->pki_key.key.pem_buf.public_cert, length);
601  buffer[length] = '\000';
602  length++;
603  ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
604  mbedtls_free(buffer);
605  }
606  else {
607  ret = mbedtls_x509_crt_parse(public_cert,
608  setup_data->pki_key.key.pem_buf.public_cert,
609  setup_data->pki_key.key.pem_buf.public_cert_len);
610  }
611  if (ret < 0) {
612  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
613  -ret, get_error_string(ret));
614  return ret;
615  }
616 
617  length = setup_data->pki_key.key.pem_buf.private_key_len;
618  if (setup_data->pki_key.key.pem_buf.private_key[length-1] != '\000') {
619  /* Need to allocate memory to add in NULL terminator */
620  buffer = mbedtls_malloc(length + 1);
621  if (!buffer) {
622  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
623  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
624  }
625  memcpy(buffer, setup_data->pki_key.key.pem_buf.private_key, length);
626  buffer[length] = '\000';
627  length++;
628 #ifdef MBEDTLS_2_X_COMPAT
629  ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
630 #else
631  ret = mbedtls_pk_parse_key(private_key, buffer, length,
632  NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
633 #endif /* MBEDTLS_2_X_COMPAT */
634  mbedtls_free(buffer);
635  }
636  else {
637 #ifdef MBEDTLS_2_X_COMPAT
638  ret = mbedtls_pk_parse_key(private_key,
639  setup_data->pki_key.key.pem_buf.private_key,
640  setup_data->pki_key.key.pem_buf.private_key_len, NULL, 0);
641 #else
642  ret = mbedtls_pk_parse_key(private_key,
643  setup_data->pki_key.key.pem_buf.private_key,
644  setup_data->pki_key.key.pem_buf.private_key_len,
645  NULL, 0, coap_rng, (void *)&m_env->ctr_drbg);
646 #endif /* MBEDTLS_2_X_COMPAT */
647  }
648  if (ret < 0) {
649  coap_log(LOG_ERR, "mbedtls_pk_parse_key returned -0x%x: '%s'\n",
650  -ret, get_error_string(ret));
651  return ret;
652  }
653 
654  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
655  if (ret < 0) {
656  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
657  -ret, get_error_string(ret));
658  return ret;
659  }
660  } else if (role == COAP_DTLS_ROLE_SERVER) {
662  "***setup_pki: (D)TLS: No Server Certificate + Private "
663  "Key defined\n");
664  return -1;
665  }
666 
667  if (setup_data->pki_key.key.pem_buf.ca_cert &&
668  setup_data->pki_key.key.pem_buf.ca_cert_len) {
669  uint8_t *buffer;
670  size_t length;
671 
672  mbedtls_x509_crt_init(cacert);
673  length = setup_data->pki_key.key.pem_buf.ca_cert_len;
674  if (setup_data->pki_key.key.pem_buf.ca_cert[length-1] != '\000') {
675  /* Need to allocate memory to add in NULL terminator */
676  buffer = mbedtls_malloc(length + 1);
677  if (!buffer) {
678  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
679  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
680  }
681  memcpy(buffer, setup_data->pki_key.key.pem_buf.ca_cert, length);
682  buffer[length] = '\000';
683  length++;
684  ret = mbedtls_x509_crt_parse(cacert, buffer, length);
685  mbedtls_free(buffer);
686  }
687  else {
688  ret = mbedtls_x509_crt_parse(cacert,
689  setup_data->pki_key.key.pem_buf.ca_cert,
690  setup_data->pki_key.key.pem_buf.ca_cert_len);
691  }
692  if (ret < 0) {
693  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
694  -ret, get_error_string(ret));
695  return ret;
696  }
697  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
698  }
699  break;
700  case COAP_PKI_KEY_ASN1:
701  if (setup_data->pki_key.key.asn1.public_cert &&
702  setup_data->pki_key.key.asn1.public_cert_len &&
703  setup_data->pki_key.key.asn1.private_key &&
704  setup_data->pki_key.key.asn1.private_key_len > 0) {
705 
706  mbedtls_x509_crt_init(public_cert);
707  mbedtls_pk_init(private_key);
708  ret = mbedtls_x509_crt_parse(public_cert,
709  (const unsigned char *)setup_data->pki_key.key.asn1.public_cert,
710  setup_data->pki_key.key.asn1.public_cert_len);
711  if (ret < 0) {
712  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
713  -ret, get_error_string(ret));
714  return ret;
715  }
716 
717 #ifdef MBEDTLS_2_X_COMPAT
718  ret = mbedtls_pk_parse_key(private_key,
719  (const unsigned char *)setup_data->pki_key.key.asn1.private_key,
720  setup_data->pki_key.key.asn1.private_key_len, NULL, 0);
721 #else
722  ret = mbedtls_pk_parse_key(private_key,
723  (const unsigned char *)setup_data->pki_key.key.asn1.private_key,
724  setup_data->pki_key.key.asn1.private_key_len, NULL, 0, coap_rng,
725  (void *)&m_env->ctr_drbg);
726 #endif /* MBEDTLS_2_X_COMPAT */
727  if (ret < 0) {
728  coap_log(LOG_ERR, "mbedtls_pk_parse_key returned -0x%x: '%s'\n",
729  -ret, get_error_string(ret));
730  return ret;
731  }
732 
733  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
734  if (ret < 0) {
735  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
736  -ret, get_error_string(ret));
737  return ret;
738  }
739  } else if (role == COAP_DTLS_ROLE_SERVER) {
741  "***setup_pki: (D)TLS: No Server Certificate + Private "
742  "Key defined\n");
743  return -1;
744  }
745 
746  if (setup_data->pki_key.key.asn1.ca_cert &&
747  setup_data->pki_key.key.asn1.ca_cert_len > 0) {
748  mbedtls_x509_crt_init(cacert);
749  ret = mbedtls_x509_crt_parse(cacert,
750  (const unsigned char *)setup_data->pki_key.key.asn1.ca_cert,
751  setup_data->pki_key.key.asn1.ca_cert_len);
752  if (ret < 0) {
753  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
754  -ret, get_error_string(ret));
755  return ret;
756  }
757  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
758  }
759  break;
760 
761  case COAP_PKI_KEY_PKCS11:
763  "***setup_pki: (D)TLS: PKCS11 not currently supported\n");
764  return -1;
765 
766  default:
768  "***setup_pki: (D)TLS: Unknown key type %d\n",
769  setup_data->pki_key.key_type);
770  return -1;
771  }
772 
773  if (m_context->root_ca_file) {
774  ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
775  if (ret < 0) {
776  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
777  -ret, get_error_string(ret));
778  return ret;
779  }
780  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
781  }
782  if (m_context->root_ca_path) {
783  ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_path);
784  if (ret < 0) {
785  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
786  -ret, get_error_string(ret));
787  return ret;
788  }
789  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
790  }
791 
792 #if defined(MBEDTLS_SSL_SRV_C)
793  mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
794  setup_data->check_common_ca ?
795  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
796  MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
797 #endif
798  mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
799  MBEDTLS_SSL_VERIFY_REQUIRED :
800  MBEDTLS_SSL_VERIFY_NONE);
801  /*
802  * Verify Peer.
803  * Need to do all checking, even if setup_data->verify_peer_cert is not set
804  */
805  mbedtls_ssl_conf_verify(&m_env->conf,
806  cert_verify_callback_mbedtls, c_session);
807 
808  return 0;
809 }
810 
811 #if defined(MBEDTLS_SSL_SRV_C)
812 /*
813  * PKI SNI callback.
814  */
815 static int
816 pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
817  const unsigned char *uname, size_t name_len)
818 {
819  unsigned int i;
820  coap_dtls_pki_t sni_setup_data;
821  coap_session_t *c_session = (coap_session_t *)p_info;
822  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
823  coap_mbedtls_context_t *m_context =
824  (coap_mbedtls_context_t *)c_session->context->dtls_context;
825  int ret = 0;
826  char *name;
827 
828  name = mbedtls_malloc(name_len+1);
829  if (!name)
830  return -1;
831 
832  memcpy(name, uname, name_len);
833  name[name_len] = '\000';
834 
835  /* Is this a cached entry? */
836  for (i = 0; i < m_context->pki_sni_count; i++) {
837  if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
838  break;
839  }
840  }
841  if (i == m_context->pki_sni_count) {
842  /*
843  * New PKI SNI request
844  */
845  coap_dtls_key_t *new_entry;
846  pki_sni_entry *pki_sni_entry_list;
847 
848  new_entry =
849  m_context->setup_data.validate_sni_call_back(name,
850  m_context->setup_data.sni_call_back_arg);
851  if (!new_entry) {
852  mbedtls_free(name);
853  return -1;
854  }
855 
856  pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
857  (i+1)*sizeof(pki_sni_entry));
858 
859  if (pki_sni_entry_list == NULL) {
860  mbedtls_free(name);
861  return -1;
862  }
863  m_context->pki_sni_entry_list = pki_sni_entry_list;
864  memset(&m_context->pki_sni_entry_list[i], 0,
865  sizeof(m_context->pki_sni_entry_list[i]));
866  m_context->pki_sni_entry_list[i].sni = name;
867  m_context->pki_sni_entry_list[i].pki_key = *new_entry;
868  sni_setup_data = m_context->setup_data;
869  sni_setup_data.pki_key = *new_entry;
870  if ((ret = setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
871  &m_context->pki_sni_entry_list[i].public_cert,
872  &m_context->pki_sni_entry_list[i].private_key,
873  m_env,
874  m_context,
875  c_session,
876  &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
877  mbedtls_free(name);
878  return -1;
879  }
880  /* name has been absorbed into pki_sni_entry_list[].sni entry */
881  m_context->pki_sni_count++;
882  }
883  else {
884  mbedtls_free(name);
885  }
886 
887  mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
888  NULL);
889  return mbedtls_ssl_set_hs_own_cert(ssl,
890  &m_context->pki_sni_entry_list[i].public_cert,
891  &m_context->pki_sni_entry_list[i].private_key);
892 }
893 
894 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
895 /*
896  * PSK SNI callback.
897  */
898 static int
899 psk_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
900  const unsigned char *uname, size_t name_len)
901 {
902  unsigned int i;
903  coap_session_t *c_session = (coap_session_t *)p_info;
904  coap_mbedtls_context_t *m_context =
905  (coap_mbedtls_context_t *)c_session->context->dtls_context;
906  char *name;
907 
908  name = mbedtls_malloc(name_len+1);
909  if (!name)
910  return -1;
911 
912  memcpy(name, uname, name_len);
913  name[name_len] = '\000';
914 
915  /* Is this a cached entry? */
916  for (i = 0; i < m_context->psk_sni_count; i++) {
917  if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
918  break;
919  }
920  }
921  if (i == m_context->psk_sni_count) {
922  /*
923  * New PSK SNI request
924  */
925  const coap_dtls_spsk_info_t *new_entry;
926  psk_sni_entry *psk_sni_entry_list;
927 
928  new_entry =
930  c_session,
932  if (!new_entry) {
933  mbedtls_free(name);
934  return -1;
935  }
936 
937  psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
938  (i+1)*sizeof(psk_sni_entry));
939 
940  if (psk_sni_entry_list == NULL) {
941  mbedtls_free(name);
942  return -1;
943  }
944  m_context->psk_sni_entry_list = psk_sni_entry_list;
945  m_context->psk_sni_entry_list[i].sni = name;
946  m_context->psk_sni_entry_list[i].psk_info = *new_entry;
947  /* name has been absorbed into psk_sni_entry_list[].sni entry */
948  m_context->psk_sni_count++;
949  }
950  else {
951  mbedtls_free(name);
952  }
953 
955  &m_context->psk_sni_entry_list[i].psk_info.hint);
957  &m_context->psk_sni_entry_list[i].psk_info.key);
958  return mbedtls_ssl_set_hs_psk(ssl,
959  m_context->psk_sni_entry_list[i].psk_info.key.s,
960  m_context->psk_sni_entry_list[i].psk_info.key.length);
961 }
962 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
963 
964 static int setup_server_ssl_session(coap_session_t *c_session,
965  coap_mbedtls_env_t *m_env)
966 {
967  coap_mbedtls_context_t *m_context =
968  (coap_mbedtls_context_t *)c_session->context->dtls_context;
969  int ret = 0;
970  m_context->psk_pki_enabled |= IS_SERVER;
971 
972  mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
973  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
974  MBEDTLS_SSL_IS_SERVER,
975  c_session->proto == COAP_PROTO_DTLS ?
976  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
977  MBEDTLS_SSL_TRANSPORT_STREAM,
978  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
979  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
980  -ret, get_error_string(ret));
981  goto fail;
982  }
983 
984  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
985 
986 #if defined(MBEDTLS_SSL_PROTO_DTLS)
987  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
988  COAP_DTLS_RETRANSMIT_TOTAL_MS);
989 #endif /* MBEDTLS_SSL_PROTO_DTLS */
990 
991  if (m_context->psk_pki_enabled & IS_PSK) {
992 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
993  mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
995  mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
996  }
997 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
998  coap_log(LOG_WARNING, "PSK not enabled in Mbed TLS library\n");
999 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1000  }
1001 
1002  if (m_context->psk_pki_enabled & IS_PKI) {
1003  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1004  &m_env->private_key, m_env, m_context,
1005  c_session, &m_context->setup_data,
1007  if (ret < 0) {
1008  coap_log(LOG_ERR, "PKI setup failed\n");
1009  return ret;
1010  }
1011  if (m_context->setup_data.validate_sni_call_back) {
1012  mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
1013  }
1014  }
1015 
1016  if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
1017  mbedtls_ctr_drbg_random,
1018  &m_env->ctr_drbg)) != 0) {
1019  coap_log(LOG_ERR, "mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
1020  -ret, get_error_string(ret));
1021  goto fail;
1022  }
1023 
1024 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1025  mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
1026  mbedtls_ssl_cookie_check,
1027  &m_env->cookie_ctx );
1028 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1029  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1030 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1031 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1032 fail:
1033  return ret;
1034 }
1035 #endif /* MBEDTLS_SSL_SRV_C */
1036 
1037 #if COAP_CLIENT_SUPPORT
1038 static int *psk_ciphers = NULL;
1039 static int *pki_ciphers = NULL;
1040 static int processed_ciphers = 0;
1041 
1042 static void
1043 set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method)
1044 {
1045  if (!processed_ciphers) {
1046  const int *list = mbedtls_ssl_list_ciphersuites();
1047  const int *base = list;
1048  int *psk_list;
1049  int *pki_list;
1050  int psk_count = 1; /* account for empty terminator */
1051  int pki_count = 1;
1052 
1053  while (*list) {
1054  const mbedtls_ssl_ciphersuite_t *cur =
1055  mbedtls_ssl_ciphersuite_from_id(*list);
1056 
1057 #if MBEDTLS_VERSION_NUMBER >= 0x03020000
1058  if (cur) {
1059  if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1060  /* Minimum of TLS1.2 required - skip */
1061  }
1062 #else
1063  if (cur) {
1064  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1065  /* Minimum of TLS1.2 required - skip */
1066  }
1067 #endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1068 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1069  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1070  psk_count++;
1071  }
1072 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1073  else {
1074  pki_count++;
1075  }
1076  }
1077  list++;
1078  }
1079  list = base;
1080 
1081  psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
1082  if (psk_ciphers == NULL) {
1083  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
1084  return;
1085  }
1086  pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
1087  if (pki_ciphers == NULL) {
1088  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
1089  mbedtls_free(psk_ciphers);
1090  psk_ciphers = NULL;
1091  return;
1092  }
1093 
1094  psk_list = psk_ciphers;
1095  pki_list = pki_ciphers;
1096 
1097  while (*list) {
1098  const mbedtls_ssl_ciphersuite_t *cur =
1099  mbedtls_ssl_ciphersuite_from_id(*list);
1100 #if MBEDTLS_VERSION_NUMBER >= 0x03020000
1101  if (cur) {
1102  if (cur->max_tls_version < MBEDTLS_SSL_VERSION_TLS1_2) {
1103  /* Minimum of TLS1.2 required - skip */
1104  }
1105 #else
1106  if (cur) {
1107  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1108  /* Minimum of TLS1.2 required - skip */
1109  }
1110 #endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1111 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1112  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1113  *psk_list = *list;
1114  psk_list++;
1115  }
1116 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1117  else {
1118  *pki_list = *list;
1119  pki_list++;
1120  }
1121  }
1122  list++;
1123  }
1124  /* zero terminate */
1125  *psk_list = 0;
1126  *pki_list = 0;
1127  processed_ciphers = 1;
1128  }
1129  mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers);
1130 }
1131 
1132 static int setup_client_ssl_session(coap_session_t *c_session,
1133  coap_mbedtls_env_t *m_env)
1134 {
1135  int ret;
1136 
1137  coap_mbedtls_context_t *m_context =
1138  (coap_mbedtls_context_t *)c_session->context->dtls_context;
1139 
1140  m_context->psk_pki_enabled |= IS_CLIENT;
1141 
1142  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1143  MBEDTLS_SSL_IS_CLIENT,
1144  c_session->proto == COAP_PROTO_DTLS ?
1145  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1146  MBEDTLS_SSL_TRANSPORT_STREAM,
1147  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1148  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1149  -ret, get_error_string(ret));
1150  goto fail;
1151  }
1152 
1153 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1154  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1155  COAP_DTLS_RETRANSMIT_TOTAL_MS);
1156 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1157 
1158  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1159  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1160 
1161  if (m_context->psk_pki_enabled & IS_PSK) {
1162 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1163  const coap_bin_const_t *psk_key;
1164  const coap_bin_const_t *psk_identity;
1165 
1166  coap_log(LOG_INFO, "Setting PSK key\n");
1167 
1168  psk_key = coap_get_session_client_psk_key(c_session);
1169  psk_identity = coap_get_session_client_psk_identity(c_session);
1170  if (psk_key == NULL || psk_identity == NULL) {
1171  ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1172  goto fail;
1173  }
1174 
1175  if ((ret = mbedtls_ssl_conf_psk(&m_env->conf, psk_key->s,
1176  psk_key->length, psk_identity->s,
1177  psk_identity->length)) != 0) {
1178  coap_log(LOG_ERR, "mbedtls_ssl_conf_psk returned -0x%x: '%s'\n",
1179  -ret, get_error_string(ret));
1180  goto fail;
1181  }
1182  if (c_session->cpsk_setup_data.client_sni) {
1183  if ((ret = mbedtls_ssl_set_hostname(&m_env->ssl,
1184  c_session->cpsk_setup_data.client_sni)) != 0) {
1185  coap_log(LOG_ERR, "mbedtls_ssl_set_hostname returned -0x%x: '%s'\n",
1186  -ret, get_error_string(ret));
1187  goto fail;
1188  }
1189  }
1190  /* Identity Hint currently not supported in Mbed TLS so code removed */
1191 
1192  set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1193 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1194  coap_log(LOG_WARNING, "PSK not enabled in Mbed TLS library\n");
1195 #endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1196  }
1197  else if ((m_context->psk_pki_enabled & IS_PKI) ||
1198  (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1199  /*
1200  * If neither PSK or PKI have been set up, use PKI basics.
1201  * This works providing COAP_PKI_KEY_PEM has a value of 0.
1202  */
1203  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1204  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1205  &m_env->private_key, m_env, m_context,
1206  c_session, &m_context->setup_data,
1208  if (ret < 0) {
1209  coap_log(LOG_ERR, "PKI setup failed\n");
1210  return ret;
1211  }
1212 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1213  if (c_session->proto == COAP_PROTO_TLS) {
1214  static const char *alpn_list[] = { "coap", NULL };
1215 
1216  ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1217  if (ret != 0) {
1218  coap_log(LOG_ERR, "ALPN setup failed %d)\n", ret);
1219  }
1220  }
1221 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1222  if (m_context->setup_data.client_sni) {
1223  mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1224  }
1225 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1226 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1227  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1228 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1229 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1230  set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1231  }
1232  return 0;
1233 
1234 fail:
1235  return ret;
1236 }
1237 #endif /* COAP_CLIENT_SUPPORT */
1238 
1239 static void mbedtls_cleanup(coap_mbedtls_env_t *m_env)
1240 {
1241  if (!m_env) {
1242  return;
1243  }
1244 
1245  mbedtls_x509_crt_free(&m_env->cacert);
1246  mbedtls_x509_crt_free(&m_env->public_cert);
1247  mbedtls_pk_free(&m_env->private_key);
1248  mbedtls_entropy_free(&m_env->entropy);
1249  mbedtls_ssl_config_free(&m_env->conf);
1250  mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1251  mbedtls_ssl_free(&m_env->ssl);
1252  mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1253 }
1254 
1255 static void
1256 coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1257  if (m_env) {
1258  if (!m_env->sent_alert)
1259  mbedtls_ssl_close_notify(&m_env->ssl);
1260  mbedtls_cleanup(m_env);
1261  mbedtls_free(m_env);
1262  }
1263 }
1264 
1265 static const char *
1266 report_mbedtls_alert(unsigned char alert) {
1267  switch (alert) {
1268  case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC: return ": Bad Record MAC";
1269  case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE: return ": Handshake failure";
1270  case MBEDTLS_SSL_ALERT_MSG_NO_CERT: return ": No Certificate provided";
1271  case MBEDTLS_SSL_ALERT_MSG_BAD_CERT: return ": Certificate is bad";
1272  case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA: return ": CA is unknown";
1273  case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED: return ": Access was denied";
1274  case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR: return ": Decrypt error";
1275  default: return "";
1276  }
1277 }
1278 
1279 /*
1280  * return -1 failure
1281  * 0 not completed
1282  * 1 established
1283  */
1284 static int do_mbedtls_handshake(coap_session_t *c_session,
1285  coap_mbedtls_env_t *m_env) {
1286  int ret;
1287  int alert;
1288 
1289  ret = mbedtls_ssl_handshake(&m_env->ssl);
1290  switch (ret) {
1291  case 0:
1292  m_env->established = 1;
1293  coap_log(LOG_DEBUG, "* %s: Mbed TLS established\n",
1294  coap_session_str(c_session));
1295  ret = 1;
1296  break;
1297  case MBEDTLS_ERR_SSL_WANT_READ:
1298  case MBEDTLS_ERR_SSL_WANT_WRITE:
1299  errno = EAGAIN;
1300  ret = 0;
1301  break;
1302  case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1303  coap_log(LOG_DEBUG, "hello verification requested\n");
1304  goto reset;
1305  case MBEDTLS_ERR_SSL_INVALID_MAC:
1306  goto fail;
1307  case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1308  alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1309  goto fail_alert;
1310 #ifdef MBEDTLS_2_X_COMPAT
1311  case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1312  case MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO:
1313  alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1314  goto fail_alert;
1315 #endif /* MBEDTLS_2_X_COMPAT */
1316  case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1317  goto fail;
1318  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1319  if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1320  coap_log(LOG_WARNING, "***%s: Alert '%d'%s\n",
1321  coap_session_str(c_session), m_env->ssl.in_msg[1],
1322  report_mbedtls_alert(m_env->ssl.in_msg[1]));
1323  /* Fall through */
1324  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1325  case MBEDTLS_ERR_SSL_CONN_EOF:
1326  case MBEDTLS_ERR_NET_CONN_RESET:
1327  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1328  ret = -1;
1329  break;
1330  default:
1332  "do_mbedtls_handshake: session establish "
1333  "returned -0x%x: '%s'\n",
1334  -ret, get_error_string(ret));
1335  ret = -1;
1336  break;
1337  }
1338  return ret;
1339 
1340 fail_alert:
1341  mbedtls_ssl_send_alert_message(&m_env->ssl,
1342  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1343  alert);
1344  m_env->sent_alert = 1;
1345 fail:
1346  c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1348  "do_mbedtls_handshake: session establish "
1349  "returned '%s'\n",
1350  get_error_string(ret));
1351 reset:
1352  mbedtls_ssl_session_reset(&m_env->ssl);
1353  return -1;
1354 }
1355 
1356 static void
1357 mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1358  const char *file, int line, const char *str) {
1359  int log_level;
1360  /*
1361  * 0 No debug
1362  * 1 Error
1363  * 2 State change
1364  * 3 Informational
1365  * 4 Verbose
1366  */
1367  switch (level) {
1368  case 4:
1369  case 3:
1370  case 2:
1371  log_level = COAP_LOG_CIPHERS;
1372  break;
1373  case 1:
1374  log_level = LOG_ERR;
1375  break;
1376  case 0:
1377  default:
1378  log_level = 0;
1379  break;
1380  }
1381  coap_log(log_level, "%s:%04d: %s", file, line, str);
1382 }
1383 
1384 #if !COAP_DISABLE_TCP
1385 /*
1386  * return +ve data amount
1387  * 0 no more
1388  * -ve Mbed TLS error
1389  */
1390 static int
1391 coap_sock_read(void *ctx, unsigned char *out, size_t outl) {
1392  ssize_t ret = MBEDTLS_ERR_SSL_CONN_EOF;
1393  coap_session_t *c_session = (coap_session_t *)ctx;
1394 
1395  if (out != NULL) {
1396 #ifdef _WIN32
1397  ret = recv(c_session->sock.fd, (char *)out, (int)outl, 0);
1398 #else
1399  ret = recv(c_session->sock.fd, out, outl, 0);
1400 #endif
1401  if (ret > 0) {
1402  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1403  coap_session_str(c_session), ret);
1404  } else if (ret < 0 && errno != EAGAIN) {
1405  coap_log(LOG_DEBUG, "* %s: failed to receive any bytes (%s)\n",
1406  coap_session_str(c_session), coap_socket_strerror());
1407  }
1408 
1409  if (ret == 0) {
1410  /* graceful shutdown */
1411  c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
1412  ret = MBEDTLS_ERR_SSL_CONN_EOF;
1413  }
1414  else if (ret == COAP_SOCKET_ERROR) {
1415 #ifdef _WIN32
1416  int lasterror = WSAGetLastError();
1417 
1418  if (lasterror == WSAEWOULDBLOCK) {
1419  ret = MBEDTLS_ERR_SSL_WANT_READ;
1420  }
1421  else if (lasterror == WSAECONNRESET) {
1422  ret = MBEDTLS_ERR_NET_CONN_RESET;
1423  }
1424 #else
1425  if (errno == EAGAIN) {
1426  ret = MBEDTLS_ERR_SSL_WANT_READ;
1427  }
1428  else if (errno == EPIPE || errno == ECONNRESET) {
1429  ret = MBEDTLS_ERR_NET_CONN_RESET;
1430  }
1431 #endif
1432  else {
1433  ret = MBEDTLS_ERR_NET_RECV_FAILED;
1434  }
1435  c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
1436  }
1437  else if (ret < (ssize_t)outl) {
1438  c_session->sock.flags &= ~COAP_SOCKET_CAN_READ;
1439  }
1440  }
1441  return (int)ret;
1442 }
1443 
1444 /*
1445  * return +ve data amount
1446  * 0 no more
1447  * -ve Mbed TLS error
1448  */
1449 static int
1450 coap_sock_write(void *context, const unsigned char *in, size_t inl) {
1451  int ret = 0;
1452  coap_session_t *c_session = (coap_session_t *)context;
1453 
1454  ret = (int)coap_socket_write(&c_session->sock, in, inl);
1455  if (ret > 0) {
1456  coap_log(LOG_DEBUG, "* %s: sent %d bytes\n",
1457  coap_session_str(c_session), ret);
1458  } else if (ret < 0) {
1459  if ((c_session->state == COAP_SESSION_STATE_CSM ||
1460  c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
1461  (errno == EPIPE || errno == ECONNRESET)) {
1462  /*
1463  * Need to handle a TCP timing window where an agent continues with
1464  * the sending of the next handshake or a CSM.
1465  * However, the peer does not like a certificate and so sends a
1466  * fatal alert and closes the TCP session.
1467  * The sending of the next handshake or CSM may get terminated because
1468  * of the closed TCP session, but there is still an outstanding alert
1469  * to be read in and reported on.
1470  * In this case, pretend that sending the info was fine so that the
1471  * alert can be read (which effectively is what happens with DTLS).
1472  */
1473  ret = inl;
1474  }
1475  else {
1476 #ifdef _WIN32
1477  int lasterror = WSAGetLastError();
1478 
1479  if (lasterror == WSAEWOULDBLOCK) {
1480  ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1481  }
1482  else if (lasterror == WSAECONNRESET) {
1483  ret = MBEDTLS_ERR_NET_CONN_RESET;
1484  }
1485 #else
1486  if (errno == EAGAIN || errno == EINTR) {
1487  ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1488  }
1489  else if (errno == EPIPE || errno == ECONNRESET) {
1490  ret = MBEDTLS_ERR_NET_CONN_RESET;
1491  }
1492 #endif
1493  else {
1494  ret = MBEDTLS_ERR_NET_SEND_FAILED;
1495  }
1496  coap_log(LOG_DEBUG, "* %s: failed to send %zd bytes (%s) state %d\n",
1497  coap_session_str(c_session), inl, coap_socket_strerror(),
1498  c_session->state);
1499  }
1500  }
1501  if (ret == 0) {
1502  errno = EAGAIN;
1503  ret = MBEDTLS_ERR_SSL_WANT_WRITE;
1504  }
1505  return ret;
1506 }
1507 #endif /* !COAP_DISABLE_TCP */
1508 
1509 static coap_mbedtls_env_t *coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1510  coap_dtls_role_t role,
1511  coap_proto_t proto)
1512 {
1513  int ret = 0;
1514  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1515 
1516  if (m_env)
1517  return m_env;
1518 
1519  m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1520  if (!m_env) {
1521  return NULL;
1522  }
1523  memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1524 
1525  mbedtls_ssl_init(&m_env->ssl);
1526  mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1527  mbedtls_ssl_config_init(&m_env->conf);
1528  mbedtls_entropy_init(&m_env->entropy);
1529 
1530 #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1531  mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1532 #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1533  if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1534  mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1535  coap_log(LOG_ERR, "mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1536  -ret, get_error_string(ret));
1537  goto fail;
1538  }
1539 
1540  if (role == COAP_DTLS_ROLE_CLIENT) {
1541 #if COAP_CLIENT_SUPPORT
1542  if (setup_client_ssl_session(c_session, m_env) != 0) {
1543  goto fail;
1544  }
1545 #else /* !COAP_CLIENT_SUPPORT */
1546  goto fail;
1547 #endif /* !COAP_CLIENT_SUPPORT */
1548  } else if (role == COAP_DTLS_ROLE_SERVER) {
1549 #if defined(MBEDTLS_SSL_SRV_C)
1550  if (setup_server_ssl_session(c_session, m_env) != 0) {
1551  goto fail;
1552  }
1553 #else /* ! MBEDTLS_SSL_SRV_C */
1554  goto fail;
1555 #endif /* ! MBEDTLS_SSL_SRV_C */
1556  } else {
1557  goto fail;
1558  }
1559 
1560 #if MBEDTLS_VERSION_NUMBER >= 0x03020000
1561  mbedtls_ssl_conf_min_tls_version(&m_env->conf, MBEDTLS_SSL_VERSION_TLS1_2);
1562 #else
1563  mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1564  MBEDTLS_SSL_MINOR_VERSION_3);
1565 #endif /* MBEDTLS_VERSION_NUMBER >= 0x03020000 */
1566 
1567  if ((ret = mbedtls_ssl_setup(&m_env->ssl, &m_env->conf)) != 0) {
1568  goto fail;
1569  }
1570  if (proto == COAP_PROTO_DTLS) {
1571  mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1572  coap_dgram_read, NULL);
1573  }
1574 #if !COAP_DISABLE_TCP
1575  else {
1576  assert(proto == COAP_PROTO_TLS);
1577  mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_sock_write,
1578  coap_sock_read, NULL);
1579  }
1580 #endif /* ! COAP_DISABLE_TCP */
1581  mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1582  mbedtls_timing_set_delay,
1583  mbedtls_timing_get_delay);
1584 
1585  mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1586  return m_env;
1587 
1588 fail:
1589  if (m_env) {
1590  mbedtls_free(m_env);
1591  }
1592  return NULL;
1593 }
1594 
1595 int coap_dtls_is_supported(void) {
1596 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1597  return 1;
1598 #else /* !MBEDTLS_SSL_PROTO_DTLS */
1599  static int reported = 0;
1600  if (!reported) {
1601  reported = 1;
1603  "libcoap not compiled for DTLS with Mbed TLS"
1604  " - update Mbed TLS to include DTLS\n");
1605  }
1606  return 0;
1607 #endif /* !MBEDTLS_SSL_PROTO_DTLS */
1608 }
1609 
1610 int coap_tls_is_supported(void)
1611 {
1612 #if !COAP_DISABLE_TCP
1613  return 1;
1614 #else /* COAP_DISABLE_TCP */
1615  return 0;
1616 #endif /* COAP_DISABLE_TCP */
1617 }
1618 
1619 void *coap_dtls_new_context(coap_context_t *c_context)
1620 {
1621  coap_mbedtls_context_t *m_context;
1622  (void)c_context;
1623 
1624  m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
1625  if (m_context) {
1626  memset(m_context, 0, sizeof(coap_mbedtls_context_t));
1627  }
1628  return m_context;
1629 }
1630 
1631 #if COAP_SERVER_SUPPORT
1632 /*
1633  * return 0 failed
1634  * 1 passed
1635  */
1636 int
1638  coap_dtls_spsk_t *setup_data
1639 ) {
1640  coap_mbedtls_context_t *m_context =
1641  ((coap_mbedtls_context_t *)c_context->dtls_context);
1642 
1643 #if !defined(MBEDTLS_SSL_SRV_C)
1644  coap_log(LOG_EMERG, "coap_context_set_spsk:"
1645  " libcoap not compiled for Server Mode for Mbed TLS"
1646  " - update Mbed TLS to include Server Mode\n");
1647  return 0;
1648 #endif /* !MBEDTLS_SSL_SRV_C */
1649  if (!m_context || !setup_data)
1650  return 0;
1651 
1652  m_context->psk_pki_enabled |= IS_PSK;
1653  return 1;
1654 }
1655 #endif /* COAP_SERVER_SUPPORT */
1656 
1657 #if COAP_CLIENT_SUPPORT
1658 /*
1659  * return 0 failed
1660  * 1 passed
1661  */
1662 int
1664  coap_dtls_cpsk_t *setup_data
1665 ) {
1666 #if !defined(MBEDTLS_SSL_CLI_C)
1667  coap_log(LOG_EMERG, "coap_context_set_cpsk:"
1668  " libcoap not compiled for Client Mode for Mbed TLS"
1669  " - update Mbed TLS to include Client Mode\n");
1670  return 0;
1671 #else /* MBEDTLS_SSL_CLI_C */
1672  coap_mbedtls_context_t *m_context =
1673  ((coap_mbedtls_context_t *)c_context->dtls_context);
1674 
1675  if (!m_context || !setup_data)
1676  return 0;
1677 
1678  if (setup_data->validate_ih_call_back) {
1680  "CoAP Client with Mbed TLS does not support Identity Hint selection\n");
1681  }
1682  m_context->psk_pki_enabled |= IS_PSK;
1683  return 1;
1684 #endif /* MBEDTLS_SSL_CLI_C */
1685 }
1686 #endif /* COAP_CLIENT_SUPPORT */
1687 
1689  const coap_dtls_pki_t *setup_data,
1690  const coap_dtls_role_t role COAP_UNUSED)
1691 {
1692  coap_mbedtls_context_t *m_context =
1693  ((coap_mbedtls_context_t *)c_context->dtls_context);
1694 
1695  m_context->setup_data = *setup_data;
1696  if (!m_context->setup_data.verify_peer_cert) {
1697  /* Needs to be clear so that no CA DNs are transmitted */
1698  m_context->setup_data.check_common_ca = 0;
1699  /* Allow all of these but warn if issue */
1700  m_context->setup_data.allow_self_signed = 1;
1701  m_context->setup_data.allow_expired_certs = 1;
1702  m_context->setup_data.cert_chain_validation = 1;
1703  m_context->setup_data.cert_chain_verify_depth = 10;
1704  m_context->setup_data.check_cert_revocation = 1;
1705  m_context->setup_data.allow_no_crl = 1;
1706  m_context->setup_data.allow_expired_crl = 1;
1707  m_context->setup_data.allow_bad_md_hash = 1;
1708  m_context->setup_data.allow_short_rsa_length = 1;
1709  }
1710  m_context->psk_pki_enabled |= IS_PKI;
1711  return 1;
1712 }
1713 
1715  const char *ca_file,
1716  const char *ca_path)
1717 {
1718  coap_mbedtls_context_t *m_context =
1719  ((coap_mbedtls_context_t *)c_context->dtls_context);
1720 
1721  if (!m_context) {
1723  "coap_context_set_pki_root_cas: (D)TLS environment "
1724  "not set up\n");
1725  return 0;
1726  }
1727 
1728  if (ca_file == NULL && ca_path == NULL) {
1730  "coap_context_set_pki_root_cas: ca_file and/or ca_path "
1731  "not defined\n");
1732  return 0;
1733  }
1734  if (m_context->root_ca_file) {
1735  mbedtls_free(m_context->root_ca_file);
1736  m_context->root_ca_file = NULL;
1737  }
1738 
1739  if (ca_file) {
1740  m_context->root_ca_file = mbedtls_strdup(ca_file);
1741  }
1742 
1743  if (m_context->root_ca_path) {
1744  mbedtls_free(m_context->root_ca_path);
1745  m_context->root_ca_path = NULL;
1746  }
1747 
1748  if (ca_path) {
1749  m_context->root_ca_path = mbedtls_strdup(ca_path);
1750  }
1751  return 1;
1752 }
1753 
1755 {
1756  coap_mbedtls_context_t *m_context =
1757  ((coap_mbedtls_context_t *)c_context->dtls_context);
1758  return m_context->psk_pki_enabled ? 1 : 0;
1759 }
1760 
1761 void coap_dtls_free_context(void *dtls_context)
1762 {
1763  coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
1764  unsigned int i;
1765 
1766  for (i = 0; i < m_context->pki_sni_count; i++) {
1767  mbedtls_free(m_context->pki_sni_entry_list[i].sni);
1768 
1769  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
1770 
1771  mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
1772 
1773  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
1774  }
1775  if (m_context->pki_sni_entry_list)
1776  mbedtls_free(m_context->pki_sni_entry_list);
1777 
1778  for (i = 0; i < m_context->psk_sni_count; i++) {
1779  mbedtls_free(m_context->psk_sni_entry_list[i].sni);
1780  }
1781  if (m_context->psk_sni_entry_list)
1782  mbedtls_free(m_context->psk_sni_entry_list);
1783 
1784  if (m_context->root_ca_path)
1785  mbedtls_free(m_context->root_ca_path);
1786  if (m_context->root_ca_file)
1787  mbedtls_free(m_context->root_ca_file);
1788 
1789  mbedtls_free(m_context);
1790 }
1791 
1792 #if COAP_CLIENT_SUPPORT
1794 {
1795 #if !defined(MBEDTLS_SSL_CLI_C)
1796  (void)c_session;
1797  coap_log(LOG_EMERG, "coap_dtls_new_client_session:"
1798  " libcoap not compiled for Client Mode for Mbed TLS"
1799  " - update Mbed TLS to include Client Mode\n");
1800  return NULL;
1801 #else /* MBEDTLS_SSL_CLI_C */
1802  coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
1804  COAP_PROTO_DTLS);
1805  int ret;
1806 
1807  if (m_env) {
1808  coap_tick_t now;
1809  coap_ticks(&now);
1810  m_env->last_timeout = now;
1811  ret = do_mbedtls_handshake(c_session, m_env);
1812  if (ret == -1) {
1813  coap_dtls_free_mbedtls_env(m_env);
1814  return NULL;
1815  }
1816  }
1817  return m_env;
1818 #endif /* MBEDTLS_SSL_CLI_C */
1819 }
1820 #endif /* COAP_CLIENT_SUPPORT */
1821 
1822 #if COAP_SERVER_SUPPORT
1824 {
1825 #if !defined(MBEDTLS_SSL_SRV_C)
1826  (void)c_session;
1827  coap_log(LOG_EMERG, "coap_dtls_new_server_session:"
1828  " libcoap not compiled for Server Mode for Mbed TLS"
1829  " - update Mbed TLS to include Server Mode\n");
1830  return NULL;
1831 #else /* MBEDTLS_SSL_SRV_C */
1832  coap_mbedtls_env_t *m_env =
1833  (coap_mbedtls_env_t *)c_session->tls;
1834  if (m_env) {
1835 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1836 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1837  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1838 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1839 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1840  }
1841  return m_env;
1842 #endif /* MBEDTLS_SSL_SRV_C */
1843 }
1844 #endif /* COAP_SERVER_SUPPORT */
1845 
1846 void coap_dtls_free_session(coap_session_t *c_session)
1847 {
1848  if (c_session && c_session->context && c_session->tls) {
1849  coap_dtls_free_mbedtls_env(c_session->tls);
1850  c_session->tls = NULL;
1851  coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session);
1852  }
1853  return;
1854 }
1855 
1857 {
1858 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1859  coap_mbedtls_env_t *m_env =
1860  (coap_mbedtls_env_t *)c_session->tls;
1861  if (m_env) {
1862 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1863  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1864 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1865  }
1866 #else /* ! MBEDTLS_SSL_PROTO_DTLS */
1867  (void)c_session;
1868 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1869 }
1870 
1871 int coap_dtls_send(coap_session_t *c_session,
1872  const uint8_t *data,
1873  size_t data_len)
1874 {
1875  int ret;
1876  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1877 
1878  assert(m_env != NULL);
1879 
1880  if (!m_env) {
1881  return -1;
1882  }
1883  c_session->dtls_event = -1;
1884  if (m_env->established) {
1885  ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char*) data, data_len);
1886  if (ret <= 0) {
1887  switch (ret) {
1888  case MBEDTLS_ERR_SSL_WANT_READ:
1889  case MBEDTLS_ERR_SSL_WANT_WRITE:
1890  ret = 0;
1891  break;
1892  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1893  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1894  ret = -1;
1895  break;
1896  default:
1898  "coap_dtls_send: "
1899  "returned -0x%x: '%s'\n",
1900  -ret, get_error_string(ret));
1901  ret = -1;
1902  break;
1903  }
1904  if (ret == -1) {
1905  coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n");
1906  }
1907  }
1908  } else {
1909  ret = do_mbedtls_handshake(c_session, m_env);
1910  if (ret == 1) {
1911  /* Just connected, so send the data */
1912  return coap_dtls_send(c_session, data, data_len);
1913  }
1914  ret = -1;
1915  }
1916 
1917  if (c_session->dtls_event >= 0) {
1918  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1919  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1920  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1921  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1922  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1924  ret = -1;
1925  }
1926  }
1927  return ret;
1928 }
1929 
1931 {
1932  return 0;
1933 }
1934 
1936 {
1937  return 0;
1938 }
1939 
1941 {
1942  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1943  int ret = mbedtls_timing_get_delay(&m_env->timer);
1944  unsigned int scalar = 1 << m_env->retry_scalar;
1945 
1946  assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1947  switch (ret) {
1948  case 0:
1949  /* int_ms has not timed out */
1950  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1951  /* Need to indicate remaining timeout time */
1952  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1953  }
1954  m_env->last_timeout = now;
1955  /* This may cause a minor extra delay */
1956  return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1957  case 1:
1958  /* int_ms has timed out, but not fin_ms */
1959  /*
1960  * Need to make sure that we do not do this too frequently
1961  */
1962  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1963  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1964  }
1965 
1966  /* Reset for the next time */
1967  m_env->last_timeout = now;
1968  return now;
1969  case 2:
1970  /* fin_ms has timed out - timed out - one final try */
1971  return now;
1972  default:
1973  break;
1974  }
1975 
1976  return 0;
1977 }
1978 
1979 /*
1980  * return 1 timed out
1981  * 0 still timing out
1982  */
1983 int
1985 {
1986  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1987 
1988  assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1989  m_env->retry_scalar++;
1990  if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
1991  (do_mbedtls_handshake(c_session, m_env) < 0)) {
1992  /* Too many retries */
1994  return 1;
1995  }
1996  return 0;
1997 }
1998 
1999 /*
2000  * return +ve data amount
2001  * 0 no more
2002  * -1 error
2003  */
2004 int coap_dtls_receive(coap_session_t *c_session,
2005  const uint8_t *data,
2006  size_t data_len)
2007 {
2008  int ret = 1;
2009 
2010  c_session->dtls_event = -1;
2011  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2012  coap_ssl_t *ssl_data;
2013 
2014  assert(m_env != NULL);
2015 
2016  ssl_data = &m_env->coap_ssl_data;
2017  if (ssl_data->pdu_len) {
2018  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
2019  coap_session_str(c_session), ssl_data->pdu_len);
2020  }
2021  ssl_data->pdu = data;
2022  ssl_data->pdu_len = (unsigned)data_len;
2023 
2024  if (m_env->established) {
2025 #if COAP_CONSTRAINED_STACK
2026  static coap_mutex_t b_static_mutex = COAP_MUTEX_INITIALIZER;
2027  static uint8_t pdu[COAP_RXBUFFER_SIZE];
2028 #else /* ! COAP_CONSTRAINED_STACK */
2029  uint8_t pdu[COAP_RXBUFFER_SIZE];
2030 #endif /* ! COAP_CONSTRAINED_STACK */
2031 
2032 #if COAP_CONSTRAINED_STACK
2033  coap_mutex_lock(&b_static_mutex);
2034 #endif /* COAP_CONSTRAINED_STACK */
2035 
2036  if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2038  c_session);
2039  coap_session_connected(c_session);
2040  }
2041 
2042  ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
2043  if (ret > 0) {
2044  ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2045 #if COAP_CONSTRAINED_STACK
2046  coap_mutex_unlock(&b_static_mutex);
2047 #endif /* COAP_CONSTRAINED_STACK */
2048  goto finish;
2049  }
2050  switch (ret) {
2051  case 0:
2052  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2053  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2054  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
2055  break;
2056  case MBEDTLS_ERR_SSL_WANT_READ:
2057  break;
2058  default:
2060  "coap_dtls_receive: "
2061  "returned -0x%x: '%s' (length %zd)\n",
2062  -ret, get_error_string(ret), data_len);
2063  break;
2064  }
2065 #if COAP_CONSTRAINED_STACK
2066  coap_mutex_unlock(&b_static_mutex);
2067 #endif /* COAP_CONSTRAINED_STACK */
2068  ret = -1;
2069  }
2070  else {
2071  ret = do_mbedtls_handshake(c_session, m_env);
2072  if (ret == 1) {
2073  /* Just connected, so send the data */
2074  coap_session_connected(c_session);
2075  } else {
2076  if (ssl_data->pdu_len) {
2077  /* Do the handshake again incase of internal timeout */
2078  ret = do_mbedtls_handshake(c_session, m_env);
2079  if (ret == 1) {
2080  /* Just connected, so send the data */
2081  coap_session_connected(c_session);
2082  } else {
2083  ret = -1;
2084  }
2085  }
2086  ret = -1;
2087  }
2088  }
2089  if (c_session->dtls_event >= 0) {
2090  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2091  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2092  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2093  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2094  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2096  ssl_data = NULL;
2097  ret = -1;
2098  }
2099  }
2100 finish:
2101  if (ssl_data && ssl_data->pdu_len) {
2102  /* pdu data is held on stack which will not stay there */
2103  coap_log(LOG_DEBUG, "coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2104  ssl_data->pdu_len = 0;
2105  ssl_data->pdu = NULL;
2106  }
2107  return ret;
2108 }
2109 
2110 #if COAP_SERVER_SUPPORT
2111 /*
2112  * return -1 failure
2113  * 0 not completed
2114  * 1 client hello seen
2115  */
2116 int coap_dtls_hello(coap_session_t *c_session,
2117  const uint8_t *data,
2118  size_t data_len)
2119 {
2120 #if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
2121  (void)c_session;
2122  (void)data;
2123  (void)data_len;
2124  coap_log(LOG_EMERG, "coap_dtls_hello:"
2125  " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
2126  " - update Mbed TLS to include DTLS and Server Mode\n");
2127  return -1;
2128 #else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2129  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2130  coap_ssl_t *ssl_data;
2131  int ret;
2132 
2133  if (!m_env) {
2134  m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER,
2135  COAP_PROTO_DTLS);
2136  if (m_env) {
2137  c_session->tls = m_env;
2138  }
2139  else {
2140  /* error should have already been reported */
2141  return -1;
2142  }
2143  }
2144 
2145  if((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
2146  (unsigned char *)&c_session->addr_info.remote,
2147  sizeof(c_session->addr_info.remote))) != 0) {
2148  coap_log(LOG_ERR,
2149  "mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
2150  -ret, get_error_string(ret));
2151  return -1;
2152  }
2153 
2154  ssl_data = &m_env->coap_ssl_data;
2155  if (ssl_data->pdu_len) {
2156  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
2157  coap_session_str(c_session), ssl_data->pdu_len);
2158  }
2159  ssl_data->pdu = data;
2160  ssl_data->pdu_len = (unsigned)data_len;
2161 
2162  ret = do_mbedtls_handshake(c_session, m_env);
2163  if (ret == 0 || m_env->seen_client_hello) {
2164  /* The test for seen_client_hello gives the ability to setup a new
2165  c_session to continue the do_mbedtls_handshake past the client hello
2166  and safely allow updating of the m_env and separately
2167  letting a new session cleanly start up.
2168  */
2169  m_env->seen_client_hello = 0;
2170  ret = 1;
2171  }
2172  else {
2173  ret = 0;
2174  }
2175 
2176  if (ssl_data->pdu_len) {
2177  /* pdu data is held on stack which will not stay there */
2178  coap_log(LOG_DEBUG, "coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2179  ssl_data->pdu_len = 0;
2180  ssl_data->pdu = NULL;
2181  }
2182  return ret;
2183 #endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
2184 }
2185 #endif /* COAP_SERVER_SUPPORT */
2186 
2187 unsigned int coap_dtls_get_overhead(coap_session_t *c_session)
2188 {
2189  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2190  int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
2191 
2192  if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
2193  return 13 + 8 + 8;
2194  }
2195  return expansion;
2196 }
2197 
2198 #if !COAP_DISABLE_TCP
2199 #if COAP_CLIENT_SUPPORT
2201  int *connected)
2202 {
2203 #if !defined(MBEDTLS_SSL_CLI_C)
2204  (void)c_session;
2205  *connected = 0;
2206  coap_log(LOG_EMERG, "coap_tls_new_client_session:"
2207  " libcoap not compiled for Client Mode for Mbed TLS"
2208  " - update Mbed TLS to include Client Mode\n");
2209  return NULL;
2210 #else /* MBEDTLS_SSL_CLI_C */
2211  coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2213  COAP_PROTO_TLS);
2214  int ret;
2215  coap_tick_t now;
2216  coap_ticks(&now);
2217 
2218  *connected = 0;
2219  if (!m_env)
2220  return NULL;
2221 
2222  m_env->last_timeout = now;
2223  c_session->tls = m_env;
2224  ret = do_mbedtls_handshake(c_session, m_env);
2225  if (ret == 1) {
2226  *connected = 1;
2227  coap_handle_event(c_session->context, COAP_EVENT_DTLS_CONNECTED, c_session);
2228  coap_session_send_csm(c_session);
2229  }
2230  return m_env;
2231 #endif /* MBEDTLS_SSL_CLI_C */
2232 }
2233 #endif /* COAP_CLIENT_SUPPORT */
2234 
2235 #if COAP_SERVER_SUPPORT
2237  int *connected COAP_UNUSED)
2238 {
2239 #if !defined(MBEDTLS_SSL_SRV_C)
2240  (void)c_session;
2241  coap_log(LOG_EMERG, "coap_tls_new_server_session:"
2242  " libcoap not compiled for Server Mode for Mbed TLS"
2243  " - update Mbed TLS to include Server Mode\n");
2244  return NULL;
2245 #else /* MBEDTLS_SSL_SRV_C */
2246  coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
2248  COAP_PROTO_TLS);
2249  int ret;
2250 
2251  c_session->tls = m_env;
2252  ret = do_mbedtls_handshake(c_session, m_env);
2253  if (ret == 1) {
2254  *connected = 1;
2255  }
2256  return m_env;
2257 #endif /* MBEDTLS_SSL_SRV_C */
2258 }
2259 #endif /* COAP_SERVER_SUPPORT */
2260 
2261 void coap_tls_free_session(coap_session_t *c_session)
2262 {
2263  coap_dtls_free_session(c_session);
2264  return;
2265 }
2266 
2267 /*
2268  * return +ve data amount
2269  * 0 no more
2270  * -1 error (error in errno)
2271  */
2272 ssize_t coap_tls_write(coap_session_t *c_session,
2273  const uint8_t *data,
2274  size_t data_len
2275  )
2276 {
2277  int ret;
2278  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2279 
2280  assert(m_env != NULL);
2281 
2282  if (!m_env) {
2283  return -1;
2284  }
2285  c_session->dtls_event = -1;
2286  if (m_env->established) {
2287  ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char*) data, data_len);
2288  if (ret <= 0) {
2289  switch (ret) {
2290  case MBEDTLS_ERR_SSL_WANT_READ:
2291  case MBEDTLS_ERR_SSL_WANT_WRITE:
2292  ret = 0;
2293  break;
2294  case MBEDTLS_ERR_NET_CONN_RESET:
2295  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2296  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
2297  ret = -1;
2298  break;
2299  default:
2301  "coap_tls_write: "
2302  "returned -0x%x: '%s'\n",
2303  -ret, get_error_string(ret));
2304  ret = -1;
2305  break;
2306  }
2307  if (ret == -1) {
2308  coap_log(LOG_WARNING, "coap_tls_write: cannot send PDU\n");
2309  }
2310  }
2311  } else {
2312  ret = do_mbedtls_handshake(c_session, m_env);
2313  if (ret == 1) {
2315  c_session);
2316  coap_session_send_csm(c_session);
2317  }
2318  else {
2319  ret = -1;
2320  }
2321  }
2322 
2323  if (c_session->dtls_event >= 0) {
2324  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2325  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2326  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2327  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2328  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2330  ret = -1;
2331  }
2332  }
2333  return ret;
2334 }
2335 
2336 /*
2337  * return +ve data amount
2338  * 0 no more
2339  * -1 error (error in errno)
2340  */
2341 ssize_t coap_tls_read(coap_session_t *c_session,
2342  uint8_t *data,
2343  size_t data_len
2344  )
2345 {
2346  int ret = -1;
2347 
2348  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
2349 
2350  if (!m_env)
2351  return -1;
2352 
2353  c_session->dtls_event = -1;
2354 
2355  if (!m_env->established && !m_env->sent_alert) {
2356  ret = do_mbedtls_handshake(c_session, m_env);
2357  if (ret == 1) {
2359  c_session);
2360  coap_session_send_csm(c_session);
2361  }
2362  }
2363 
2364  if (c_session->state != COAP_SESSION_STATE_NONE && m_env->established) {
2365  ret = mbedtls_ssl_read(&m_env->ssl, data, data_len);
2366  if (ret <= 0) {
2367  switch (ret) {
2368  case 0:
2369  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
2370  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
2371  ret = -1;
2372  break;
2373  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
2374  /* Stop the sending of an alert on closedown */
2375  m_env->sent_alert = 1;
2376  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
2377  ret = -1;
2378  break;
2379  case MBEDTLS_ERR_SSL_WANT_READ:
2380  errno = EAGAIN;
2381  ret = 0;
2382  break;
2383  default:
2385  "coap_tls_read: "
2386  "returned -0x%x: '%s' (length %zd)\n",
2387  -ret, get_error_string(ret), data_len);
2388  ret = -1;
2389  break;
2390  }
2391  }
2392  }
2393 
2394  if (c_session->dtls_event >= 0) {
2395  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
2396  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2397  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
2398  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2399  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2401  ret = -1;
2402  }
2403  }
2404  return ret;
2405 }
2406 #endif /* !COAP_DISABLE_TCP */
2407 
2408 void coap_dtls_startup(void)
2409 {
2410 }
2411 
2412 void coap_dtls_shutdown(void) {
2413 #if COAP_CLIENT_SUPPORT
2414  mbedtls_free(psk_ciphers);
2415  mbedtls_free(pki_ciphers);
2416  psk_ciphers = NULL;
2417  pki_ciphers = NULL;
2418  processed_ciphers = 0;
2419 #endif /* COAP_CLIENT_SUPPORT */
2420 }
2421 
2422 void *
2423 coap_dtls_get_tls(const coap_session_t *c_session,
2424  coap_tls_library_t *tls_lib) {
2425  if (tls_lib)
2426  *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
2427  if (c_session && c_session->tls) {
2428  coap_mbedtls_env_t *m_env;
2429 
2430  /* To get around const issue */
2431  memcpy(&m_env, &c_session->tls, sizeof(m_env));
2432 
2433  return (void *)&m_env->ssl;
2434  }
2435  return NULL;
2436 }
2437 
2438 static int keep_log_level = 0;
2439 
2440 void coap_dtls_set_log_level(int level)
2441 {
2442 #if !defined(ESPIDF_VERSION)
2443  int use_level;
2444  /*
2445  * Mbed TLS debug levels filter
2446  * 0 No debug
2447  * 1 Error
2448  * 2 State change
2449  * 3 Informational
2450  * 4 Verbose
2451  */
2452 
2453  if (level <= LOG_ERR) {
2454  use_level = 1;
2455  }
2456  else {
2457  use_level = (level >= LOG_DEBUG) ? level - LOG_DEBUG + 2 : 0;
2458  }
2459  mbedtls_debug_set_threshold(use_level);
2460 #endif /* !ESPIDF_VERSION) */
2461  keep_log_level = level;
2462 }
2463 
2464 int coap_dtls_get_log_level(void)
2465 {
2466  return keep_log_level;
2467 }
2468 
2470 {
2471  static coap_tls_version_t version;
2472  version.version = mbedtls_version_get_number();
2473  version.built_version = MBEDTLS_VERSION_NUMBER;
2474  version.type = COAP_TLS_LIBRARY_MBEDTLS;
2475  return &version;
2476 }
2477 
2478 #if COAP_SERVER_SUPPORT
2480 coap_digest_setup(void) {
2481  mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
2482 
2483  if (digest_ctx) {
2484  mbedtls_sha256_init(digest_ctx);
2485 #ifdef MBEDTLS_2_X_COMPAT
2486  if (mbedtls_sha256_starts_ret(digest_ctx, 0) != 0) {
2487 #else
2488  if (mbedtls_sha256_starts(digest_ctx, 0) != 0) {
2489 #endif /* MBEDTLS_2_X_COMPAT */
2490  return NULL;
2491  }
2492  }
2493  return digest_ctx;
2494 }
2495 
2496 void
2497 coap_digest_free(coap_digest_ctx_t *digest_ctx) {
2498  mbedtls_sha256_free(digest_ctx);
2499  mbedtls_free(digest_ctx);
2500 }
2501 
2502 int
2504  const uint8_t *data,
2505  size_t data_len) {
2506 #ifdef MBEDTLS_2_X_COMPAT
2507  int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
2508 #else
2509  int ret = mbedtls_sha256_update(digest_ctx, data, data_len);
2510 #endif /* MBEDTLS_2_X_COMPAT */
2511 
2512  return ret == 0;
2513 }
2514 
2515 int
2517  coap_digest_t *digest_buffer) {
2518 #ifdef MBEDTLS_2_X_COMPAT
2519  int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t*)digest_buffer);
2520 #else
2521  int ret = mbedtls_sha256_finish(digest_ctx, (uint8_t*)digest_buffer);
2522 #endif /* MBEDTLS_2_X_COMPAT */
2523 
2524  coap_digest_free(digest_ctx);
2525  return ret == 0;
2526 }
2527 #endif /* COAP_SERVER_SUPPORT */
2528 
2529 #else /* !HAVE_MBEDTLS */
2530 
2531 #ifdef __clang__
2532 /* Make compilers happy that do not like empty modules. As this function is
2533  * never used, we ignore -Wunused-function at the end of compiling this file
2534  */
2535 #pragma GCC diagnostic ignored "-Wunused-function"
2536 #endif
2537 static inline void dummy(void) {
2538 }
2539 
2540 #endif /* HAVE_MBEDTLS */
Pulls together all the internal only header files.
ssize_t coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len)
Definition: coap_io.c:483
const char * coap_socket_strerror(void)
Definition: coap_io.c:1604
#define COAP_RXBUFFER_SIZE
Definition: coap_io.h:29
#define COAP_SOCKET_ERROR
Definition: coap_io.h:49
@ COAP_NACK_TLS_FAILED
Definition: coap_io.h:73
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
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:41
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition: coap_notls.c:150
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition: coap_notls.c:107
int 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:134
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:207
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition: coap_notls.c:145
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:164
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:181
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition: coap_notls.c:75
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:200
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:130
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:49
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:159
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition: coap_notls.c:112
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:127
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition: coap_notls.c:86
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:197
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
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
void coap_ticks(coap_tick_t *t)
Sets t to the internal time with COAP_TICKS_PER_SECOND resolution.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition: coap_time.h:127
int coap_prng(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition: coap_prng.c:105
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: net.c:2040
int coap_handle_event(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: net.c:3352
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *session)
Get the current client's PSK identity.
Definition: net.c:318
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_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:82
void * coap_tls_new_client_session(coap_session_t *coap_session, int *connected)
Create a new TLS client-side session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition: coap_notls.c:141
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:93
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
void * coap_dtls_new_client_session(coap_session_t *coap_session)
Create a new client-side session.
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
void * coap_tls_new_server_session(coap_session_t *coap_session, int *connected)
Create a TLS new server-side session.
void * coap_dtls_new_server_session(coap_session_t *coap_session)
Create a new DTLS server-side session.
coap_dtls_role_t
Definition: coap_dtls.h:43
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition: coap_notls.c:28
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:33
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition: coap_notls.c:23
coap_tls_library_t
Definition: coap_dtls.h:64
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:45
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition: coap_dtls.h:44
@ COAP_PKI_KEY_PKCS11
The PKI key type is PKCS11 (DER)
Definition: coap_dtls.h:164
@ COAP_PKI_KEY_PEM_BUF
The PKI key type is PEM buffer.
Definition: coap_dtls.h:163
@ COAP_PKI_KEY_PEM
The PKI key type is PEM file.
Definition: coap_dtls.h:161
@ COAP_PKI_KEY_ASN1
The PKI key type is ASN.1 (DER) buffer.
Definition: coap_dtls.h:162
@ COAP_TLS_LIBRARY_MBEDTLS
Using Mbed TLS library.
Definition: coap_dtls.h:69
@ 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
void coap_dtls_set_log_level(int level)
Sets the (D)TLS logging level to the specified level.
Definition: coap_notls.c:97
#define LOG_EMERG
Definition: coap_debug.h:60
#define LOG_DEBUG
Definition: coap_debug.h:81
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define LOG_ERR
Definition: coap_debug.h:69
#define COAP_LOG_CIPHERS
Definition: coap_debug.h:87
int coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition: coap_notls.c:102
#define LOG_WARNING
Definition: coap_debug.h:72
#define LOG_INFO
Definition: coap_debug.h:78
#define coap_log(level,...)
Logging function.
Definition: coap_debug.h:165
coap_proto_t
CoAP protocol types.
Definition: pdu.h:292
@ COAP_PROTO_DTLS
Definition: pdu.h:295
@ COAP_PROTO_TLS
Definition: pdu.h:297
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).
void coap_session_send_csm(coap_session_t *session)
Notify session transport has just connected and CSM exchange can now start.
Definition: coap_session.c:479
ssize_t coap_session_send(coap_session_t *session, const uint8_t *data, size_t datalen)
Function interface for datagram data transmission.
Definition: coap_session.c:401
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.
Definition: coap_session.c:534
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(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:593
@ COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:56
@ COAP_SESSION_STATE_CSM
Definition: coap_session.h:57
@ COAP_SESSION_STATE_NONE
Definition: coap_session.h:54
#define COAP_UNUSED
Definition: libcoap.h:60
coap_address_t remote
remote address and port
Definition: coap_io.h:56
CoAP binary data definition with const data.
Definition: str.h:64
size_t length
length of binary data
Definition: str.h:65
const uint8_t * s
read-only binary data
Definition: str.h:66
The CoAP stack's global state is stored in a coap_context_t object.
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
The structure used for defining the Client PSK setup data to be used.
Definition: coap_dtls.h:350
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition: coap_dtls.h:374
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition: coap_dtls.h:370
The structure that holds the PKI key information.
Definition: coap_dtls.h:224
coap_pki_key_pem_t pem
for PEM file keys
Definition: coap_dtls.h:227
union coap_dtls_key_t::@2 key
coap_pki_key_pem_buf_t pem_buf
for PEM memory keys
Definition: coap_dtls.h:228
coap_pki_key_t key_type
key format type
Definition: coap_dtls.h:225
coap_pki_key_asn1_t asn1
for ASN.1 (DER) memory keys
Definition: coap_dtls.h:229
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:256
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition: coap_dtls.h:261
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition: coap_dtls.h:274
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:262
coap_dtls_key_t pki_key
PKI key definition.
Definition: coap_dtls.h:313
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:386
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:437
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition: coap_dtls.h:464
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition: coap_dtls.h:456
void * id_call_back_arg
Passed in to the Identity callback function.
Definition: coap_dtls.h:457
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition: coap_dtls.h:465
const uint8_t * private_key
ASN1 (DER) Private Key.
Definition: coap_dtls.h:202
size_t public_cert_len
ASN1 Public Cert length.
Definition: coap_dtls.h:204
size_t private_key_len
ASN1 Private Key length.
Definition: coap_dtls.h:205
const uint8_t * ca_cert
ASN1 (DER) Common CA Cert.
Definition: coap_dtls.h:200
size_t ca_cert_len
ASN1 CA Cert length.
Definition: coap_dtls.h:203
const uint8_t * public_cert
ASN1 (DER) Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:201
size_t ca_cert_len
PEM buffer CA Cert length.
Definition: coap_dtls.h:191
const uint8_t * ca_cert
PEM buffer Common CA Cert.
Definition: coap_dtls.h:186
size_t private_key_len
PEM buffer Private Key length.
Definition: coap_dtls.h:193
const uint8_t * private_key
PEM buffer Private Key If RPK and 'EC PRIVATE KEY' this can be used for both the public_cert and priv...
Definition: coap_dtls.h:188
size_t public_cert_len
PEM buffer Public Cert length.
Definition: coap_dtls.h:192
const uint8_t * public_cert
PEM buffer Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:187
const char * ca_file
File location of Common CA in PEM format.
Definition: coap_dtls.h:171
const char * public_cert
File location of Public Cert.
Definition: coap_dtls.h:172
const char * private_key
File location of Private Key in PEM format.
Definition: coap_dtls.h:173
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_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationaship with peer
coap_addr_tuple_t addr_info
key: remote/local address info
coap_proto_t proto
protocol used
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
int dtls_event
Tracking any (D)TLS events on this sesison.
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
coap_context_t * context
session's context
coap_socket_flags_t flags
The structure used for returning the underlying (D)TLS library information.
Definition: coap_dtls.h:76
uint64_t built_version
(D)TLS Built against Library Version
Definition: coap_dtls.h:79
coap_tls_library_t type
Library type.
Definition: coap_dtls.h:78
uint64_t version
(D)TLS runtime Library Version
Definition: coap_dtls.h:77