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