libcoap  4.3.0beta
coap_mbedtls.c
Go to the documentation of this file.
1 /*
2 * coap_mbedtls.c -- mbedTLS Datagram Transport Layer Support for libcoap
3 *
4 * Copyright (C) 2019-2021 Jon Shallow <supjps-libcoap@jpshallow.com>
5 * 2019 Jitin George <jitin@espressif.com>
6 *
7 * This file is part of the CoAP library libcoap. Please see README for terms
8 * of use.
9 */
10 
11 /*
12  * Naming used to prevent confusion between coap sessions, mbedtls sessions etc.
13  * when reading the code.
14  *
15  * c_context A coap_context_t *
16  * c_session A coap_session_t *
17  * m_context A coap_mbedtls_context_t * (held in c_context->dtls_context)
18  * m_env A coap_mbedtls_env_t * (held in c_session->tls)
19  */
20 
21 #include "coap_internal.h"
22 
23 #ifdef HAVE_MBEDTLS
24 
25 /*
26  * This code can be conditionally compiled to remove some components if
27  * they are not required to make a lighter footprint - all based on how
28  * the mbedtls library has been built. These are not defined within the
29  * libcoap environment.
30  *
31  * MBEDTLS_SSL_SRV_C - defined for server side functionality
32  * MBEDTLS_SSL_CLI_C - defined for client side functionality
33  * MBEDTLS_SSL_PROTO_DTLS - defined for DTLS support
34  * MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED - defined if PSK is to be supported
35  * or MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED - defined if PSK is to be supported
36  *
37  * Note: TLS is not currently supported until additional code is added
38  */
39 
40 #include <mbedtls/version.h>
41 #include <mbedtls/platform.h>
42 #include <mbedtls/net_sockets.h>
43 #include <mbedtls/ssl.h>
44 #include <mbedtls/entropy.h>
45 #include <mbedtls/ctr_drbg.h>
46 #include <mbedtls/error.h>
47 #include <mbedtls/certs.h>
48 #include <mbedtls/timing.h>
49 #include <mbedtls/ssl_cookie.h>
50 #include <mbedtls/oid.h>
51 #include <mbedtls/debug.h>
52 #include <mbedtls/sha256.h>
53 #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
54 #include <mbedtls/esp_debug.h>
55 #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
56 #include <errno.h>
57 
58 #define mbedtls_malloc(a) malloc(a)
59 #define mbedtls_realloc(a,b) realloc(a,b)
60 #define mbedtls_strdup(a) strdup(a)
61 #define mbedtls_strndup(a,b) strndup(a,b)
62 
63 #ifndef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
64 /* definition changed in later mbedtls code versions */
65 #ifdef MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED
66 #define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
67 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
68 #endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
69 
70 #ifdef __GNUC__
71 #define UNUSED __attribute__((unused))
72 #else /* __GNUC__ */
73 #define UNUSED
74 #endif /* __GNUC__ */
75 
76 #ifdef _WIN32
77 #define strcasecmp _stricmp
78 #endif
79 
80 #define IS_PSK (1 << 0)
81 #define IS_PKI (1 << 1)
82 #define IS_CLIENT (1 << 6)
83 #define IS_SERVER (1 << 7)
84 
85 typedef struct coap_ssl_t {
86  const uint8_t *pdu;
87  unsigned pdu_len;
88  unsigned peekmode;
89 } coap_ssl_t;
90 
91 /*
92  * This structure encapsulates the mbedTLS session object.
93  * It handles both TLS and DTLS.
94  * c_session->tls points to this.
95  */
96 typedef struct coap_mbedtls_env_t {
97  mbedtls_ssl_context ssl;
98  mbedtls_entropy_context entropy;
99  mbedtls_ctr_drbg_context ctr_drbg;
100  mbedtls_ssl_config conf;
101  mbedtls_timing_delay_context timer;
102  mbedtls_x509_crt cacert;
103  mbedtls_x509_crt public_cert;
104  mbedtls_pk_context private_key;
105  mbedtls_ssl_cookie_ctx cookie_ctx;
106  /* If not set, need to do do_mbedtls_handshake */
107  int established;
108  int seen_client_hello;
109  coap_tick_t last_timeout;
110  unsigned int retry_scalar;
111  coap_ssl_t coap_ssl_data;
112 } coap_mbedtls_env_t;
113 
114 typedef struct pki_sni_entry {
115  char *sni;
116  coap_dtls_key_t pki_key;
117  mbedtls_x509_crt cacert;
118  mbedtls_x509_crt public_cert;
119  mbedtls_pk_context private_key;
120 } pki_sni_entry;
121 
122 typedef struct psk_sni_entry {
123  char* sni;
124  coap_dtls_spsk_info_t psk_info;
125 } psk_sni_entry;
126 
127 typedef struct coap_mbedtls_context_t {
128  coap_dtls_pki_t setup_data;
129  size_t pki_sni_count;
130  pki_sni_entry *pki_sni_entry_list;
131  size_t psk_sni_count;
132  psk_sni_entry *psk_sni_entry_list;
133  char *root_ca_file;
134  char *root_ca_path;
135  int psk_pki_enabled;
136 } coap_mbedtls_context_t;
137 
138 typedef enum coap_enc_method_t {
139  COAP_ENC_PSK,
140  COAP_ENC_PKI,
141 } coap_enc_method_t;
142 
143 static int coap_dgram_read(void *ctx, unsigned char *out, size_t outl)
144 {
145  ssize_t ret = 0;
146  coap_session_t *c_session = (struct coap_session_t *)ctx;
147  coap_ssl_t *data;
148 
149  if (!c_session->tls) {
150  errno = EAGAIN;
151  return MBEDTLS_ERR_SSL_WANT_READ;
152  }
153  data = &((coap_mbedtls_env_t *)c_session->tls)->coap_ssl_data;
154 
155  if (out != NULL) {
156  if (data->pdu_len > 0) {
157  if (outl < data->pdu_len) {
158  memcpy(out, data->pdu, outl);
159  ret = outl;
160  data->pdu += outl;
161  data->pdu_len -= outl;
162  }
163  else {
164  memcpy(out, data->pdu, data->pdu_len);
165  ret = data->pdu_len;
166  if (!data->peekmode) {
167  data->pdu_len = 0;
168  data->pdu = NULL;
169  }
170  }
171  }
172  else {
173  ret = MBEDTLS_ERR_SSL_WANT_READ;
174  errno = EAGAIN;
175  }
176  }
177  return ret;
178 }
179 
180 /*
181  * return +ve data amount
182  * 0 no more
183  * -1 error (error in errno)
184  */
185 /* callback function given to mbedtls for sending data over socket */
186 static int
187 coap_dgram_write(void *ctx, const unsigned char *send_buffer,
188  size_t send_buffer_length)
189 {
190  ssize_t result = -1;
191  coap_session_t *c_session = (struct coap_session_t *)ctx;
192 
193  if (c_session) {
194  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
195  result = coap_session_send(c_session, send_buffer, send_buffer_length);
196  if (result != (ssize_t)send_buffer_length) {
197  coap_log(LOG_WARNING, "coap_network_send failed (%zd != %zu)\n",
198  result, send_buffer_length);
199  result = 0;
200  }
201  else if (m_env) {
202  coap_tick_t now;
203  coap_ticks(&now);
204  m_env->last_timeout = now;
205  }
206  } else {
207  result = 0;
208  }
209  return result;
210 }
211 
212 #if defined(MBEDTLS_SSL_PROTO_DTLS) && defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) && defined(MBEDTLS_SSL_SRV_C)
213 /*
214  * Server side PSK callback
215  */
216 static int psk_server_callback(void *p_info, mbedtls_ssl_context *ssl,
217  const unsigned char *name, size_t name_len )
218 {
219  coap_session_t *c_session = (coap_session_t *)p_info;
220  uint8_t buf[128];
221  size_t psk_len;
222  coap_dtls_spsk_t *setup_data;
223  coap_mbedtls_env_t *m_env;
224 
225  coap_log(LOG_DEBUG, "got psk_identity: '%.*s'\n",
226  (int)name_len, name);
227 
228  if (c_session == NULL || c_session->context == NULL ||
229  c_session->context->get_server_psk == NULL) {
230  return -1;
231  }
232  m_env = (coap_mbedtls_env_t *)c_session->tls;
233  setup_data = &c_session->context->spsk_setup_data;
234 
235  if (setup_data->validate_id_call_back) {
236  coap_bin_const_t lidentity;
237  lidentity.length = name_len;
238  lidentity.s = (const uint8_t*)name;
239  const coap_bin_const_t *psk_key =
240  setup_data->validate_id_call_back(&lidentity,
241  c_session,
242  setup_data->id_call_back_arg);
243 
244  if (psk_key == NULL)
245  return -1;
246  mbedtls_ssl_set_hs_psk(ssl, psk_key->s, psk_key->length);
248  m_env->seen_client_hello = 1;
249  return 0;
250  }
251 
252  psk_len = c_session->context->get_server_psk(c_session,
253  (const uint8_t*)name,
254  name_len,
255  (uint8_t*)buf, sizeof(buf));
256  m_env->seen_client_hello = 1;
257  mbedtls_ssl_set_hs_psk(ssl, buf, psk_len);
258  return 0;
259 }
260 #endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED && MBEDTLS_SSL_SRV_C */
261 
262 static char*
263 get_san_or_cn_from_cert(mbedtls_x509_crt *crt)
264 {
265  if (crt) {
266  mbedtls_asn1_named_data * cn_data;
267 
268  if (crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME) {
269  mbedtls_asn1_sequence *seq = &crt->subject_alt_names;
270  while (seq && seq->buf.p == NULL) {
271  seq = seq->next;
272  }
273  if (seq) {
274  /* Return the Subject Alt Name */
275  return mbedtls_strndup((const char *)seq->buf.p,
276  seq->buf.len);
277  }
278  }
279 
280  cn_data = mbedtls_asn1_find_named_data(&crt->subject,
281  MBEDTLS_OID_AT_CN,
282  MBEDTLS_OID_SIZE(MBEDTLS_OID_AT_CN));
283  if (cn_data) {
284  /* Return the Common Name */
285  return mbedtls_strndup((const char *)cn_data->val.p,
286  cn_data->val.len);
287  }
288  }
289  return NULL;
290 }
291 
292 static char *
293 get_error_string(int ret) {
294  static char buf[128] = {0};
295  mbedtls_strerror(ret, buf, sizeof(buf)-1);
296  return buf;
297 }
298 
299 /*
300  * return 0 All OK
301  * -ve Error Code
302  */
303 static int
304 cert_verify_callback_mbedtls(void *data, mbedtls_x509_crt *crt,
305  int depth, uint32_t *flags)
306 {
307  coap_session_t *c_session = (coap_session_t*)data;
308  coap_mbedtls_context_t *m_context =
309  (coap_mbedtls_context_t *)c_session->context->dtls_context;
310  coap_dtls_pki_t *setup_data = &m_context->setup_data;
311  char *cn = NULL;
312 
313  if (*flags == 0)
314  return 0;
315 
316  cn = get_san_or_cn_from_cert(crt);
317 
318  if (*flags & MBEDTLS_X509_BADCERT_EXPIRED) {
319  if (setup_data->allow_expired_certs) {
320  *flags &= ~MBEDTLS_X509_BADCERT_EXPIRED;
322  " %s: %s: overridden: '%s' depth %d\n",
323  coap_session_str(c_session),
324  "The certificate has expired", cn ? cn : "?", depth);
325  }
326  }
327  if (*flags & MBEDTLS_X509_BADCERT_FUTURE) {
328  if (setup_data->allow_expired_certs) {
329  *flags &= ~MBEDTLS_X509_BADCERT_FUTURE;
331  " %s: %s: overridden: '%s' depth %d\n",
332  coap_session_str(c_session),
333  "The certificate has a future date", cn ? cn : "?", depth);
334  }
335  }
336  if (*flags & MBEDTLS_X509_BADCERT_BAD_MD) {
337  if (setup_data->allow_bad_md_hash) {
338  *flags &= ~MBEDTLS_X509_BADCERT_BAD_MD;
340  " %s: %s: overridden: '%s' depth %d\n",
341  coap_session_str(c_session),
342  "The certificate has a bad MD hash", cn ? cn : "?", depth);
343  }
344  }
345  if (*flags & MBEDTLS_X509_BADCERT_BAD_KEY) {
346  if (setup_data->allow_short_rsa_length) {
347  *flags &= ~MBEDTLS_X509_BADCERT_BAD_KEY;
349  " %s: %s: overridden: '%s' depth %d\n",
350  coap_session_str(c_session),
351  "The certificate has a short RSA length", cn ? cn : "?", depth);
352  }
353  }
354  if (*flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
355  uint32_t lflags;
356  int self_signed = !mbedtls_x509_crt_verify(crt, crt, NULL, NULL, &lflags,
357  NULL, NULL);
358  if (self_signed && depth == 0) {
359  if (setup_data->allow_self_signed &&
360  !setup_data->check_common_ca) {
361  *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
363  " %s: %s: overridden: '%s' depth %d\n",
364  coap_session_str(c_session),
365  "Self-signed",
366  cn ? cn : "?", depth);
367  }
368  }
369  else {
370  if (!setup_data->verify_peer_cert) {
371  *flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
373  " %s: %s: overridden: '%s' depth %d\n",
374  coap_session_str(c_session),
375  "The certificate's CA does not match", cn ? cn : "?", depth);
376  }
377  }
378  }
379  if (*flags & MBEDTLS_X509_BADCRL_EXPIRED) {
380  if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
381  *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
383  " %s: %s: overridden: '%s' depth %d\n",
384  coap_session_str(c_session),
385  "The certificate's CRL has expired", cn ? cn : "?", depth);
386  }
387  else if (!setup_data->check_cert_revocation) {
388  *flags &= ~MBEDTLS_X509_BADCRL_EXPIRED;
389  }
390  }
391  if (*flags & MBEDTLS_X509_BADCRL_FUTURE) {
392  if (setup_data->check_cert_revocation && setup_data->allow_expired_crl) {
393  *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
395  " %s: %s: overridden: '%s' depth %d\n",
396  coap_session_str(c_session),
397  "The certificate's CRL has a future date", cn ? cn : "?", depth);
398  }
399  else if (!setup_data->check_cert_revocation) {
400  *flags &= ~MBEDTLS_X509_BADCRL_FUTURE;
401  }
402  }
403  if (setup_data->cert_chain_validation &&
404  depth > (setup_data->cert_chain_verify_depth)) {
405  *flags |= MBEDTLS_X509_BADCERT_OTHER;
407  " %s: %s: '%s' depth %d\n",
408  coap_session_str(c_session),
409  "The certificate's verify depth is too long",
410  cn ? cn : "?", depth);
411  }
412 
413  if (*flags & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
414  *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
415  }
416  if (setup_data->validate_cn_call_back) {
417  if (!setup_data->validate_cn_call_back(cn,
418  crt->raw.p,
419  crt->raw.len,
420  c_session,
421  depth,
422  *flags == 0,
423  setup_data->cn_call_back_arg)) {
424  *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
425  }
426  }
427  if (*flags != 0) {
428  char buf[128];
429  char *tcp;
430  int ret = mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
431 
432  if (ret >= 0) {
433  tcp = strchr(buf, '\n');
434  while (tcp) {
435  *tcp = '\000';
437  " %s: %s: issue 0x%x: '%s' depth %d\n",
438  coap_session_str(c_session),
439  buf, *flags, cn ? cn : "?", depth);
440  tcp = strchr(tcp+1, '\n');
441  }
442  }
443  else {
444  coap_log(LOG_ERR, "mbedtls_x509_crt_verify_info returned -0x%x: '%s'\n",
445  -ret, get_error_string(ret));
446  }
447  }
448 
449  if (cn)
450  mbedtls_free(cn);
451 
452  return 0;
453 }
454 
455 static int
456 setup_pki_credentials(mbedtls_x509_crt *cacert,
457  mbedtls_x509_crt *public_cert,
458  mbedtls_pk_context *private_key,
459  coap_mbedtls_env_t *m_env,
460  coap_mbedtls_context_t *m_context,
461  coap_session_t *c_session,
462  coap_dtls_pki_t *setup_data,
463  coap_dtls_role_t role)
464 {
465  int ret;
466 
467  if (setup_data->is_rpk_not_cert) {
469  "RPK Support not available in MbedTLS\n");
470  return -1;
471  }
472  switch (setup_data->pki_key.key_type) {
473  case COAP_PKI_KEY_PEM:
474  if (setup_data->pki_key.key.pem.public_cert &&
475  setup_data->pki_key.key.pem.public_cert[0] &&
476  setup_data->pki_key.key.pem.private_key &&
477  setup_data->pki_key.key.pem.private_key[0]) {
478 
479  mbedtls_x509_crt_init(public_cert);
480  mbedtls_pk_init(private_key);
481 
482  ret = mbedtls_x509_crt_parse_file(public_cert,
483  setup_data->pki_key.key.pem.public_cert);
484  if (ret < 0) {
485  coap_log(LOG_ERR, "mbedtls_x509_crt_parse_file returned -0x%x: '%s'\n",
486  -ret, get_error_string(ret));
487  return ret;
488  }
489 
490  ret = mbedtls_pk_parse_keyfile(private_key,
491  setup_data->pki_key.key.pem.private_key, NULL);
492  if (ret < 0) {
493  coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n",
494  -ret, get_error_string(ret));
495  return ret;
496  }
497 
498  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
499  if (ret < 0) {
500  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
501  -ret, get_error_string(ret));
502  return ret;
503  }
504  }
505  else if (role == COAP_DTLS_ROLE_SERVER) {
507  "***setup_pki: (D)TLS: No Server Certificate + Private "
508  "Key defined\n");
509  return -1;
510  }
511 
512  if (setup_data->pki_key.key.pem.ca_file &&
513  setup_data->pki_key.key.pem.ca_file[0]) {
514  mbedtls_x509_crt_init(cacert);
515  ret = mbedtls_x509_crt_parse_file(cacert,
516  setup_data->pki_key.key.pem.ca_file);
517  if (ret < 0) {
518  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
519  -ret, get_error_string(ret));
520  return ret;
521  }
522  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
523  }
524  break;
526  if (setup_data->pki_key.key.pem_buf.public_cert &&
527  setup_data->pki_key.key.pem_buf.public_cert_len &&
528  setup_data->pki_key.key.pem_buf.private_key &&
529  setup_data->pki_key.key.pem_buf.private_key_len) {
530  uint8_t *buffer;
531  size_t length;
532 
533  mbedtls_x509_crt_init(public_cert);
534  mbedtls_pk_init(private_key);
535 
536  length = setup_data->pki_key.key.pem_buf.public_cert_len;
537  if (setup_data->pki_key.key.pem_buf.public_cert[length-1] != '\000') {
538  /* Need to allocate memory to add in NULL terminator */
539  buffer = mbedtls_malloc(length + 1);
540  if (!buffer) {
541  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
542  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
543  }
544  memcpy(buffer, setup_data->pki_key.key.pem_buf.public_cert, length);
545  buffer[length] = '\000';
546  length++;
547  ret = mbedtls_x509_crt_parse(public_cert, buffer, length);
548  mbedtls_free(buffer);
549  }
550  else {
551  ret = mbedtls_x509_crt_parse(public_cert,
552  setup_data->pki_key.key.pem_buf.public_cert,
553  setup_data->pki_key.key.pem_buf.public_cert_len);
554  }
555  if (ret < 0) {
556  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
557  -ret, get_error_string(ret));
558  return ret;
559  }
560 
561  length = setup_data->pki_key.key.pem_buf.private_key_len;
562  if (setup_data->pki_key.key.pem_buf.private_key[length-1] != '\000') {
563  /* Need to allocate memory to add in NULL terminator */
564  buffer = mbedtls_malloc(length + 1);
565  if (!buffer) {
566  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
567  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
568  }
569  memcpy(buffer, setup_data->pki_key.key.pem_buf.private_key, length);
570  buffer[length] = '\000';
571  length++;
572  ret = mbedtls_pk_parse_key(private_key, buffer, length, NULL, 0);
573  mbedtls_free(buffer);
574  }
575  else {
576  ret = mbedtls_pk_parse_key(private_key,
577  setup_data->pki_key.key.pem_buf.private_key,
578  setup_data->pki_key.key.pem_buf.private_key_len, NULL, 0);
579  }
580  if (ret < 0) {
581  coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n",
582  -ret, get_error_string(ret));
583  return ret;
584  }
585 
586  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
587  if (ret < 0) {
588  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
589  -ret, get_error_string(ret));
590  return ret;
591  }
592  } else if (role == COAP_DTLS_ROLE_SERVER) {
594  "***setup_pki: (D)TLS: No Server Certificate + Private "
595  "Key defined\n");
596  return -1;
597  }
598 
599  if (setup_data->pki_key.key.pem_buf.ca_cert &&
600  setup_data->pki_key.key.pem_buf.ca_cert_len) {
601  uint8_t *buffer;
602  size_t length;
603 
604  mbedtls_x509_crt_init(cacert);
605  length = setup_data->pki_key.key.pem_buf.ca_cert_len;
606  if (setup_data->pki_key.key.pem_buf.ca_cert[length-1] != '\000') {
607  /* Need to allocate memory to add in NULL terminator */
608  buffer = mbedtls_malloc(length + 1);
609  if (!buffer) {
610  coap_log(LOG_ERR, "mbedtls_malloc failed\n");
611  return MBEDTLS_ERR_SSL_ALLOC_FAILED;
612  }
613  memcpy(buffer, setup_data->pki_key.key.pem_buf.ca_cert, length);
614  buffer[length] = '\000';
615  length++;
616  ret = mbedtls_x509_crt_parse(cacert, buffer, length);
617  mbedtls_free(buffer);
618  }
619  else {
620  ret = mbedtls_x509_crt_parse(cacert,
621  setup_data->pki_key.key.pem_buf.ca_cert,
622  setup_data->pki_key.key.pem_buf.ca_cert_len);
623  }
624  if (ret < 0) {
625  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
626  -ret, get_error_string(ret));
627  return ret;
628  }
629  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
630  }
631  break;
632  case COAP_PKI_KEY_ASN1:
633  if (setup_data->pki_key.key.asn1.public_cert &&
634  setup_data->pki_key.key.asn1.public_cert_len &&
635  setup_data->pki_key.key.asn1.private_key &&
636  setup_data->pki_key.key.asn1.private_key_len > 0) {
637 
638  mbedtls_x509_crt_init(public_cert);
639  mbedtls_pk_init(private_key);
640  ret = mbedtls_x509_crt_parse(public_cert,
641  (const unsigned char *)setup_data->pki_key.key.asn1.public_cert,
642  setup_data->pki_key.key.asn1.public_cert_len);
643  if (ret < 0) {
644  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
645  -ret, get_error_string(ret));
646  return ret;
647  }
648 
649  ret = mbedtls_pk_parse_key(private_key,
650  (const unsigned char *)setup_data->pki_key.key.asn1.private_key,
651  setup_data->pki_key.key.asn1.private_key_len, NULL, 0);
652  if (ret < 0) {
653  coap_log(LOG_ERR, "mbedtls_pk_parse_keyfile returned -0x%x: '%s'\n",
654  -ret, get_error_string(ret));
655  return ret;
656  }
657 
658  ret = mbedtls_ssl_conf_own_cert(&m_env->conf, public_cert, private_key);
659  if (ret < 0) {
660  coap_log(LOG_ERR, "mbedtls_ssl_conf_own_cert returned -0x%x: '%s'\n",
661  -ret, get_error_string(ret));
662  return ret;
663  }
664  } else if (role == COAP_DTLS_ROLE_SERVER) {
666  "***setup_pki: (D)TLS: No Server Certificate + Private "
667  "Key defined\n");
668  return -1;
669  }
670 
671  if (setup_data->pki_key.key.asn1.ca_cert &&
672  setup_data->pki_key.key.asn1.ca_cert_len > 0) {
673  mbedtls_x509_crt_init(cacert);
674  ret = mbedtls_x509_crt_parse(cacert,
675  (const unsigned char *)setup_data->pki_key.key.asn1.ca_cert,
676  setup_data->pki_key.key.asn1.ca_cert_len);
677  if (ret < 0) {
678  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
679  -ret, get_error_string(ret));
680  return ret;
681  }
682  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
683  }
684  break;
685 
686  case COAP_PKI_KEY_PKCS11:
688  "***setup_pki: (D)TLS: PKCS11 not currently supported\n");
689  return -1;
690 
691  default:
693  "***setup_pki: (D)TLS: Unknown key type %d\n",
694  setup_data->pki_key.key_type);
695  return -1;
696  }
697 
698  if (m_context->root_ca_file) {
699  ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_file);
700  if (ret < 0) {
701  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
702  -ret, get_error_string(ret));
703  return ret;
704  }
705  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
706  }
707  if (m_context->root_ca_path) {
708  ret = mbedtls_x509_crt_parse_file(cacert, m_context->root_ca_path);
709  if (ret < 0) {
710  coap_log(LOG_ERR, "mbedtls_x509_crt_parse returned -0x%x: '%s'\n",
711  -ret, get_error_string(ret));
712  return ret;
713  }
714  mbedtls_ssl_conf_ca_chain(&m_env->conf, cacert, NULL);
715  }
716 
717  mbedtls_ssl_conf_cert_req_ca_list(&m_env->conf,
718  setup_data->check_common_ca ?
719  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED :
720  MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED);
721  mbedtls_ssl_conf_authmode(&m_env->conf, setup_data->verify_peer_cert ?
722  MBEDTLS_SSL_VERIFY_REQUIRED :
723  MBEDTLS_SSL_VERIFY_NONE);
724  /*
725  * Verify Peer.
726  * Need to do all checking, even if setup_data->verify_peer_cert is not set
727  */
728  mbedtls_ssl_conf_verify(&m_env->conf,
729  cert_verify_callback_mbedtls, c_session);
730 
731  return 0;
732 }
733 
734 #if defined(MBEDTLS_SSL_SRV_C)
735 /*
736  * PKI SNI callback.
737  */
738 static int
739 pki_sni_callback(void *p_info, mbedtls_ssl_context *ssl,
740  const unsigned char *uname, size_t name_len)
741 {
742  unsigned int i;
743  coap_dtls_pki_t sni_setup_data;
744  coap_session_t *c_session = (coap_session_t *)p_info;
745  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
746  coap_mbedtls_context_t *m_context =
747  (coap_mbedtls_context_t *)c_session->context->dtls_context;
748  int ret = 0;
749  char *name;
750 
751  name = mbedtls_malloc(name_len+1);
752  if (!name)
753  return -1;
754 
755  memcpy(name, uname, name_len);
756  name[name_len] = '\000';
757 
758  /* Is this a cached entry? */
759  for (i = 0; i < m_context->pki_sni_count; i++) {
760  if (strcasecmp(name, m_context->pki_sni_entry_list[i].sni) == 0) {
761  break;
762  }
763  }
764  if (i == m_context->pki_sni_count) {
765  /*
766  * New PKI SNI request
767  */
768  coap_dtls_key_t *new_entry;
769 
770  new_entry =
771  m_context->setup_data.validate_sni_call_back(name,
772  m_context->setup_data.sni_call_back_arg);
773  if (!new_entry) {
774  mbedtls_free(name);
775  return -1;
776  }
777 
778  m_context->pki_sni_entry_list =
779  mbedtls_realloc(m_context->pki_sni_entry_list,
780  (i+1)*sizeof(pki_sni_entry));
781  memset(&m_context->pki_sni_entry_list[i], 0,
782  sizeof(m_context->pki_sni_entry_list[i]));
783  m_context->pki_sni_entry_list[i].sni = name;
784  m_context->pki_sni_entry_list[i].pki_key = *new_entry;
785  sni_setup_data = m_context->setup_data;
786  sni_setup_data.pki_key = *new_entry;
787  if ((ret = setup_pki_credentials(&m_context->pki_sni_entry_list[i].cacert,
788  &m_context->pki_sni_entry_list[i].public_cert,
789  &m_context->pki_sni_entry_list[i].private_key,
790  m_env,
791  m_context,
792  c_session,
793  &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
794  mbedtls_free(name);
795  return -1;
796  }
797  /* name has been absorbed into pki_sni_entry_list[].sni entry */
798  m_context->pki_sni_count++;
799  }
800  else {
801  mbedtls_free(name);
802  }
803 
804  mbedtls_ssl_set_hs_ca_chain(ssl, &m_context->pki_sni_entry_list[i].cacert,
805  NULL);
806  return mbedtls_ssl_set_hs_own_cert(ssl,
807  &m_context->pki_sni_entry_list[i].public_cert,
808  &m_context->pki_sni_entry_list[i].private_key);
809 }
810 
811 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
812 /*
813  * PSK SNI callback.
814  */
815 static int
816 psk_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_session_t *c_session = (coap_session_t *)p_info;
821  coap_mbedtls_context_t *m_context =
822  (coap_mbedtls_context_t *)c_session->context->dtls_context;
823  char *name;
824 
825  name = mbedtls_malloc(name_len+1);
826  if (!name)
827  return -1;
828 
829  memcpy(name, uname, name_len);
830  name[name_len] = '\000';
831 
832  /* Is this a cached entry? */
833  for (i = 0; i < m_context->psk_sni_count; i++) {
834  if (strcasecmp(name, m_context->psk_sni_entry_list[i].sni) == 0) {
835  break;
836  }
837  }
838  if (i == m_context->psk_sni_count) {
839  /*
840  * New PSK SNI request
841  */
842  const coap_dtls_spsk_info_t *new_entry;
843 
844  new_entry =
846  c_session,
848  if (!new_entry) {
849  mbedtls_free(name);
850  return -1;
851  }
852 
853  m_context->psk_sni_entry_list =
854  mbedtls_realloc(m_context->psk_sni_entry_list,
855  (i+1)*sizeof(psk_sni_entry));
856 
857  m_context->psk_sni_entry_list[i].sni = name;
858  m_context->psk_sni_entry_list[i].psk_info = *new_entry;
859  /* name has been absorbed into psk_sni_entry_list[].sni entry */
860  m_context->psk_sni_count++;
861  }
862  else {
863  mbedtls_free(name);
864  }
865 
867  &m_context->psk_sni_entry_list[i].psk_info.hint);
869  &m_context->psk_sni_entry_list[i].psk_info.key);
870  return mbedtls_ssl_set_hs_psk(ssl,
871  m_context->psk_sni_entry_list[i].psk_info.key.s,
872  m_context->psk_sni_entry_list[i].psk_info.key.length);
873 }
874 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
875 
876 static int setup_server_ssl_session(coap_session_t *c_session,
877  coap_mbedtls_env_t *m_env)
878 {
879  coap_mbedtls_context_t *m_context =
880  (coap_mbedtls_context_t *)c_session->context->dtls_context;
881  int ret = 0;
882  m_context->psk_pki_enabled |= IS_SERVER;
883 
884  mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
885  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
886  MBEDTLS_SSL_IS_SERVER,
887  c_session->proto == COAP_PROTO_DTLS ?
888  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
889  MBEDTLS_SSL_TRANSPORT_STREAM,
890  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
891  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
892  -ret, get_error_string(ret));
893  goto fail;
894  }
895 
896  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
897 
898 #if defined(MBEDTLS_SSL_PROTO_DTLS)
899  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
901 
902  if (m_context->psk_pki_enabled & IS_PSK) {
903 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
904  mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
906  mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
907  }
908 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
909  coap_log(LOG_WARNING, "PSK not enabled in MbedTLS library\n");
910 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
911  }
912 #endif /* MBEDTLS_SSL_PROTO_DTLS */
913 
914  if (m_context->psk_pki_enabled & IS_PKI) {
915  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
916  &m_env->private_key, m_env, m_context,
917  c_session, &m_context->setup_data,
919  if (ret < 0) {
920  coap_log(LOG_ERR, "PKI setup failed\n");
921  return ret;
922  }
923  if (m_context->setup_data.validate_sni_call_back) {
924  mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
925  }
926  }
927 
928  if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
929  mbedtls_ctr_drbg_random,
930  &m_env->ctr_drbg)) != 0) {
931  coap_log(LOG_ERR, "mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
932  -ret, get_error_string(ret));
933  goto fail;
934  }
935 
936 #if defined(MBEDTLS_SSL_PROTO_DTLS)
937  mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
938  mbedtls_ssl_cookie_check,
939  &m_env->cookie_ctx );
940 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
941  mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu);
942 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
943 #endif /* MBEDTLS_SSL_PROTO_DTLS */
944 fail:
945  return ret;
946 }
947 #endif /* MBEDTLS_SSL_SRV_C */
948 
949 static int *psk_ciphers = NULL;
950 static int *pki_ciphers = NULL;
951 static int processed_ciphers = 0;
952 
953 static void
954 set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method)
955 {
956  if (!processed_ciphers) {
957  const int *list = mbedtls_ssl_list_ciphersuites();
958  const int *base = list;
959  int *psk_list;
960  int *pki_list;
961  int psk_count = 1; /* account for empty terminator */
962  int pki_count = 1;
963 
964  while (*list) {
965  const mbedtls_ssl_ciphersuite_t *cur =
966  mbedtls_ssl_ciphersuite_from_id(*list);
967 
968  if (cur) {
969  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
970  /* Minimum of TLS1.2 required - skip */
971  }
972  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
973  psk_count++;
974  }
975  else {
976  pki_count++;
977  }
978  }
979  list++;
980  }
981  list = base;
982 
983  psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
984  if (psk_ciphers == NULL) {
985  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
986  return;
987  }
988  pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
989  if (pki_ciphers == NULL) {
990  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
991  return;
992  }
993 
994  psk_list = psk_ciphers;
995  pki_list = pki_ciphers;
996 
997  while (*list) {
998  const mbedtls_ssl_ciphersuite_t *cur =
999  mbedtls_ssl_ciphersuite_from_id(*list);
1000  if (cur) {
1001  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1002  /* Minimum of TLS1.2 required - skip */
1003  }
1004  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1005  *psk_list = *list;
1006  psk_list++;
1007  }
1008  else {
1009  *pki_list = *list;
1010  pki_list++;
1011  }
1012  }
1013  list++;
1014  }
1015  /* zero terminate */
1016  *psk_list = 0;
1017  *pki_list = 0;
1018  processed_ciphers = 1;
1019  }
1020  mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers);
1021 }
1022 
1023 static int setup_client_ssl_session(coap_session_t *c_session,
1024  coap_mbedtls_env_t *m_env)
1025 {
1026  int ret;
1027 
1028  coap_mbedtls_context_t *m_context =
1029  (coap_mbedtls_context_t *)c_session->context->dtls_context;
1030 
1031  m_context->psk_pki_enabled |= IS_CLIENT;
1032 
1033  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1034  MBEDTLS_SSL_IS_CLIENT,
1035  c_session->proto == COAP_PROTO_DTLS ?
1036  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1037  MBEDTLS_SSL_TRANSPORT_STREAM,
1038  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1039  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1040  -ret, get_error_string(ret));
1041  goto fail;
1042  }
1043 
1044 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1045  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1047 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1048 
1049  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1050  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1051 
1052  if (m_context->psk_pki_enabled & IS_PSK) {
1053 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1054  uint8_t identity[64];
1055  size_t identity_len;
1056  uint8_t psk_key[64];
1057  size_t psk_len;
1058  size_t max_identity_len = sizeof(identity);
1059 
1060  coap_log(LOG_INFO, "Setting PSK key\n");
1061  psk_len = c_session->context->get_client_psk(c_session,
1062  NULL,
1063  0,
1064  identity,
1065  &identity_len,
1066  max_identity_len,
1067  psk_key,
1068  sizeof(psk_key));
1069  assert(identity_len <= sizeof(identity));
1070  mbedtls_ssl_conf_psk(&m_env->conf, (const unsigned char *)psk_key,
1071  psk_len, (const unsigned char *)identity,
1072  identity_len);
1073  if (c_session->cpsk_setup_data.client_sni) {
1074  mbedtls_ssl_set_hostname(&m_env->ssl,
1075  c_session->cpsk_setup_data.client_sni);
1076  }
1077  /* Identity Hint currently not supported in MbedTLS so code removed */
1078 
1079  set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1080 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1081  coap_log(LOG_WARNING, "PSK not enabled in MbedTLS library\n");
1082 #endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1083  }
1084  else if ((m_context->psk_pki_enabled & IS_PKI) ||
1085  (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1086  /*
1087  * If neither PSK or PKI have been set up, use PKI basics.
1088  * This works providing COAP_PKI_KEY_PEM has a value of 0.
1089  */
1090  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1091  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1092  &m_env->private_key, m_env, m_context,
1093  c_session, &m_context->setup_data,
1095  if (ret < 0) {
1096  coap_log(LOG_ERR, "PKI setup failed\n");
1097  return ret;
1098  }
1099 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1100  if (c_session->proto == COAP_PROTO_TLS) {
1101  const char *alpn_list[] = { "coap", NULL };
1102 
1103  ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1104  if (ret != 0) {
1105  coap_log(LOG_ERR, "ALPN setup failed %d)\n", ret);
1106  }
1107  }
1108 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1109  if (m_context->setup_data.client_sni) {
1110  mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1111  }
1112 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1113 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1114  mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu);
1115 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1116 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1117  set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1118  }
1119  return 0;
1120 
1121 fail:
1122  return ret;
1123 }
1124 
1125 static void mbedtls_cleanup(coap_mbedtls_env_t *m_env)
1126 {
1127  if (!m_env) {
1128  return;
1129  }
1130 
1131  mbedtls_x509_crt_free(&m_env->cacert);
1132  mbedtls_x509_crt_free(&m_env->public_cert);
1133  mbedtls_pk_free(&m_env->private_key);
1134  mbedtls_entropy_free(&m_env->entropy);
1135  mbedtls_ssl_config_free(&m_env->conf);
1136  mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1137  mbedtls_ssl_free(&m_env->ssl);
1138  mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1139 }
1140 
1141 static void
1142 coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1143  if (m_env) {
1144  mbedtls_cleanup(m_env);
1145  mbedtls_free(m_env);
1146  }
1147 }
1148 
1149 static const char *
1150 report_mbedtls_alert(unsigned char alert) {
1151  switch (alert) {
1152  case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC: return ": Bad Record MAC";
1153  case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE: return ": Handshake failure";
1154  case MBEDTLS_SSL_ALERT_MSG_NO_CERT: return ": No Certificate provided";
1155  case MBEDTLS_SSL_ALERT_MSG_BAD_CERT: return ": Certificate is bad";
1156  case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA: return ": CA is unknown";
1157  case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED: return ": Access was denied";
1158  case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR: return ": Decrypt error";
1159  default: return "";
1160  }
1161 }
1162 
1163 /*
1164  * return -1 failure
1165  * 0 not completed
1166  * 1 established
1167  */
1168 static int do_mbedtls_handshake(coap_session_t *c_session,
1169  coap_mbedtls_env_t *m_env) {
1170  int ret;
1171  int alert;
1172 
1173  ret = mbedtls_ssl_handshake(&m_env->ssl);
1174  switch (ret) {
1175  case 0:
1176  m_env->established = 1;
1177  coap_log(LOG_DEBUG, "* %s: MbedTLS established\n",
1178  coap_session_str(c_session));
1179  ret = 1;
1180  break;
1181  case MBEDTLS_ERR_SSL_WANT_READ:
1182  case MBEDTLS_ERR_SSL_WANT_WRITE:
1183  errno = EAGAIN;
1184  ret = 0;
1185  break;
1186  case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1187  coap_log(LOG_DEBUG, "hello verification requested\n");
1188  goto reset;
1189  case MBEDTLS_ERR_SSL_INVALID_MAC:
1190  goto fail;
1191  case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1192  alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1193  goto fail_alert;
1194  case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1195  alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1196  goto fail_alert;
1197  case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1198  goto fail;
1199  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1200  if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1201  coap_log(LOG_WARNING, "***%s: Alert '%d'%s\n",
1202  coap_session_str(c_session), m_env->ssl.in_msg[1],
1203  report_mbedtls_alert(m_env->ssl.in_msg[1]));
1204  /* Fall through */
1205  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1206  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1207  ret = -1;
1208  break;
1209  default:
1211  "do_mbedtls_handshake: session establish "
1212  "returned -0x%x: '%s'\n",
1213  -ret, get_error_string(ret));
1214  ret = -1;
1215  break;
1216  }
1217  return ret;
1218 
1219 fail_alert:
1220  mbedtls_ssl_send_alert_message(&m_env->ssl,
1221  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1222  alert);
1223 fail:
1224  c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1226  "do_mbedtls_handshake: session establish "
1227  "returned '%s'\n",
1228  get_error_string(ret));
1229 reset:
1230  mbedtls_ssl_session_reset(&m_env->ssl);
1231  return -1;
1232 }
1233 
1234 static void
1235 mbedtls_debug_out(void *ctx UNUSED, int level,
1236  const char *file, int line, const char *str) {
1237  int log_level;
1238  /*
1239  * 0 No debug
1240  * 1 Error
1241  * 2 State change
1242  * 3 Informational
1243  * 4 Verbose
1244  */
1245  switch (level) {
1246  case 4:
1247  case 3:
1248  case 2:
1249  log_level = COAP_LOG_CIPHERS;
1250  break;
1251  case 1:
1252  log_level = LOG_ERR;
1253  break;
1254  case 0:
1255  default:
1256  log_level = 0;
1257  break;
1258  }
1259  coap_log(log_level, "%s:%04d: %s", file, line, str);
1260 }
1261 
1262 static coap_mbedtls_env_t *coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1263  coap_dtls_role_t role)
1264 {
1265  int ret = 0;
1266  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1267 
1268  if (m_env)
1269  return m_env;
1270 
1271  m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1272  if (!m_env) {
1273  return NULL;
1274  }
1275  memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1276 
1277  mbedtls_ssl_init(&m_env->ssl);
1278  mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1279  mbedtls_ssl_config_init(&m_env->conf);
1280  mbedtls_entropy_init(&m_env->entropy);
1281 
1282 #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1283  mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1284 #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1285  if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1286  mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1287  coap_log(LOG_ERR, "mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1288  -ret, get_error_string(ret));
1289  goto fail;
1290  }
1291 
1292  if (role == COAP_DTLS_ROLE_CLIENT) {
1293  if (setup_client_ssl_session(c_session, m_env) != 0) {
1294  goto fail;
1295  }
1296 #if defined(MBEDTLS_SSL_SRV_C)
1297  } else if (role == COAP_DTLS_ROLE_SERVER) {
1298  if (setup_server_ssl_session(c_session, m_env) != 0) {
1299  goto fail;
1300  }
1301 #endif /* MBEDTLS_SSL_SRV_C */
1302  } else {
1303  goto fail;
1304  }
1305 
1306  mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1307  MBEDTLS_SSL_MINOR_VERSION_3);
1308 
1309  if ((ret = mbedtls_ssl_setup(&m_env->ssl, &m_env->conf)) != 0) {
1310  goto fail;
1311  }
1312  mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1313  coap_dgram_read, NULL);
1314  mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1315  mbedtls_timing_set_delay,
1316  mbedtls_timing_get_delay);
1317 
1318  mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1319  return m_env;
1320 
1321 fail:
1322  if (m_env) {
1323  mbedtls_free(m_env);
1324  }
1325  return NULL;
1326 }
1327 
1328 int coap_dtls_is_supported(void) {
1329 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1330  return 1;
1331 #else /* !MBEDTLS_SSL_PROTO_DTLS */
1333  "libcoap not compiled for DTLS with MbedTLS"
1334  " - update MbedTLS to include DTLS\n");
1335  return 0;
1336 #endif /* !MBEDTLS_SSL_PROTO_DTLS */
1337 }
1338 
1339 int coap_tls_is_supported(void)
1340 {
1341  return 0;
1342 }
1343 
1344 void *coap_dtls_new_context(struct coap_context_t *c_context)
1345 {
1346  coap_mbedtls_context_t *m_context;
1347  (void)c_context;
1348 
1349  m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
1350  if (m_context) {
1351  memset(m_context, 0, sizeof(coap_mbedtls_context_t));
1352  }
1353  return m_context;
1354 }
1355 
1356 /*
1357  * return 0 failed
1358  * 1 passed
1359  */
1360 int
1362  coap_dtls_spsk_t *setup_data
1363 ) {
1364  coap_mbedtls_context_t *m_context =
1365  ((coap_mbedtls_context_t *)c_context->dtls_context);
1366 
1367 #if !defined(MBEDTLS_SSL_SRV_C)
1368  coap_log(LOG_EMERG, "coap_context_set_spsk:"
1369  " libcoap not compiled for Server Mode for MbedTLS"
1370  " - update MbedTLS to include Server Mode\n");
1371  return 0;
1372 #endif /* !MBEDTLS_SSL_SRV_C */
1373  if (!m_context || !setup_data)
1374  return 0;
1375 
1376  m_context->psk_pki_enabled |= IS_PSK;
1377  return 1;
1378 }
1379 
1380 /*
1381  * return 0 failed
1382  * 1 passed
1383  */
1384 int
1386  coap_dtls_cpsk_t *setup_data
1387 ) {
1388 #if !defined(MBEDTLS_SSL_CLI_C)
1389  coap_log(LOG_EMERG, "coap_context_set_spsk:"
1390  " libcoap not compiled for Client Mode for MbedTLS"
1391  " - update MbedTLS to include Client Mode\n");
1392  return 0;
1393 #endif /* !MBEDTLS_SSL_CLI_C */
1394  coap_mbedtls_context_t *m_context =
1395  ((coap_mbedtls_context_t *)c_context->dtls_context);
1396 
1397  if (!m_context || !setup_data)
1398  return 0;
1399 
1400  if (setup_data->validate_ih_call_back) {
1402  "CoAP Client with MbedTLS does not support Identity Hint selection\n");
1403  }
1404  m_context->psk_pki_enabled |= IS_PSK;
1405  return 1;
1406 }
1407 
1409  const coap_dtls_pki_t *setup_data,
1410  const coap_dtls_role_t role UNUSED)
1411 {
1412  coap_mbedtls_context_t *m_context =
1413  ((coap_mbedtls_context_t *)c_context->dtls_context);
1414 
1415  m_context->setup_data = *setup_data;
1416  if (!m_context->setup_data.verify_peer_cert) {
1417  /* Needs to be clear so that no CA DNs are transmitted */
1418  m_context->setup_data.check_common_ca = 0;
1419  /* Allow all of these but warn if issue */
1420  m_context->setup_data.allow_self_signed = 1;
1421  m_context->setup_data.allow_expired_certs = 1;
1422  m_context->setup_data.cert_chain_validation = 1;
1423  m_context->setup_data.cert_chain_verify_depth = 10;
1424  m_context->setup_data.check_cert_revocation = 1;
1425  m_context->setup_data.allow_no_crl = 1;
1426  m_context->setup_data.allow_expired_crl = 1;
1427  m_context->setup_data.allow_bad_md_hash = 1;
1428  m_context->setup_data.allow_short_rsa_length = 1;
1429  }
1430  m_context->psk_pki_enabled |= IS_PKI;
1431  return 1;
1432 }
1433 
1435  const char *ca_file,
1436  const char *ca_path)
1437 {
1438  coap_mbedtls_context_t *m_context =
1439  ((coap_mbedtls_context_t *)c_context->dtls_context);
1440 
1441  if (!m_context) {
1443  "coap_context_set_pki_root_cas: (D)TLS environment "
1444  "not set up\n");
1445  return 0;
1446  }
1447 
1448  if (ca_file == NULL && ca_path == NULL) {
1450  "coap_context_set_pki_root_cas: ca_file and/or ca_path "
1451  "not defined\n");
1452  return 0;
1453  }
1454  if (m_context->root_ca_file) {
1455  mbedtls_free(m_context->root_ca_file);
1456  m_context->root_ca_file = NULL;
1457  }
1458 
1459  if (ca_file) {
1460  m_context->root_ca_file = mbedtls_strdup(ca_file);
1461  }
1462 
1463  if (m_context->root_ca_path) {
1464  mbedtls_free(m_context->root_ca_path);
1465  m_context->root_ca_path = NULL;
1466  }
1467 
1468  if (ca_path) {
1469  m_context->root_ca_path = mbedtls_strdup(ca_path);
1470  }
1471  return 1;
1472 }
1473 
1475 {
1476  coap_mbedtls_context_t *m_context =
1477  ((coap_mbedtls_context_t *)c_context->dtls_context);
1478  return m_context->psk_pki_enabled ? 1 : 0;
1479 }
1480 
1481 void coap_dtls_free_context(void *dtls_context)
1482 {
1483  coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
1484  unsigned int i;
1485 
1486  for (i = 0; i < m_context->pki_sni_count; i++) {
1487  mbedtls_free(m_context->pki_sni_entry_list[i].sni);
1488 
1489  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
1490 
1491  mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
1492 
1493  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
1494  }
1495  if (m_context->pki_sni_entry_list)
1496  mbedtls_free(m_context->pki_sni_entry_list);
1497 
1498  for (i = 0; i < m_context->psk_sni_count; i++) {
1499  mbedtls_free(m_context->psk_sni_entry_list[i].sni);
1500  }
1501  if (m_context->psk_sni_entry_list)
1502  mbedtls_free(m_context->psk_sni_entry_list);
1503 
1504  if (m_context->root_ca_path)
1505  mbedtls_free(m_context->root_ca_path);
1506  if (m_context->root_ca_file)
1507  mbedtls_free(m_context->root_ca_file);
1508 
1509  mbedtls_free(m_context);
1510 }
1511 
1513 {
1514 #if !defined(MBEDTLS_SSL_CLI_C)
1515  (void)c_session;
1516  coap_log(LOG_EMERG, "coap_dtls_new_client_session:"
1517  " libcoap not compiled for Client Mode for MbedTLS"
1518  " - update MbedTLS to include Client Mode\n");
1519  return NULL;
1520 #else /* MBEDTLS_SSL_CLI_C */
1521  coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
1523  int ret;
1524 
1525  if (m_env) {
1526  coap_tick_t now;
1527  coap_ticks(&now);
1528  m_env->last_timeout = now;
1529  ret = do_mbedtls_handshake(c_session, m_env);
1530  if (ret == -1) {
1531  coap_dtls_free_mbedtls_env(m_env);
1532  return NULL;
1533  }
1534  }
1535  return m_env;
1536 #endif /* MBEDTLS_SSL_CLI_C */
1537 }
1538 
1540 {
1541  coap_mbedtls_env_t *m_env =
1542  (coap_mbedtls_env_t *)c_session->tls;
1543  if (m_env) {
1544 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1545 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1546  mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu);
1547 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1548 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1549  }
1550  return m_env;
1551 }
1552 
1553 void coap_dtls_free_session(coap_session_t *c_session)
1554 {
1555  if (c_session && c_session->context && c_session->tls) {
1556  coap_dtls_free_mbedtls_env(c_session->tls);
1557  c_session->tls = NULL;
1558  coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session);
1559  }
1560  return;
1561 }
1562 
1564 {
1565 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1566  coap_mbedtls_env_t *m_env =
1567  (coap_mbedtls_env_t *)c_session->tls;
1568  if (m_env) {
1569 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1570  mbedtls_ssl_set_mtu(&m_env->ssl, c_session->mtu);
1571 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1572  }
1573 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1574 }
1575 
1576 int coap_dtls_send(coap_session_t *c_session,
1577  const uint8_t *data,
1578  size_t data_len)
1579 {
1580  int ret;
1581  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1582 
1583  assert(m_env != NULL);
1584 
1585  if (!m_env) {
1586  return -1;
1587  }
1588  c_session->dtls_event = -1;
1589  if (m_env->established) {
1590  ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char*) data, data_len);
1591  if (ret <= 0) {
1592  switch (ret) {
1593  case MBEDTLS_ERR_SSL_WANT_READ:
1594  case MBEDTLS_ERR_SSL_WANT_WRITE:
1595  ret = 0;
1596  break;
1597  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1598  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1599  ret = -1;
1600  break;
1601  default:
1603  "coap_dtls_send: "
1604  "returned -0x%x: '%s'\n",
1605  -ret, get_error_string(ret));
1606  ret = -1;
1607  break;
1608  }
1609  if (ret == -1) {
1610  coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n");
1611  }
1612  }
1613  } else {
1614  ret = do_mbedtls_handshake(c_session, m_env);
1615  if (ret == 1) {
1616  /* Just connected, so send the data */
1617  return coap_dtls_send(c_session, data, data_len);
1618  }
1619  ret = -1;
1620  }
1621 
1622  if (c_session->dtls_event >= 0) {
1623  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1624  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1625  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1626  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1627  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1629  ret = -1;
1630  }
1631  }
1632  return ret;
1633 }
1634 
1636 {
1637  return 0;
1638 }
1639 
1641 {
1642  return 0;
1643 }
1644 
1646 {
1647  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1648  int ret = mbedtls_timing_get_delay(&m_env->timer);
1649  unsigned int scalar = 1 << m_env->retry_scalar;
1650 
1651  assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1652  switch (ret) {
1653  case 0:
1654  /* int_ms has not timed out */
1655  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1656  /* Need to indicate remaining timeout time */
1657  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1658  }
1659  m_env->last_timeout = now;
1660  /* This may cause a minor extra delay */
1661  return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1662  case 1:
1663  /* int_ms has timed out, but not fin_ms */
1664  /*
1665  * Need to make sure that we do not do this too frequently
1666  */
1667  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1668  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1669  }
1670 
1671  /* Reset for the next time */
1672  m_env->last_timeout = now;
1673  return now;
1674  case 2:
1675  /* fin_ms has timed out - timed out - one final try */
1676  return now;
1677  default:
1678  break;
1679  }
1680 
1681  return 0;
1682 }
1683 
1685 {
1686  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1687 
1688  assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1689  m_env->retry_scalar++;
1690  if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
1691  (do_mbedtls_handshake(c_session, m_env) < 0)) {
1692  /* Too many retries */
1694  }
1695  return;
1696 }
1697 
1698 /*
1699  * return +ve data amount
1700  * 0 no more
1701  * -1 error
1702  */
1703 int coap_dtls_receive(coap_session_t *c_session,
1704  const uint8_t *data,
1705  size_t data_len)
1706 {
1707  int ret = 1;
1708 
1709  c_session->dtls_event = -1;
1710  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1711  coap_ssl_t *ssl_data;
1712 
1713  assert(m_env != NULL);
1714 
1715  ssl_data = &m_env->coap_ssl_data;
1716  if (ssl_data->pdu_len) {
1717  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
1718  coap_session_str(c_session), ssl_data->pdu_len);
1719  }
1720  ssl_data->pdu = data;
1721  ssl_data->pdu_len = (unsigned)data_len;
1722 
1723  if (m_env->established) {
1724 #if COAP_CONSTRAINED_STACK
1725  static coap_mutex_t b_static_mutex = COAP_MUTEX_INITIALIZER;
1726  static uint8_t pdu[COAP_RXBUFFER_SIZE];
1727 #else /* ! COAP_CONSTRAINED_STACK */
1729 #endif /* ! COAP_CONSTRAINED_STACK */
1730 
1731 #if COAP_CONSTRAINED_STACK
1732  coap_mutex_lock(&b_static_mutex);
1733 #endif /* COAP_CONSTRAINED_STACK */
1734 
1735  if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
1737  c_session);
1738  coap_session_connected(c_session);
1739  }
1740 
1741  ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
1742  if (ret > 0) {
1743  ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
1744 #if COAP_CONSTRAINED_STACK
1745  coap_mutex_unlock(&b_static_mutex);
1746 #endif /* COAP_CONSTRAINED_STACK */
1747  goto finish;
1748  }
1749  switch (ret) {
1750  case 0:
1751  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1752  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1753  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1754  break;
1755  case MBEDTLS_ERR_SSL_WANT_READ:
1756  break;
1757  default:
1759  "coap_dtls_receive: "
1760  "returned -0x%x: '%s' (length %zd)\n",
1761  -ret, get_error_string(ret), data_len);
1762  break;
1763  }
1764 #if COAP_CONSTRAINED_STACK
1765  coap_mutex_unlock(&b_static_mutex);
1766 #endif /* COAP_CONSTRAINED_STACK */
1767  ret = -1;
1768  }
1769  else {
1770  ret = do_mbedtls_handshake(c_session, m_env);
1771  if (ret == 1) {
1772  /* Just connected, so send the data */
1773  coap_session_connected(c_session);
1774  } else {
1775  if (ssl_data->pdu_len) {
1776  /* Do the handshake again incase of internal timeout */
1777  ret = do_mbedtls_handshake(c_session, m_env);
1778  if (ret == 1) {
1779  /* Just connected, so send the data */
1780  coap_session_connected(c_session);
1781  } else {
1782  ret = -1;
1783  }
1784  }
1785  ret = -1;
1786  }
1787  }
1788  if (c_session->dtls_event >= 0) {
1789  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1790  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1791  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1792  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1793  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1795  ssl_data = NULL;
1796  ret = -1;
1797  }
1798  }
1799 finish:
1800  if (ssl_data && ssl_data->pdu_len) {
1801  /* pdu data is held on stack which will not stay there */
1802  coap_log(LOG_DEBUG, "coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
1803  ssl_data->pdu_len = 0;
1804  ssl_data->pdu = NULL;
1805  }
1806  return ret;
1807 }
1808 
1809 /*
1810  * return -1 failure
1811  * 0 not completed
1812  * 1 client hello seen
1813  */
1814 int coap_dtls_hello(coap_session_t *c_session,
1815  const uint8_t *data,
1816  size_t data_len)
1817 {
1818 #if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
1819  (void)c_session;
1820  (void)data;
1821  (void)data_len;
1822  coap_log(LOG_EMERG, "coap_dtls_hello:"
1823  " libcoap not compiled for DTLS or Server Mode for MbedTLS"
1824  " - update MbedTLS to include DTLS and Server Mode\n");
1825  return -1;
1826 #else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
1827  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1828  coap_ssl_t *ssl_data;
1829  int ret;
1830 
1831  if (!m_env) {
1832  m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER);
1833  if (m_env) {
1834  c_session->tls = m_env;
1835  }
1836  else {
1837  /* error should have already been reported */
1838  return -1;
1839  }
1840  }
1841 
1842  if((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
1843  (unsigned char *)&c_session->addr_info.remote,
1844  sizeof(c_session->addr_info.remote))) != 0) {
1845  coap_log(LOG_ERR,
1846  "mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
1847  -ret, get_error_string(ret));
1848  return -1;
1849  }
1850 
1851  ssl_data = &m_env->coap_ssl_data;
1852  if (ssl_data->pdu_len) {
1853  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
1854  coap_session_str(c_session), ssl_data->pdu_len);
1855  }
1856  ssl_data->pdu = data;
1857  ssl_data->pdu_len = (unsigned)data_len;
1858 
1859  ret = do_mbedtls_handshake(c_session, m_env);
1860  if (ret == 0 || m_env->seen_client_hello) {
1861  /* The test for seen_client_hello gives the ability to setup a new
1862  c_session to continue the do_mbedtls_handshake past the client hello
1863  and safely allow updating of the m_env and separately
1864  letting a new session cleanly start up.
1865  */
1866  m_env->seen_client_hello = 0;
1867  ret = 1;
1868  }
1869  else {
1870  ret = 0;
1871  }
1872 
1873  if (ssl_data && ssl_data->pdu_len) {
1874  /* pdu data is held on stack which will not stay there */
1875  coap_log(LOG_DEBUG, "coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
1876  ssl_data->pdu_len = 0;
1877  ssl_data->pdu = NULL;
1878  }
1879  return ret;
1880 #endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
1881 }
1882 
1883 unsigned int coap_dtls_get_overhead(coap_session_t *c_session)
1884 {
1885  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1886  int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
1887 
1888  if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
1889  return 13 + 8 + 8;
1890  }
1891  return expansion;
1892 }
1893 
1894 #if !COAP_DISABLE_TCP
1895 void *coap_tls_new_client_session(coap_session_t *c_session UNUSED, int *connected UNUSED)
1896 {
1897  return NULL;
1898 }
1899 
1900 void *coap_tls_new_server_session(coap_session_t *c_session UNUSED, int *connected UNUSED)
1901 {
1902  return NULL;
1903 }
1904 
1906 {
1907 }
1908 
1909 ssize_t coap_tls_write(coap_session_t *c_session UNUSED,
1910  const uint8_t *data UNUSED,
1911  size_t data_len UNUSED
1912  )
1913 {
1914  return 0;
1915 }
1916 
1917 ssize_t coap_tls_read(coap_session_t *c_session UNUSED,
1918  uint8_t *data UNUSED,
1919  size_t data_len UNUSED
1920  )
1921 {
1922  return 0;
1923 }
1924 #endif /* !COAP_DISABLE_TCP */
1925 
1926 void coap_dtls_startup(void)
1927 {
1928 }
1929 
1930 void coap_dtls_shutdown(void) {
1931 }
1932 
1933 static int keep_log_level = 0;
1934 
1935 void coap_dtls_set_log_level(int level)
1936 {
1937 #if !defined(ESPIDF_VERSION)
1938  int use_level;
1939  /*
1940  * MbedTLS debug levels filter
1941  * 0 No debug
1942  * 1 Error
1943  * 2 State change
1944  * 3 Informational
1945  * 4 Verbose
1946  */
1947 
1948  if (level <= LOG_ERR) {
1949  use_level = 1;
1950  }
1951  else {
1952  use_level = (level >= LOG_DEBUG) ? level - LOG_DEBUG + 2 : 0;
1953  }
1954  mbedtls_debug_set_threshold(use_level);
1955 #endif /* !ESPIDF_VERSION) */
1956  keep_log_level = level;
1957 }
1958 
1959 int coap_dtls_get_log_level(void)
1960 {
1961  return keep_log_level;
1962 }
1963 
1965 {
1966  static coap_tls_version_t version;
1967  version.version = mbedtls_version_get_number();
1968  version.built_version = MBEDTLS_VERSION_NUMBER;
1969  version.type = COAP_TLS_LIBRARY_MBEDTLS;
1970  return &version;
1971 }
1972 
1974 coap_digest_setup(void) {
1975  mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
1976 
1977  if (digest_ctx) {
1978  mbedtls_sha256_init(digest_ctx);
1979  mbedtls_sha256_starts_ret(digest_ctx, 0);
1980  }
1981  return digest_ctx;
1982 }
1983 
1984 void
1985 coap_digest_free(coap_digest_ctx_t *digest_ctx) {
1986  mbedtls_sha256_free(digest_ctx);
1987  mbedtls_free(digest_ctx);
1988 }
1989 
1990 int
1992  const uint8_t *data,
1993  size_t data_len) {
1994  int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
1995 
1996  return ret == 0;
1997 }
1998 
1999 int
2001  coap_digest_t *digest_buffer) {
2002  int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t*)digest_buffer);
2003 
2004  coap_digest_free(digest_ctx);
2005  return ret == 0;
2006 }
2007 
2008 #else /* !HAVE_MBEDTLS */
2009 
2010 #ifdef __clang__
2011 /* Make compilers happy that do not like empty modules. As this function is
2012  * never used, we ignore -Wunused-function at the end of compiling this file
2013  */
2014 #pragma GCC diagnostic ignored "-Wunused-function"
2015 #endif
2016 static inline void dummy(void) {
2017 }
2018 
2019 #endif /* HAVE_MBEDTLS */
void coap_dtls_free_context(struct coap_dtls_context_t *dtls_context)
Releases the storage allocated for dtls_context.
int coap_dtls_send(struct coap_context_t *coap_context, struct coap_dtls_session_t *session, const coap_pdu_t *pdu)
void coap_dtls_free_session(struct coap_dtls_context_t *dtls_context, struct coap_dtls_session_t *session)
#define UNUSED
Pulls together all the internal only header files.
#define COAP_RXBUFFER_SIZE
Definition: coap_io.h:22
@ COAP_NACK_TLS_FAILED
Definition: coap_io.h:218
static void dummy(void)
int coap_dtls_context_set_pki_root_cas(struct coap_context_t *ctx UNUSED, const char *ca_file UNUSED, const char *ca_path UNUSED)
Definition: coap_notls.c:47
int coap_dtls_context_set_pki(coap_context_t *ctx UNUSED, const coap_dtls_pki_t *setup_data UNUSED, const coap_dtls_role_t role UNUSED)
Definition: coap_notls.c:39
void * coap_dtls_new_client_session(coap_session_t *session UNUSED)
Definition: coap_notls.c:105
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context UNUSED)
Definition: coap_notls.c:127
void * coap_tls_new_client_session(coap_session_t *session UNUSED, int *connected UNUSED)
Definition: coap_notls.c:159
int coap_dtls_receive(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:140
int coap_dtls_hello(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:148
void * coap_tls_new_server_session(coap_session_t *session UNUSED, int *connected UNUSED)
Definition: coap_notls.c:163
int coap_dtls_context_set_cpsk(coap_context_t *ctx UNUSED, coap_dtls_cpsk_t *setup_data UNUSED)
Definition: coap_notls.c:55
void * coap_dtls_new_server_session(coap_session_t *session UNUSED)
Definition: coap_notls.c:101
ssize_t coap_tls_read(coap_session_t *session UNUSED, uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:177
int coap_dtls_context_set_spsk(coap_context_t *ctx UNUSED, coap_dtls_spsk_t *setup_data UNUSED)
Definition: coap_notls.c:62
coap_tick_t coap_dtls_get_timeout(coap_session_t *session UNUSED, coap_tick_t now UNUSED)
Definition: coap_notls.c:132
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx UNUSED)
Definition: coap_notls.c:69
void coap_tls_free_session(coap_session_t *coap_session UNUSED)
Definition: coap_notls.c:167
void coap_dtls_session_update_mtu(coap_session_t *session UNUSED)
Definition: coap_notls.c:112
void coap_dtls_handle_timeout(coap_session_t *session UNUSED)
Definition: coap_notls.c:136
unsigned int coap_dtls_get_overhead(coap_session_t *session UNUSED)
Definition: coap_notls.c:155
ssize_t coap_tls_write(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:170
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Definition: coap_session.c:937
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:242
int coap_session_refresh_psk_key(coap_session_t *session, const coap_bin_const_t *psk_key)
Definition: coap_session.c:966
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
Definition: coap_session.c:363
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:420
#define COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:56
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
Definition: coap_notls.c:201
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
Definition: coap_notls.c:190
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.
Definition: coap_notls.c:218
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.
Definition: coap_notls.c:206
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:120
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:76
coap_dtls_role_t
Definition: coap_dtls.h:481
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition: coap_notls.c:123
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition: coap_notls.c:79
struct coap_dtls_context_t * coap_dtls_new_context(struct coap_context_t *coap_context)
Creates a new DTLS context for the given coap_context.
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:483
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition: coap_dtls.h:482
#define COAP_DTLS_RETRANSMIT_MS
Definition: coap_dtls.h:29
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition: coap_notls.c:26
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:31
int coap_dtls_is_supported(void)
Returns 1 if support for DTLS is enabled, or 0 otherwise.
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
Definition: coap_dtls.h:35
#define COAP_DTLS_RETRANSMIT_TOTAL_MS
Definition: coap_dtls.h:32
@ COAP_PKI_KEY_PKCS11
The PKI key type is PKCS11 (DER)
Definition: coap_dtls.h:153
@ COAP_PKI_KEY_PEM_BUF
The PKI key type is PEM buffer.
Definition: coap_dtls.h:152
@ COAP_PKI_KEY_PEM
The PKI key type is PEM file.
Definition: coap_dtls.h:150
@ COAP_PKI_KEY_ASN1
The PKI key type is ASN.1 (DER) buffer.
Definition: coap_dtls.h:151
@ COAP_TLS_LIBRARY_MBEDTLS
Using MbedTLS library.
Definition: coap_dtls.h:58
#define COAP_EVENT_DTLS_ERROR
Definition: coap_event.h:33
#define COAP_EVENT_DTLS_CLOSED
(D)TLS events for COAP_PROTO_DTLS and COAP_PROTO_TLS
Definition: coap_event.h:30
#define COAP_EVENT_DTLS_CONNECTED
Definition: coap_event.h:31
void coap_dtls_set_log_level(int level)
Sets the log level to the specified value.
const char * coap_session_str(const coap_session_t *session)
Get session description.
int coap_dtls_get_log_level(void)
Returns the current log level.
#define coap_log(level,...)
Logging function.
Definition: coap_debug.h:150
@ LOG_ERR
Error.
Definition: coap_debug.h:53
@ LOG_INFO
Information.
Definition: coap_debug.h:56
@ LOG_WARNING
Warning.
Definition: coap_debug.h:54
@ LOG_DEBUG
Debug.
Definition: coap_debug.h:57
@ COAP_LOG_CIPHERS
CipherInfo.
Definition: coap_debug.h:58
@ LOG_EMERG
Emergency.
Definition: coap_debug.h:50
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:1749
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:2884
#define COAP_PROTO_TLS
Definition: pdu.h:347
#define COAP_PROTO_DTLS
Definition: pdu.h:345
coap_address_t remote
remote address and port
Definition: coap_io.h:49
CoAP binary data definition with const data.
Definition: str.h:56
size_t length
length of binary data
Definition: str.h:57
const uint8_t * s
read-only binary data
Definition: str.h:58
The CoAP stack's global state is stored in a coap_context_t object.
Definition: net.h:141
size_t(* get_server_psk)(const coap_session_t *session, const uint8_t *identity, size_t identity_len, uint8_t *psk, size_t max_psk_len)
Definition: net.h:192
void * dtls_context
Definition: net.h:195
size_t(* get_client_psk)(const coap_session_t *session, const uint8_t *hint, size_t hint_len, uint8_t *identity, size_t *identity_len, size_t max_identity_len, uint8_t *psk, size_t max_psk_len)
Definition: net.h:191
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
Definition: net.h:197
The structure used for defining the Client PSK setup data to be used.
Definition: coap_dtls.h:339
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition: coap_dtls.h:363
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition: coap_dtls.h:359
The structure that holds the PKI key information.
Definition: coap_dtls.h:213
coap_pki_key_pem_t pem
for PEM file keys
Definition: coap_dtls.h:216
union coap_dtls_key_t::@1 key
coap_pki_key_pem_buf_t pem_buf
for PEM memory keys
Definition: coap_dtls.h:217
coap_pki_key_t key_type
key format type
Definition: coap_dtls.h:214
coap_pki_key_asn1_t asn1
for ASN.1 (DER) memory keys
Definition: coap_dtls.h:218
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:245
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition: coap_dtls.h:250
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition: coap_dtls.h:263
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:251
coap_dtls_key_t pki_key
PKI key definition.
Definition: coap_dtls.h:302
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:375
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:426
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition: coap_dtls.h:453
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition: coap_dtls.h:445
void * id_call_back_arg
Passed in to the Identity callback function.
Definition: coap_dtls.h:446
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition: coap_dtls.h:454
const uint8_t * private_key
ASN1 (DER) Private Key.
Definition: coap_dtls.h:191
size_t public_cert_len
ASN1 Public Cert length.
Definition: coap_dtls.h:193
size_t private_key_len
ASN1 Private Key length.
Definition: coap_dtls.h:194
const uint8_t * ca_cert
ASN1 (DER) Common CA Cert.
Definition: coap_dtls.h:189
size_t ca_cert_len
ASN1 CA Cert length.
Definition: coap_dtls.h:192
const uint8_t * public_cert
ASN1 (DER) Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:190
size_t ca_cert_len
PEM buffer CA Cert length.
Definition: coap_dtls.h:180
const uint8_t * ca_cert
PEM buffer Common CA Cert.
Definition: coap_dtls.h:175
size_t private_key_len
PEM buffer Private Key length.
Definition: coap_dtls.h:182
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:177
size_t public_cert_len
PEM buffer Public Cert length.
Definition: coap_dtls.h:181
const uint8_t * public_cert
PEM buffer Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:176
const char * ca_file
File location of Common CA in PEM format.
Definition: coap_dtls.h:160
const char * public_cert
File location of Public Cert.
Definition: coap_dtls.h:161
const char * private_key
File location of Private Key in PEM format.
Definition: coap_dtls.h:162
unsigned int dtls_timeout_count
dtls setup retry counter
Definition: coap_session.h:122
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
Definition: coap_session.h:100
unsigned int max_retransmit
maximum re-transmit count (default 4)
Definition: coap_session.h:119
coap_session_state_t state
current state of relationaship with peer
Definition: coap_session.h:63
coap_addr_tuple_t addr_info
key: remote/local address info
Definition: coap_session.h:69
coap_proto_t proto
protocol used
Definition: coap_session.h:61
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
Definition: coap_session.h:89
struct coap_context_t * context
session's context
Definition: coap_session.h:73
int dtls_event
Tracking any (D)TLS events on this sesison.
Definition: coap_session.h:123
void * tls
security parameters
Definition: coap_session.h:74
uint64_t mtu
path or CSM mtu
Definition: coap_session.h:66
The structure used for returning the underlying (D)TLS library information.
Definition: coap_dtls.h:65
uint64_t built_version
(D)TLS Built against Library Version
Definition: coap_dtls.h:68
coap_tls_library_t type
Library type.
Definition: coap_dtls.h:67
uint64_t version
(D)TLS runtime Library Version
Definition: coap_dtls.h:66
unsigned int uint32_t
Definition: uthash.h:78
unsigned char uint8_t
Definition: uthash.h:79