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