libcoap 4.3.5b
Loading...
Searching...
No Matches
coap_gnutls.c
Go to the documentation of this file.
1/*
2 * coap_gnutls.c -- GnuTLS Datagram Transport Layer Support for libcoap
3 *
4 * Copyright (C) 2017 Dag Bjorklund <dag.bjorklund@comsel.fi>
5 * Copyright (C) 2018-2025 Jon Shallow <supjps-libcoap@jpshallow.com>
6 *
7 * SPDX-License-Identifier: BSD-2-Clause
8 *
9 * This file is part of the CoAP library libcoap. Please see README for terms
10 * of use.
11 */
12
17
18/*
19 * Naming used to prevent confusion between coap sessions, gnutls sessions etc.
20 * when reading the code.
21 *
22 * c_context A coap_context_t *
23 * c_session A coap_session_t *
24 * g_context A coap_gnutls_context_t * (held in c_context->dtls_context)
25 * g_session A gnutls_session_t (which has the * in the typedef)
26 * g_env A coap_gnutls_env_t * (held in c_session->tls)
27 */
28
29/*
30 * Notes
31 *
32 * There is a memory leak in GnuTLS prior to 3.3.26 when hint is not freed off
33 * when server psk credentials are freed off.
34 *
35 * ca_path in coap_dtls_context_set_pki_root_cas() is not supported until 3.3.6
36 *
37 * Identity Hint is not provided if using DH and versions prior to 3.4.4
38 *
39 * 3.5.5 or later is required to interoperate with TinyDTLS as CCM algorithm
40 * support is required.
41 *
42 * TLS 1.3 is properly supported from 3.6.5 onwards
43 * (but is not enabled by default in 3.6.4)
44 *
45 * Starting with 3.6.3, fixed in 3.6.13, Client Hellos may fail with some
46 * server implementations (e.g. Californium) as random value is all zeros
47 * - CVE-2020-11501 - a security weakness.
48 * 3.6.6 or later is required to support Raw Public Key(RPK)
49 */
50
52
53#ifdef COAP_WITH_LIBGNUTLS
54
55#define MIN_GNUTLS_VERSION "3.3.0"
56
57#include <stdio.h>
58#include <gnutls/gnutls.h>
59#include <gnutls/x509.h>
60#include <gnutls/dtls.h>
61#include <gnutls/pkcs11.h>
62#include <gnutls/crypto.h>
63#include <gnutls/abstract.h>
64#include <unistd.h>
65#if (GNUTLS_VERSION_NUMBER >= 0x030606)
66#define COAP_GNUTLS_KEY_RPK GNUTLS_KEY_DIGITAL_SIGNATURE | \
67 GNUTLS_KEY_NON_REPUDIATION | \
68 GNUTLS_KEY_KEY_ENCIPHERMENT | \
69 GNUTLS_KEY_DATA_ENCIPHERMENT | \
70 GNUTLS_KEY_KEY_AGREEMENT | \
71 GNUTLS_KEY_KEY_CERT_SIGN
72#endif /* GNUTLS_VERSION_NUMBER >= 0x030606 */
73
74#ifndef GNUTLS_CRT_RAW
75#define GNUTLS_CRT_RAW GNUTLS_CRT_RAWPK
76#endif /* GNUTLS_CRT_RAW */
77
78#ifdef _WIN32
79#define strcasecmp _stricmp
80#endif
81
82typedef struct coap_ssl_t {
83 const uint8_t *pdu;
84 unsigned pdu_len;
85 unsigned peekmode;
86 gnutls_datum_t cookie_key;
87} coap_ssl_t;
88
89/*
90 * This structure encapsulates the GnuTLS session object.
91 * It handles both TLS and DTLS.
92 * c_session->tls points to this.
93 */
94typedef struct coap_gnutls_env_t {
95 gnutls_session_t g_session;
96 gnutls_psk_client_credentials_t psk_cl_credentials;
97 gnutls_psk_server_credentials_t psk_sv_credentials;
98 gnutls_certificate_credentials_t pki_credentials;
99 coap_ssl_t coap_ssl_data;
100 /* If not set, need to do gnutls_handshake */
101 int established;
102 int doing_dtls_timeout;
103 coap_tick_t last_timeout;
104 int sent_alert;
105} coap_gnutls_env_t;
106
107#define IS_PSK (1 << 0)
108#define IS_PKI (1 << 1)
109#define IS_CLIENT (1 << 6)
110#define IS_SERVER (1 << 7)
111
112typedef struct pki_sni_entry {
113 char *sni;
114 coap_dtls_key_t pki_key;
115 gnutls_certificate_credentials_t pki_credentials;
116} pki_sni_entry;
117
118typedef struct psk_sni_entry {
119 char *sni;
120 coap_dtls_spsk_info_t psk_info;
121 gnutls_psk_server_credentials_t psk_credentials;
122} psk_sni_entry;
123
124typedef struct coap_gnutls_context_t {
125 coap_dtls_pki_t setup_data;
126 int psk_pki_enabled;
127 size_t pki_sni_count;
128 pki_sni_entry *pki_sni_entry_list;
129 size_t psk_sni_count;
130 psk_sni_entry *psk_sni_entry_list;
131 gnutls_datum_t alpn_proto; /* Will be "coap", but that is a const */
132 char *root_ca_file;
133 char *root_ca_path;
134 gnutls_priority_t priority_cache;
135} coap_gnutls_context_t;
136
137typedef enum coap_free_bye_t {
138 COAP_FREE_BYE_AS_TCP,
139 COAP_FREE_BYE_AS_UDP,
140 COAP_FREE_BYE_NONE
141} coap_free_bye_t;
142
143#define VARIANTS_3_6_6 "NORMAL:+ECDHE-PSK:+PSK:+ECDHE-ECDSA:+AES-128-CCM-8:+CTYPE-CLI-ALL:+CTYPE-SRV-ALL:+SHA256"
144#define VARIANTS_3_5_5 "NORMAL:+ECDHE-PSK:+PSK:+ECDHE-ECDSA:+AES-128-CCM-8"
145#define VARIANTS_BASE "NORMAL:+ECDHE-PSK:+PSK"
146
147#define VARIANTS_NO_TLS13_3_6_6 VARIANTS_3_6_6 ":-VERS-TLS1.3"
148#define VARIANTS_NO_TLS13_3_6_4 VARIANTS_3_5_5 ":-VERS-TLS1.3"
149
150#define G_ACTION(xx) do { \
151 ret = (xx); \
152 } while (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
153
154#define G_CHECK(xx,func) do { \
155 if ((ret = (xx)) < 0) { \
156 coap_log_warn("%s: '%s'\n", func, gnutls_strerror(ret)); \
157 goto fail; \
158 } \
159 } while (0)
160
161#define G_ACTION_CHECK(xx,func) do { \
162 G_ACTION(xx); \
163 G_CHECK(xx, func); \
164 } while 0
165
167
168#if COAP_SERVER_SUPPORT
169static int post_client_hello_gnutls_pki(gnutls_session_t g_session);
170static int post_client_hello_gnutls_psk(gnutls_session_t g_session);
171static int psk_server_callback(gnutls_session_t g_session,
172 const char *identity,
173 gnutls_datum_t *key);
174#endif /* COAP_SERVER_SUPPORT */
175
176/*
177 * return 0 failed
178 * 1 passed
179 */
180int
182 if (gnutls_check_version(MIN_GNUTLS_VERSION) == NULL) {
183 coap_log_err("GnuTLS " MIN_GNUTLS_VERSION " or later is required\n");
184 return 0;
185 }
186 return 1;
187}
188
189/*
190 * return 0 failed
191 * 1 passed
192 */
193int
195#if !COAP_DISABLE_TCP
196 if (gnutls_check_version(MIN_GNUTLS_VERSION) == NULL) {
197 coap_log_err("GnuTLS " MIN_GNUTLS_VERSION " or later is required\n");
198 return 0;
199 }
200 return 1;
201#else /* COAP_DISABLE_TCP */
202 return 0;
203#endif /* COAP_DISABLE_TCP */
204}
205
206/*
207 * return 0 failed
208 * 1 passed
209 */
210int
212 return 1;
213}
214
215/*
216 * return 0 failed
217 * 1 passed
218 */
219int
221 return 1;
222}
223
224/*
225 * return 0 failed
226 * 1 passed
227 */
228int
230 return 1;
231}
232
233/*
234 * return 0 failed
235 * 1 passed
236 */
237int
239#if (GNUTLS_VERSION_NUMBER >= 0x030606)
240 return 1;
241#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
242 return 0;
243#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
244}
245
246/*
247 * return 0 failed
248 * 1 passed
249 */
250int
252 return 0;
253}
254
255#if COAP_CLIENT_SUPPORT
256int
257coap_dtls_set_cid_tuple_change(coap_context_t *c_context, uint8_t every) {
258 (void)c_context;
259 (void)every;
260 return 0;
261}
262#endif /* COAP_CLIENT_SUPPORT */
263
266 static coap_tls_version_t version;
267 const char *vers = gnutls_check_version(NULL);
268
269 version.version = 0;
270 if (vers) {
271 int p1, p2, p3;
272
273 sscanf(vers, "%d.%d.%d", &p1, &p2, &p3);
274 version.version = (p1 << 16) | (p2 << 8) | p3;
275 }
276 version.built_version = GNUTLS_VERSION_NUMBER;
278 return &version;
279}
280
281static void
282coap_gnutls_audit_log_func(gnutls_session_t g_session, const char *text) {
283#if COAP_MAX_LOGGING_LEVEL > 0
284 if (g_session) {
285 coap_session_t *c_session =
286 (coap_session_t *)gnutls_transport_get_ptr(g_session);
287 coap_log_warn("** %s: %s",
288 coap_session_str(c_session), text);
289 } else {
290 coap_log_warn("** (null): %s", text);
291 }
292#else /* COAP_MAX_LOGGING_LEVEL == 0 */
293 (void)g_session;
294 (void)text;
295#endif /* COAP_MAX_LOGGING_LEVEL == 0 */
296}
297
298static void
299coap_gnutls_log_func(int level, const char *text) {
300 /* Things get noisy, even at level 1 */
301 if (level > 0)
302 level += COAP_LOG_WARN;
303 if (level > COAP_LOG_DEBUG)
304 level = COAP_LOG_DEBUG;
305 coap_dtls_log(level, "%s", text);
306}
307
308/*
309 * return 0 failed
310 * 1 passed
311 */
312int
314 const coap_dtls_pki_t *setup_data,
315 const coap_dtls_role_t role COAP_UNUSED) {
316 coap_dtls_key_t key;
317 coap_gnutls_context_t *g_context =
318 ((coap_gnutls_context_t *)c_context->dtls_context);
319
320 if (!g_context || !setup_data)
321 return 0;
322
323 g_context->setup_data = *setup_data;
324 if (!g_context->setup_data.verify_peer_cert) {
325 /* Needs to be clear so that no CA DNs are transmitted */
326 g_context->setup_data.check_common_ca = 0;
327 if (g_context->setup_data.is_rpk_not_cert) {
328 /* Disable all of these as they cannot be checked */
329 g_context->setup_data.allow_self_signed = 0;
330 g_context->setup_data.allow_expired_certs = 0;
331 g_context->setup_data.cert_chain_validation = 0;
332 g_context->setup_data.cert_chain_verify_depth = 0;
333 g_context->setup_data.check_cert_revocation = 0;
334 g_context->setup_data.allow_no_crl = 0;
335 g_context->setup_data.allow_expired_crl = 0;
336 g_context->setup_data.allow_bad_md_hash = 0;
337 g_context->setup_data.allow_short_rsa_length = 0;
338 } else {
339 /* Allow all of these but warn if issue */
340 g_context->setup_data.allow_self_signed = 1;
341 g_context->setup_data.allow_expired_certs = 1;
342 g_context->setup_data.cert_chain_validation = 1;
343 g_context->setup_data.cert_chain_verify_depth = 10;
344 g_context->setup_data.check_cert_revocation = 1;
345 g_context->setup_data.allow_no_crl = 1;
346 g_context->setup_data.allow_expired_crl = 1;
347 g_context->setup_data.allow_bad_md_hash = 1;
348 g_context->setup_data.allow_short_rsa_length = 1;
349 }
350 }
351 /* Map over to the new define format to save code duplication */
352 coap_dtls_map_key_type_to_define(&g_context->setup_data, &key);
353 g_context->setup_data.pki_key = key;
354 g_context->psk_pki_enabled |= IS_PKI;
355 if (setup_data->use_cid) {
356 coap_log_warn("GnuTLS has no Connection-ID support\n");
357 }
358 return 1;
359}
360
361/*
362 * return 0 failed
363 * 1 passed
364 */
365int
367 const char *ca_file,
368 const char *ca_path) {
369 coap_gnutls_context_t *g_context =
370 ((coap_gnutls_context_t *)c_context->dtls_context);
371 if (!g_context) {
372 coap_log_warn("coap_context_set_pki_root_cas: (D)TLS environment "
373 "not set up\n");
374 return 0;
375 }
376
377 if (ca_file == NULL && ca_path == NULL) {
378 coap_log_warn("coap_context_set_pki_root_cas: ca_file and/or ca_path "
379 "not defined\n");
380 return 0;
381 }
382 if (g_context->root_ca_file) {
383 gnutls_free(g_context->root_ca_file);
384 g_context->root_ca_file = NULL;
385 }
386 if (ca_file) {
387 g_context->root_ca_file = gnutls_strdup(ca_file);
388 }
389 if (g_context->root_ca_path) {
390 gnutls_free(g_context->root_ca_path);
391 g_context->root_ca_path = NULL;
392 }
393 if (ca_path) {
394#if (GNUTLS_VERSION_NUMBER >= 0x030306)
395 g_context->root_ca_path = gnutls_strdup(ca_path);
396#else
397 coap_log_err("ca_path not supported in GnuTLS < 3.3.6\n");
398#endif
399 }
400 return 1;
401}
402
403#if COAP_SERVER_SUPPORT
404/*
405 * return 0 failed
406 * 1 passed
407 */
408int
410 coap_dtls_spsk_t *setup_data
411 ) {
412 coap_gnutls_context_t *g_context =
413 ((coap_gnutls_context_t *)c_context->dtls_context);
414
415 if (!g_context || !setup_data)
416 return 0;
417
418 if (setup_data->ec_jpake) {
419 coap_log_warn("GnuTLS has no EC-JPAKE support\n");
420 }
421 g_context->psk_pki_enabled |= IS_PSK;
422 return 1;
423}
424#endif /* COAP_SERVER_SUPPORT */
425
426#if COAP_CLIENT_SUPPORT
427/*
428 * return 0 failed
429 * 1 passed
430 */
431int
433 coap_dtls_cpsk_t *setup_data
434 ) {
435 coap_gnutls_context_t *g_context =
436 ((coap_gnutls_context_t *)c_context->dtls_context);
437
438 if (!g_context || !setup_data)
439 return 0;
440
441 if (setup_data->ec_jpake) {
442 coap_log_warn("GnuTLS has no EC-JPAKE support\n");
443 }
444 if (setup_data->use_cid) {
445 coap_log_warn("GnuTLS has no Connection-ID support\n");
446 }
447 g_context->psk_pki_enabled |= IS_PSK;
448 return 1;
449}
450#endif /* COAP_CLIENT_SUPPORT */
451
452/*
453 * return 0 failed
454 * 1 passed
455 */
456int
458 coap_gnutls_context_t *g_context =
459 ((coap_gnutls_context_t *)c_context->dtls_context);
460 return g_context->psk_pki_enabled ? 1 : 0;
461}
462
463void
464coap_dtls_startup(void) {
465 gnutls_global_set_audit_log_function(coap_gnutls_audit_log_func);
466 gnutls_global_set_log_function(coap_gnutls_log_func);
467}
468
469void
470coap_dtls_shutdown(void) {
472}
473
474void
476}
477
478void *
479coap_dtls_get_tls(const coap_session_t *c_session,
480 coap_tls_library_t *tls_lib) {
481 if (tls_lib)
482 *tls_lib = COAP_TLS_LIBRARY_GNUTLS;
483 if (c_session && c_session->tls) {
484 const coap_gnutls_env_t *g_env = (const coap_gnutls_env_t *)c_session->tls;
485
486 return g_env->g_session;
487 }
488 return NULL;
489}
490
491void
493 dtls_log_level = level;
494 gnutls_global_set_log_level(dtls_log_level);
495}
496
497/*
498 * return current logging level
499 */
502 return dtls_log_level;
503}
504
505/*
506 * return +ve new g_context
507 * NULL failure
508 */
509void *
511 const char *err = "Unknown Error";
512 int ret;
513 coap_gnutls_context_t *g_context =
514 (coap_gnutls_context_t *)
515 gnutls_malloc(sizeof(coap_gnutls_context_t));
516
517 if (g_context) {
519 const char *priority;
520
521 memset(g_context, 0, sizeof(coap_gnutls_context_t));
522 G_CHECK(gnutls_global_init(), "gnutls_global_init");
523 g_context->alpn_proto.data = gnutls_malloc(4);
524 if (g_context->alpn_proto.data) {
525 memcpy(g_context->alpn_proto.data, "coap", 4);
526 g_context->alpn_proto.size = 4;
527 }
528
529 if (tls_version->version >= 0x030606) {
530 priority = VARIANTS_3_6_6;
531 } else if (tls_version->version >= 0x030505) {
532 priority = VARIANTS_3_5_5;
533 } else {
534 priority = VARIANTS_BASE;
535 }
536 ret = gnutls_priority_init(&g_context->priority_cache, priority, &err);
537 if (ret != GNUTLS_E_SUCCESS) {
538 if (ret == GNUTLS_E_INVALID_REQUEST)
539 coap_log_warn("gnutls_priority_init: Syntax error at: %s\n", err);
540 else
541 coap_log_warn("gnutls_priority_init: %s\n", gnutls_strerror(ret));
542 goto fail;
543 }
544 }
545 return g_context;
546
547fail:
548 if (g_context)
549 coap_dtls_free_context(g_context);
550 return NULL;
551}
552
553void
554coap_dtls_free_context(void *handle) {
555 size_t i;
556 coap_gnutls_context_t *g_context = (coap_gnutls_context_t *)handle;
557
558 gnutls_free(g_context->alpn_proto.data);
559 gnutls_free(g_context->root_ca_file);
560 gnutls_free(g_context->root_ca_path);
561 for (i = 0; i < g_context->pki_sni_count; i++) {
562 gnutls_free(g_context->pki_sni_entry_list[i].sni);
563 gnutls_certificate_free_credentials(
564 g_context->pki_sni_entry_list[i].pki_credentials);
565 }
566 if (g_context->pki_sni_entry_list)
567 gnutls_free(g_context->pki_sni_entry_list);
568
569 for (i = 0; i < g_context->psk_sni_count; i++) {
570 gnutls_free(g_context->psk_sni_entry_list[i].sni);
571 /* YUK - A memory leak in 3.3.0 (fixed by 3.3.26) of hint */
572 gnutls_psk_free_server_credentials(
573 g_context->psk_sni_entry_list[i].psk_credentials);
574 }
575 if (g_context->psk_sni_entry_list)
576 gnutls_free(g_context->psk_sni_entry_list);
577
578 gnutls_priority_deinit(g_context->priority_cache);
579
580 gnutls_global_deinit();
581 gnutls_free(g_context);
582}
583
584#if COAP_CLIENT_SUPPORT
585/*
586 * gnutls_psk_client_credentials_function return values
587 * (see gnutls_psk_set_client_credentials_function())
588 *
589 * return -1 failed
590 * 0 passed
591 */
592static int
593psk_client_callback(gnutls_session_t g_session,
594 char **username, gnutls_datum_t *key) {
595 coap_session_t *c_session =
596 (coap_session_t *)gnutls_transport_get_ptr(g_session);
597 coap_gnutls_context_t *g_context;
598 coap_dtls_cpsk_t *setup_data;
599 const char *hint = gnutls_psk_client_get_hint(g_session);
600 coap_bin_const_t temp;
601 const coap_bin_const_t *psk_key;
602 const coap_bin_const_t *psk_identity;
603 const coap_dtls_cpsk_info_t *cpsk_info;
604
605 /* Initialize result parameters. */
606 *username = NULL;
607 key->data = NULL;
608
609 if (c_session == NULL)
610 return -1;
611
612 g_context = (coap_gnutls_context_t *)c_session->context->dtls_context;
613 if (g_context == NULL)
614 return -1;
615
616 setup_data = &c_session->cpsk_setup_data;
617
618 temp.s = hint ? (const uint8_t *)hint : (const uint8_t *)"";
619 temp.length = strlen((const char *)temp.s);
620 coap_session_refresh_psk_hint(c_session, &temp);
621
622 coap_log_debug("got psk_identity_hint: '%.*s'\n", (int)temp.length,
623 (const char *)temp.s);
624
625 if (setup_data->validate_ih_call_back) {
626 coap_str_const_t lhint;
627
628 lhint.length = temp.length;
629 lhint.s = temp.s;
630 coap_lock_callback_ret(cpsk_info, c_session->context,
631 setup_data->validate_ih_call_back(&lhint,
632 c_session,
633 setup_data->ih_call_back_arg));
634
635 if (cpsk_info == NULL)
636 return -1;
637
638 coap_session_refresh_psk_identity(c_session, &cpsk_info->identity);
639 coap_session_refresh_psk_key(c_session, &cpsk_info->key);
640 psk_identity = &cpsk_info->identity;
641 psk_key = &cpsk_info->key;
642 } else {
643 psk_identity = coap_get_session_client_psk_identity(c_session);
644 psk_key = coap_get_session_client_psk_key(c_session);
645 }
646
647 if (psk_identity == NULL || psk_key == NULL) {
648 coap_log_warn("no PSK available\n");
649 return -1;
650 }
651
652 *username = gnutls_malloc(psk_identity->length+1);
653 if (*username == NULL)
654 return -1;
655 memcpy(*username, psk_identity->s, psk_identity->length);
656 (*username)[psk_identity->length] = '\000';
657
658 key->data = gnutls_malloc(psk_key->length);
659 if (key->data == NULL) {
660 gnutls_free(*username);
661 *username = NULL;
662 return -1;
663 }
664 memcpy(key->data, psk_key->s, psk_key->length);
665 key->size = psk_key->length;
666 return 0;
667}
668#endif /* COAP_CLIENT_SUPPORT */
669
670typedef struct {
671 gnutls_certificate_type_t certificate_type;
672 char *san_or_cn;
673 const gnutls_datum_t *cert_list;
674 unsigned int cert_list_size;
675 int self_signed; /* 1 if cert self-signed, 0 otherwise */
676} coap_gnutls_certificate_info_t;
677
678/*
679 * return Type of certificate and SAN or CN if appropriate derived from
680 * certificate. GNUTLS_CRT_UNKNOWN if failure.
681 */
682static gnutls_certificate_type_t
683get_san_or_cn(gnutls_session_t g_session,
684 coap_gnutls_certificate_info_t *cert_info) {
685 gnutls_x509_crt_t cert;
686 char dn[256];
687 size_t size;
688 int n;
689 char *cn;
690 int ret;
691
692#if (GNUTLS_VERSION_NUMBER >= 0x030606)
693 cert_info->certificate_type = gnutls_certificate_type_get2(g_session,
694 GNUTLS_CTYPE_PEERS);
695#else /* < 3.6.6 */
696 cert_info->certificate_type = gnutls_certificate_type_get(g_session);
697#endif /* < 3.6.6 */
698
699 cert_info->san_or_cn = NULL;
700
701 cert_info->cert_list = gnutls_certificate_get_peers(g_session,
702 &cert_info->cert_list_size);
703 if (cert_info->cert_list_size == 0) {
704 return GNUTLS_CRT_UNKNOWN;
705 }
706
707 if (cert_info->certificate_type != GNUTLS_CRT_X509)
708 return cert_info->certificate_type;
709
710 G_CHECK(gnutls_x509_crt_init(&cert), "gnutls_x509_crt_init");
711
712 /* Interested only in first cert in chain */
713 G_CHECK(gnutls_x509_crt_import(cert, &cert_info->cert_list[0],
714 GNUTLS_X509_FMT_DER), "gnutls_x509_crt_import");
715
716 cert_info->self_signed = gnutls_x509_crt_check_issuer(cert, cert);
717
718 size = sizeof(dn) -1;
719 /* See if there is a Subject Alt Name first */
720 ret = gnutls_x509_crt_get_subject_alt_name(cert, 0, dn, &size, NULL);
721 if (ret >= 0) {
722 dn[size] = '\000';
723 gnutls_x509_crt_deinit(cert);
724 cert_info->san_or_cn = gnutls_strdup(dn);
725 return cert_info->certificate_type;
726 }
727
728 size = sizeof(dn);
729 G_CHECK(gnutls_x509_crt_get_dn(cert, dn, &size), "gnutls_x509_crt_get_dn");
730
731 gnutls_x509_crt_deinit(cert);
732
733 /* Need to emulate strcasestr() here. Looking for CN= */
734 n = strlen(dn) - 3;
735 cn = dn;
736 while (n > 0) {
737 if (((cn[0] == 'C') || (cn[0] == 'c')) &&
738 ((cn[1] == 'N') || (cn[1] == 'n')) &&
739 (cn[2] == '=')) {
740 cn += 3;
741 break;
742 }
743 cn++;
744 n--;
745 }
746 if (n > 0) {
747 char *ecn = strchr(cn, ',');
748 if (ecn) {
749 cn[ecn-cn] = '\000';
750 }
751 cert_info->san_or_cn = gnutls_strdup(cn);
752 return cert_info->certificate_type;
753 }
754 return GNUTLS_CRT_UNKNOWN;
755
756fail:
757 return GNUTLS_CRT_UNKNOWN;
758}
759
760#if (GNUTLS_VERSION_NUMBER >= 0x030606)
761#define OUTPUT_CERT_NAME (cert_type == GNUTLS_CRT_X509 ? \
762 cert_info.san_or_cn : \
763 cert_type == GNUTLS_CRT_RAW ? \
764 COAP_DTLS_RPK_CERT_CN : "?")
765#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
766#define OUTPUT_CERT_NAME (cert_type == GNUTLS_CRT_X509 ? \
767 cert_info.san_or_cn : "?")
768#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
769
770#if (GNUTLS_VERSION_NUMBER >= 0x030606)
771static int
772check_rpk_cert(coap_gnutls_context_t *g_context,
773 coap_gnutls_certificate_info_t *cert_info,
774 coap_session_t *c_session) {
775 int ret;
776
777 if (g_context->setup_data.validate_cn_call_back) {
778 gnutls_pcert_st pcert;
779 uint8_t der[2048];
780 size_t size;
781
782 G_CHECK(gnutls_pcert_import_rawpk_raw(&pcert, &cert_info->cert_list[0],
783 GNUTLS_X509_FMT_DER, 0, 0),
784 "gnutls_pcert_import_rawpk_raw");
785
786 size = sizeof(der);
787 G_CHECK(gnutls_pubkey_export(pcert.pubkey, GNUTLS_X509_FMT_DER, der, &size),
788 "gnutls_pubkey_export");
789 gnutls_pcert_deinit(&pcert);
790 coap_lock_callback_ret(ret, c_session->context,
791 g_context->setup_data.validate_cn_call_back(COAP_DTLS_RPK_CERT_CN,
792 der,
793 size,
794 c_session,
795 0,
796 1,
797 g_context->setup_data.cn_call_back_arg));
798 if (!ret) {
799 return 0;
800 }
801 }
802 return 1;
803fail:
804 return 0;
805}
806#endif /* >= 3.6.6 */
807
808/*
809 * return 0 failed
810 * 1 passed
811 */
812static int
813cert_verify_gnutls(gnutls_session_t g_session) {
814 unsigned int status = 0;
815 unsigned int fail = 0;
816 coap_session_t *c_session =
817 (coap_session_t *)gnutls_transport_get_ptr(g_session);
818 coap_gnutls_context_t *g_context =
819 (coap_gnutls_context_t *)c_session->context->dtls_context;
820 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
821 int alert = GNUTLS_A_BAD_CERTIFICATE;
822 int ret;
823 coap_gnutls_certificate_info_t cert_info;
824 gnutls_certificate_type_t cert_type;
825
826 memset(&cert_info, 0, sizeof(cert_info));
827 cert_type = get_san_or_cn(g_session, &cert_info);
828#if (GNUTLS_VERSION_NUMBER >= 0x030606)
829 if (cert_type == GNUTLS_CRT_RAW) {
830 if (!check_rpk_cert(g_context, &cert_info, c_session)) {
831 alert = GNUTLS_A_ACCESS_DENIED;
832 goto fail;
833 }
834 goto ok;
835 }
836#endif /* >= 3.6.6 */
837
838 if (cert_info.cert_list_size == 0) {
839 if (!g_context->setup_data.verify_peer_cert)
840 goto ok;
841 else
842 goto fail;
843 }
844
845 G_CHECK(gnutls_certificate_verify_peers(g_session, NULL, 0, &status),
846 "gnutls_certificate_verify_peers");
847
848 if (status) {
849 status &= ~(GNUTLS_CERT_INVALID);
850 if (status & (GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED)) {
851 status &= ~(GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED);
852 if (g_context->setup_data.allow_expired_certs) {
853 coap_log_info(" %s: %s: overridden: '%s'\n",
854 coap_session_str(c_session),
855 "The certificate has an invalid usage date",
856 OUTPUT_CERT_NAME);
857 } else {
858 fail = 1;
859 coap_log_warn(" %s: %s: '%s'\n",
860 coap_session_str(c_session),
861 "The certificate has an invalid usage date",
862 OUTPUT_CERT_NAME);
863 }
864 }
865 if (status & (GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
866 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE)) {
867 status &= ~(GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
868 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE);
869 if (g_context->setup_data.allow_expired_crl) {
870 coap_log_info(" %s: %s: overridden: '%s'\n",
871 coap_session_str(c_session),
872 "The certificate's CRL entry has an invalid usage date",
873 OUTPUT_CERT_NAME);
874 } else {
875 fail = 1;
876 coap_log_warn(" %s: %s: '%s'\n",
877 coap_session_str(c_session),
878 "The certificate's CRL entry has an invalid usage date",
879 OUTPUT_CERT_NAME);
880 }
881 }
882 if (status & (GNUTLS_CERT_SIGNER_NOT_FOUND)) {
883 status &= ~(GNUTLS_CERT_SIGNER_NOT_FOUND);
884 if (cert_info.self_signed) {
885 if (g_context->setup_data.allow_self_signed &&
886 !g_context->setup_data.check_common_ca) {
887 coap_log_info(" %s: %s: overridden: '%s'\n",
888 coap_session_str(c_session),
889 "Self-signed",
890 OUTPUT_CERT_NAME);
891 } else {
892 fail = 1;
893 alert = GNUTLS_A_UNKNOWN_CA;
894 coap_log_warn(" %s: %s: '%s'\n",
895 coap_session_str(c_session),
896 "Self-signed",
897 OUTPUT_CERT_NAME);
898 }
899 } else {
900 if (!g_context->setup_data.verify_peer_cert) {
901 coap_log_info(" %s: %s: overridden: '%s'\n",
902 coap_session_str(c_session),
903 "The peer certificate's CA is unknown",
904 OUTPUT_CERT_NAME);
905 } else {
906 fail = 1;
907 alert = GNUTLS_A_UNKNOWN_CA;
908 coap_log_warn(" %s: %s: '%s'\n",
909 coap_session_str(c_session),
910 "The peer certificate's CA is unknown",
911 OUTPUT_CERT_NAME);
912 }
913 }
914 }
915 if (status & (GNUTLS_CERT_INSECURE_ALGORITHM)) {
916 status &= ~(GNUTLS_CERT_INSECURE_ALGORITHM);
917 fail = 1;
918 coap_log_warn(" %s: %s: '%s'\n",
919 coap_session_str(c_session),
920 "The certificate uses an insecure algorithm",
921 OUTPUT_CERT_NAME);
922 }
923
924 if (status) {
925 fail = 1;
926 coap_log_warn(" %s: gnutls_certificate_verify_peers() status 0x%x: '%s'\n",
927 coap_session_str(c_session),
928 status, OUTPUT_CERT_NAME);
929 }
930 }
931
932 if (fail)
933 goto fail;
934
935 if (g_context->setup_data.validate_cn_call_back) {
936 gnutls_x509_crt_t cert;
937 uint8_t der[2048];
938 size_t size;
939 /* status == 0 indicates that the certificate passed to
940 * setup_data.validate_cn_call_back has been validated. */
941 const int cert_is_trusted = !status;
942
943 G_CHECK(gnutls_x509_crt_init(&cert), "gnutls_x509_crt_init");
944
945 /* Interested only in first cert in chain */
946 G_CHECK(gnutls_x509_crt_import(cert, &cert_info.cert_list[0],
947 GNUTLS_X509_FMT_DER), "gnutls_x509_crt_import");
948
949 size = sizeof(der);
950 G_CHECK(gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, der, &size),
951 "gnutls_x509_crt_export");
952 gnutls_x509_crt_deinit(cert);
953 coap_lock_callback_ret(ret, c_session->context,
954 g_context->setup_data.validate_cn_call_back(OUTPUT_CERT_NAME,
955 der,
956 size,
957 c_session,
958 0,
959 cert_is_trusted,
960 g_context->setup_data.cn_call_back_arg));
961 if (!ret) {
962 alert = GNUTLS_A_ACCESS_DENIED;
963 goto fail;
964 }
965 }
966
967 if (g_context->setup_data.additional_tls_setup_call_back) {
968 /* Additional application setup wanted */
969 if (!g_context->setup_data.additional_tls_setup_call_back(g_session,
970 &g_context->setup_data)) {
971 goto fail;
972 }
973 }
974
975ok:
976 if (cert_info.san_or_cn)
977 gnutls_free(cert_info.san_or_cn);
978
979 return 1;
980
981fail:
982 if (cert_info.san_or_cn)
983 gnutls_free(cert_info.san_or_cn);
984
985 if (!g_env->sent_alert) {
986 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL, alert));
987 g_env->sent_alert = 1;
988 }
990 return 0;
991}
992
993/*
994 * gnutls_certificate_verify_function return values
995 * (see gnutls_certificate_set_verify_function())
996 *
997 * return -1 failed
998 * 0 passed
999 */
1000static int
1001cert_verify_callback_gnutls(gnutls_session_t g_session) {
1002 if (gnutls_auth_get_type(g_session) == GNUTLS_CRD_CERTIFICATE) {
1003 if (cert_verify_gnutls(g_session) == 0) {
1004 return -1;
1005 }
1006 }
1007 return 0;
1008}
1009
1010#ifndef min
1011#define min(a,b) ((a) < (b) ? (a) : (b))
1012#endif
1013
1014static int
1015pin_callback(void *user_data, int attempt,
1016 const char *token_url COAP_UNUSED,
1017 const char *token_label COAP_UNUSED,
1018 unsigned int flags COAP_UNUSED,
1019 char *pin,
1020 size_t pin_max) {
1021 coap_dtls_key_t *key = (coap_dtls_key_t *)user_data;
1022
1023 /* Only do this on first attempt to prevent token lockout */
1024 if (attempt == 0 && key && key->key.define.user_pin) {
1025 int len = min(pin_max - 1, strlen(key->key.define.user_pin));
1026
1027 memcpy(pin, key->key.define.user_pin, len);
1028 pin[len] = 0;
1029 return 0;
1030 }
1031 return -1;
1032}
1033
1034static int
1035check_null_memory(gnutls_datum_t *datum,
1036 const uint8_t *buf, size_t len, int *alloced) {
1037 datum->size = len;
1038 *alloced = 0;
1039 if (buf[len-1] != '\000') {
1040 /* Need to allocate memory, rather than just copying pointers across */
1041 *alloced = 1;
1042 datum->data = gnutls_malloc(len + 1);
1043 if (!datum->data) {
1044 coap_log_err("gnutls_malloc failure\n");
1045 return GNUTLS_E_MEMORY_ERROR;
1046 }
1047 memcpy(datum->data, buf, len);
1048 datum->data[len] = '\000';
1049 datum->size++;
1050 } else {
1051 /* To get around const issue */
1052 memcpy(&datum->data,
1053 &buf, sizeof(datum->data));
1054 }
1055 return 0;
1056}
1057
1058/*
1059 * return 0 Success (GNUTLS_E_SUCCESS)
1060 * neg GNUTLS_E_* error code
1061 */
1062static int
1063setup_pki_credentials(gnutls_certificate_credentials_t *pki_credentials,
1064 gnutls_session_t g_session,
1065 coap_gnutls_context_t *g_context,
1066 coap_dtls_pki_t *setup_data, coap_dtls_role_t role) {
1067 coap_dtls_key_t key;
1068 int ret;
1069 gnutls_datum_t cert;
1070 gnutls_datum_t pkey;
1071 gnutls_datum_t ca;
1072 int alloced_cert_memory = 0;
1073 int alloced_pkey_memory = 0;
1074 int alloced_ca_memory = 0;
1075 int have_done_key = 0;
1076
1077 /* Map over to the new define format to save code duplication */
1078 coap_dtls_map_key_type_to_define(setup_data, &key);
1079
1080 assert(key.key_type == COAP_PKI_KEY_DEFINE);
1081
1082 G_CHECK(gnutls_certificate_allocate_credentials(pki_credentials),
1083 "gnutls_certificate_allocate_credentials");
1084
1085 /*
1086 * Configure the Private Key
1087 */
1088 if (key.key.define.private_key.u_byte &&
1089 key.key.define.private_key.u_byte[0]) {
1090 switch (key.key.define.private_key_def) {
1091 case COAP_PKI_KEY_DEF_PEM: /* define private key */
1092 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
1093 case COAP_PKI_KEY_DEF_DER: /* define private key */
1094 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
1095 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
1096 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
1097 /* Handled under public key */
1098 break;
1099 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
1100#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1101 /* Handled under public key */
1102 break;
1103#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1104 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1107 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1108#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1109 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
1110 default:
1113 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1114 }
1115 } else if (role == COAP_DTLS_ROLE_SERVER ||
1117 key.key.define.public_cert.u_byte[0])) {
1120 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1121 }
1122
1123 /*
1124 * Configure the Public Certificate / Key
1125 */
1126 if (key.key.define.public_cert.u_byte &&
1127 key.key.define.public_cert.u_byte[0]) {
1128 /* Both Public and Private keys are handled here and MUST be the same type */
1129 if (!(key.key.define.private_key.s_byte &&
1130 key.key.define.private_key.s_byte[0] &&
1134 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1135 }
1136 switch (key.key.define.public_cert_def) {
1137 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
1138 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1141 GNUTLS_X509_FMT_PEM) < 0)) {
1144 &key, role, ret);
1145 }
1146 break;
1147 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
1148 if ((ret = check_null_memory(&cert,
1151 &alloced_cert_memory)) < 0) {
1154 &key, role, ret);
1155 }
1156 if ((ret = check_null_memory(&pkey,
1159 &alloced_pkey_memory)) < 0) {
1160 if (alloced_cert_memory)
1161 gnutls_free(cert.data);
1164 &key, role, ret);
1165 }
1166 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1167 &cert,
1168 &pkey,
1169 GNUTLS_X509_FMT_PEM)) < 0) {
1170 if (alloced_cert_memory)
1171 gnutls_free(cert.data);
1172 if (alloced_pkey_memory)
1173 gnutls_free(pkey.data);
1176 &key, role, ret);
1177 }
1178 if (alloced_cert_memory)
1179 gnutls_free(cert.data);
1180 if (alloced_pkey_memory)
1181 gnutls_free(pkey.data);
1182 break;
1183 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
1184#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1185 if ((ret = check_null_memory(&cert,
1188 &alloced_cert_memory)) < 0) {
1191 &key, role, ret);
1192 }
1193 if ((ret = check_null_memory(&pkey,
1196 &alloced_pkey_memory)) < 0) {
1197 if (alloced_cert_memory)
1198 gnutls_free(cert.data);
1201 &key, role, ret);
1202 }
1203 if (strstr((char *)pkey.data, "-----BEGIN EC PRIVATE KEY-----")) {
1204 gnutls_datum_t der_private;
1205
1206 if (gnutls_pem_base64_decode2("EC PRIVATE KEY", &pkey,
1207 &der_private) == 0) {
1208 coap_binary_t *spki = get_asn1_spki(der_private.data,
1209 der_private.size);
1210
1211 if (spki) {
1212 gnutls_datum_t tspki;
1213
1214 tspki.data = spki->s;
1215 tspki.size = spki->length;
1216 ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1217 &tspki,
1218 &der_private,
1219 GNUTLS_X509_FMT_DER, NULL,
1220 COAP_GNUTLS_KEY_RPK,
1221 NULL, 0, 0);
1222 if (ret >= 0) {
1223 have_done_key = 1;
1224 }
1225 coap_delete_binary(spki);
1226 }
1227 gnutls_free(der_private.data);
1228 }
1229 }
1230 if (!have_done_key) {
1231 if ((ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1232 &cert,
1233 &pkey,
1234 GNUTLS_X509_FMT_PEM, NULL,
1235 COAP_GNUTLS_KEY_RPK,
1236 NULL, 0, 0)) < 0) {
1237 if (alloced_cert_memory)
1238 gnutls_free(cert.data);
1239 if (alloced_pkey_memory)
1240 gnutls_free(pkey.data);
1243 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1244 }
1245 }
1246 if (alloced_cert_memory)
1247 gnutls_free(cert.data);
1248 if (alloced_pkey_memory)
1249 gnutls_free(pkey.data);
1250 break;
1251#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1252 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1255 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1256#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1257 case COAP_PKI_KEY_DEF_DER: /* define public cert */
1258 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1261 GNUTLS_X509_FMT_DER) < 0)) {
1264 &key, role, ret);
1265 }
1266 break;
1267 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
1268 if ((ret = check_null_memory(&cert,
1271 &alloced_cert_memory)) < 0) {
1274 &key, role, ret);
1275 }
1276 if ((ret = check_null_memory(&pkey,
1279 &alloced_pkey_memory)) < 0) {
1280 if (alloced_cert_memory)
1281 gnutls_free(cert.data);
1284 &key, role, ret);
1285 }
1286 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1287 &cert,
1288 &pkey,
1289 GNUTLS_X509_FMT_DER)) < 0) {
1290 if (alloced_cert_memory)
1291 gnutls_free(cert.data);
1292 if (alloced_pkey_memory)
1293 gnutls_free(pkey.data);
1296 &key, role, ret);
1297 }
1298 if (alloced_cert_memory)
1299 gnutls_free(cert.data);
1300 if (alloced_pkey_memory)
1301 gnutls_free(pkey.data);
1302 break;
1303 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
1304 gnutls_pkcs11_set_pin_function(pin_callback, &setup_data->pki_key);
1305 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1308 GNUTLS_X509_FMT_DER)) < 0) {
1311 &key, role, ret);
1312 }
1313 break;
1314 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
1315#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1316 gnutls_pkcs11_set_pin_function(pin_callback, setup_data);
1317 if ((ret = gnutls_certificate_set_rawpk_key_file(*pki_credentials,
1320 GNUTLS_X509_FMT_PEM, NULL,
1321 COAP_GNUTLS_KEY_RPK,
1322 NULL, 0, GNUTLS_PKCS_PLAIN, 0))) {
1325 &key, role, ret);
1326 }
1327#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1328 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1329 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1330#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1331 break;
1332 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
1333 default:
1336 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1337 }
1338 }
1339
1340 /*
1341 * Configure the CA
1342 */
1343 if (setup_data->check_common_ca && key.key.define.ca.u_byte &&
1344 key.key.define.ca.u_byte[0]) {
1345 switch (key.key.define.ca_def) {
1347 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1348 key.key.define.ca.s_byte,
1349 GNUTLS_X509_FMT_PEM) < 0)) {
1352 &key, role, ret);
1353 }
1354 break;
1355 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
1356 if ((ret = check_null_memory(&ca,
1357 key.key.define.ca.u_byte,
1358 key.key.define.ca_len,
1359 &alloced_ca_memory)) < 0) {
1362 &key, role, ret);
1363 }
1364 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1365 &ca,
1366 GNUTLS_X509_FMT_PEM)) < 0) {
1367 if (alloced_ca_memory)
1368 gnutls_free(ca.data);
1371 &key, role, ret);
1372 }
1373 if (alloced_ca_memory)
1374 gnutls_free(ca.data);
1375 break;
1376 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
1377 /* Ignore if set */
1378 break;
1379 case COAP_PKI_KEY_DEF_DER: /* define ca */
1380 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1381 key.key.define.ca.s_byte,
1382 GNUTLS_X509_FMT_DER) < 0)) {
1385 &key, role, ret);
1386 }
1387 break;
1388 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
1389 if ((ret = check_null_memory(&ca,
1390 key.key.define.ca.u_byte,
1391 key.key.define.ca_len,
1392 &alloced_ca_memory)) < 0) {
1395 &key, role, ret);
1396 }
1397 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1398 &ca,
1399 GNUTLS_X509_FMT_DER)) <= 0) {
1400 if (alloced_ca_memory)
1401 gnutls_free(ca.data);
1404 &key, role, ret);
1405 }
1406 if (alloced_ca_memory)
1407 gnutls_free(ca.data);
1408 break;
1409 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
1410 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1411 key.key.define.ca.s_byte,
1412 GNUTLS_X509_FMT_DER)) <= 0) {
1415 &key, role, ret);
1416 }
1417 break;
1418 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
1419 /* Ignore if set */
1420 break;
1421 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
1422 default:
1425 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1426 }
1427 }
1428
1429 if (g_context->root_ca_file) {
1430 ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1431 g_context->root_ca_file,
1432 GNUTLS_X509_FMT_PEM);
1433 if (ret == 0) {
1434 coap_log_warn("gnutls_certificate_set_x509_trust_file: Root CA: No certificates found\n");
1435 }
1436 }
1437 if (g_context->root_ca_path) {
1438#if (GNUTLS_VERSION_NUMBER >= 0x030306)
1439 G_CHECK(gnutls_certificate_set_x509_trust_dir(*pki_credentials,
1440 g_context->root_ca_path,
1441 GNUTLS_X509_FMT_PEM),
1442 "gnutls_certificate_set_x509_trust_dir");
1443#endif
1444 }
1445 gnutls_certificate_send_x509_rdn_sequence(g_session,
1446 setup_data->check_common_ca ? 0 : 1);
1447 if (!(g_context->psk_pki_enabled & IS_PKI)) {
1448 /* No PKI defined at all - still need a trust set up for 3.6.0 or later */
1449 G_CHECK(gnutls_certificate_set_x509_system_trust(*pki_credentials),
1450 "gnutls_certificate_set_x509_system_trust");
1451 }
1452
1453 /* Verify Peer */
1454 gnutls_certificate_set_verify_function(*pki_credentials,
1455 cert_verify_callback_gnutls);
1456
1457 /* Cert chain checking (can raise GNUTLS_E_CONSTRAINT_ERROR) */
1458 if (setup_data->cert_chain_validation) {
1459 gnutls_certificate_set_verify_limits(*pki_credentials,
1460 0,
1461 setup_data->cert_chain_verify_depth + 2);
1462 }
1463
1464 /*
1465 * Check for self signed
1466 * CRL checking (can raise GNUTLS_CERT_MISSING_OCSP_STATUS)
1467 */
1468 gnutls_certificate_set_verify_flags(*pki_credentials,
1469 (setup_data->check_cert_revocation == 0 ?
1470 GNUTLS_VERIFY_DISABLE_CRL_CHECKS : 0)
1471 );
1472
1473 return GNUTLS_E_SUCCESS;
1474
1475fail:
1476 return ret;
1477}
1478
1479#if COAP_SERVER_SUPPORT
1480/*
1481 * return 0 Success (GNUTLS_E_SUCCESS)
1482 * neg GNUTLS_E_* error code
1483 */
1484static int
1485setup_psk_credentials(gnutls_psk_server_credentials_t *psk_credentials,
1486 coap_gnutls_context_t *g_context COAP_UNUSED,
1487 coap_dtls_spsk_t *setup_data) {
1488 int ret;
1489 char hint[COAP_DTLS_HINT_LENGTH];
1490
1491 G_CHECK(gnutls_psk_allocate_server_credentials(psk_credentials),
1492 "gnutls_psk_allocate_server_credentials");
1493 gnutls_psk_set_server_credentials_function(*psk_credentials,
1494 psk_server_callback);
1495 if (setup_data->psk_info.hint.s) {
1496 snprintf(hint, sizeof(hint), "%.*s", (int)setup_data->psk_info.hint.length,
1497 setup_data->psk_info.hint.s);
1498 G_CHECK(gnutls_psk_set_server_credentials_hint(*psk_credentials, hint),
1499 "gnutls_psk_set_server_credentials_hint");
1500 }
1501
1502 return GNUTLS_E_SUCCESS;
1503
1504fail:
1505 return ret;
1506}
1507
1508/*
1509 * return 0 Success (GNUTLS_E_SUCCESS)
1510 * neg GNUTLS_E_* error code
1511 */
1512static int
1513post_client_hello_gnutls_psk(gnutls_session_t g_session) {
1514 coap_session_t *c_session =
1515 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1516 coap_gnutls_context_t *g_context =
1517 (coap_gnutls_context_t *)c_session->context->dtls_context;
1518 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1519 int ret = GNUTLS_E_SUCCESS;
1520 char *name = NULL;
1521
1523 coap_dtls_spsk_t sni_setup_data;
1524 /* DNS names (only type supported) may be at most 256 byte long */
1525 size_t len = 256;
1526 unsigned int type;
1527 unsigned int i;
1528
1529 name = gnutls_malloc(len);
1530 if (name == NULL)
1531 return GNUTLS_E_MEMORY_ERROR;
1532
1533 for (i=0; ;) {
1534 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1535 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1536 char *new_name;
1537 new_name = gnutls_realloc(name, len);
1538 if (new_name == NULL) {
1539 ret = GNUTLS_E_MEMORY_ERROR;
1540 goto end;
1541 }
1542 name = new_name;
1543 continue; /* retry call with same index */
1544 }
1545
1546 /* check if it is the last entry in list */
1547 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1548 break;
1549 i++;
1550 if (ret != GNUTLS_E_SUCCESS)
1551 goto end;
1552 /* unknown types need to be ignored */
1553 if (type != GNUTLS_NAME_DNS)
1554 continue;
1555
1556 }
1557 /* If no extension provided, make it a dummy entry */
1558 if (i == 0) {
1559 name[0] = '\000';
1560 len = 0;
1561 }
1562
1563 /* Is this a cached entry? */
1564 for (i = 0; i < g_context->psk_sni_count; i++) {
1565 if (strcasecmp(name, g_context->psk_sni_entry_list[i].sni) == 0) {
1566 break;
1567 }
1568 }
1569 if (i == g_context->psk_sni_count) {
1570 /*
1571 * New SNI request
1572 */
1573 const coap_dtls_spsk_info_t *new_entry;
1574
1575 coap_lock_callback_ret(new_entry, c_session->context,
1577 c_session,
1579 if (!new_entry) {
1580 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1581 GNUTLS_A_UNRECOGNIZED_NAME));
1582 g_env->sent_alert = 1;
1583 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1584 goto end;
1585 }
1586
1587 g_context->psk_sni_entry_list =
1588 gnutls_realloc(g_context->psk_sni_entry_list,
1589 (i+1)*sizeof(psk_sni_entry));
1590 g_context->psk_sni_entry_list[i].sni = gnutls_strdup(name);
1591 g_context->psk_sni_entry_list[i].psk_info = *new_entry;
1592 sni_setup_data = c_session->context->spsk_setup_data;
1593 sni_setup_data.psk_info = *new_entry;
1594 if ((ret = setup_psk_credentials(
1595 &g_context->psk_sni_entry_list[i].psk_credentials,
1596 g_context,
1597 &sni_setup_data)) < 0) {
1598 int keep_ret = ret;
1599 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1600 GNUTLS_A_BAD_CERTIFICATE));
1601 g_env->sent_alert = 1;
1602 ret = keep_ret;
1603 goto end;
1604 }
1605 g_context->psk_sni_count++;
1606 }
1607 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1608 g_context->psk_sni_entry_list[i].psk_credentials),
1609 "gnutls_credentials_set");
1611 &g_context->psk_sni_entry_list[i].psk_info.hint);
1613 &g_context->psk_sni_entry_list[i].psk_info.key);
1614 }
1615
1616end:
1617 free(name);
1618 return ret;
1619
1620fail:
1621 return ret;
1622}
1623
1624/*
1625 * return 0 Success (GNUTLS_E_SUCCESS)
1626 * neg GNUTLS_E_* error code
1627 */
1628static int
1629post_client_hello_gnutls_pki(gnutls_session_t g_session) {
1630 coap_session_t *c_session =
1631 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1632 coap_gnutls_context_t *g_context =
1633 (coap_gnutls_context_t *)c_session->context->dtls_context;
1634 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1635 int ret = GNUTLS_E_SUCCESS;
1636 char *name = NULL;
1637
1638 if (g_context->setup_data.validate_sni_call_back) {
1639 /* DNS names (only type supported) may be at most 256 byte long */
1640 size_t len = 256;
1641 unsigned int type;
1642 unsigned int i;
1643 coap_dtls_pki_t sni_setup_data;
1644
1645 name = gnutls_malloc(len);
1646 if (name == NULL)
1647 return GNUTLS_E_MEMORY_ERROR;
1648
1649 for (i=0; ;) {
1650 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1651 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1652 char *new_name;
1653 new_name = gnutls_realloc(name, len);
1654 if (new_name == NULL) {
1655 ret = GNUTLS_E_MEMORY_ERROR;
1656 goto end;
1657 }
1658 name = new_name;
1659 continue; /* retry call with same index */
1660 }
1661
1662 /* check if it is the last entry in list */
1663 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1664 break;
1665 i++;
1666 if (ret != GNUTLS_E_SUCCESS)
1667 goto end;
1668 /* unknown types need to be ignored */
1669 if (type != GNUTLS_NAME_DNS)
1670 continue;
1671
1672 }
1673 /* If no extension provided, make it a dummy entry */
1674 if (i == 0) {
1675 name[0] = '\000';
1676 len = 0;
1677 }
1678
1679 /* Is this a cached entry? */
1680 for (i = 0; i < g_context->pki_sni_count; i++) {
1681 if (strcasecmp(name, g_context->pki_sni_entry_list[i].sni) == 0) {
1682 break;
1683 }
1684 }
1685 if (i == g_context->pki_sni_count) {
1686 /*
1687 * New SNI request
1688 */
1689 coap_dtls_key_t *new_entry;
1690
1691 coap_lock_callback_ret(new_entry, c_session->context,
1692 g_context->setup_data.validate_sni_call_back(name,
1693 g_context->setup_data.sni_call_back_arg));
1694 if (!new_entry) {
1695 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1696 GNUTLS_A_UNRECOGNIZED_NAME));
1697 g_env->sent_alert = 1;
1698 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1699 goto end;
1700 }
1701
1702 g_context->pki_sni_entry_list = gnutls_realloc(
1703 g_context->pki_sni_entry_list,
1704 (i+1)*sizeof(pki_sni_entry));
1705 g_context->pki_sni_entry_list[i].sni = gnutls_strdup(name);
1706 g_context->pki_sni_entry_list[i].pki_key = *new_entry;
1707 sni_setup_data = g_context->setup_data;
1708 sni_setup_data.pki_key = *new_entry;
1709 if ((ret = setup_pki_credentials(&g_context->pki_sni_entry_list[i].pki_credentials,
1710 g_session,
1711 g_context,
1712 &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
1713 int keep_ret = ret;
1714 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1715 GNUTLS_A_BAD_CERTIFICATE));
1716 g_env->sent_alert = 1;
1717 ret = keep_ret;
1718 goto end;
1719 }
1720 g_context->pki_sni_count++;
1721 }
1722 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1723 g_context->pki_sni_entry_list[i].pki_credentials),
1724 "gnutls_credentials_set");
1725 }
1726
1727end:
1728 free(name);
1729 return ret;
1730
1731fail:
1732 return ret;
1733}
1734#endif /* COAP_SERVER_SUPPORT */
1735
1736#if COAP_CLIENT_SUPPORT
1737/*
1738 * return 0 Success (GNUTLS_E_SUCCESS)
1739 * neg GNUTLS_E_* error code
1740 */
1741static int
1742setup_client_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
1743 coap_gnutls_context_t *g_context =
1744 (coap_gnutls_context_t *)c_session->context->dtls_context;
1745 int ret;
1746
1747 g_context->psk_pki_enabled |= IS_CLIENT;
1748 if (g_context->psk_pki_enabled & IS_PSK) {
1749 coap_dtls_cpsk_t *setup_data = &c_session->cpsk_setup_data;
1750 G_CHECK(gnutls_psk_allocate_client_credentials(&g_env->psk_cl_credentials),
1751 "gnutls_psk_allocate_client_credentials");
1752 gnutls_psk_set_client_credentials_function(g_env->psk_cl_credentials,
1753 psk_client_callback);
1754 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1755 g_env->psk_cl_credentials),
1756 "gnutls_credentials_set");
1757 /* Issue SNI if requested */
1758 if (setup_data->client_sni) {
1759 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1760 setup_data->client_sni,
1761 strlen(setup_data->client_sni)),
1762 "gnutls_server_name_set");
1763 }
1764 if (setup_data->validate_ih_call_back) {
1765 const char *err;
1767
1768 if (tls_version->version >= 0x030604) {
1769 /* Disable TLS1.3 if Identity Hint Callback set */
1770 const char *priority;
1771
1772 if (tls_version->version >= 0x030606) {
1773 priority = VARIANTS_NO_TLS13_3_6_6;
1774 } else {
1775 priority = VARIANTS_NO_TLS13_3_6_4;
1776 }
1777 ret = gnutls_priority_set_direct(g_env->g_session,
1778 priority, &err);
1779 if (ret < 0) {
1780 if (ret == GNUTLS_E_INVALID_REQUEST)
1781 coap_log_warn("gnutls_priority_set_direct: Syntax error at: %s\n", err);
1782 else
1783 coap_log_warn("gnutls_priority_set_direct: %s\n", gnutls_strerror(ret));
1784 goto fail;
1785 }
1786 }
1787 }
1788 }
1789
1790 if ((g_context->psk_pki_enabled & IS_PKI) ||
1791 (g_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1792 /*
1793 * If neither PSK or PKI have been set up, use PKI basics.
1794 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1795 */
1796 coap_dtls_pki_t *setup_data = &g_context->setup_data;
1797 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
1798 g_context, setup_data,
1800 "setup_pki_credentials");
1801
1802 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1803 g_env->pki_credentials),
1804 "gnutls_credentials_set");
1805
1806 if (c_session->proto == COAP_PROTO_TLS)
1807 G_CHECK(gnutls_alpn_set_protocols(g_env->g_session,
1808 &g_context->alpn_proto, 1, 0),
1809 "gnutls_alpn_set_protocols");
1810
1811 /* Issue SNI if requested (only happens if PKI defined) */
1812 if (setup_data->client_sni) {
1813 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1814 setup_data->client_sni,
1815 strlen(setup_data->client_sni)),
1816 "gnutls_server_name_set");
1817 }
1818 }
1819 return GNUTLS_E_SUCCESS;
1820
1821fail:
1822 return ret;
1823}
1824#endif /* COAP_CLIENT_SUPPORT */
1825
1826#if COAP_SERVER_SUPPORT
1827/*
1828 * gnutls_psk_server_credentials_function return values
1829 * (see gnutls_psk_set_server_credentials_function())
1830 *
1831 * return -1 failed
1832 * 0 passed
1833 */
1834static int
1835psk_server_callback(gnutls_session_t g_session,
1836 const char *identity,
1837 gnutls_datum_t *key) {
1838 coap_session_t *c_session =
1839 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1840 coap_gnutls_context_t *g_context;
1841 coap_dtls_spsk_t *setup_data;
1842 coap_bin_const_t lidentity;
1843 const coap_bin_const_t *psk_key;
1844
1845 if (c_session == NULL)
1846 return -1;
1847
1848 g_context = (coap_gnutls_context_t *)c_session->context->dtls_context;
1849 if (g_context == NULL)
1850 return -1;
1851 setup_data = &c_session->context->spsk_setup_data;
1852
1853
1854 /* Track the Identity being used */
1855 lidentity.s = identity ? (const uint8_t *)identity : (const uint8_t *)"";
1856 lidentity.length = strlen((const char *)lidentity.s);
1857 coap_session_refresh_psk_identity(c_session, &lidentity);
1858
1859 coap_log_debug("got psk_identity: '%.*s'\n",
1860 (int)lidentity.length, (const char *)lidentity.s);
1861
1862 if (setup_data->validate_id_call_back) {
1863 psk_key = setup_data->validate_id_call_back(&lidentity,
1864 c_session,
1865 setup_data->id_call_back_arg);
1866
1867 coap_session_refresh_psk_key(c_session, psk_key);
1868 } else {
1869 psk_key = coap_get_session_server_psk_key(c_session);
1870 }
1871
1872 if (psk_key == NULL)
1873 return -1;
1874
1875 key->data = gnutls_malloc(psk_key->length);
1876 if (key->data == NULL)
1877 return -1;
1878 memcpy(key->data, psk_key->s, psk_key->length);
1879 key->size = psk_key->length;
1880 return 0;
1881}
1882
1883/*
1884 * return 0 Success (GNUTLS_E_SUCCESS)
1885 * neg GNUTLS_E_* error code
1886 */
1887static int
1888setup_server_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
1889 coap_gnutls_context_t *g_context =
1890 (coap_gnutls_context_t *)c_session->context->dtls_context;
1891 int ret = GNUTLS_E_SUCCESS;
1892
1893 g_context->psk_pki_enabled |= IS_SERVER;
1894 if (g_context->psk_pki_enabled & IS_PSK) {
1895 G_CHECK(setup_psk_credentials(
1896 &g_env->psk_sv_credentials,
1897 g_context,
1898 &c_session->context->spsk_setup_data),
1899 "setup_psk_credentials\n");
1900 G_CHECK(gnutls_credentials_set(g_env->g_session,
1901 GNUTLS_CRD_PSK,
1902 g_env->psk_sv_credentials),
1903 "gnutls_credentials_set\n");
1904 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
1905 post_client_hello_gnutls_psk);
1906 }
1907
1908 if (g_context->psk_pki_enabled & IS_PKI) {
1909 coap_dtls_pki_t *setup_data = &g_context->setup_data;
1910 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
1911 g_context, setup_data,
1913 "setup_pki_credentials");
1914
1915 if (setup_data->verify_peer_cert) {
1916 gnutls_certificate_server_set_request(g_env->g_session,
1917 GNUTLS_CERT_REQUIRE);
1918 } else if (setup_data->is_rpk_not_cert) {
1919 gnutls_certificate_server_set_request(g_env->g_session,
1920 GNUTLS_CERT_REQUEST);
1921 } else {
1922 gnutls_certificate_server_set_request(g_env->g_session,
1923 GNUTLS_CERT_IGNORE);
1924 }
1925
1926 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
1927 post_client_hello_gnutls_pki);
1928
1929 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1930 g_env->pki_credentials),
1931 "gnutls_credentials_set\n");
1932 }
1933 return GNUTLS_E_SUCCESS;
1934
1935fail:
1936 return ret;
1937}
1938#endif /* COAP_SERVER_SUPPORT */
1939
1940/*
1941 * return +ve data amount
1942 * 0 no more
1943 * -1 error (error in errno)
1944 */
1945static ssize_t
1946coap_dgram_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
1947 ssize_t ret = 0;
1948 coap_session_t *c_session = (coap_session_t *)context;
1949 coap_ssl_t *data;
1950
1951 if (!c_session->tls) {
1952 errno = EAGAIN;
1953 return -1;
1954 }
1955 data = &((coap_gnutls_env_t *)c_session->tls)->coap_ssl_data;
1956
1957 if (out != NULL) {
1958 if (data != NULL && data->pdu_len > 0) {
1959 if (outl < data->pdu_len) {
1960 memcpy(out, data->pdu, outl);
1961 ret = outl;
1962 if (!data->peekmode) {
1963 data->pdu += outl;
1964 data->pdu_len -= outl;
1965 }
1966 } else {
1967 memcpy(out, data->pdu, data->pdu_len);
1968 ret = data->pdu_len;
1969 if (!data->peekmode) {
1970 data->pdu_len = 0;
1971 data->pdu = NULL;
1972 }
1973 }
1974 } else {
1975 errno = EAGAIN;
1976 ret = -1;
1977 }
1978 }
1979 return ret;
1980}
1981
1982/*
1983 * return +ve data amount
1984 * 0 no more
1985 * -1 error (error in errno)
1986 */
1987/* callback function given to gnutls for sending data over socket */
1988static ssize_t
1989coap_dgram_write(gnutls_transport_ptr_t context, const void *send_buffer,
1990 size_t send_buffer_length) {
1991 ssize_t result = -1;
1992 coap_session_t *c_session = (coap_session_t *)context;
1993
1994 if (c_session) {
1995 if (!coap_netif_available(c_session)
1997 && c_session->endpoint == NULL
1998#endif /* COAP_SERVER_SUPPORT */
1999 ) {
2000 /* socket was closed on client due to error */
2001 errno = ECONNRESET;
2002 return -1;
2003 }
2004 result = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
2005 send_buffer, send_buffer_length);
2006 if (result != (int)send_buffer_length) {
2007 int keep_errno = errno;
2008
2009 coap_log_warn("coap_netif_dgrm_write failed (%zd != %zu)\n",
2010 result, send_buffer_length);
2011 errno = keep_errno;
2012 if (result < 0) {
2013 return -1;
2014 } else {
2015 result = 0;
2016 }
2017 }
2018 } else {
2019 result = 0;
2020 }
2021 return result;
2022}
2023
2024/*
2025 * return 1 fd has activity
2026 * 0 timeout
2027 * -1 error (error in errno)
2028 */
2029static int
2030receive_timeout(gnutls_transport_ptr_t context, unsigned int ms COAP_UNUSED) {
2031 coap_session_t *c_session = (coap_session_t *)context;
2032
2033 if (c_session) {
2034 fd_set readfds, writefds, exceptfds;
2035 struct timeval tv;
2036 int nfds = c_session->sock.fd +1;
2037 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2038
2039 /* If data has been read in by libcoap ahead of GnuTLS, say it is there */
2040 if (c_session->proto == COAP_PROTO_DTLS && g_env &&
2041 g_env->coap_ssl_data.pdu_len > 0) {
2042 return 1;
2043 }
2044
2045 FD_ZERO(&readfds);
2046 FD_ZERO(&writefds);
2047 FD_ZERO(&exceptfds);
2048 FD_SET(c_session->sock.fd, &readfds);
2049 if (!(g_env && g_env->doing_dtls_timeout)) {
2050 FD_SET(c_session->sock.fd, &writefds);
2051 FD_SET(c_session->sock.fd, &exceptfds);
2052 }
2053 /* Polling */
2054 tv.tv_sec = 0;
2055 tv.tv_usec = 0;
2056
2057 return select(nfds, &readfds, &writefds, &exceptfds, &tv);
2058 }
2059 return 1;
2060}
2061
2062static coap_gnutls_env_t *
2063coap_dtls_new_gnutls_env(coap_session_t *c_session, int type) {
2064 coap_gnutls_context_t *g_context =
2065 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2066 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2067#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2068 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2069#else /* < 3.6.6 */
2070 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK;
2071#endif /* < 3.6.6 */
2072 int ret;
2073
2074 if (g_env)
2075 return g_env;
2076
2077 g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2078 if (!g_env)
2079 return NULL;
2080
2081 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2082
2083 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2084
2085 gnutls_transport_set_pull_function(g_env->g_session, coap_dgram_read);
2086 gnutls_transport_set_push_function(g_env->g_session, coap_dgram_write);
2087 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2088 /* So we can track the coap_session_t in callbacks */
2089 gnutls_transport_set_ptr(g_env->g_session, c_session);
2090
2091 G_CHECK(gnutls_priority_set(g_env->g_session, g_context->priority_cache),
2092 "gnutls_priority_set");
2093
2094 if (type == GNUTLS_SERVER) {
2095#if COAP_SERVER_SUPPORT
2096 G_CHECK(setup_server_ssl_session(c_session, g_env),
2097 "setup_server_ssl_session");
2098#else /* ! COAP_SERVER_SUPPORT */
2099 goto fail;
2100#endif /* ! COAP_SERVER_SUPPORT */
2101 } else {
2102#if COAP_CLIENT_SUPPORT
2103 G_CHECK(setup_client_ssl_session(c_session, g_env),
2104 "setup_client_ssl_session");
2105#else /* COAP_CLIENT_SUPPORT */
2106 goto fail;
2107#endif /* COAP_CLIENT_SUPPORT */
2108 }
2109
2110 gnutls_handshake_set_timeout(g_env->g_session,
2111 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2112 gnutls_dtls_set_timeouts(g_env->g_session, COAP_DTLS_RETRANSMIT_MS,
2113 COAP_DTLS_RETRANSMIT_TOTAL_MS);
2114
2115 return g_env;
2116
2117fail:
2118 if (g_env)
2119 gnutls_free(g_env);
2120 return NULL;
2121}
2122
2123static void
2124coap_dtls_free_gnutls_env(coap_gnutls_context_t *g_context,
2125 coap_gnutls_env_t *g_env,
2126 coap_free_bye_t free_bye) {
2127 if (g_env) {
2128 /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
2129 * connections because the peer's closure message might
2130 * be lost */
2131 if (free_bye != COAP_FREE_BYE_NONE && !g_env->sent_alert) {
2132 /* Only do this if appropriate */
2133 gnutls_bye(g_env->g_session, free_bye == COAP_FREE_BYE_AS_UDP ?
2134 GNUTLS_SHUT_WR : GNUTLS_SHUT_RDWR);
2135 }
2136 gnutls_deinit(g_env->g_session);
2137 g_env->g_session = NULL;
2138 if (g_context->psk_pki_enabled & IS_PSK) {
2139 if ((g_context->psk_pki_enabled & IS_CLIENT) &&
2140 g_env->psk_cl_credentials != NULL) {
2141 gnutls_psk_free_client_credentials(g_env->psk_cl_credentials);
2142 g_env->psk_cl_credentials = NULL;
2143 } else {
2144 /* YUK - A memory leak in 3.3.0 (fixed by 3.3.26) of hint */
2145 if (g_env->psk_sv_credentials != NULL)
2146 gnutls_psk_free_server_credentials(g_env->psk_sv_credentials);
2147 g_env->psk_sv_credentials = NULL;
2148 }
2149 }
2150 if ((g_context->psk_pki_enabled & IS_PKI) ||
2151 (g_context->psk_pki_enabled &
2152 (IS_PSK | IS_PKI | IS_CLIENT)) == IS_CLIENT) {
2153 gnutls_certificate_free_credentials(g_env->pki_credentials);
2154 g_env->pki_credentials = NULL;
2155 }
2156 gnutls_free(g_env->coap_ssl_data.cookie_key.data);
2157 gnutls_free(g_env);
2158 }
2159}
2160
2161#if COAP_SERVER_SUPPORT
2162void *
2164 coap_gnutls_env_t *g_env =
2165 (coap_gnutls_env_t *)c_session->tls;
2166
2167 gnutls_transport_set_ptr(g_env->g_session, c_session);
2168
2169 return g_env;
2170}
2171#endif /* COAP_SERVER_SUPPORT */
2172
2173static void
2174log_last_alert(coap_session_t *c_session,
2175 gnutls_session_t g_session) {
2176#if COAP_MAX_LOGGING_LEVEL > 0
2177 int last_alert = gnutls_alert_get(g_session);
2178
2179 if (last_alert == GNUTLS_A_CLOSE_NOTIFY)
2180 coap_log_debug("***%s: Alert '%d': %s\n",
2181 coap_session_str(c_session),
2182 last_alert, gnutls_alert_get_name(last_alert));
2183 else
2184 coap_log_warn("***%s: Alert '%d': %s\n",
2185 coap_session_str(c_session),
2186 last_alert, gnutls_alert_get_name(last_alert));
2187#else /* COAP_MAX_LOGGING_LEVEL == 0 */
2188 (void)c_session;
2189 (void)g_session;
2190#endif /* COAP_MAX_LOGGING_LEVEL == 0 */
2191}
2192
2193/*
2194 * return -1 failure
2195 * 0 not completed
2196 * 1 established
2197 */
2198static int
2199do_gnutls_handshake(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
2200 int ret;
2201
2202 ret = gnutls_handshake(g_env->g_session);
2203 switch (ret) {
2204 case GNUTLS_E_SUCCESS:
2205 g_env->established = 1;
2206 coap_log_debug("* %s: GnuTLS established\n",
2207 coap_session_str(c_session));
2208 ret = 1;
2209 break;
2210 case GNUTLS_E_INTERRUPTED:
2211 errno = EINTR;
2212 ret = 0;
2213 break;
2214 case GNUTLS_E_AGAIN:
2215 errno = EAGAIN;
2216 ret = 0;
2217 break;
2218 case GNUTLS_E_INSUFFICIENT_CREDENTIALS:
2219 coap_log_warn("Insufficient credentials provided.\n");
2220 ret = -1;
2221 break;
2222 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2223 /* Stop the sending of an alert on closedown */
2224 g_env->sent_alert = 1;
2225 log_last_alert(c_session, g_env->g_session);
2226 /* Fall through */
2227 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET:
2228 case GNUTLS_E_UNEXPECTED_PACKET:
2230 ret = -1;
2231 break;
2232 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2233 log_last_alert(c_session, g_env->g_session);
2234 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2235 ret = 0;
2236 break;
2237 case GNUTLS_E_NO_CERTIFICATE_FOUND:
2238#if (GNUTLS_VERSION_NUMBER > 0x030606)
2239 case GNUTLS_E_CERTIFICATE_REQUIRED:
2240#endif /* GNUTLS_VERSION_NUMBER > 0x030606 */
2241 coap_log_warn("Client Certificate requested and required, but not provided\n"
2242 );
2243 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2244 GNUTLS_A_BAD_CERTIFICATE));
2245 g_env->sent_alert = 1;
2247 ret = -1;
2248 break;
2249 case GNUTLS_E_DECRYPTION_FAILED:
2250 coap_log_warn("do_gnutls_handshake: session establish "
2251 "returned '%s'\n",
2252 gnutls_strerror(ret));
2253 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2254 GNUTLS_A_DECRYPT_ERROR));
2255 g_env->sent_alert = 1;
2257 ret = -1;
2258 break;
2259 case GNUTLS_E_CERTIFICATE_ERROR:
2260 if (g_env->sent_alert) {
2262 ret = -1;
2263 break;
2264 }
2265 /* Fall through */
2266 case GNUTLS_E_UNKNOWN_CIPHER_SUITE:
2267 case GNUTLS_E_NO_CIPHER_SUITES:
2268 case GNUTLS_E_INVALID_SESSION:
2269 coap_log_warn("do_gnutls_handshake: session establish "
2270 "returned '%s'\n",
2271 gnutls_strerror(ret));
2272 if (!g_env->sent_alert) {
2273 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2274 GNUTLS_A_HANDSHAKE_FAILURE));
2275 g_env->sent_alert = 1;
2276 }
2278 ret = -1;
2279 break;
2280 case GNUTLS_E_SESSION_EOF:
2281 case GNUTLS_E_PREMATURE_TERMINATION:
2282 case GNUTLS_E_TIMEDOUT:
2283 case GNUTLS_E_PULL_ERROR:
2284 case GNUTLS_E_PUSH_ERROR:
2286 ret = -1;
2287 break;
2288 default:
2289 coap_log_warn("do_gnutls_handshake: session establish "
2290 "returned %d: '%s'\n",
2291 ret, gnutls_strerror(ret));
2292 ret = -1;
2293 break;
2294 }
2295 return ret;
2296}
2297
2298#if COAP_CLIENT_SUPPORT
2299void *
2301 coap_gnutls_env_t *g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_CLIENT);
2302 int ret;
2303
2304 if (g_env) {
2305 ret = do_gnutls_handshake(c_session, g_env);
2306 if (ret == -1) {
2307 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2308 g_env,
2309 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2310 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2311 return NULL;
2312 }
2313 }
2314 return g_env;
2315}
2316#endif /* COAP_CLIENT_SUPPORT */
2317
2318void
2320 if (c_session && c_session->context && c_session->tls) {
2321 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2322 c_session->tls,
2323 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2324 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2325 c_session->tls = NULL;
2327 }
2328}
2329
2330void
2332 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2333 int ret;
2334
2335 if (g_env)
2336 G_CHECK(gnutls_dtls_set_data_mtu(g_env->g_session,
2337 (unsigned int)c_session->mtu),
2338 "gnutls_dtls_set_data_mtu");
2339fail:
2340 ;;
2341}
2342
2343/*
2344 * return +ve data amount
2345 * 0 no more
2346 * -1 error
2347 */
2348ssize_t
2350 const uint8_t *data, size_t data_len) {
2351 int ret;
2352 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2353
2354 assert(g_env != NULL);
2355
2356 c_session->dtls_event = -1;
2357 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2358 coap_session_str(c_session), (int)data_len);
2359 if (g_env->established) {
2360 ret = gnutls_record_send(g_env->g_session, data, data_len);
2361
2362 if (ret <= 0) {
2363 switch (ret) {
2364 case GNUTLS_E_AGAIN:
2365 ret = 0;
2366 break;
2367 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2368 /* Stop the sending of an alert on closedown */
2369 g_env->sent_alert = 1;
2370 log_last_alert(c_session, g_env->g_session);
2372 ret = -1;
2373 break;
2374 default:
2375 coap_log_debug("coap_dtls_send: gnutls_record_send "
2376 "returned %d: '%s'\n",
2377 ret, gnutls_strerror(ret));
2378 ret = -1;
2379 break;
2380 }
2381 if (ret == -1) {
2382 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2383 }
2384 }
2385 } else {
2386 ret = do_gnutls_handshake(c_session, g_env);
2387 if (ret == 1) {
2388 /* Just connected, so send the data */
2389 return coap_dtls_send(c_session, data, data_len);
2390 }
2391 ret = -1;
2392 }
2393
2394 if (c_session->dtls_event >= 0) {
2395 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2396 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2397 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2398 ret = -1;
2399 }
2400 }
2401
2402 return ret;
2403}
2404
2405int
2407 return 0;
2408}
2409
2411coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2412 return 0;
2413}
2414
2417 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2418
2419 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2420 if (g_env && g_env->g_session) {
2421 unsigned int rem_ms = gnutls_dtls_get_timeout(g_env->g_session);
2422
2423 if (rem_ms == 0) {
2424 /*
2425 * Need to make sure that we do not do this too frequently as some
2426 * versions of gnutls reset retransmit if a spurious packet is received
2427 * (e.g. duplicate Client Hello), but last_transmit does not get updated
2428 * when gnutls_handshake() is called and there is 'nothing' to resend.
2429 */
2430 if (g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS > now)
2431 return g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS;
2432 }
2433 /* Reset for the next time */
2434 g_env->last_timeout = now;
2435 return now + rem_ms;
2436 }
2437
2438 return 0;
2439}
2440
2441/*
2442 * return 1 timed out
2443 * 0 still timing out
2444 */
2445int
2447 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2448
2449 assert(g_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2450 g_env->doing_dtls_timeout = 1;
2451 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2452 (do_gnutls_handshake(c_session, g_env) < 0)) {
2453 /* Too many retries */
2454 g_env->doing_dtls_timeout = 0;
2456 return 1;
2457 } else {
2458 g_env->doing_dtls_timeout = 0;
2459 return 0;
2460 }
2461}
2462
2463/*
2464 * return +ve data amount
2465 * 0 no more
2466 * -1 error
2467 */
2468int
2469coap_dtls_receive(coap_session_t *c_session, const uint8_t *data,
2470 size_t data_len) {
2471 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2472 int ret = 0;
2473 coap_ssl_t *ssl_data = &g_env->coap_ssl_data;
2474
2475 uint8_t pdu[COAP_RXBUFFER_SIZE];
2476
2477 assert(g_env != NULL);
2478
2479 if (ssl_data->pdu_len)
2480 coap_log_err("** %s: Previous data not read %u bytes\n",
2481 coap_session_str(c_session), ssl_data->pdu_len);
2482 ssl_data->pdu = data;
2483 ssl_data->pdu_len = data_len;
2484
2485 c_session->dtls_event = -1;
2486 if (g_env->established) {
2487 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2489 c_session);
2490 gnutls_transport_set_ptr(g_env->g_session, c_session);
2491 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2492 }
2493 ret = gnutls_record_recv(g_env->g_session, pdu, (int)sizeof(pdu));
2494 if (ret > 0) {
2495 return coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2496 } else if (ret == 0) {
2498 } else {
2499 switch (ret) {
2500 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2501 /* Stop the sending of an alert on closedown */
2502 g_env->sent_alert = 1;
2503 log_last_alert(c_session, g_env->g_session);
2505 ret = -1;
2506 break;
2507 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2508 log_last_alert(c_session, g_env->g_session);
2509 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2510 ret = 0;
2511 break;
2512 default:
2513 coap_log_warn("coap_dtls_receive: gnutls_record_recv returned %d\n", ret);
2514 ret = -1;
2515 break;
2516 }
2517 }
2518 } else {
2519 ret = do_gnutls_handshake(c_session, g_env);
2520 if (ret == 1) {
2521 coap_session_connected(c_session);
2522 } else {
2523 ret = -1;
2524 if (ssl_data->pdu_len && !g_env->sent_alert) {
2525 /* Do the handshake again incase of internal timeout */
2526 ret = do_gnutls_handshake(c_session, g_env);
2527 if (ret == 1) {
2528 /* Just connected, so send the data */
2529 coap_session_connected(c_session);
2530 }
2531 }
2532 }
2533 }
2534
2535 if (c_session->dtls_event >= 0) {
2536 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2537 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2538 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2540 ssl_data = NULL;
2541 ret = -1;
2542 }
2543 }
2544 if (ssl_data && ssl_data->pdu_len) {
2545 /* pdu data is held on stack which will not stay there */
2546 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2547 ssl_data->pdu_len = 0;
2548 ssl_data->pdu = NULL;
2549 }
2550 if (ret > 0) {
2551 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2552 coap_session_str(c_session), ret);
2553 }
2554 return ret;
2555}
2556
2557#if COAP_SERVER_SUPPORT
2558/*
2559 * return -1 failure
2560 * 0 not completed
2561 * 1 client hello seen
2562 */
2563int
2565 const uint8_t *data,
2566 size_t data_len
2567 ) {
2568 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2569 coap_ssl_t *ssl_data;
2570 int ret;
2571
2572 if (!g_env) {
2573 g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_SERVER);
2574 if (g_env) {
2575 c_session->tls = g_env;
2576 gnutls_key_generate(&g_env->coap_ssl_data.cookie_key,
2577 GNUTLS_COOKIE_KEY_SIZE);
2578 } else {
2579 /* error should have already been reported */
2580 return -1;
2581 }
2582 }
2583 if (data_len > 0) {
2584 gnutls_dtls_prestate_st prestate;
2585 uint8_t *data_rw;
2586
2587 memset(&prestate, 0, sizeof(prestate));
2588 /* Need to do this to not get a compiler warning about const parameters */
2589 memcpy(&data_rw, &data, sizeof(data_rw));
2590 ret = gnutls_dtls_cookie_verify(&g_env->coap_ssl_data.cookie_key,
2591 &c_session->addr_info,
2592 sizeof(c_session->addr_info),
2593 data_rw, data_len,
2594 &prestate);
2595 if (ret < 0) { /* cookie not valid */
2596 coap_log_debug("Invalid Cookie - sending Hello Verify\n");
2597 gnutls_dtls_cookie_send(&g_env->coap_ssl_data.cookie_key,
2598 &c_session->addr_info,
2599 sizeof(c_session->addr_info),
2600 &prestate,
2601 c_session,
2602 coap_dgram_write);
2603 return 0;
2604 }
2605 gnutls_dtls_prestate_set(g_env->g_session, &prestate);
2606 }
2607
2608 ssl_data = &g_env->coap_ssl_data;
2609 ssl_data->pdu = data;
2610 ssl_data->pdu_len = data_len;
2611
2612 ret = do_gnutls_handshake(c_session, g_env);
2613 if (ret < 0) {
2614 /*
2615 * as the above failed, need to remove g_env to clean up any
2616 * pollution of the information
2617 */
2618 coap_dtls_free_gnutls_env(((coap_gnutls_context_t *)c_session->context->dtls_context),
2619 g_env, COAP_FREE_BYE_NONE);
2620 c_session->tls = NULL;
2621 ssl_data = NULL;
2622 ret = -1;
2623 } else {
2624 /* Client Hello has been seen */
2625 ret = 1;
2626 }
2627
2628 if (ssl_data && ssl_data->pdu_len) {
2629 /* pdu data is held on stack which will not stay there */
2630 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2631 ssl_data->pdu_len = 0;
2632 ssl_data->pdu = NULL;
2633 }
2634 return ret;
2635}
2636#endif /* COAP_SERVER_SUPPORT */
2637
2638unsigned int
2640 return 37;
2641}
2642
2643#if !COAP_DISABLE_TCP
2644/*
2645 * strm
2646 * return +ve data amount
2647 * 0 connection closed
2648 * -1 error (error in errno)
2649 */
2650static ssize_t
2651coap_sock_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
2652 int ret = 0;
2653 coap_session_t *c_session = (coap_session_t *)context;
2654
2655 if (out != NULL) {
2656 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
2657 /* Translate layer returns into what GnuTLS expects */
2658 if (ret == 0) {
2659 errno = EAGAIN;
2660 ret = -1;
2661 }
2662 }
2663 return ret;
2664}
2665
2666/*
2667 * strm
2668 * return +ve data amount
2669 * 0 no more
2670 * -1 error (error in errno)
2671 */
2672static ssize_t
2673coap_sock_write(gnutls_transport_ptr_t context, const void *in, size_t inl) {
2674 int ret = 0;
2675 coap_session_t *c_session = (coap_session_t *)context;
2676
2677 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session, in, inl);
2678 /* Translate layer what returns into what GnuTLS expects */
2679 if (ret < 0) {
2680 if ((c_session->state == COAP_SESSION_STATE_CSM ||
2681 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
2682 (errno == EPIPE || errno == ECONNRESET)) {
2683 /*
2684 * Need to handle a TCP timing window where an agent continues with
2685 * the sending of the next handshake or a CSM.
2686 * However, the peer does not like a certificate and so sends a
2687 * fatal alert and closes the TCP session.
2688 * The sending of the next handshake or CSM may get terminated because
2689 * of the closed TCP session, but there is still an outstanding alert
2690 * to be read in and reported on.
2691 * In this case, pretend that sending the info was fine so that the
2692 * alert can be read (which effectively is what happens with DTLS).
2693 */
2694 ret = inl;
2695 } else {
2696 coap_log_debug("* %s: failed to send %zd bytes (%s) state %d\n",
2697 coap_session_str(c_session), inl, coap_socket_strerror(),
2698 c_session->state);
2699 }
2700 }
2701 if (ret == 0) {
2702 errno = EAGAIN;
2703 ret = -1;
2704 }
2705 return ret;
2706}
2707
2708#if COAP_CLIENT_SUPPORT
2709void *
2711 coap_gnutls_env_t *g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2712 coap_gnutls_context_t *g_context =
2713 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2714#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2715 int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2716#else /* < 3.6.6 */
2717 int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
2718#endif /* < 3.6.6 */
2719 int ret;
2720
2721 if (!g_env) {
2722 return NULL;
2723 }
2724 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2725
2726 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2727
2728 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2729 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2730 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2731 /* So we can track the coap_session_t in callbacks */
2732 gnutls_transport_set_ptr(g_env->g_session, c_session);
2733
2734 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2735 setup_client_ssl_session(c_session, g_env);
2736
2737 gnutls_handshake_set_timeout(g_env->g_session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2738
2739 c_session->tls = g_env;
2740 ret = do_gnutls_handshake(c_session, g_env);
2741 if (ret == 1) {
2743 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2744 }
2745 return g_env;
2746
2747fail:
2748 if (g_env)
2749 gnutls_free(g_env);
2750 return NULL;
2751}
2752#endif /* COAP_CLIENT_SUPPORT */
2753
2754#if COAP_SERVER_SUPPORT
2755void *
2757 coap_gnutls_env_t *g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2758 coap_gnutls_context_t *g_context =
2759 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2760#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2761 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2762#else /* < 3.6.6 */
2763 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK;
2764#endif /* < 3.6.6 */
2765 int ret;
2766
2767 if (!g_env)
2768 return NULL;
2769 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2770
2771 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2772
2773 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2774 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2775 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2776 /* So we can track the coap_session_t in callbacks */
2777 gnutls_transport_set_ptr(g_env->g_session, c_session);
2778
2779 setup_server_ssl_session(c_session, g_env);
2780
2781 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2782 gnutls_handshake_set_timeout(g_env->g_session,
2783 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2784
2785 c_session->tls = g_env;
2786 ret = do_gnutls_handshake(c_session, g_env);
2787 if (ret == 1) {
2789 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2790 }
2791 return g_env;
2792
2793fail:
2794 return NULL;
2795}
2796#endif /* COAP_SERVER_SUPPORT */
2797
2798void
2800 coap_dtls_free_session(c_session);
2801 return;
2802}
2803
2804/*
2805 * strm
2806 * return +ve Number of bytes written.
2807 * -1 Error (error in errno).
2808 */
2809ssize_t
2810coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2811 size_t data_len) {
2812 int ret;
2813 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2814
2815 assert(g_env != NULL);
2816
2817 c_session->dtls_event = -1;
2818 if (g_env->established) {
2819 ret = gnutls_record_send(g_env->g_session, data, data_len);
2820
2821 if (ret <= 0) {
2822 switch (ret) {
2823 case GNUTLS_E_AGAIN:
2824 ret = 0;
2825 break;
2826 case GNUTLS_E_PUSH_ERROR:
2827 case GNUTLS_E_PULL_ERROR:
2828 case GNUTLS_E_PREMATURE_TERMINATION:
2830 break;
2831 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2832 /* Stop the sending of an alert on closedown */
2833 g_env->sent_alert = 1;
2834 log_last_alert(c_session, g_env->g_session);
2836 break;
2837 default:
2838 coap_log_warn("coap_tls_write: gnutls_record_send "
2839 "returned %d: '%s'\n",
2840 ret, gnutls_strerror(ret));
2841 ret = -1;
2842 break;
2843 }
2844 if (ret == -1) {
2845 coap_log_info("coap_tls_write: cannot send PDU\n");
2846 }
2847 }
2848 } else {
2849 ret = do_gnutls_handshake(c_session, g_env);
2850 if (ret == 1) {
2852 c_session);
2853 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2854 ret = 0;
2855 } else {
2856 ret = -1;
2857 }
2858 }
2859
2860 if (c_session->dtls_event >= 0) {
2861 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2862 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2863 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2864 ret = -1;
2865 }
2866 }
2867
2868 if (ret > 0) {
2869 if (ret == (ssize_t)data_len)
2870 coap_log_debug("* %s: tls: sent %4d bytes\n",
2871 coap_session_str(c_session), ret);
2872 else
2873 coap_log_debug("* %s: tls: sent %4d of %4zd bytes\n",
2874 coap_session_str(c_session), ret, data_len);
2875 }
2876 return ret;
2877}
2878
2879/*
2880 * strm
2881 * return >=0 Number of bytes read.
2882 * -1 Error (error in errno).
2883 */
2884ssize_t
2885coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
2886 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2887 int ret = -1;
2888
2889 if (!g_env) {
2890 errno = ENXIO;
2891 return -1;
2892 }
2893
2894 c_session->dtls_event = -1;
2895 if (!g_env->established && !g_env->sent_alert) {
2896 ret = do_gnutls_handshake(c_session, g_env);
2897 if (ret == 1) {
2899 c_session);
2900 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2901 ret = 0;
2902 }
2903 }
2904 if (c_session->state != COAP_SESSION_STATE_NONE && g_env->established) {
2905 ret = gnutls_record_recv(g_env->g_session, data, (int)data_len);
2906 if (ret <= 0) {
2907 switch (ret) {
2908 case 0:
2910 break;
2911 case GNUTLS_E_AGAIN:
2912 errno = EAGAIN;
2913 ret = 0;
2914 break;
2915 case GNUTLS_E_PULL_ERROR:
2916 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2917 break;
2918 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2919 /* Stop the sending of an alert on closedown */
2920 g_env->sent_alert = 1;
2921 log_last_alert(c_session, g_env->g_session);
2923 break;
2924 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2925 log_last_alert(c_session, g_env->g_session);
2926 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2927 break;
2928 default:
2929 coap_log_warn("coap_tls_read: gnutls_record_recv "
2930 "returned %d: '%s'\n",
2931 ret, gnutls_strerror(ret));
2932 ret = -1;
2933 break;
2934 }
2935 }
2936 }
2937
2938 if (c_session->dtls_event >= 0) {
2939 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2940 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2941 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2943 ret = -1;
2944 }
2945 }
2946 if (ret > 0) {
2947 coap_log_debug("* %s: tls: recv %4d bytes\n",
2948 coap_session_str(c_session), ret);
2949 }
2950 return ret;
2951}
2952#endif /* !COAP_DISABLE_TCP */
2953
2954#if COAP_SERVER_SUPPORT
2956coap_digest_setup(void) {
2957 gnutls_hash_hd_t digest_ctx;
2958
2959 if (gnutls_hash_init(&digest_ctx, GNUTLS_DIG_SHA256)) {
2960 return NULL;
2961 }
2962 return digest_ctx;
2963}
2964
2965void
2967 if (digest_ctx)
2968 gnutls_hash_deinit(digest_ctx, NULL);
2969}
2970
2971int
2973 const uint8_t *data,
2974 size_t data_len) {
2975 int ret = gnutls_hash(digest_ctx, data, data_len);
2976
2977 return ret == 0;
2978}
2979
2980int
2982 coap_digest_t *digest_buffer) {
2983 gnutls_hash_output(digest_ctx, (uint8_t *)digest_buffer);
2984
2985 coap_digest_free(digest_ctx);
2986 return 1;
2987}
2988#endif /* COAP_SERVER_SUPPORT */
2989
2990#if COAP_WS_SUPPORT
2991/*
2992 * The struct hash_algs and the function get_hash_alg() are used to
2993 * determine which hash type to use for creating the required hash object.
2994 */
2995static struct hash_algs {
2996 cose_alg_t alg;
2997 gnutls_digest_algorithm_t dig_type;
2998 size_t dig_size;
2999} hashs[] = {
3000 {COSE_ALGORITHM_SHA_1, GNUTLS_DIG_SHA1, 20},
3001 {COSE_ALGORITHM_SHA_256_256, GNUTLS_DIG_SHA256, 32},
3002 {COSE_ALGORITHM_SHA_512, GNUTLS_DIG_SHA512, 64},
3003};
3004
3005static gnutls_digest_algorithm_t
3006get_hash_alg(cose_alg_t alg, size_t *hash_len) {
3007 size_t idx;
3008
3009 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
3010 if (hashs[idx].alg == alg) {
3011 *hash_len = hashs[idx].dig_size;
3012 return hashs[idx].dig_type;
3013 }
3014 }
3015 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
3016 return GNUTLS_DIG_UNKNOWN;
3017}
3018
3019int
3021 const coap_bin_const_t *data,
3022 coap_bin_const_t **hash) {
3023 size_t hash_length;
3024 gnutls_digest_algorithm_t dig_type = get_hash_alg(alg, &hash_length);
3025 gnutls_hash_hd_t digest_ctx;
3026 coap_binary_t *dummy = NULL;
3027 int ret;
3028
3029 if (dig_type == GNUTLS_DIG_UNKNOWN) {
3030 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3031 return 0;
3032 }
3033
3034 if (gnutls_hash_init(&digest_ctx, dig_type)) {
3035 return 0;
3036 }
3037 ret = gnutls_hash(digest_ctx, data->s, data->length);
3038 if (ret != 0)
3039 goto error;
3040
3041 dummy = coap_new_binary(hash_length);
3042 if (!dummy)
3043 goto error;
3044 gnutls_hash_output(digest_ctx, dummy->s);
3045
3046 *hash = (coap_bin_const_t *)(dummy);
3047 gnutls_hash_deinit(digest_ctx, NULL);
3048 return 1;
3049
3050error:
3052 gnutls_hash_deinit(digest_ctx, NULL);
3053 return 0;
3054}
3055#endif /* COAP_WS_SUPPORT */
3056
3057#if COAP_OSCORE_SUPPORT
3058int
3060 return 1;
3061}
3062
3063/*
3064 * The struct cipher_algs and the function get_cipher_alg() are used to
3065 * determine which cipher type to use for creating the required cipher
3066 * suite object.
3067 */
3068static struct cipher_algs {
3069 cose_alg_t alg;
3070 gnutls_cipher_algorithm_t cipher_type;
3071} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, GNUTLS_CIPHER_AES_128_CCM_8},
3072 {COSE_ALGORITHM_AES_CCM_16_64_256, GNUTLS_CIPHER_AES_256_CCM_8}
3073};
3074
3075static gnutls_cipher_algorithm_t
3076get_cipher_alg(cose_alg_t alg) {
3077 size_t idx;
3078
3079 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
3080 if (ciphers[idx].alg == alg)
3081 return ciphers[idx].cipher_type;
3082 }
3083 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
3084 return 0;
3085}
3086
3087/*
3088 * The struct hmac_algs and the function get_hmac_alg() are used to
3089 * determine which hmac type to use for creating the required hmac
3090 * suite object.
3091 */
3092static struct hmac_algs {
3093 cose_hmac_alg_t hmac_alg;
3094 gnutls_mac_algorithm_t hmac_type;
3095} hmacs[] = {
3096 {COSE_HMAC_ALG_HMAC256_256, GNUTLS_MAC_SHA256},
3097 {COSE_HMAC_ALG_HMAC512_512, GNUTLS_MAC_SHA512},
3098};
3099
3100static gnutls_mac_algorithm_t
3101get_hmac_alg(cose_hmac_alg_t hmac_alg) {
3102 size_t idx;
3103
3104 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
3105 if (hmacs[idx].hmac_alg == hmac_alg)
3106 return hmacs[idx].hmac_type;
3107 }
3108 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
3109 return 0;
3110}
3111
3112int
3114 return get_cipher_alg(alg);
3115}
3116
3117int
3119 cose_hmac_alg_t hmac_alg;
3120
3121 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3122 return 0;
3123 return get_hmac_alg(hmac_alg);
3124}
3125
3126int
3128 coap_bin_const_t *data,
3129 coap_bin_const_t *aad,
3130 uint8_t *result,
3131 size_t *max_result_len) {
3132 gnutls_aead_cipher_hd_t ctx;
3133 gnutls_datum_t key;
3134 const coap_crypto_aes_ccm_t *ccm;
3135 int ret = 0;
3136 size_t result_len = *max_result_len;
3137 gnutls_cipher_algorithm_t algo;
3138 unsigned tag_size;
3139 uint8_t *key_data_rw;
3140 coap_bin_const_t laad;
3141
3142 if (data == NULL)
3143 return 0;
3144
3145 assert(params != NULL);
3146 if (!params) {
3147 return 0;
3148 }
3149 if ((algo = get_cipher_alg(params->alg)) == 0) {
3150 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
3151 params->alg);
3152 return 0;
3153 }
3154 tag_size = gnutls_cipher_get_tag_size(algo);
3155 ccm = &params->params.aes;
3156
3157 /* Get a RW copy of data */
3158 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3159 key.data = key_data_rw;
3160 key.size = ccm->key.length;
3161
3162 if (aad) {
3163 laad = *aad;
3164 } else {
3165 laad.s = NULL;
3166 laad.length = 0;
3167 }
3168
3169 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3170
3171 G_CHECK(gnutls_aead_cipher_encrypt(ctx,
3172 ccm->nonce,
3173 15 - ccm->l, /* iv */
3174 laad.s,
3175 laad.length, /* ad */
3176 tag_size,
3177 data->s,
3178 data->length, /* input */
3179 result,
3180 &result_len), /* output */
3181 "gnutls_aead_cipher_encrypt");
3182 *max_result_len = result_len;
3183 ret = 1;
3184fail:
3185 gnutls_aead_cipher_deinit(ctx);
3186 return ret == 1 ? 1 : 0;
3187}
3188
3189int
3191 coap_bin_const_t *data,
3192 coap_bin_const_t *aad,
3193 uint8_t *result,
3194 size_t *max_result_len) {
3195 gnutls_aead_cipher_hd_t ctx;
3196 gnutls_datum_t key;
3197 const coap_crypto_aes_ccm_t *ccm;
3198 int ret = 0;
3199 size_t result_len = *max_result_len;
3200 gnutls_cipher_algorithm_t algo;
3201 unsigned tag_size;
3202 uint8_t *key_data_rw;
3203 coap_bin_const_t laad;
3204
3205 if (data == NULL)
3206 return 0;
3207
3208 assert(params != NULL);
3209
3210 if (!params) {
3211 return 0;
3212 }
3213 if ((algo = get_cipher_alg(params->alg)) == 0) {
3214 coap_log_debug("coap_crypto_decrypt: algorithm %d not supported\n",
3215 params->alg);
3216 return 0;
3217 }
3218 tag_size = gnutls_cipher_get_tag_size(algo);
3219 ccm = &params->params.aes;
3220
3221 /* Get a RW copy of data */
3222 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3223 key.data = key_data_rw;
3224 key.size = ccm->key.length;
3225
3226 if (aad) {
3227 laad = *aad;
3228 } else {
3229 laad.s = NULL;
3230 laad.length = 0;
3231 }
3232
3233 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3234
3235 G_CHECK(gnutls_aead_cipher_decrypt(ctx,
3236 ccm->nonce,
3237 15 - ccm->l, /* iv */
3238 laad.s,
3239 laad.length, /* ad */
3240 tag_size,
3241 data->s,
3242 data->length, /* input */
3243 result,
3244 &result_len), /* output */
3245 "gnutls_aead_cipher_decrypt");
3246 *max_result_len = result_len;
3247 ret = 1;
3248fail:
3249 gnutls_aead_cipher_deinit(ctx);
3250 return ret == 1 ? 1 : 0;
3251}
3252
3253int
3255 coap_bin_const_t *key,
3256 coap_bin_const_t *data,
3257 coap_bin_const_t **hmac) {
3258 gnutls_hmac_hd_t ctx;
3259 int ret = 0;
3260 unsigned len;
3261 gnutls_mac_algorithm_t mac_algo;
3262 coap_binary_t *dummy = NULL;
3263
3264 if (data == NULL)
3265 return 0;
3266
3267 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3268 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3269 return 0;
3270 }
3271 len = gnutls_hmac_get_len(mac_algo);
3272 if (len == 0)
3273 return 0;
3274
3275 dummy = coap_new_binary(len);
3276 if (dummy == NULL)
3277 return 0;
3278 G_CHECK(gnutls_hmac_init(&ctx, mac_algo, key->s, key->length),
3279 "gnutls_hmac_init");
3280 G_CHECK(gnutls_hmac(ctx, data->s, data->length), "gnutls_hmac");
3281 gnutls_hmac_output(ctx, dummy->s);
3282 *hmac = (coap_bin_const_t *)dummy;
3283 dummy = NULL;
3284 ret = 1;
3285fail:
3287 gnutls_hmac_deinit(ctx, NULL);
3288 return ret == 1 ? 1 : 0;
3289}
3290
3291#endif /* COAP_OSCORE_SUPPORT */
3292
3293#else /* !COAP_WITH_LIBGNUTLS */
3294
3295#ifdef __clang__
3296/* Make compilers happy that do not like empty modules. As this function is
3297 * never used, we ignore -Wunused-function at the end of compiling this file
3298 */
3299#pragma GCC diagnostic ignored "-Wunused-function"
3300#endif
3301static inline void
3302dummy(void) {
3303}
3304
3305#endif /* !COAP_WITH_LIBGNUTLS */
#define min(a, b)
Definition coap_block.c:19
#define COAP_SERVER_SUPPORT
static void dummy(void)
const char * coap_socket_strerror(void)
Definition coap_io.c:1899
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
@ COAP_NACK_TLS_FAILED
Definition coap_io.h:66
@ COAP_LAYER_TLS
Library specific build wrapper for coap_internal.h.
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition coap_notls.c:228
ssize_t coap_tls_read(coap_session_t *session COAP_UNUSED, uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:300
coap_tick_t coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED)
Definition coap_notls.c:223
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:242
void * coap_dtls_get_tls(const coap_session_t *c_session COAP_UNUSED, coap_tls_library_t *tls_lib)
Definition coap_notls.c:153
unsigned int coap_dtls_get_overhead(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:260
static coap_log_t dtls_log_level
Definition coap_notls.c:146
int coap_dtls_context_check_keys_enabled(coap_context_t *ctx COAP_UNUSED)
Definition coap_notls.c:142
ssize_t coap_dtls_send(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:211
ssize_t coap_tls_write(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition coap_notls.c:288
void coap_dtls_session_update_mtu(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:207
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition coap_notls.c:116
int coap_dtls_handle_timeout(coap_session_t *session COAP_UNUSED)
Definition coap_notls.c:237
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition coap_notls.c:185
void coap_dtls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:203
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition coap_notls.c:180
void coap_tls_free_session(coap_session_t *coap_session COAP_UNUSED)
Definition coap_notls.c:279
coap_binary_t * get_asn1_spki(const uint8_t *data, size_t size)
Abstract SPKI public key from the ASN1.
Definition coap_asn1.c:153
void coap_digest_free(coap_digest_ctx_t *digest_ctx)
Free off coap_digest_ctx_t.
int coap_digest_final(coap_digest_ctx_t *digest_ctx, coap_digest_t *digest_buffer)
Finalize the coap_digest information into the provided digest_buffer.
int coap_digest_update(coap_digest_ctx_t *digest_ctx, const uint8_t *data, size_t data_len)
Update the coap_digest information with the next chunk of data.
void coap_digest_ctx_t
coap_digest_ctx_t * coap_digest_setup(void)
Initialize a coap_digest.
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition coap_time.h:143
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4378
int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len)
Parses and interprets a CoAP datagram with context ctx.
Definition coap_net.c:2487
int coap_crypto_hmac(cose_hmac_alg_t hmac_alg, coap_bin_const_t *key, coap_bin_const_t *data, coap_bin_const_t **hmac)
Create a HMAC hash of the provided data.
int coap_crypto_aead_decrypt(const coap_crypto_param_t *params, coap_bin_const_t *data, coap_bin_const_t *aad, uint8_t *result, size_t *max_result_len)
Decrypt the provided encrypted data into plaintext.
int coap_crypto_aead_encrypt(const coap_crypto_param_t *params, coap_bin_const_t *data, coap_bin_const_t *aad, uint8_t *result, size_t *max_result_len)
Encrypt the provided plaintext data.
int coap_crypto_hash(cose_alg_t alg, const coap_bin_const_t *data, coap_bin_const_t **hash)
Create a hash of the provided data.
int coap_crypto_check_hkdf_alg(cose_hkdf_alg_t hkdf_alg)
Check whether the defined hkdf algorithm is supported by the underlying crypto library.
int coap_crypto_check_cipher_alg(cose_alg_t alg)
Check whether the defined cipher algorithm is supported by the underlying crypto library.
void * coap_tls_new_server_session(coap_session_t *coap_session)
Create a TLS new server-side session.
const coap_bin_const_t * coap_get_session_client_psk_identity(const coap_session_t *coap_session)
Get the current client's PSK identity.
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition coap_notls.c:149
int coap_dtls_define_issue(coap_define_issue_key_t type, coap_define_issue_fail_t fail, coap_dtls_key_t *key, const coap_dtls_role_t role, int ret)
Report PKI DEFINE type issue.
Definition coap_dtls.c:165
void * coap_dtls_new_client_session(coap_session_t *coap_session)
Create a new client-side session.
void coap_dtls_thread_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:166
void * coap_dtls_new_server_session(coap_session_t *coap_session)
Create a new DTLS server-side session.
int coap_dtls_hello(coap_session_t *coap_session, const uint8_t *data, size_t data_len)
Handling client HELLO messages from a new candiate peer.
int coap_dtls_set_cid_tuple_change(coap_context_t *context, uint8_t every)
Set the Connection ID client tuple frequency change for testing CIDs.
int coap_dtls_is_context_timeout(void)
Check if timeout is handled per CoAP session or per CoAP context.
Definition coap_notls.c:218
int coap_dtls_context_set_cpsk(coap_context_t *coap_context, coap_dtls_cpsk_t *setup_data)
Set the DTLS context's default client PSK information.
int coap_dtls_context_set_spsk(coap_context_t *coap_context, coap_dtls_spsk_t *setup_data)
Set the DTLS context's default server PSK information.
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition coap_notls.c:161
const coap_bin_const_t * coap_get_session_client_psk_key(const coap_session_t *coap_session)
Get the current client's PSK key.
void * coap_tls_new_client_session(coap_session_t *coap_session)
Create a new TLS client-side session.
#define COAP_DTLS_RETRANSMIT_COAP_TICKS
void coap_dtls_map_key_type_to_define(const coap_dtls_pki_t *setup_data, coap_dtls_key_t *key)
Map the PKI key definitions to the new DEFINE format.
Definition coap_dtls.c:26
const coap_bin_const_t * coap_get_session_server_psk_key(const coap_session_t *coap_session)
Get the current server's PSK key.
@ COAP_DEFINE_KEY_PRIVATE
@ COAP_DEFINE_KEY_CA
@ COAP_DEFINE_KEY_PUBLIC
@ COAP_DEFINE_FAIL_NONE
@ COAP_DEFINE_FAIL_NOT_SUPPORTED
@ COAP_DEFINE_FAIL_BAD
#define COAP_DTLS_HINT_LENGTH
Definition coap_dtls.h:35
coap_tls_version_t * coap_get_tls_library_version(void)
Determine the type and version of the underlying (D)TLS library.
Definition coap_notls.c:100
struct coap_dtls_key_t coap_dtls_key_t
The structure that holds the PKI key information.
coap_dtls_role_t
Definition coap_dtls.h:44
#define COAP_DTLS_RPK_CERT_CN
Definition coap_dtls.h:49
struct coap_dtls_spsk_info_t coap_dtls_spsk_info_t
The structure that holds the Server Pre-Shared Key and Identity Hint information.
coap_tls_library_t
Definition coap_dtls.h:70
struct coap_dtls_pki_t coap_dtls_pki_t
Definition coap_dtls.h:32
@ COAP_PKI_KEY_DEF_PKCS11
The PKI key type is PKCS11 (pkcs11:...).
Definition coap_dtls.h:245
@ COAP_PKI_KEY_DEF_DER_BUF
The PKI key type is DER buffer (ASN.1).
Definition coap_dtls.h:242
@ COAP_PKI_KEY_DEF_PEM_BUF
The PKI key type is PEM buffer.
Definition coap_dtls.h:236
@ COAP_PKI_KEY_DEF_PEM
The PKI key type is PEM file.
Definition coap_dtls.h:234
@ COAP_PKI_KEY_DEF_ENGINE
The PKI key type is to be passed to ENGINE.
Definition coap_dtls.h:251
@ COAP_PKI_KEY_DEF_RPK_BUF
The PKI key type is RPK in buffer.
Definition coap_dtls.h:238
@ COAP_PKI_KEY_DEF_DER
The PKI key type is DER file.
Definition coap_dtls.h:240
@ COAP_PKI_KEY_DEF_PKCS11_RPK
The PKI key type is PKCS11 w/ RPK (pkcs11:...).
Definition coap_dtls.h:248
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:46
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition coap_dtls.h:45
@ COAP_PKI_KEY_DEFINE
The individual PKI key types are Definable.
Definition coap_dtls.h:172
@ COAP_TLS_LIBRARY_GNUTLS
Using GnuTLS library.
Definition coap_dtls.h:74
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:39
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:41
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:45
#define coap_lock_callback_ret(r, c, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
coap_log_t
Logging type.
Definition coap_debug.h:50
coap_log_t coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition coap_notls.c:175
#define coap_dtls_log(level,...)
Logging function.
Definition coap_debug.h:300
void coap_dtls_set_log_level(coap_log_t level)
Sets the (D)TLS logging level to the specified level.
Definition coap_notls.c:170
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
@ COAP_LOG_EMERG
Definition coap_debug.h:51
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
@ COAP_LOG_WARN
Definition coap_debug.h:55
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
int cose_get_hmac_alg_for_hkdf(cose_hkdf_alg_t hkdf_alg, cose_hmac_alg_t *hmac_alg)
cose_hkdf_alg_t
cose_hmac_alg_t
cose_alg_t
@ COSE_HMAC_ALG_HMAC256_256
@ COSE_HMAC_ALG_HMAC512_512
@ COSE_ALGORITHM_SHA_256_256
@ COSE_ALGORITHM_SHA_1
@ COSE_ALGORITHM_AES_CCM_16_64_128
@ COSE_ALGORITHM_SHA_512
@ COSE_ALGORITHM_AES_CCM_16_64_256
@ COAP_PROTO_DTLS
Definition coap_pdu.h:316
@ COAP_PROTO_TLS
Definition coap_pdu.h:318
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Refresh the session's current Identity Hint (PSK).
int coap_session_refresh_psk_key(coap_session_t *session, const coap_bin_const_t *psk_key)
Refresh the session's current pre-shared key (PSK).
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
int coap_session_refresh_psk_identity(coap_session_t *session, const coap_bin_const_t *psk_identity)
Refresh the session's current pre-shared identity (PSK).
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
#define COAP_PROTO_NOT_RELIABLE(p)
@ COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_NONE
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
int coap_dtls_cid_is_supported(void)
Check whether (D)TLS CID is available.
Definition coap_notls.c:86
int coap_dtls_psk_is_supported(void)
Check whether (D)TLS PSK is available.
Definition coap_notls.c:50
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_oscore_is_supported(void)
Check whether OSCORE is available.
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_dtls_pki_is_supported(void)
Check whether (D)TLS PKI is available.
Definition coap_notls.c:59
int coap_dtls_rpk_is_supported(void)
Check whether (D)TLS RPK is available.
Definition coap_notls.c:77
int coap_dtls_pkcs11_is_supported(void)
Check whether (D)TLS PKCS11 is available.
Definition coap_notls.c:68
#define COAP_UNUSED
Definition libcoap.h:70
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
The structure that holds the AES Crypto information.
size_t l
The number of bytes in the length field.
const uint8_t * nonce
must be exactly 15 - l bytes
coap_crypto_key_t key
The Key to use.
The common structure that holds the Crypto information.
union coap_crypto_param_t::@242136240037311335022001367112102231100333222137 params
coap_crypto_aes_ccm_t aes
Used if AES type encryption.
cose_alg_t alg
The COSE algorith to use.
The structure that holds the Client PSK information.
Definition coap_dtls.h:379
coap_bin_const_t key
Definition coap_dtls.h:381
coap_bin_const_t identity
Definition coap_dtls.h:380
The structure used for defining the Client PSK setup data to be used.
Definition coap_dtls.h:410
uint8_t use_cid
Set to 1 if DTLS Connection ID is to be used.
Definition coap_dtls.h:417
void * ih_call_back_arg
Passed in to the Identity Hint callback function.
Definition coap_dtls.h:434
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:437
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition coap_dtls.h:433
uint8_t ec_jpake
Set to COAP_DTLS_CPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:415
The structure that holds the PKI key information.
Definition coap_dtls.h:279
union coap_dtls_key_t::@067104111220140054257241314117327310146344167156 key
coap_pki_key_define_t define
for definable type keys
Definition coap_dtls.h:286
coap_pki_key_t key_type
key format type
Definition coap_dtls.h:280
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t cert_chain_validation
1 if to check cert_chain_verify_depth
Definition coap_dtls.h:323
uint8_t use_cid
1 if DTLS Connection ID is to be used (Client only, server always enabled) if supported
Definition coap_dtls.h:333
uint8_t check_cert_revocation
1 if revocation checks wanted
Definition coap_dtls.h:325
uint8_t cert_chain_verify_depth
recommended depth is 3
Definition coap_dtls.h:324
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:317
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:368
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition coap_dtls.h:330
uint8_t check_common_ca
1 if peer cert is to be signed by the same CA as the local cert
Definition coap_dtls.h:318
coap_dtls_key_t pki_key
PKI key definition.
Definition coap_dtls.h:373
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition coap_dtls.h:450
coap_bin_const_t hint
Definition coap_dtls.h:451
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:501
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition coap_dtls.h:530
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition coap_dtls.h:522
void * id_call_back_arg
Passed in to the Identity callback function.
Definition coap_dtls.h:523
uint8_t ec_jpake
Set to COAP_DTLS_SPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:506
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition coap_dtls.h:531
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:533
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
coap_const_char_ptr_t public_cert
define: Public Cert
Definition coap_dtls.h:261
const char * user_pin
define: User pin to access type PKCS11.
Definition coap_dtls.h:271
coap_const_char_ptr_t private_key
define: Private Key
Definition coap_dtls.h:262
coap_const_char_ptr_t ca
define: Common CA Certificate
Definition coap_dtls.h:260
size_t public_cert_len
define Public Cert length (if needed)
Definition coap_dtls.h:264
size_t ca_len
define CA Cert length (if needed)
Definition coap_dtls.h:263
coap_pki_define_t private_key_def
define: Private Key type definition
Definition coap_dtls.h:268
size_t private_key_len
define Private Key length (if needed)
Definition coap_dtls.h:265
coap_pki_define_t ca_def
define: Common CA type definition
Definition coap_dtls.h:266
coap_pki_define_t public_cert_def
define: Public Cert type definition
Definition coap_dtls.h:267
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
unsigned int dtls_timeout_count
dtls setup retry counter
coap_endpoint_t * endpoint
session's endpoint
coap_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationship with peer
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
int dtls_event
Tracking any (D)TLS events on this session.
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
coap_context_t * context
session's context
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
CoAP string data definition with const data.
Definition coap_str.h:46
const uint8_t * s
read-only string data
Definition coap_str.h:48
size_t length
length of string
Definition coap_str.h:47
The structure used for returning the underlying (D)TLS library information.
Definition coap_dtls.h:83
uint64_t built_version
(D)TLS Built against Library Version
Definition coap_dtls.h:86
coap_tls_library_t type
Library type.
Definition coap_dtls.h:85
uint64_t version
(D)TLS runtime Library Version
Definition coap_dtls.h:84
const char * s_byte
signed char ptr
Definition coap_str.h:73
const uint8_t * u_byte
unsigned char ptr
Definition coap_str.h:74