libcoap  4.3.0rc3
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 "coap3/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 = (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 = (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);
241  coap_session_refresh_psk_key(c_session, psk_key);
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  pki_sni_entry *pki_sni_entry_list;
764 
765  new_entry =
766  m_context->setup_data.validate_sni_call_back(name,
767  m_context->setup_data.sni_call_back_arg);
768  if (!new_entry) {
769  mbedtls_free(name);
770  return -1;
771  }
772 
773  pki_sni_entry_list = mbedtls_realloc(m_context->pki_sni_entry_list,
774  (i+1)*sizeof(pki_sni_entry));
775 
776  if (pki_sni_entry_list == NULL) {
777  mbedtls_free(name);
778  return -1;
779  }
780  m_context->pki_sni_entry_list = pki_sni_entry_list;
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  psk_sni_entry *psk_sni_entry_list;
844 
845  new_entry =
847  c_session,
849  if (!new_entry) {
850  mbedtls_free(name);
851  return -1;
852  }
853 
854  psk_sni_entry_list = mbedtls_realloc(m_context->psk_sni_entry_list,
855  (i+1)*sizeof(psk_sni_entry));
856 
857  if (psk_sni_entry_list == NULL) {
858  mbedtls_free(name);
859  return -1;
860  }
861  m_context->psk_sni_entry_list = psk_sni_entry_list;
862  m_context->psk_sni_entry_list[i].sni = name;
863  m_context->psk_sni_entry_list[i].psk_info = *new_entry;
864  /* name has been absorbed into psk_sni_entry_list[].sni entry */
865  m_context->psk_sni_count++;
866  }
867  else {
868  mbedtls_free(name);
869  }
870 
872  &m_context->psk_sni_entry_list[i].psk_info.hint);
874  &m_context->psk_sni_entry_list[i].psk_info.key);
875  return mbedtls_ssl_set_hs_psk(ssl,
876  m_context->psk_sni_entry_list[i].psk_info.key.s,
877  m_context->psk_sni_entry_list[i].psk_info.key.length);
878 }
879 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
880 
881 static int setup_server_ssl_session(coap_session_t *c_session,
882  coap_mbedtls_env_t *m_env)
883 {
884  coap_mbedtls_context_t *m_context =
885  (coap_mbedtls_context_t *)c_session->context->dtls_context;
886  int ret = 0;
887  m_context->psk_pki_enabled |= IS_SERVER;
888 
889  mbedtls_ssl_cookie_init(&m_env->cookie_ctx);
890  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
891  MBEDTLS_SSL_IS_SERVER,
892  c_session->proto == COAP_PROTO_DTLS ?
893  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
894  MBEDTLS_SSL_TRANSPORT_STREAM,
895  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
896  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
897  -ret, get_error_string(ret));
898  goto fail;
899  }
900 
901  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
902 
903 #if defined(MBEDTLS_SSL_PROTO_DTLS)
904  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
906 
907  if (m_context->psk_pki_enabled & IS_PSK) {
908 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
909  mbedtls_ssl_conf_psk_cb(&m_env->conf, psk_server_callback, c_session);
911  mbedtls_ssl_conf_sni(&m_env->conf, psk_sni_callback, c_session);
912  }
913 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
914  coap_log(LOG_WARNING, "PSK not enabled in Mbed TLS library\n");
915 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
916  }
917 #endif /* MBEDTLS_SSL_PROTO_DTLS */
918 
919  if (m_context->psk_pki_enabled & IS_PKI) {
920  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
921  &m_env->private_key, m_env, m_context,
922  c_session, &m_context->setup_data,
924  if (ret < 0) {
925  coap_log(LOG_ERR, "PKI setup failed\n");
926  return ret;
927  }
928  if (m_context->setup_data.validate_sni_call_back) {
929  mbedtls_ssl_conf_sni(&m_env->conf, pki_sni_callback, c_session);
930  }
931  }
932 
933  if ((ret = mbedtls_ssl_cookie_setup(&m_env->cookie_ctx,
934  mbedtls_ctr_drbg_random,
935  &m_env->ctr_drbg)) != 0) {
936  coap_log(LOG_ERR, "mbedtls_ssl_cookie_setup: returned -0x%x: '%s'\n",
937  -ret, get_error_string(ret));
938  goto fail;
939  }
940 
941 #if defined(MBEDTLS_SSL_PROTO_DTLS)
942  mbedtls_ssl_conf_dtls_cookies(&m_env->conf, mbedtls_ssl_cookie_write,
943  mbedtls_ssl_cookie_check,
944  &m_env->cookie_ctx );
945 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
946  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
947 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
948 #endif /* MBEDTLS_SSL_PROTO_DTLS */
949 fail:
950  return ret;
951 }
952 #endif /* MBEDTLS_SSL_SRV_C */
953 
954 static int *psk_ciphers = NULL;
955 static int *pki_ciphers = NULL;
956 static int processed_ciphers = 0;
957 
958 static void
959 set_ciphersuites(mbedtls_ssl_config *conf, coap_enc_method_t method)
960 {
961  if (!processed_ciphers) {
962  const int *list = mbedtls_ssl_list_ciphersuites();
963  const int *base = list;
964  int *psk_list;
965  int *pki_list;
966  int psk_count = 1; /* account for empty terminator */
967  int pki_count = 1;
968 
969  while (*list) {
970  const mbedtls_ssl_ciphersuite_t *cur =
971  mbedtls_ssl_ciphersuite_from_id(*list);
972 
973  if (cur) {
974  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
975  /* Minimum of TLS1.2 required - skip */
976  }
977  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
978  psk_count++;
979  }
980  else {
981  pki_count++;
982  }
983  }
984  list++;
985  }
986  list = base;
987 
988  psk_ciphers = mbedtls_malloc(psk_count * sizeof(psk_ciphers[0]));
989  if (psk_ciphers == NULL) {
990  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", psk_count);
991  return;
992  }
993  pki_ciphers = mbedtls_malloc(pki_count * sizeof(pki_ciphers[0]));
994  if (pki_ciphers == NULL) {
995  coap_log(LOG_ERR, "set_ciphers: mbedtls_malloc with count %d failed\n", pki_count);
996  return;
997  }
998 
999  psk_list = psk_ciphers;
1000  pki_list = pki_ciphers;
1001 
1002  while (*list) {
1003  const mbedtls_ssl_ciphersuite_t *cur =
1004  mbedtls_ssl_ciphersuite_from_id(*list);
1005  if (cur) {
1006  if (cur->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1007  /* Minimum of TLS1.2 required - skip */
1008  }
1009  else if (mbedtls_ssl_ciphersuite_uses_psk(cur)) {
1010  *psk_list = *list;
1011  psk_list++;
1012  }
1013  else {
1014  *pki_list = *list;
1015  pki_list++;
1016  }
1017  }
1018  list++;
1019  }
1020  /* zero terminate */
1021  *psk_list = 0;
1022  *pki_list = 0;
1023  processed_ciphers = 1;
1024  }
1025  mbedtls_ssl_conf_ciphersuites(conf, method == COAP_ENC_PSK ? psk_ciphers : pki_ciphers);
1026 }
1027 
1028 static int setup_client_ssl_session(coap_session_t *c_session,
1029  coap_mbedtls_env_t *m_env)
1030 {
1031  int ret;
1032 
1033  coap_mbedtls_context_t *m_context =
1034  (coap_mbedtls_context_t *)c_session->context->dtls_context;
1035 
1036  m_context->psk_pki_enabled |= IS_CLIENT;
1037 
1038  if ((ret = mbedtls_ssl_config_defaults(&m_env->conf,
1039  MBEDTLS_SSL_IS_CLIENT,
1040  c_session->proto == COAP_PROTO_DTLS ?
1041  MBEDTLS_SSL_TRANSPORT_DATAGRAM :
1042  MBEDTLS_SSL_TRANSPORT_STREAM,
1043  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
1044  coap_log(LOG_ERR, "mbedtls_ssl_config_defaults returned -0x%x: '%s'\n",
1045  -ret, get_error_string(ret));
1046  goto fail;
1047  }
1048 
1049 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1050  mbedtls_ssl_conf_handshake_timeout(&m_env->conf, COAP_DTLS_RETRANSMIT_MS,
1052 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1053 
1054  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
1055  mbedtls_ssl_conf_rng(&m_env->conf, mbedtls_ctr_drbg_random, &m_env->ctr_drbg);
1056 
1057  if (m_context->psk_pki_enabled & IS_PSK) {
1058 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1059  uint8_t identity[64];
1060  size_t identity_len;
1061  uint8_t psk_key[64];
1062  size_t psk_len;
1063  size_t max_identity_len = sizeof(identity);
1064 
1065  coap_log(LOG_INFO, "Setting PSK key\n");
1066  psk_len = c_session->context->get_client_psk(c_session,
1067  NULL,
1068  0,
1069  identity,
1070  &identity_len,
1071  max_identity_len,
1072  psk_key,
1073  sizeof(psk_key));
1074  assert(identity_len <= sizeof(identity));
1075  mbedtls_ssl_conf_psk(&m_env->conf, (const unsigned char *)psk_key,
1076  psk_len, (const unsigned char *)identity,
1077  identity_len);
1078  if (c_session->cpsk_setup_data.client_sni) {
1079  mbedtls_ssl_set_hostname(&m_env->ssl,
1080  c_session->cpsk_setup_data.client_sni);
1081  }
1082  /* Identity Hint currently not supported in Mbed TLS so code removed */
1083 
1084  set_ciphersuites(&m_env->conf, COAP_ENC_PSK);
1085 #else /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1086  coap_log(LOG_WARNING, "PSK not enabled in Mbed TLS library\n");
1087 #endif /* ! MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1088  }
1089  else if ((m_context->psk_pki_enabled & IS_PKI) ||
1090  (m_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1091  /*
1092  * If neither PSK or PKI have been set up, use PKI basics.
1093  * This works providing COAP_PKI_KEY_PEM has a value of 0.
1094  */
1095  mbedtls_ssl_conf_authmode(&m_env->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
1096  ret = setup_pki_credentials(&m_env->cacert, &m_env->public_cert,
1097  &m_env->private_key, m_env, m_context,
1098  c_session, &m_context->setup_data,
1100  if (ret < 0) {
1101  coap_log(LOG_ERR, "PKI setup failed\n");
1102  return ret;
1103  }
1104 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_ALPN)
1105  if (c_session->proto == COAP_PROTO_TLS) {
1106  const char *alpn_list[] = { "coap", NULL };
1107 
1108  ret = mbedtls_ssl_conf_alpn_protocols(&m_env->conf, alpn_list);
1109  if (ret != 0) {
1110  coap_log(LOG_ERR, "ALPN setup failed %d)\n", ret);
1111  }
1112  }
1113 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_ALPN */
1114  if (m_context->setup_data.client_sni) {
1115  mbedtls_ssl_set_hostname(&m_env->ssl, m_context->setup_data.client_sni);
1116  }
1117 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1118 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1119  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1120 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1121 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1122  set_ciphersuites(&m_env->conf, COAP_ENC_PKI);
1123  }
1124  return 0;
1125 
1126 fail:
1127  return ret;
1128 }
1129 
1130 static void mbedtls_cleanup(coap_mbedtls_env_t *m_env)
1131 {
1132  if (!m_env) {
1133  return;
1134  }
1135 
1136  mbedtls_x509_crt_free(&m_env->cacert);
1137  mbedtls_x509_crt_free(&m_env->public_cert);
1138  mbedtls_pk_free(&m_env->private_key);
1139  mbedtls_entropy_free(&m_env->entropy);
1140  mbedtls_ssl_config_free(&m_env->conf);
1141  mbedtls_ctr_drbg_free(&m_env->ctr_drbg);
1142  mbedtls_ssl_free(&m_env->ssl);
1143  mbedtls_ssl_cookie_free(&m_env->cookie_ctx);
1144 }
1145 
1146 static void
1147 coap_dtls_free_mbedtls_env(coap_mbedtls_env_t *m_env) {
1148  if (m_env) {
1149  mbedtls_cleanup(m_env);
1150  mbedtls_free(m_env);
1151  }
1152 }
1153 
1154 static const char *
1155 report_mbedtls_alert(unsigned char alert) {
1156  switch (alert) {
1157  case MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC: return ": Bad Record MAC";
1158  case MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE: return ": Handshake failure";
1159  case MBEDTLS_SSL_ALERT_MSG_NO_CERT: return ": No Certificate provided";
1160  case MBEDTLS_SSL_ALERT_MSG_BAD_CERT: return ": Certificate is bad";
1161  case MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA: return ": CA is unknown";
1162  case MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED: return ": Access was denied";
1163  case MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR: return ": Decrypt error";
1164  default: return "";
1165  }
1166 }
1167 
1168 /*
1169  * return -1 failure
1170  * 0 not completed
1171  * 1 established
1172  */
1173 static int do_mbedtls_handshake(coap_session_t *c_session,
1174  coap_mbedtls_env_t *m_env) {
1175  int ret;
1176  int alert;
1177 
1178  ret = mbedtls_ssl_handshake(&m_env->ssl);
1179  switch (ret) {
1180  case 0:
1181  m_env->established = 1;
1182  coap_log(LOG_DEBUG, "* %s: Mbed TLS established\n",
1183  coap_session_str(c_session));
1184  ret = 1;
1185  break;
1186  case MBEDTLS_ERR_SSL_WANT_READ:
1187  case MBEDTLS_ERR_SSL_WANT_WRITE:
1188  errno = EAGAIN;
1189  ret = 0;
1190  break;
1191  case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
1192  coap_log(LOG_DEBUG, "hello verification requested\n");
1193  goto reset;
1194  case MBEDTLS_ERR_SSL_INVALID_MAC:
1195  goto fail;
1196  case MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE:
1197  alert = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
1198  goto fail_alert;
1199  case MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO:
1200  alert = MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE;
1201  goto fail_alert;
1202  case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
1203  goto fail;
1204  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1205  if (m_env->ssl.in_msg[1] != MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY)
1206  coap_log(LOG_WARNING, "***%s: Alert '%d'%s\n",
1207  coap_session_str(c_session), m_env->ssl.in_msg[1],
1208  report_mbedtls_alert(m_env->ssl.in_msg[1]));
1209  /* Fall through */
1210  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1211  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1212  ret = -1;
1213  break;
1214  default:
1216  "do_mbedtls_handshake: session establish "
1217  "returned -0x%x: '%s'\n",
1218  -ret, get_error_string(ret));
1219  ret = -1;
1220  break;
1221  }
1222  return ret;
1223 
1224 fail_alert:
1225  mbedtls_ssl_send_alert_message(&m_env->ssl,
1226  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1227  alert);
1228 fail:
1229  c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
1231  "do_mbedtls_handshake: session establish "
1232  "returned '%s'\n",
1233  get_error_string(ret));
1234 reset:
1235  mbedtls_ssl_session_reset(&m_env->ssl);
1236  return -1;
1237 }
1238 
1239 static void
1240 mbedtls_debug_out(void *ctx COAP_UNUSED, int level,
1241  const char *file, int line, const char *str) {
1242  int log_level;
1243  /*
1244  * 0 No debug
1245  * 1 Error
1246  * 2 State change
1247  * 3 Informational
1248  * 4 Verbose
1249  */
1250  switch (level) {
1251  case 4:
1252  case 3:
1253  case 2:
1254  log_level = COAP_LOG_CIPHERS;
1255  break;
1256  case 1:
1257  log_level = LOG_ERR;
1258  break;
1259  case 0:
1260  default:
1261  log_level = 0;
1262  break;
1263  }
1264  coap_log(log_level, "%s:%04d: %s", file, line, str);
1265 }
1266 
1267 static coap_mbedtls_env_t *coap_dtls_new_mbedtls_env(coap_session_t *c_session,
1268  coap_dtls_role_t role)
1269 {
1270  int ret = 0;
1271  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1272 
1273  if (m_env)
1274  return m_env;
1275 
1276  m_env = (coap_mbedtls_env_t *)mbedtls_malloc(sizeof(coap_mbedtls_env_t));
1277  if (!m_env) {
1278  return NULL;
1279  }
1280  memset(m_env, 0, sizeof(coap_mbedtls_env_t));
1281 
1282  mbedtls_ssl_init(&m_env->ssl);
1283  mbedtls_ctr_drbg_init(&m_env->ctr_drbg);
1284  mbedtls_ssl_config_init(&m_env->conf);
1285  mbedtls_entropy_init(&m_env->entropy);
1286 
1287 #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG)
1288  mbedtls_esp_enable_debug_log(&m_env->conf, CONFIG_MBEDTLS_DEBUG_LEVEL);
1289 #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */
1290  if ((ret = mbedtls_ctr_drbg_seed(&m_env->ctr_drbg,
1291  mbedtls_entropy_func, &m_env->entropy, NULL, 0)) != 0) {
1292  coap_log(LOG_ERR, "mbedtls_ctr_drbg_seed returned -0x%x: '%s'\n",
1293  -ret, get_error_string(ret));
1294  goto fail;
1295  }
1296 
1297  if (role == COAP_DTLS_ROLE_CLIENT) {
1298  if (setup_client_ssl_session(c_session, m_env) != 0) {
1299  goto fail;
1300  }
1301 #if defined(MBEDTLS_SSL_SRV_C)
1302  } else if (role == COAP_DTLS_ROLE_SERVER) {
1303  if (setup_server_ssl_session(c_session, m_env) != 0) {
1304  goto fail;
1305  }
1306 #endif /* MBEDTLS_SSL_SRV_C */
1307  } else {
1308  goto fail;
1309  }
1310 
1311  mbedtls_ssl_conf_min_version(&m_env->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
1312  MBEDTLS_SSL_MINOR_VERSION_3);
1313 
1314  if ((ret = mbedtls_ssl_setup(&m_env->ssl, &m_env->conf)) != 0) {
1315  goto fail;
1316  }
1317  mbedtls_ssl_set_bio(&m_env->ssl, c_session, coap_dgram_write,
1318  coap_dgram_read, NULL);
1319  mbedtls_ssl_set_timer_cb(&m_env->ssl, &m_env->timer,
1320  mbedtls_timing_set_delay,
1321  mbedtls_timing_get_delay);
1322 
1323  mbedtls_ssl_conf_dbg(&m_env->conf, mbedtls_debug_out, stdout);
1324  return m_env;
1325 
1326 fail:
1327  if (m_env) {
1328  mbedtls_free(m_env);
1329  }
1330  return NULL;
1331 }
1332 
1333 int coap_dtls_is_supported(void) {
1334 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1335  return 1;
1336 #else /* !MBEDTLS_SSL_PROTO_DTLS */
1338  "libcoap not compiled for DTLS with Mbed TLS"
1339  " - update Mbed TLS to include DTLS\n");
1340  return 0;
1341 #endif /* !MBEDTLS_SSL_PROTO_DTLS */
1342 }
1343 
1344 int coap_tls_is_supported(void)
1345 {
1346  return 0;
1347 }
1348 
1349 void *coap_dtls_new_context(coap_context_t *c_context)
1350 {
1351  coap_mbedtls_context_t *m_context;
1352  (void)c_context;
1353 
1354  m_context = (coap_mbedtls_context_t *)mbedtls_malloc(sizeof(coap_mbedtls_context_t));
1355  if (m_context) {
1356  memset(m_context, 0, sizeof(coap_mbedtls_context_t));
1357  }
1358  return m_context;
1359 }
1360 
1361 /*
1362  * return 0 failed
1363  * 1 passed
1364  */
1365 int
1367  coap_dtls_spsk_t *setup_data
1368 ) {
1369  coap_mbedtls_context_t *m_context =
1370  ((coap_mbedtls_context_t *)c_context->dtls_context);
1371 
1372 #if !defined(MBEDTLS_SSL_SRV_C)
1373  coap_log(LOG_EMERG, "coap_context_set_spsk:"
1374  " libcoap not compiled for Server Mode for Mbed TLS"
1375  " - update Mbed TLS to include Server Mode\n");
1376  return 0;
1377 #endif /* !MBEDTLS_SSL_SRV_C */
1378  if (!m_context || !setup_data)
1379  return 0;
1380 
1381  m_context->psk_pki_enabled |= IS_PSK;
1382  return 1;
1383 }
1384 
1385 /*
1386  * return 0 failed
1387  * 1 passed
1388  */
1389 int
1391  coap_dtls_cpsk_t *setup_data
1392 ) {
1393 #if !defined(MBEDTLS_SSL_CLI_C)
1394  coap_log(LOG_EMERG, "coap_context_set_spsk:"
1395  " libcoap not compiled for Client Mode for Mbed TLS"
1396  " - update Mbed TLS to include Client Mode\n");
1397  return 0;
1398 #endif /* !MBEDTLS_SSL_CLI_C */
1399  coap_mbedtls_context_t *m_context =
1400  ((coap_mbedtls_context_t *)c_context->dtls_context);
1401 
1402  if (!m_context || !setup_data)
1403  return 0;
1404 
1405  if (setup_data->validate_ih_call_back) {
1407  "CoAP Client with Mbed TLS does not support Identity Hint selection\n");
1408  }
1409  m_context->psk_pki_enabled |= IS_PSK;
1410  return 1;
1411 }
1412 
1414  const coap_dtls_pki_t *setup_data,
1415  const coap_dtls_role_t role COAP_UNUSED)
1416 {
1417  coap_mbedtls_context_t *m_context =
1418  ((coap_mbedtls_context_t *)c_context->dtls_context);
1419 
1420  m_context->setup_data = *setup_data;
1421  if (!m_context->setup_data.verify_peer_cert) {
1422  /* Needs to be clear so that no CA DNs are transmitted */
1423  m_context->setup_data.check_common_ca = 0;
1424  /* Allow all of these but warn if issue */
1425  m_context->setup_data.allow_self_signed = 1;
1426  m_context->setup_data.allow_expired_certs = 1;
1427  m_context->setup_data.cert_chain_validation = 1;
1428  m_context->setup_data.cert_chain_verify_depth = 10;
1429  m_context->setup_data.check_cert_revocation = 1;
1430  m_context->setup_data.allow_no_crl = 1;
1431  m_context->setup_data.allow_expired_crl = 1;
1432  m_context->setup_data.allow_bad_md_hash = 1;
1433  m_context->setup_data.allow_short_rsa_length = 1;
1434  }
1435  m_context->psk_pki_enabled |= IS_PKI;
1436  return 1;
1437 }
1438 
1440  const char *ca_file,
1441  const char *ca_path)
1442 {
1443  coap_mbedtls_context_t *m_context =
1444  ((coap_mbedtls_context_t *)c_context->dtls_context);
1445 
1446  if (!m_context) {
1448  "coap_context_set_pki_root_cas: (D)TLS environment "
1449  "not set up\n");
1450  return 0;
1451  }
1452 
1453  if (ca_file == NULL && ca_path == NULL) {
1455  "coap_context_set_pki_root_cas: ca_file and/or ca_path "
1456  "not defined\n");
1457  return 0;
1458  }
1459  if (m_context->root_ca_file) {
1460  mbedtls_free(m_context->root_ca_file);
1461  m_context->root_ca_file = NULL;
1462  }
1463 
1464  if (ca_file) {
1465  m_context->root_ca_file = mbedtls_strdup(ca_file);
1466  }
1467 
1468  if (m_context->root_ca_path) {
1469  mbedtls_free(m_context->root_ca_path);
1470  m_context->root_ca_path = NULL;
1471  }
1472 
1473  if (ca_path) {
1474  m_context->root_ca_path = mbedtls_strdup(ca_path);
1475  }
1476  return 1;
1477 }
1478 
1480 {
1481  coap_mbedtls_context_t *m_context =
1482  ((coap_mbedtls_context_t *)c_context->dtls_context);
1483  return m_context->psk_pki_enabled ? 1 : 0;
1484 }
1485 
1486 void coap_dtls_free_context(void *dtls_context)
1487 {
1488  coap_mbedtls_context_t *m_context = (coap_mbedtls_context_t *)dtls_context;
1489  unsigned int i;
1490 
1491  for (i = 0; i < m_context->pki_sni_count; i++) {
1492  mbedtls_free(m_context->pki_sni_entry_list[i].sni);
1493 
1494  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].public_cert);
1495 
1496  mbedtls_pk_free(&m_context->pki_sni_entry_list[i].private_key);
1497 
1498  mbedtls_x509_crt_free(&m_context->pki_sni_entry_list[i].cacert);
1499  }
1500  if (m_context->pki_sni_entry_list)
1501  mbedtls_free(m_context->pki_sni_entry_list);
1502 
1503  for (i = 0; i < m_context->psk_sni_count; i++) {
1504  mbedtls_free(m_context->psk_sni_entry_list[i].sni);
1505  }
1506  if (m_context->psk_sni_entry_list)
1507  mbedtls_free(m_context->psk_sni_entry_list);
1508 
1509  if (m_context->root_ca_path)
1510  mbedtls_free(m_context->root_ca_path);
1511  if (m_context->root_ca_file)
1512  mbedtls_free(m_context->root_ca_file);
1513 
1514  mbedtls_free(m_context);
1515 }
1516 
1518 {
1519 #if !defined(MBEDTLS_SSL_CLI_C)
1520  (void)c_session;
1521  coap_log(LOG_EMERG, "coap_dtls_new_client_session:"
1522  " libcoap not compiled for Client Mode for Mbed TLS"
1523  " - update Mbed TLS to include Client Mode\n");
1524  return NULL;
1525 #else /* MBEDTLS_SSL_CLI_C */
1526  coap_mbedtls_env_t *m_env = coap_dtls_new_mbedtls_env(c_session,
1528  int ret;
1529 
1530  if (m_env) {
1531  coap_tick_t now;
1532  coap_ticks(&now);
1533  m_env->last_timeout = now;
1534  ret = do_mbedtls_handshake(c_session, m_env);
1535  if (ret == -1) {
1536  coap_dtls_free_mbedtls_env(m_env);
1537  return NULL;
1538  }
1539  }
1540  return m_env;
1541 #endif /* MBEDTLS_SSL_CLI_C */
1542 }
1543 
1545 {
1546  coap_mbedtls_env_t *m_env =
1547  (coap_mbedtls_env_t *)c_session->tls;
1548  if (m_env) {
1549 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1550 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1551  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1552 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1553 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1554  }
1555  return m_env;
1556 }
1557 
1558 void coap_dtls_free_session(coap_session_t *c_session)
1559 {
1560  if (c_session && c_session->context && c_session->tls) {
1561  coap_dtls_free_mbedtls_env(c_session->tls);
1562  c_session->tls = NULL;
1563  coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session);
1564  }
1565  return;
1566 }
1567 
1569 {
1570 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1571  coap_mbedtls_env_t *m_env =
1572  (coap_mbedtls_env_t *)c_session->tls;
1573  if (m_env) {
1574 #if MBEDTLS_VERSION_NUMBER >= 0x02100100
1575  mbedtls_ssl_set_mtu(&m_env->ssl, (uint16_t)c_session->mtu);
1576 #endif /* MBEDTLS_VERSION_NUMBER >= 0x02100100 */
1577  }
1578 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1579 }
1580 
1581 int coap_dtls_send(coap_session_t *c_session,
1582  const uint8_t *data,
1583  size_t data_len)
1584 {
1585  int ret;
1586  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1587 
1588  assert(m_env != NULL);
1589 
1590  if (!m_env) {
1591  return -1;
1592  }
1593  c_session->dtls_event = -1;
1594  if (m_env->established) {
1595  ret = mbedtls_ssl_write(&m_env->ssl, (const unsigned char*) data, data_len);
1596  if (ret <= 0) {
1597  switch (ret) {
1598  case MBEDTLS_ERR_SSL_WANT_READ:
1599  case MBEDTLS_ERR_SSL_WANT_WRITE:
1600  ret = 0;
1601  break;
1602  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1603  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1604  ret = -1;
1605  break;
1606  default:
1608  "coap_dtls_send: "
1609  "returned -0x%x: '%s'\n",
1610  -ret, get_error_string(ret));
1611  ret = -1;
1612  break;
1613  }
1614  if (ret == -1) {
1615  coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n");
1616  }
1617  }
1618  } else {
1619  ret = do_mbedtls_handshake(c_session, m_env);
1620  if (ret == 1) {
1621  /* Just connected, so send the data */
1622  return coap_dtls_send(c_session, data, data_len);
1623  }
1624  ret = -1;
1625  }
1626 
1627  if (c_session->dtls_event >= 0) {
1628  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1629  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1630  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1631  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1632  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1634  ret = -1;
1635  }
1636  }
1637  return ret;
1638 }
1639 
1641 {
1642  return 0;
1643 }
1644 
1646 {
1647  return 0;
1648 }
1649 
1651 {
1652  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1653  int ret = mbedtls_timing_get_delay(&m_env->timer);
1654  unsigned int scalar = 1 << m_env->retry_scalar;
1655 
1656  assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1657  switch (ret) {
1658  case 0:
1659  /* int_ms has not timed out */
1660  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1661  /* Need to indicate remaining timeout time */
1662  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1663  }
1664  m_env->last_timeout = now;
1665  /* This may cause a minor extra delay */
1666  return now + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1667  case 1:
1668  /* int_ms has timed out, but not fin_ms */
1669  /*
1670  * Need to make sure that we do not do this too frequently
1671  */
1672  if (m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar > now) {
1673  return m_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS * scalar;
1674  }
1675 
1676  /* Reset for the next time */
1677  m_env->last_timeout = now;
1678  return now;
1679  case 2:
1680  /* fin_ms has timed out - timed out - one final try */
1681  return now;
1682  default:
1683  break;
1684  }
1685 
1686  return 0;
1687 }
1688 
1690 {
1691  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1692 
1693  assert(m_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
1694  m_env->retry_scalar++;
1695  if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
1696  (do_mbedtls_handshake(c_session, m_env) < 0)) {
1697  /* Too many retries */
1699  }
1700  return;
1701 }
1702 
1703 /*
1704  * return +ve data amount
1705  * 0 no more
1706  * -1 error
1707  */
1708 int coap_dtls_receive(coap_session_t *c_session,
1709  const uint8_t *data,
1710  size_t data_len)
1711 {
1712  int ret = 1;
1713 
1714  c_session->dtls_event = -1;
1715  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1716  coap_ssl_t *ssl_data;
1717 
1718  assert(m_env != NULL);
1719 
1720  ssl_data = &m_env->coap_ssl_data;
1721  if (ssl_data->pdu_len) {
1722  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
1723  coap_session_str(c_session), ssl_data->pdu_len);
1724  }
1725  ssl_data->pdu = data;
1726  ssl_data->pdu_len = (unsigned)data_len;
1727 
1728  if (m_env->established) {
1729 #if COAP_CONSTRAINED_STACK
1730  static coap_mutex_t b_static_mutex = COAP_MUTEX_INITIALIZER;
1731  static uint8_t pdu[COAP_RXBUFFER_SIZE];
1732 #else /* ! COAP_CONSTRAINED_STACK */
1733  uint8_t pdu[COAP_RXBUFFER_SIZE];
1734 #endif /* ! COAP_CONSTRAINED_STACK */
1735 
1736 #if COAP_CONSTRAINED_STACK
1737  coap_mutex_lock(&b_static_mutex);
1738 #endif /* COAP_CONSTRAINED_STACK */
1739 
1740  if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
1742  c_session);
1743  coap_session_connected(c_session);
1744  }
1745 
1746  ret = mbedtls_ssl_read(&m_env->ssl, pdu, sizeof(pdu));
1747  if (ret > 0) {
1748  ret = coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
1749 #if COAP_CONSTRAINED_STACK
1750  coap_mutex_unlock(&b_static_mutex);
1751 #endif /* COAP_CONSTRAINED_STACK */
1752  goto finish;
1753  }
1754  switch (ret) {
1755  case 0:
1756  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
1757  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
1758  c_session->dtls_event = COAP_EVENT_DTLS_CLOSED;
1759  break;
1760  case MBEDTLS_ERR_SSL_WANT_READ:
1761  break;
1762  default:
1764  "coap_dtls_receive: "
1765  "returned -0x%x: '%s' (length %zd)\n",
1766  -ret, get_error_string(ret), data_len);
1767  break;
1768  }
1769 #if COAP_CONSTRAINED_STACK
1770  coap_mutex_unlock(&b_static_mutex);
1771 #endif /* COAP_CONSTRAINED_STACK */
1772  ret = -1;
1773  }
1774  else {
1775  ret = do_mbedtls_handshake(c_session, m_env);
1776  if (ret == 1) {
1777  /* Just connected, so send the data */
1778  coap_session_connected(c_session);
1779  } else {
1780  if (ssl_data->pdu_len) {
1781  /* Do the handshake again incase of internal timeout */
1782  ret = do_mbedtls_handshake(c_session, m_env);
1783  if (ret == 1) {
1784  /* Just connected, so send the data */
1785  coap_session_connected(c_session);
1786  } else {
1787  ret = -1;
1788  }
1789  }
1790  ret = -1;
1791  }
1792  }
1793  if (c_session->dtls_event >= 0) {
1794  /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
1795  if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
1796  coap_handle_event(c_session->context, c_session->dtls_event, c_session);
1797  if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
1798  c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
1800  ssl_data = NULL;
1801  ret = -1;
1802  }
1803  }
1804 finish:
1805  if (ssl_data && ssl_data->pdu_len) {
1806  /* pdu data is held on stack which will not stay there */
1807  coap_log(LOG_DEBUG, "coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
1808  ssl_data->pdu_len = 0;
1809  ssl_data->pdu = NULL;
1810  }
1811  return ret;
1812 }
1813 
1814 /*
1815  * return -1 failure
1816  * 0 not completed
1817  * 1 client hello seen
1818  */
1819 int coap_dtls_hello(coap_session_t *c_session,
1820  const uint8_t *data,
1821  size_t data_len)
1822 {
1823 #if !defined(MBEDTLS_SSL_PROTO_DTLS) || !defined(MBEDTLS_SSL_SRV_C)
1824  (void)c_session;
1825  (void)data;
1826  (void)data_len;
1827  coap_log(LOG_EMERG, "coap_dtls_hello:"
1828  " libcoap not compiled for DTLS or Server Mode for Mbed TLS"
1829  " - update Mbed TLS to include DTLS and Server Mode\n");
1830  return -1;
1831 #else /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
1832  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1833  coap_ssl_t *ssl_data;
1834  int ret;
1835 
1836  if (!m_env) {
1837  m_env = coap_dtls_new_mbedtls_env(c_session, COAP_DTLS_ROLE_SERVER);
1838  if (m_env) {
1839  c_session->tls = m_env;
1840  }
1841  else {
1842  /* error should have already been reported */
1843  return -1;
1844  }
1845  }
1846 
1847  if((ret = mbedtls_ssl_set_client_transport_id(&m_env->ssl,
1848  (unsigned char *)&c_session->addr_info.remote,
1849  sizeof(c_session->addr_info.remote))) != 0) {
1850  coap_log(LOG_ERR,
1851  "mbedtls_ssl_set_client_transport_id() returned -0x%x: '%s'\n",
1852  -ret, get_error_string(ret));
1853  return -1;
1854  }
1855 
1856  ssl_data = &m_env->coap_ssl_data;
1857  if (ssl_data->pdu_len) {
1858  coap_log(LOG_ERR, "** %s: Previous data not read %u bytes\n",
1859  coap_session_str(c_session), ssl_data->pdu_len);
1860  }
1861  ssl_data->pdu = data;
1862  ssl_data->pdu_len = (unsigned)data_len;
1863 
1864  ret = do_mbedtls_handshake(c_session, m_env);
1865  if (ret == 0 || m_env->seen_client_hello) {
1866  /* The test for seen_client_hello gives the ability to setup a new
1867  c_session to continue the do_mbedtls_handshake past the client hello
1868  and safely allow updating of the m_env and separately
1869  letting a new session cleanly start up.
1870  */
1871  m_env->seen_client_hello = 0;
1872  ret = 1;
1873  }
1874  else {
1875  ret = 0;
1876  }
1877 
1878  if (ssl_data && ssl_data->pdu_len) {
1879  /* pdu data is held on stack which will not stay there */
1880  coap_log(LOG_DEBUG, "coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
1881  ssl_data->pdu_len = 0;
1882  ssl_data->pdu = NULL;
1883  }
1884  return ret;
1885 #endif /* MBEDTLS_SSL_PROTO_DTLS && MBEDTLS_SSL_SRV_C */
1886 }
1887 
1888 unsigned int coap_dtls_get_overhead(coap_session_t *c_session)
1889 {
1890  coap_mbedtls_env_t *m_env = (coap_mbedtls_env_t *)c_session->tls;
1891  int expansion = mbedtls_ssl_get_record_expansion(&m_env->ssl);
1892 
1893  if (expansion == MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) {
1894  return 13 + 8 + 8;
1895  }
1896  return expansion;
1897 }
1898 
1899 #if !COAP_DISABLE_TCP
1901  int *connected COAP_UNUSED)
1902 {
1903  return NULL;
1904 }
1905 
1907  int *connected COAP_UNUSED)
1908 {
1909  return NULL;
1910 }
1911 
1913 {
1914 }
1915 
1916 ssize_t coap_tls_write(coap_session_t *c_session COAP_UNUSED,
1917  const uint8_t *data COAP_UNUSED,
1918  size_t data_len COAP_UNUSED
1919  )
1920 {
1921  return 0;
1922 }
1923 
1924 ssize_t coap_tls_read(coap_session_t *c_session COAP_UNUSED,
1925  uint8_t *data COAP_UNUSED,
1926  size_t data_len COAP_UNUSED
1927  )
1928 {
1929  return 0;
1930 }
1931 #endif /* !COAP_DISABLE_TCP */
1932 
1933 void coap_dtls_startup(void)
1934 {
1935 }
1936 
1937 void coap_dtls_shutdown(void) {
1938 }
1939 
1940 void *
1941 coap_dtls_get_tls(const coap_session_t *c_session,
1942  coap_tls_library_t *tls_lib) {
1943  if (tls_lib)
1944  *tls_lib = COAP_TLS_LIBRARY_MBEDTLS;
1945  if (c_session && c_session->tls) {
1946  coap_mbedtls_env_t *m_env;
1947 
1948  /* To get around const issue */
1949  memcpy(&m_env, &c_session->tls, sizeof(m_env));
1950 
1951  return (void *)&m_env->ssl;
1952  }
1953  return NULL;
1954 }
1955 
1956 static int keep_log_level = 0;
1957 
1958 void coap_dtls_set_log_level(int level)
1959 {
1960 #if !defined(ESPIDF_VERSION)
1961  int use_level;
1962  /*
1963  * Mbed TLS debug levels filter
1964  * 0 No debug
1965  * 1 Error
1966  * 2 State change
1967  * 3 Informational
1968  * 4 Verbose
1969  */
1970 
1971  if (level <= LOG_ERR) {
1972  use_level = 1;
1973  }
1974  else {
1975  use_level = (level >= LOG_DEBUG) ? level - LOG_DEBUG + 2 : 0;
1976  }
1977  mbedtls_debug_set_threshold(use_level);
1978 #endif /* !ESPIDF_VERSION) */
1979  keep_log_level = level;
1980 }
1981 
1982 int coap_dtls_get_log_level(void)
1983 {
1984  return keep_log_level;
1985 }
1986 
1988 {
1989  static coap_tls_version_t version;
1990  version.version = mbedtls_version_get_number();
1991  version.built_version = MBEDTLS_VERSION_NUMBER;
1992  version.type = COAP_TLS_LIBRARY_MBEDTLS;
1993  return &version;
1994 }
1995 
1997 coap_digest_setup(void) {
1998  mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context));
1999 
2000  if (digest_ctx) {
2001  mbedtls_sha256_init(digest_ctx);
2002  mbedtls_sha256_starts_ret(digest_ctx, 0);
2003  }
2004  return digest_ctx;
2005 }
2006 
2007 void
2008 coap_digest_free(coap_digest_ctx_t *digest_ctx) {
2009  mbedtls_sha256_free(digest_ctx);
2010  mbedtls_free(digest_ctx);
2011 }
2012 
2013 int
2015  const uint8_t *data,
2016  size_t data_len) {
2017  int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len);
2018 
2019  return ret == 0;
2020 }
2021 
2022 int
2024  coap_digest_t *digest_buffer) {
2025  int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t*)digest_buffer);
2026 
2027  coap_digest_free(digest_ctx);
2028  return ret == 0;
2029 }
2030 
2031 #else /* !HAVE_MBEDTLS */
2032 
2033 #ifdef __clang__
2034 /* Make compilers happy that do not like empty modules. As this function is
2035  * never used, we ignore -Wunused-function at the end of compiling this file
2036  */
2037 #pragma GCC diagnostic ignored "-Wunused-function"
2038 #endif
2039 static inline void dummy(void) {
2040 }
2041 
2042 #endif /* HAVE_MBEDTLS */
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:66
static void dummy(void)
void * coap_dtls_new_server_session(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:103
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:138
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:134
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition: coap_notls.c:95
int coap_dtls_send(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:118
void * coap_dtls_new_client_session(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:107
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:179
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition: coap_notls.c:129
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:142
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:157
void * coap_tls_new_client_session(coap_session_t *session COAP_UNUSED, int *connected COAP_UNUSED)
Definition: coap_notls.c:161
void * coap_tls_new_server_session(coap_session_t *session COAP_UNUSED, int *connected COAP_UNUSED)
Definition: coap_notls.c:165
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:150
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:172
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:114
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition: coap_notls.c:41
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition: coap_notls.c:100
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:111
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition: coap_notls.c:74
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition: coap_notls.c:169
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
Definition: coap_notls.c:203
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
Definition: coap_notls.c:192
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:220
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:208
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
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:1899
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:3171
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:70
#define COAP_DTLS_RETRANSMIT_MS
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition: coap_notls.c:125
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition: coap_notls.c:81
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
#define COAP_DTLS_RETRANSMIT_TOTAL_MS
coap_dtls_role_t
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)
Check whether DTLS is available.
Definition: coap_notls.c:15
coap_tls_library_t
Definition: coap_dtls.h:50
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:31
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition: coap_dtls.h:30
@ COAP_PKI_KEY_PKCS11
The PKI key type is PKCS11 (DER)
Definition: coap_dtls.h:150
@ COAP_PKI_KEY_PEM_BUF
The PKI key type is PEM buffer.
Definition: coap_dtls.h:149
@ COAP_PKI_KEY_PEM
The PKI key type is PEM file.
Definition: coap_dtls.h:147
@ COAP_PKI_KEY_ASN1
The PKI key type is ASN.1 (DER) buffer.
Definition: coap_dtls.h:148
@ COAP_TLS_LIBRARY_MBEDTLS
Using Mbed TLS library.
Definition: coap_dtls.h:55
#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 (D)TLS logging level to the specified level.
Definition: coap_notls.c:85
const char * coap_session_str(const coap_session_t *session)
Get session description.
int coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition: coap_notls.c:90
#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
@ COAP_PROTO_DTLS
Definition: pdu.h:281
@ COAP_PROTO_TLS
Definition: pdu.h:283
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Refresh the session's current Identity Hint (PSK).
Definition: coap_session.c:994
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)
Refresh the session's current pre-shared key (PSK).
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
Definition: coap_session.c: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
@ COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:53
#define COAP_UNUSED
Definition: libcoap.h:53
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.
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)
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)
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
The structure used for defining the Client PSK setup data to be used.
Definition: coap_dtls.h:336
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition: coap_dtls.h:360
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition: coap_dtls.h:356
The structure that holds the PKI key information.
Definition: coap_dtls.h:210
coap_pki_key_pem_t pem
for PEM file keys
Definition: coap_dtls.h:213
union coap_dtls_key_t::@2 key
coap_pki_key_pem_buf_t pem_buf
for PEM memory keys
Definition: coap_dtls.h:214
coap_pki_key_t key_type
key format type
Definition: coap_dtls.h:211
coap_pki_key_asn1_t asn1
for ASN.1 (DER) memory keys
Definition: coap_dtls.h:215
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:242
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition: coap_dtls.h:247
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition: coap_dtls.h:260
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:248
coap_dtls_key_t pki_key
PKI key definition.
Definition: coap_dtls.h:299
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:372
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:423
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition: coap_dtls.h:450
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition: coap_dtls.h:442
void * id_call_back_arg
Passed in to the Identity callback function.
Definition: coap_dtls.h:443
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition: coap_dtls.h:451
const uint8_t * private_key
ASN1 (DER) Private Key.
Definition: coap_dtls.h:188
size_t public_cert_len
ASN1 Public Cert length.
Definition: coap_dtls.h:190
size_t private_key_len
ASN1 Private Key length.
Definition: coap_dtls.h:191
const uint8_t * ca_cert
ASN1 (DER) Common CA Cert.
Definition: coap_dtls.h:186
size_t ca_cert_len
ASN1 CA Cert length.
Definition: coap_dtls.h:189
const uint8_t * public_cert
ASN1 (DER) Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:187
size_t ca_cert_len
PEM buffer CA Cert length.
Definition: coap_dtls.h:177
const uint8_t * ca_cert
PEM buffer Common CA Cert.
Definition: coap_dtls.h:172
size_t private_key_len
PEM buffer Private Key length.
Definition: coap_dtls.h:179
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:174
size_t public_cert_len
PEM buffer Public Cert length.
Definition: coap_dtls.h:178
const uint8_t * public_cert
PEM buffer Public Cert, or Public Key if RPK.
Definition: coap_dtls.h:173
const char * ca_file
File location of Common CA in PEM format.
Definition: coap_dtls.h:157
const char * public_cert
File location of Public Cert.
Definition: coap_dtls.h:158
const char * private_key
File location of Private Key in PEM format.
Definition: coap_dtls.h:159
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
unsigned int dtls_timeout_count
dtls setup retry counter
unsigned int max_retransmit
maximum re-transmit count (default 4)
coap_session_state_t state
current state of relationaship with peer
coap_addr_tuple_t addr_info
key: remote/local address info
coap_proto_t proto
protocol used
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu
int dtls_event
Tracking any (D)TLS events on this sesison.
void * tls
security parameters
coap_context_t * context
session's context
The structure used for returning the underlying (D)TLS library information.
Definition: coap_dtls.h:62
uint64_t built_version
(D)TLS Built against Library Version
Definition: coap_dtls.h:65
coap_tls_library_t type
Library type.
Definition: coap_dtls.h:64
uint64_t version
(D)TLS runtime Library Version
Definition: coap_dtls.h:63