libcoap 4.3.5-develop-daa4e05
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#ifdef COAP_WITH_LIBGNUTLS
54
55#define MIN_GNUTLS_VERSION "3.3.0"
56
57#include <stdio.h>
58#include <gnutls/gnutls.h>
59#include <gnutls/x509.h>
60#include <gnutls/dtls.h>
61#include <gnutls/pkcs11.h>
62#include <gnutls/crypto.h>
63#include <gnutls/abstract.h>
64#include <unistd.h>
65#if (GNUTLS_VERSION_NUMBER >= 0x030606)
66#define COAP_GNUTLS_KEY_RPK GNUTLS_KEY_DIGITAL_SIGNATURE | \
67 GNUTLS_KEY_NON_REPUDIATION | \
68 GNUTLS_KEY_KEY_ENCIPHERMENT | \
69 GNUTLS_KEY_DATA_ENCIPHERMENT | \
70 GNUTLS_KEY_KEY_AGREEMENT | \
71 GNUTLS_KEY_KEY_CERT_SIGN
72#endif /* GNUTLS_VERSION_NUMBER >= 0x030606 */
73
74#ifndef GNUTLS_CRT_RAW
75#define GNUTLS_CRT_RAW GNUTLS_CRT_RAWPK
76#endif /* GNUTLS_CRT_RAW */
77
78#ifdef _WIN32
79#define strcasecmp _stricmp
80#endif
81
82typedef struct coap_ssl_t {
83 const uint8_t *pdu;
84 unsigned pdu_len;
85 unsigned peekmode;
86 gnutls_datum_t cookie_key;
87} coap_ssl_t;
88
89/*
90 * This structure encapsulates the GnuTLS session object.
91 * It handles both TLS and DTLS.
92 * c_session->tls points to this.
93 */
94typedef struct coap_gnutls_env_t {
95 gnutls_session_t g_session;
96 gnutls_psk_client_credentials_t psk_cl_credentials;
97 gnutls_psk_server_credentials_t psk_sv_credentials;
98 gnutls_certificate_credentials_t pki_credentials;
99 coap_ssl_t coap_ssl_data;
100 /* If not set, need to do gnutls_handshake */
101 int established;
102 int doing_dtls_timeout;
103 coap_tick_t last_timeout;
104 int sent_alert;
105} coap_gnutls_env_t;
106
107#define IS_PSK (1 << 0)
108#define IS_PKI (1 << 1)
109#define IS_CLIENT (1 << 6)
110#define IS_SERVER (1 << 7)
111
112typedef struct pki_sni_entry {
113 char *sni;
114 coap_dtls_key_t pki_key;
115 gnutls_certificate_credentials_t pki_credentials;
116} pki_sni_entry;
117
118typedef struct psk_sni_entry {
119 char *sni;
120 coap_dtls_spsk_info_t psk_info;
121 gnutls_psk_server_credentials_t psk_credentials;
122} psk_sni_entry;
123
124typedef struct coap_gnutls_context_t {
125 coap_dtls_pki_t setup_data;
126 int psk_pki_enabled;
127 size_t pki_sni_count;
128 pki_sni_entry *pki_sni_entry_list;
129 size_t psk_sni_count;
130 psk_sni_entry *psk_sni_entry_list;
131 gnutls_datum_t alpn_proto; /* Will be "coap", but that is a const */
132 char *root_ca_file;
133 char *root_ca_path;
134 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;
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 G_CHECK(gnutls_global_init(), "gnutls_global_init");
543 memset(g_context, 0, sizeof(coap_gnutls_context_t));
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, c_session->context,
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);
811 coap_lock_callback_ret(ret, c_session->context,
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 && !g_context->setup_data.verify_peer_cert)
860 goto ok;
861
862 G_CHECK(gnutls_certificate_verify_peers(g_session, NULL, 0, &status),
863 "gnutls_certificate_verify_peers");
864
865 coap_dtls_log(COAP_LOG_DEBUG, "error %x cert '%s'\n",
866 status, cert_info.san_or_cn);
867 if (status) {
868 status &= ~(GNUTLS_CERT_INVALID);
869 if (status & (GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED)) {
870 status &= ~(GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED);
871 if (g_context->setup_data.allow_expired_certs) {
872 coap_log_info(" %s: %s: overridden: '%s'\n",
873 coap_session_str(c_session),
874 "The certificate has an invalid usage date",
875 OUTPUT_CERT_NAME);
876 } else {
877 fail = 1;
878 coap_log_warn(" %s: %s: '%s'\n",
879 coap_session_str(c_session),
880 "The certificate has an invalid usage date",
881 OUTPUT_CERT_NAME);
882 }
883 }
884 if (status & (GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
885 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE)) {
886 status &= ~(GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
887 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE);
888 if (g_context->setup_data.allow_expired_crl) {
889 coap_log_info(" %s: %s: overridden: '%s'\n",
890 coap_session_str(c_session),
891 "The certificate's CRL entry has an invalid usage date",
892 OUTPUT_CERT_NAME);
893 } else {
894 fail = 1;
895 coap_log_warn(" %s: %s: '%s'\n",
896 coap_session_str(c_session),
897 "The certificate's CRL entry has an invalid usage date",
898 OUTPUT_CERT_NAME);
899 }
900 }
901 if (status & (GNUTLS_CERT_SIGNER_NOT_FOUND)) {
902 status &= ~(GNUTLS_CERT_SIGNER_NOT_FOUND);
903 if (cert_info.self_signed) {
904 if (g_context->setup_data.allow_self_signed &&
905 !g_context->setup_data.check_common_ca) {
906 coap_log_info(" %s: %s: overridden: '%s'\n",
907 coap_session_str(c_session),
908 "Self-signed",
909 OUTPUT_CERT_NAME);
910 } else {
911 fail = 1;
912 alert = GNUTLS_A_UNKNOWN_CA;
913 coap_log_warn(" %s: %s: '%s'\n",
914 coap_session_str(c_session),
915 "Self-signed",
916 OUTPUT_CERT_NAME);
917 }
918 } else {
919 if (!g_context->setup_data.verify_peer_cert) {
920 coap_log_info(" %s: %s: overridden: '%s'\n",
921 coap_session_str(c_session),
922 "The peer certificate's CA is unknown",
923 OUTPUT_CERT_NAME);
924 } else {
925 fail = 1;
926 alert = GNUTLS_A_UNKNOWN_CA;
927 coap_log_warn(" %s: %s: '%s'\n",
928 coap_session_str(c_session),
929 "The peer certificate's CA is unknown",
930 OUTPUT_CERT_NAME);
931 }
932 }
933 }
934 if (status & (GNUTLS_CERT_INSECURE_ALGORITHM)) {
935 status &= ~(GNUTLS_CERT_INSECURE_ALGORITHM);
936 fail = 1;
937 coap_log_warn(" %s: %s: '%s'\n",
938 coap_session_str(c_session),
939 "The certificate uses an insecure algorithm",
940 OUTPUT_CERT_NAME);
941 }
942
943 if (status) {
944 fail = 1;
945 coap_log_warn(" %s: gnutls_certificate_verify_peers() status 0x%x: '%s'\n",
946 coap_session_str(c_session),
947 status, OUTPUT_CERT_NAME);
948 }
949 }
950
951 if (fail)
952 goto fail;
953
954 if (g_context->setup_data.validate_cn_call_back) {
955 gnutls_x509_crt_t cert;
956 uint8_t der[2048];
957 size_t size;
958 /* status == 0 indicates that the certificate passed to
959 * setup_data.validate_cn_call_back has been validated. */
960 const int cert_is_trusted = !status;
961
962 G_CHECK(gnutls_x509_crt_init(&cert), "gnutls_x509_crt_init");
963
964 /* Interested only in first cert in chain */
965 G_CHECK(gnutls_x509_crt_import(cert, &cert_info.cert_list[0],
966 GNUTLS_X509_FMT_DER), "gnutls_x509_crt_import");
967
968 size = sizeof(der);
969 G_CHECK(gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, der, &size),
970 "gnutls_x509_crt_export");
971 gnutls_x509_crt_deinit(cert);
972 coap_lock_callback_ret(ret, c_session->context,
973 g_context->setup_data.validate_cn_call_back(OUTPUT_CERT_NAME,
974 der,
975 size,
976 c_session,
977 0,
978 cert_is_trusted,
979 g_context->setup_data.cn_call_back_arg));
980 if (!ret) {
981 alert = GNUTLS_A_ACCESS_DENIED;
982 goto fail;
983 }
984 }
985
986 if (g_context->setup_data.additional_tls_setup_call_back) {
987 /* Additional application setup wanted */
988 if (!g_context->setup_data.additional_tls_setup_call_back(g_session,
989 &g_context->setup_data)) {
990 goto fail;
991 }
992 }
993
994ok:
995 if (cert_info.san_or_cn)
996 gnutls_free(cert_info.san_or_cn);
997
998 return 1;
999
1000fail:
1001 if (cert_info.san_or_cn)
1002 gnutls_free(cert_info.san_or_cn);
1003
1004 if (!g_env->sent_alert) {
1005 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL, alert));
1006 g_env->sent_alert = 1;
1007 }
1009 return 0;
1010}
1011
1012/*
1013 * gnutls_certificate_verify_function return values
1014 * (see gnutls_certificate_set_verify_function())
1015 *
1016 * return -1 failed
1017 * 0 passed
1018 */
1019static int
1020cert_verify_callback_gnutls(gnutls_session_t g_session) {
1021 if (gnutls_auth_get_type(g_session) == GNUTLS_CRD_CERTIFICATE) {
1022 if (cert_verify_gnutls(g_session) == 0) {
1023 return -1;
1024 }
1025 }
1026 return 0;
1027}
1028
1029#ifndef min
1030#define min(a,b) ((a) < (b) ? (a) : (b))
1031#endif
1032
1033static int
1034pin_callback(void *user_data, int attempt,
1035 const char *token_url COAP_UNUSED,
1036 const char *token_label COAP_UNUSED,
1037 unsigned int flags COAP_UNUSED,
1038 char *pin,
1039 size_t pin_max) {
1040 coap_dtls_key_t *key = (coap_dtls_key_t *)user_data;
1041
1042 /* Only do this on first attempt to prevent token lockout */
1043 if (attempt == 0 && key && key->key.define.user_pin) {
1044 int len = min(pin_max - 1, strlen(key->key.define.user_pin));
1045
1046 memcpy(pin, key->key.define.user_pin, len);
1047 pin[len] = 0;
1048 return 0;
1049 }
1050 return -1;
1051}
1052
1053static int
1054check_null_memory(gnutls_datum_t *datum,
1055 const uint8_t *buf, size_t len, int *alloced) {
1056 datum->size = len;
1057 *alloced = 0;
1058 if (buf[len-1] != '\000') {
1059 /* Need to allocate memory, rather than just copying pointers across */
1060 *alloced = 1;
1061 datum->data = gnutls_malloc(len + 1);
1062 if (!datum->data) {
1063 coap_log_err("gnutls_malloc failure\n");
1064 return GNUTLS_E_MEMORY_ERROR;
1065 }
1066 memcpy(datum->data, buf, len);
1067 datum->data[len] = '\000';
1068 datum->size++;
1069 } else {
1070 /* To get around const issue */
1071 memcpy(&datum->data,
1072 &buf, sizeof(datum->data));
1073 }
1074 return 0;
1075}
1076
1077/*
1078 * return 0 Success (GNUTLS_E_SUCCESS)
1079 * neg GNUTLS_E_* error code
1080 */
1081static int
1082setup_pki_credentials(gnutls_certificate_credentials_t *pki_credentials,
1083 gnutls_session_t g_session,
1084 coap_gnutls_context_t *g_context,
1085 coap_dtls_pki_t *setup_data, coap_dtls_role_t role) {
1086 coap_dtls_key_t key;
1087 int ret;
1088 gnutls_datum_t cert;
1089 gnutls_datum_t pkey;
1090 gnutls_datum_t ca;
1091 int alloced_cert_memory = 0;
1092 int alloced_pkey_memory = 0;
1093 int alloced_ca_memory = 0;
1094 int have_done_key = 0;
1095
1096 /* Map over to the new define format to save code duplication */
1097 coap_dtls_map_key_type_to_define(setup_data, &key);
1098
1099 assert(key.key_type == COAP_PKI_KEY_DEFINE);
1100
1101 G_CHECK(gnutls_certificate_allocate_credentials(pki_credentials),
1102 "gnutls_certificate_allocate_credentials");
1103
1104 /*
1105 * Configure the Private Key
1106 */
1107 if (key.key.define.private_key.u_byte &&
1108 key.key.define.private_key.u_byte[0]) {
1109 switch (key.key.define.private_key_def) {
1110 case COAP_PKI_KEY_DEF_PEM: /* define private key */
1111 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
1112 case COAP_PKI_KEY_DEF_DER: /* define private key */
1113 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
1114 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
1115 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
1116 /* Handled under public key */
1117 break;
1118 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
1119#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1120 /* Handled under public key */
1121 break;
1122#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1123 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1126 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1127#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1128 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
1129 default:
1132 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1133 }
1134 } else if (role == COAP_DTLS_ROLE_SERVER ||
1136 key.key.define.public_cert.u_byte[0])) {
1139 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1140 }
1141
1142 /*
1143 * Configure the Public Certificate / Key
1144 */
1145 if (key.key.define.public_cert.u_byte &&
1146 key.key.define.public_cert.u_byte[0]) {
1147 /* Both Public and Private keys are handled here and MUST be the same type */
1148 if (!(key.key.define.private_key.s_byte &&
1149 key.key.define.private_key.s_byte[0] &&
1153 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1154 }
1155 switch (key.key.define.public_cert_def) {
1156 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
1157 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1160 GNUTLS_X509_FMT_PEM)) < 0) {
1163 &key, role, ret);
1164 }
1165 break;
1166 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
1167 if ((ret = check_null_memory(&cert,
1170 &alloced_cert_memory)) < 0) {
1173 &key, role, ret);
1174 }
1175 if ((ret = check_null_memory(&pkey,
1178 &alloced_pkey_memory)) < 0) {
1179 if (alloced_cert_memory)
1180 gnutls_free(cert.data);
1183 &key, role, ret);
1184 }
1185 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1186 &cert,
1187 &pkey,
1188 GNUTLS_X509_FMT_PEM)) < 0) {
1189 if (alloced_cert_memory)
1190 gnutls_free(cert.data);
1191 if (alloced_pkey_memory)
1192 gnutls_free(pkey.data);
1195 &key, role, ret);
1196 }
1197 if (alloced_cert_memory)
1198 gnutls_free(cert.data);
1199 if (alloced_pkey_memory)
1200 gnutls_free(pkey.data);
1201 break;
1202 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
1203#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1204 if ((ret = check_null_memory(&cert,
1207 &alloced_cert_memory)) < 0) {
1210 &key, role, ret);
1211 }
1212 if ((ret = check_null_memory(&pkey,
1215 &alloced_pkey_memory)) < 0) {
1216 if (alloced_cert_memory)
1217 gnutls_free(cert.data);
1220 &key, role, ret);
1221 }
1222 if (strstr((char *)pkey.data, "-----BEGIN EC PRIVATE KEY-----")) {
1223 gnutls_datum_t der_private;
1224
1225 if (gnutls_pem_base64_decode2("EC PRIVATE KEY", &pkey,
1226 &der_private) == 0) {
1227 coap_binary_t *spki = get_asn1_spki(der_private.data,
1228 der_private.size);
1229
1230 if (spki) {
1231 gnutls_datum_t tspki;
1232
1233 tspki.data = spki->s;
1234 tspki.size = spki->length;
1235 ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1236 &tspki,
1237 &der_private,
1238 GNUTLS_X509_FMT_DER, NULL,
1239 COAP_GNUTLS_KEY_RPK,
1240 NULL, 0, 0);
1241 if (ret >= 0) {
1242 have_done_key = 1;
1243 }
1244 coap_delete_binary(spki);
1245 }
1246 gnutls_free(der_private.data);
1247 }
1248 }
1249 if (!have_done_key) {
1250 if ((ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1251 &cert,
1252 &pkey,
1253 GNUTLS_X509_FMT_PEM, NULL,
1254 COAP_GNUTLS_KEY_RPK,
1255 NULL, 0, 0)) < 0) {
1256 if (alloced_cert_memory)
1257 gnutls_free(cert.data);
1258 if (alloced_pkey_memory)
1259 gnutls_free(pkey.data);
1262 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1263 }
1264 }
1265 if (alloced_cert_memory)
1266 gnutls_free(cert.data);
1267 if (alloced_pkey_memory)
1268 gnutls_free(pkey.data);
1269 break;
1270#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1271 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1274 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1275#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1276 case COAP_PKI_KEY_DEF_DER: /* define public cert */
1277 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1280 GNUTLS_X509_FMT_DER) < 0)) {
1283 &key, role, ret);
1284 }
1285 break;
1286 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
1287 if ((ret = check_null_memory(&cert,
1290 &alloced_cert_memory)) < 0) {
1293 &key, role, ret);
1294 }
1295 if ((ret = check_null_memory(&pkey,
1298 &alloced_pkey_memory)) < 0) {
1299 if (alloced_cert_memory)
1300 gnutls_free(cert.data);
1303 &key, role, ret);
1304 }
1305 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1306 &cert,
1307 &pkey,
1308 GNUTLS_X509_FMT_DER)) < 0) {
1309 if (alloced_cert_memory)
1310 gnutls_free(cert.data);
1311 if (alloced_pkey_memory)
1312 gnutls_free(pkey.data);
1315 &key, role, ret);
1316 }
1317 if (alloced_cert_memory)
1318 gnutls_free(cert.data);
1319 if (alloced_pkey_memory)
1320 gnutls_free(pkey.data);
1321 break;
1322 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
1323 gnutls_pkcs11_set_pin_function(pin_callback, &setup_data->pki_key);
1324 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1327 GNUTLS_X509_FMT_DER)) < 0) {
1330 &key, role, ret);
1331 }
1332 break;
1333 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
1334#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1335 gnutls_pkcs11_set_pin_function(pin_callback, setup_data);
1336 if ((ret = gnutls_certificate_set_rawpk_key_file(*pki_credentials,
1339 GNUTLS_X509_FMT_PEM, NULL,
1340 COAP_GNUTLS_KEY_RPK,
1341 NULL, 0, GNUTLS_PKCS_PLAIN, 0))) {
1344 &key, role, ret);
1345 }
1346#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1347 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1348 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1349#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1350 break;
1351 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
1352 default:
1355 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1356 }
1357 }
1358
1359 /*
1360 * Configure the CA
1361 */
1362 if (key.key.define.ca.u_byte &&
1363 key.key.define.ca.u_byte[0]) {
1364 switch (key.key.define.ca_def) {
1366 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1367 key.key.define.ca.s_byte,
1368 GNUTLS_X509_FMT_PEM) < 0)) {
1371 &key, role, ret);
1372 }
1373 break;
1374 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
1375 if ((ret = check_null_memory(&ca,
1376 key.key.define.ca.u_byte,
1377 key.key.define.ca_len,
1378 &alloced_ca_memory)) < 0) {
1381 &key, role, ret);
1382 }
1383 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1384 &ca,
1385 GNUTLS_X509_FMT_PEM)) < 0) {
1386 if (alloced_ca_memory)
1387 gnutls_free(ca.data);
1390 &key, role, ret);
1391 }
1392 if (alloced_ca_memory)
1393 gnutls_free(ca.data);
1394 break;
1395 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
1396 /* Ignore if set */
1397 break;
1398 case COAP_PKI_KEY_DEF_DER: /* define ca */
1399 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1400 key.key.define.ca.s_byte,
1401 GNUTLS_X509_FMT_DER) < 0)) {
1404 &key, role, ret);
1405 }
1406 break;
1407 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
1408 if ((ret = check_null_memory(&ca,
1409 key.key.define.ca.u_byte,
1410 key.key.define.ca_len,
1411 &alloced_ca_memory)) < 0) {
1414 &key, role, ret);
1415 }
1416 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1417 &ca,
1418 GNUTLS_X509_FMT_DER)) <= 0) {
1419 if (alloced_ca_memory)
1420 gnutls_free(ca.data);
1423 &key, role, ret);
1424 }
1425 if (alloced_ca_memory)
1426 gnutls_free(ca.data);
1427 break;
1428 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
1429 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1430 key.key.define.ca.s_byte,
1431 GNUTLS_X509_FMT_DER)) <= 0) {
1434 &key, role, ret);
1435 }
1436 break;
1437 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
1438 /* Ignore if set */
1439 break;
1440 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
1441 default:
1444 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1445 }
1446 }
1447
1448#if (GNUTLS_VERSION_NUMBER >= 0x030020)
1449 if (g_context->trust_store_defined) {
1450 G_CHECK(gnutls_certificate_set_x509_system_trust(*pki_credentials),
1451 "gnutls_certificate_set_x509_system_trust");
1452 }
1453#endif
1454 if (g_context->root_ca_file) {
1455 ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1456 g_context->root_ca_file,
1457 GNUTLS_X509_FMT_PEM);
1458 if (ret == 0) {
1459 coap_log_warn("gnutls_certificate_set_x509_trust_file: Root CA: No certificates found\n");
1460 }
1461 }
1462 if (g_context->root_ca_path) {
1463#if (GNUTLS_VERSION_NUMBER >= 0x030306)
1464 G_CHECK(gnutls_certificate_set_x509_trust_dir(*pki_credentials,
1465 g_context->root_ca_path,
1466 GNUTLS_X509_FMT_PEM),
1467 "gnutls_certificate_set_x509_trust_dir");
1468#endif
1469 }
1470 gnutls_certificate_send_x509_rdn_sequence(g_session,
1471 setup_data->check_common_ca ? 0 : 1);
1472#if (GNUTLS_VERSION_NUMBER >= 0x030020)
1473 if (!(g_context->psk_pki_enabled & IS_PKI) && !g_context->trust_store_defined) {
1474 /* No PKI defined at all - still need a trust set up for 3.6.0 or later */
1475 G_CHECK(gnutls_certificate_set_x509_system_trust(*pki_credentials),
1476 "gnutls_certificate_set_x509_system_trust");
1477 }
1478#endif
1479
1480 /* Verify Peer */
1481 gnutls_certificate_set_verify_function(*pki_credentials,
1482 cert_verify_callback_gnutls);
1483
1484 /* Cert chain checking (can raise GNUTLS_E_CONSTRAINT_ERROR) */
1485 if (setup_data->cert_chain_validation) {
1486 gnutls_certificate_set_verify_limits(*pki_credentials,
1487 0,
1488 setup_data->cert_chain_verify_depth + 2);
1489 }
1490
1491 /*
1492 * Check for self signed
1493 * CRL checking (can raise GNUTLS_CERT_MISSING_OCSP_STATUS)
1494 */
1495 gnutls_certificate_set_verify_flags(*pki_credentials,
1496 (setup_data->check_cert_revocation == 0 ?
1497 GNUTLS_VERIFY_DISABLE_CRL_CHECKS : 0)
1498 );
1499
1500 return GNUTLS_E_SUCCESS;
1501
1502fail:
1503 return ret;
1504}
1505
1506#if COAP_SERVER_SUPPORT
1507/*
1508 * return 0 Success (GNUTLS_E_SUCCESS)
1509 * neg GNUTLS_E_* error code
1510 */
1511static int
1512setup_psk_credentials(gnutls_psk_server_credentials_t *psk_credentials,
1513 coap_gnutls_context_t *g_context COAP_UNUSED,
1514 coap_dtls_spsk_t *setup_data) {
1515 int ret;
1516 char hint[COAP_DTLS_HINT_LENGTH];
1517
1518 G_CHECK(gnutls_psk_allocate_server_credentials(psk_credentials),
1519 "gnutls_psk_allocate_server_credentials");
1520 gnutls_psk_set_server_credentials_function(*psk_credentials,
1521 psk_server_callback);
1522 if (setup_data->psk_info.hint.s) {
1523 snprintf(hint, sizeof(hint), "%.*s", (int)setup_data->psk_info.hint.length,
1524 setup_data->psk_info.hint.s);
1525 G_CHECK(gnutls_psk_set_server_credentials_hint(*psk_credentials, hint),
1526 "gnutls_psk_set_server_credentials_hint");
1527 }
1528
1529 return GNUTLS_E_SUCCESS;
1530
1531fail:
1532 return ret;
1533}
1534
1535/*
1536 * return 0 Success (GNUTLS_E_SUCCESS)
1537 * neg GNUTLS_E_* error code
1538 */
1539static int
1540post_client_hello_gnutls_psk(gnutls_session_t g_session) {
1541 coap_session_t *c_session =
1542 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1543 coap_gnutls_context_t *g_context =
1544 (coap_gnutls_context_t *)c_session->context->dtls_context;
1545 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1546 int ret = GNUTLS_E_SUCCESS;
1547 char *name = NULL;
1548
1550 coap_dtls_spsk_t sni_setup_data;
1551 /* DNS names (only type supported) may be at most 256 byte long */
1552 size_t len = 256;
1553 unsigned int type;
1554 unsigned int i;
1555
1556 name = gnutls_malloc(len);
1557 if (name == NULL)
1558 return GNUTLS_E_MEMORY_ERROR;
1559
1560 for (i=0; ;) {
1561 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1562 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1563 char *new_name;
1564 new_name = gnutls_realloc(name, len);
1565 if (new_name == NULL) {
1566 ret = GNUTLS_E_MEMORY_ERROR;
1567 goto end;
1568 }
1569 name = new_name;
1570 continue; /* retry call with same index */
1571 }
1572
1573 /* check if it is the last entry in list */
1574 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1575 break;
1576 i++;
1577 if (ret != GNUTLS_E_SUCCESS)
1578 goto end;
1579 /* unknown types need to be ignored */
1580 if (type != GNUTLS_NAME_DNS)
1581 continue;
1582
1583 }
1584 /* If no extension provided, make it a dummy entry */
1585 if (i == 0) {
1586 name[0] = '\000';
1587 len = 0;
1588 }
1589
1590 /* Is this a cached entry? */
1591 for (i = 0; i < g_context->psk_sni_count; i++) {
1592 if (strcasecmp(name, g_context->psk_sni_entry_list[i].sni) == 0) {
1593 break;
1594 }
1595 }
1596 if (i == g_context->psk_sni_count) {
1597 /*
1598 * New SNI request
1599 */
1600 const coap_dtls_spsk_info_t *new_entry;
1601
1602 coap_lock_callback_ret(new_entry, c_session->context,
1604 c_session,
1606 if (!new_entry) {
1607 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1608 GNUTLS_A_UNRECOGNIZED_NAME));
1609 g_env->sent_alert = 1;
1610 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1611 goto end;
1612 }
1613
1614 g_context->psk_sni_entry_list =
1615 gnutls_realloc(g_context->psk_sni_entry_list,
1616 (i+1)*sizeof(psk_sni_entry));
1617 g_context->psk_sni_entry_list[i].sni = gnutls_strdup(name);
1618 g_context->psk_sni_entry_list[i].psk_info = *new_entry;
1619 sni_setup_data = c_session->context->spsk_setup_data;
1620 sni_setup_data.psk_info = *new_entry;
1621 if ((ret = setup_psk_credentials(
1622 &g_context->psk_sni_entry_list[i].psk_credentials,
1623 g_context,
1624 &sni_setup_data)) < 0) {
1625 int keep_ret = ret;
1626 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1627 GNUTLS_A_BAD_CERTIFICATE));
1628 g_env->sent_alert = 1;
1629 ret = keep_ret;
1630 goto end;
1631 }
1632 g_context->psk_sni_count++;
1633 }
1634 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1635 g_context->psk_sni_entry_list[i].psk_credentials),
1636 "gnutls_credentials_set");
1638 &g_context->psk_sni_entry_list[i].psk_info.hint);
1640 &g_context->psk_sni_entry_list[i].psk_info.key);
1641 }
1642
1643end:
1644 free(name);
1645 return ret;
1646
1647fail:
1648 return ret;
1649}
1650
1651/*
1652 * return 0 Success (GNUTLS_E_SUCCESS)
1653 * neg GNUTLS_E_* error code
1654 */
1655static int
1656post_client_hello_gnutls_pki(gnutls_session_t g_session) {
1657 coap_session_t *c_session =
1658 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1659 coap_gnutls_context_t *g_context =
1660 (coap_gnutls_context_t *)c_session->context->dtls_context;
1661 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1662 int ret = GNUTLS_E_SUCCESS;
1663 char *name = NULL;
1664
1665 if (g_context->setup_data.validate_sni_call_back) {
1666 /* DNS names (only type supported) may be at most 256 byte long */
1667 size_t len = 256;
1668 unsigned int type;
1669 unsigned int i;
1670 coap_dtls_pki_t sni_setup_data;
1671
1672 name = gnutls_malloc(len);
1673 if (name == NULL)
1674 return GNUTLS_E_MEMORY_ERROR;
1675
1676 for (i=0; ;) {
1677 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1678 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1679 char *new_name;
1680 new_name = gnutls_realloc(name, len);
1681 if (new_name == NULL) {
1682 ret = GNUTLS_E_MEMORY_ERROR;
1683 goto end;
1684 }
1685 name = new_name;
1686 continue; /* retry call with same index */
1687 }
1688
1689 /* check if it is the last entry in list */
1690 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1691 break;
1692 i++;
1693 if (ret != GNUTLS_E_SUCCESS)
1694 goto end;
1695 /* unknown types need to be ignored */
1696 if (type != GNUTLS_NAME_DNS)
1697 continue;
1698
1699 }
1700 /* If no extension provided, make it a dummy entry */
1701 if (i == 0) {
1702 name[0] = '\000';
1703 len = 0;
1704 }
1705
1706 /* Is this a cached entry? */
1707 for (i = 0; i < g_context->pki_sni_count; i++) {
1708 if (strcasecmp(name, g_context->pki_sni_entry_list[i].sni) == 0) {
1709 break;
1710 }
1711 }
1712 if (i == g_context->pki_sni_count) {
1713 /*
1714 * New SNI request
1715 */
1716 coap_dtls_key_t *new_entry;
1717
1718 coap_lock_callback_ret(new_entry, c_session->context,
1719 g_context->setup_data.validate_sni_call_back(name,
1720 g_context->setup_data.sni_call_back_arg));
1721 if (!new_entry) {
1722 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1723 GNUTLS_A_UNRECOGNIZED_NAME));
1724 g_env->sent_alert = 1;
1725 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1726 goto end;
1727 }
1728
1729 g_context->pki_sni_entry_list = gnutls_realloc(
1730 g_context->pki_sni_entry_list,
1731 (i+1)*sizeof(pki_sni_entry));
1732 g_context->pki_sni_entry_list[i].sni = gnutls_strdup(name);
1733 g_context->pki_sni_entry_list[i].pki_key = *new_entry;
1734 sni_setup_data = g_context->setup_data;
1735 sni_setup_data.pki_key = *new_entry;
1736 if ((ret = setup_pki_credentials(&g_context->pki_sni_entry_list[i].pki_credentials,
1737 g_session,
1738 g_context,
1739 &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
1740 int keep_ret = ret;
1741 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1742 GNUTLS_A_BAD_CERTIFICATE));
1743 g_env->sent_alert = 1;
1744 ret = keep_ret;
1745 goto end;
1746 }
1747 g_context->pki_sni_count++;
1748 }
1749 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1750 g_context->pki_sni_entry_list[i].pki_credentials),
1751 "gnutls_credentials_set");
1752 }
1753
1754end:
1755 free(name);
1756 return ret;
1757
1758fail:
1759 return ret;
1760}
1761#endif /* COAP_SERVER_SUPPORT */
1762
1763#if COAP_CLIENT_SUPPORT
1764/*
1765 * return 0 Success (GNUTLS_E_SUCCESS)
1766 * neg GNUTLS_E_* error code
1767 */
1768static int
1769setup_client_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
1770 coap_gnutls_context_t *g_context =
1771 (coap_gnutls_context_t *)c_session->context->dtls_context;
1772 int ret;
1773
1774 g_context->psk_pki_enabled |= IS_CLIENT;
1775 if (g_context->psk_pki_enabled & IS_PSK) {
1776 coap_dtls_cpsk_t *setup_data = &c_session->cpsk_setup_data;
1777 G_CHECK(gnutls_psk_allocate_client_credentials(&g_env->psk_cl_credentials),
1778 "gnutls_psk_allocate_client_credentials");
1779 gnutls_psk_set_client_credentials_function(g_env->psk_cl_credentials,
1780 psk_client_callback);
1781 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1782 g_env->psk_cl_credentials),
1783 "gnutls_credentials_set");
1784 /* Issue SNI if requested */
1785 if (setup_data->client_sni) {
1786 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1787 setup_data->client_sni,
1788 strlen(setup_data->client_sni)),
1789 "gnutls_server_name_set");
1790 }
1791 if (setup_data->validate_ih_call_back) {
1792 const char *err;
1794
1795 if (tls_version->version >= 0x030604) {
1796 /* Disable TLS1.3 if Identity Hint Callback set */
1797 const char *priority;
1798
1799 if (tls_version->version >= 0x030606) {
1800 priority = VARIANTS_NO_TLS13_3_6_6;
1801 } else {
1802 priority = VARIANTS_NO_TLS13_3_6_4;
1803 }
1804 ret = gnutls_priority_set_direct(g_env->g_session,
1805 priority, &err);
1806 if (ret < 0) {
1807 if (ret == GNUTLS_E_INVALID_REQUEST)
1808 coap_log_warn("gnutls_priority_set_direct: Syntax error at: %s\n", err);
1809 else
1810 coap_log_warn("gnutls_priority_set_direct: %s\n", gnutls_strerror(ret));
1811 goto fail;
1812 }
1813 }
1814 }
1815 }
1816
1817 if ((g_context->psk_pki_enabled & IS_PKI) ||
1818 (g_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1819 /*
1820 * If neither PSK or PKI have been set up, use PKI basics.
1821 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1822 */
1823 coap_dtls_pki_t *setup_data = &g_context->setup_data;
1824
1825 if (!(g_context->psk_pki_enabled & IS_PKI)) {
1826 /* PKI not defined - set up some defaults */
1827 setup_data->verify_peer_cert = 1;
1828 setup_data->check_common_ca = 0;
1829 setup_data->allow_self_signed = 1;
1830 setup_data->allow_expired_certs = 1;
1831 setup_data->cert_chain_validation = 1;
1832 setup_data->cert_chain_verify_depth = 2;
1833 setup_data->check_cert_revocation = 1;
1834 setup_data->allow_no_crl = 1;
1835 setup_data->allow_expired_crl = 1;
1836 setup_data->is_rpk_not_cert = 0;
1837 setup_data->use_cid = 0;
1838 }
1839 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
1840 g_context, setup_data,
1842 "setup_pki_credentials");
1843
1844 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1845 g_env->pki_credentials),
1846 "gnutls_credentials_set");
1847
1848 if (c_session->proto == COAP_PROTO_TLS)
1849 G_CHECK(gnutls_alpn_set_protocols(g_env->g_session,
1850 &g_context->alpn_proto, 1, 0),
1851 "gnutls_alpn_set_protocols");
1852
1853 /* Issue SNI if requested (only happens if PKI defined) */
1854 if (setup_data->client_sni) {
1855 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1856 setup_data->client_sni,
1857 strlen(setup_data->client_sni)),
1858 "gnutls_server_name_set");
1859 }
1860 }
1861 return GNUTLS_E_SUCCESS;
1862
1863fail:
1864 return ret;
1865}
1866#endif /* COAP_CLIENT_SUPPORT */
1867
1868#if COAP_SERVER_SUPPORT
1869/*
1870 * gnutls_psk_server_credentials_function return values
1871 * (see gnutls_psk_set_server_credentials_function())
1872 *
1873 * return -1 failed
1874 * 0 passed
1875 */
1876static int
1877psk_server_callback(gnutls_session_t g_session,
1878 const char *identity,
1879 gnutls_datum_t *key) {
1880 coap_session_t *c_session =
1881 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1882 coap_gnutls_context_t *g_context;
1883 coap_dtls_spsk_t *setup_data;
1884 coap_bin_const_t lidentity;
1885 const coap_bin_const_t *psk_key;
1886
1887 if (c_session == NULL)
1888 return -1;
1889
1890 g_context = (coap_gnutls_context_t *)c_session->context->dtls_context;
1891 if (g_context == NULL)
1892 return -1;
1893 setup_data = &c_session->context->spsk_setup_data;
1894
1895
1896 /* Track the Identity being used */
1897 lidentity.s = identity ? (const uint8_t *)identity : (const uint8_t *)"";
1898 lidentity.length = strlen((const char *)lidentity.s);
1899 coap_session_refresh_psk_identity(c_session, &lidentity);
1900
1901 coap_log_debug("got psk_identity: '%.*s'\n",
1902 (int)lidentity.length, (const char *)lidentity.s);
1903
1904 if (setup_data->validate_id_call_back) {
1905 psk_key = setup_data->validate_id_call_back(&lidentity,
1906 c_session,
1907 setup_data->id_call_back_arg);
1908
1909 coap_session_refresh_psk_key(c_session, psk_key);
1910 } else {
1911 psk_key = coap_get_session_server_psk_key(c_session);
1912 }
1913
1914 if (psk_key == NULL)
1915 return -1;
1916
1917 key->data = gnutls_malloc(psk_key->length);
1918 if (key->data == NULL)
1919 return -1;
1920 memcpy(key->data, psk_key->s, psk_key->length);
1921 key->size = psk_key->length;
1922 return 0;
1923}
1924
1925/*
1926 * return 0 Success (GNUTLS_E_SUCCESS)
1927 * neg GNUTLS_E_* error code
1928 */
1929static int
1930setup_server_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
1931 coap_gnutls_context_t *g_context =
1932 (coap_gnutls_context_t *)c_session->context->dtls_context;
1933 int ret = GNUTLS_E_SUCCESS;
1934
1935 g_context->psk_pki_enabled |= IS_SERVER;
1936 if (g_context->psk_pki_enabled & IS_PSK) {
1937 G_CHECK(setup_psk_credentials(
1938 &g_env->psk_sv_credentials,
1939 g_context,
1940 &c_session->context->spsk_setup_data),
1941 "setup_psk_credentials\n");
1942 G_CHECK(gnutls_credentials_set(g_env->g_session,
1943 GNUTLS_CRD_PSK,
1944 g_env->psk_sv_credentials),
1945 "gnutls_credentials_set\n");
1946 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
1947 post_client_hello_gnutls_psk);
1948 }
1949
1950 if (g_context->psk_pki_enabled & IS_PKI) {
1951 coap_dtls_pki_t *setup_data = &g_context->setup_data;
1952 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
1953 g_context, setup_data,
1955 "setup_pki_credentials");
1956
1957 if (setup_data->verify_peer_cert) {
1958 gnutls_certificate_server_set_request(g_env->g_session,
1959 GNUTLS_CERT_REQUIRE);
1960 } else if (setup_data->is_rpk_not_cert) {
1961 gnutls_certificate_server_set_request(g_env->g_session,
1962 GNUTLS_CERT_REQUEST);
1963 } else {
1964 gnutls_certificate_server_set_request(g_env->g_session,
1965 GNUTLS_CERT_IGNORE);
1966 }
1967
1968 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
1969 post_client_hello_gnutls_pki);
1970
1971 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1972 g_env->pki_credentials),
1973 "gnutls_credentials_set\n");
1974 }
1975 return GNUTLS_E_SUCCESS;
1976
1977fail:
1978 return ret;
1979}
1980#endif /* COAP_SERVER_SUPPORT */
1981
1982/*
1983 * return +ve data amount
1984 * 0 no more
1985 * -1 error (error in errno)
1986 */
1987static ssize_t
1988coap_dgram_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
1989 ssize_t ret = 0;
1990 coap_session_t *c_session = (coap_session_t *)context;
1991 coap_ssl_t *data;
1992
1993 if (!c_session->tls) {
1994 errno = EAGAIN;
1995 return -1;
1996 }
1997 data = &((coap_gnutls_env_t *)c_session->tls)->coap_ssl_data;
1998
1999 if (out != NULL) {
2000 if (data != NULL && data->pdu_len > 0) {
2001 if (outl < data->pdu_len) {
2002 memcpy(out, data->pdu, outl);
2003 ret = outl;
2004 if (!data->peekmode) {
2005 data->pdu += outl;
2006 data->pdu_len -= outl;
2007 }
2008 } else {
2009 memcpy(out, data->pdu, data->pdu_len);
2010 ret = data->pdu_len;
2011 if (!data->peekmode) {
2012 data->pdu_len = 0;
2013 data->pdu = NULL;
2014 }
2015 }
2016 } else {
2017 errno = EAGAIN;
2018 ret = -1;
2019 }
2020 }
2021 return ret;
2022}
2023
2024/*
2025 * return +ve data amount
2026 * 0 no more
2027 * -1 error (error in errno)
2028 */
2029/* callback function given to gnutls for sending data over socket */
2030static ssize_t
2031coap_dgram_write(gnutls_transport_ptr_t context, const void *send_buffer,
2032 size_t send_buffer_length) {
2033 ssize_t result = -1;
2034 coap_session_t *c_session = (coap_session_t *)context;
2035
2036 if (c_session) {
2037 if (!coap_netif_available(c_session)
2038#if COAP_SERVER_SUPPORT
2039 && c_session->endpoint == NULL
2040#endif /* COAP_SERVER_SUPPORT */
2041 ) {
2042 /* socket was closed on client due to error */
2043 errno = ECONNRESET;
2044 return -1;
2045 }
2046 result = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
2047 send_buffer, send_buffer_length);
2048 if (result != (int)send_buffer_length) {
2049 int keep_errno = errno;
2050
2051 coap_log_warn("coap_netif_dgrm_write failed (%zd != %zu)\n",
2052 result, send_buffer_length);
2053 errno = keep_errno;
2054 if (result < 0) {
2055 if (errno == ENOTCONN || errno == ECONNREFUSED)
2056 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2057 return -1;
2058 } else {
2059 result = 0;
2060 }
2061 }
2062 } else {
2063 result = 0;
2064 }
2065 return result;
2066}
2067
2068/*
2069 * return 1 fd has activity
2070 * 0 timeout
2071 * -1 error (error in errno)
2072 */
2073static int
2074receive_timeout(gnutls_transport_ptr_t context, unsigned int ms COAP_UNUSED) {
2075 coap_session_t *c_session = (coap_session_t *)context;
2076
2077 if (c_session) {
2078 fd_set readfds, writefds, exceptfds;
2079 struct timeval tv;
2080 int nfds = c_session->sock.fd +1;
2081 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2082
2083 /* If data has been read in by libcoap ahead of GnuTLS, say it is there */
2084 if (c_session->proto == COAP_PROTO_DTLS && g_env &&
2085 g_env->coap_ssl_data.pdu_len > 0) {
2086 return 1;
2087 }
2088
2089 FD_ZERO(&readfds);
2090 FD_ZERO(&writefds);
2091 FD_ZERO(&exceptfds);
2092 FD_SET(c_session->sock.fd, &readfds);
2093 if (!(g_env && g_env->doing_dtls_timeout)) {
2094 FD_SET(c_session->sock.fd, &writefds);
2095 FD_SET(c_session->sock.fd, &exceptfds);
2096 }
2097 /* Polling */
2098 tv.tv_sec = 0;
2099 tv.tv_usec = 0;
2100
2101 return select(nfds, &readfds, &writefds, &exceptfds, &tv);
2102 }
2103 return 1;
2104}
2105
2106static coap_gnutls_env_t *
2107coap_dtls_new_gnutls_env(coap_session_t *c_session, int type) {
2108 coap_gnutls_context_t *g_context =
2109 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2110 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2111#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2112 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2113#else /* < 3.6.6 */
2114 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK;
2115#endif /* < 3.6.6 */
2116 int ret;
2117
2118 if (g_env)
2119 return g_env;
2120
2121 g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2122 if (!g_env)
2123 return NULL;
2124
2125 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2126
2127 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2128
2129 gnutls_transport_set_pull_function(g_env->g_session, coap_dgram_read);
2130 gnutls_transport_set_push_function(g_env->g_session, coap_dgram_write);
2131 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2132 /* So we can track the coap_session_t in callbacks */
2133 gnutls_transport_set_ptr(g_env->g_session, c_session);
2134
2135 G_CHECK(gnutls_priority_set(g_env->g_session, g_context->priority_cache),
2136 "gnutls_priority_set");
2137
2138 if (type == GNUTLS_SERVER) {
2139#if COAP_SERVER_SUPPORT
2140 G_CHECK(setup_server_ssl_session(c_session, g_env),
2141 "setup_server_ssl_session");
2142#else /* ! COAP_SERVER_SUPPORT */
2143 goto fail;
2144#endif /* ! COAP_SERVER_SUPPORT */
2145 } else {
2146#if COAP_CLIENT_SUPPORT
2147 G_CHECK(setup_client_ssl_session(c_session, g_env),
2148 "setup_client_ssl_session");
2149#else /* COAP_CLIENT_SUPPORT */
2150 goto fail;
2151#endif /* COAP_CLIENT_SUPPORT */
2152 }
2153
2154 gnutls_handshake_set_timeout(g_env->g_session,
2155 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2156 gnutls_dtls_set_timeouts(g_env->g_session, COAP_DTLS_RETRANSMIT_MS,
2157 COAP_DTLS_RETRANSMIT_TOTAL_MS);
2158
2159 return g_env;
2160
2161fail:
2162 if (g_env)
2163 gnutls_free(g_env);
2164 return NULL;
2165}
2166
2167static void
2168coap_dtls_free_gnutls_env(coap_gnutls_context_t *g_context,
2169 coap_gnutls_env_t *g_env,
2170 coap_free_bye_t free_bye) {
2171 if (g_env) {
2172 /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
2173 * connections because the peer's closure message might
2174 * be lost */
2175 if (free_bye != COAP_FREE_BYE_NONE && !g_env->sent_alert) {
2176 /* Only do this if appropriate */
2177 gnutls_bye(g_env->g_session, free_bye == COAP_FREE_BYE_AS_UDP ?
2178 GNUTLS_SHUT_WR : GNUTLS_SHUT_RDWR);
2179 }
2180 gnutls_deinit(g_env->g_session);
2181 g_env->g_session = NULL;
2182 if (g_context->psk_pki_enabled & IS_PSK) {
2183 if ((g_context->psk_pki_enabled & IS_CLIENT) &&
2184 g_env->psk_cl_credentials != NULL) {
2185 gnutls_psk_free_client_credentials(g_env->psk_cl_credentials);
2186 g_env->psk_cl_credentials = NULL;
2187 } else {
2188 /* YUK - A memory leak in 3.3.0 (fixed by 3.3.26) of hint */
2189 if (g_env->psk_sv_credentials != NULL)
2190 gnutls_psk_free_server_credentials(g_env->psk_sv_credentials);
2191 g_env->psk_sv_credentials = NULL;
2192 }
2193 }
2194 if ((g_context->psk_pki_enabled & IS_PKI) ||
2195 (g_context->psk_pki_enabled &
2196 (IS_PSK | IS_PKI | IS_CLIENT)) == IS_CLIENT) {
2197 gnutls_certificate_free_credentials(g_env->pki_credentials);
2198 g_env->pki_credentials = NULL;
2199 }
2200 gnutls_free(g_env->coap_ssl_data.cookie_key.data);
2201 gnutls_free(g_env);
2202 }
2203}
2204
2205#if COAP_SERVER_SUPPORT
2206void *
2208 coap_gnutls_env_t *g_env =
2209 (coap_gnutls_env_t *)c_session->tls;
2210
2211 gnutls_transport_set_ptr(g_env->g_session, c_session);
2212
2213 return g_env;
2214}
2215#endif /* COAP_SERVER_SUPPORT */
2216
2217static void
2218log_last_alert(coap_session_t *c_session,
2219 gnutls_session_t g_session) {
2220#if COAP_MAX_LOGGING_LEVEL > 0
2221 int last_alert = gnutls_alert_get(g_session);
2222
2223 if (last_alert == GNUTLS_A_CLOSE_NOTIFY)
2224 coap_log_debug("***%s: Alert '%d': %s\n",
2225 coap_session_str(c_session),
2226 last_alert, gnutls_alert_get_name(last_alert));
2227 else
2228 coap_log_warn("***%s: Alert '%d': %s\n",
2229 coap_session_str(c_session),
2230 last_alert, gnutls_alert_get_name(last_alert));
2231#else /* COAP_MAX_LOGGING_LEVEL == 0 */
2232 (void)c_session;
2233 (void)g_session;
2234#endif /* COAP_MAX_LOGGING_LEVEL == 0 */
2235}
2236
2237/*
2238 * return -1 failure
2239 * 0 not completed
2240 * 1 established
2241 */
2242static int
2243do_gnutls_handshake(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
2244 int ret;
2245
2246 ret = gnutls_handshake(g_env->g_session);
2247 switch (ret) {
2248 case GNUTLS_E_SUCCESS:
2249 g_env->established = 1;
2250 coap_log_debug("* %s: GnuTLS established\n",
2251 coap_session_str(c_session));
2252 ret = 1;
2253 break;
2254 case GNUTLS_E_INTERRUPTED:
2255 errno = EINTR;
2256 ret = 0;
2257 break;
2258 case GNUTLS_E_AGAIN:
2259 errno = EAGAIN;
2260 ret = 0;
2261 break;
2262 case GNUTLS_E_INSUFFICIENT_CREDENTIALS:
2263 coap_log_warn("Insufficient credentials provided.\n");
2264 ret = -1;
2265 break;
2266 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2267 /* Stop the sending of an alert on closedown */
2268 g_env->sent_alert = 1;
2269 log_last_alert(c_session, g_env->g_session);
2270 /* Fall through */
2271 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET:
2272 case GNUTLS_E_UNEXPECTED_PACKET:
2274 ret = -1;
2275 break;
2276 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2277 log_last_alert(c_session, g_env->g_session);
2278 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2279 ret = 0;
2280 break;
2281 case GNUTLS_E_NO_CERTIFICATE_FOUND:
2282#if (GNUTLS_VERSION_NUMBER > 0x030606)
2283 case GNUTLS_E_CERTIFICATE_REQUIRED:
2284#endif /* GNUTLS_VERSION_NUMBER > 0x030606 */
2285 coap_log_warn("Client Certificate requested and required, but not provided\n"
2286 );
2287 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2288 GNUTLS_A_BAD_CERTIFICATE));
2289 g_env->sent_alert = 1;
2291 ret = -1;
2292 break;
2293 case GNUTLS_E_DECRYPTION_FAILED:
2294 coap_log_warn("do_gnutls_handshake: session establish "
2295 "returned '%s'\n",
2296 gnutls_strerror(ret));
2297 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2298 GNUTLS_A_DECRYPT_ERROR));
2299 g_env->sent_alert = 1;
2301 ret = -1;
2302 break;
2303 case GNUTLS_E_CERTIFICATE_ERROR:
2304 if (g_env->sent_alert) {
2306 ret = -1;
2307 break;
2308 }
2309 /* Fall through */
2310 case GNUTLS_E_UNKNOWN_CIPHER_SUITE:
2311 case GNUTLS_E_NO_CIPHER_SUITES:
2312 case GNUTLS_E_INVALID_SESSION:
2313 coap_log_warn("do_gnutls_handshake: session establish "
2314 "returned '%s'\n",
2315 gnutls_strerror(ret));
2316 if (!g_env->sent_alert) {
2317 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2318 GNUTLS_A_HANDSHAKE_FAILURE));
2319 g_env->sent_alert = 1;
2320 }
2322 ret = -1;
2323 break;
2324 case GNUTLS_E_SESSION_EOF:
2325 case GNUTLS_E_PREMATURE_TERMINATION:
2326 case GNUTLS_E_TIMEDOUT:
2327 case GNUTLS_E_PULL_ERROR:
2328 case GNUTLS_E_PUSH_ERROR:
2330 ret = -1;
2331 break;
2332 default:
2333 coap_log_warn("do_gnutls_handshake: session establish "
2334 "returned %d: '%s'\n",
2335 ret, gnutls_strerror(ret));
2336 ret = -1;
2337 break;
2338 }
2339 return ret;
2340}
2341
2342#if COAP_CLIENT_SUPPORT
2343void *
2345 coap_gnutls_env_t *g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_CLIENT);
2346 int ret;
2347
2348 if (g_env) {
2349 ret = do_gnutls_handshake(c_session, g_env);
2350 if (ret == -1) {
2351 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2352 g_env,
2353 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2354 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2355 return NULL;
2356 }
2357 }
2358 return g_env;
2359}
2360#endif /* COAP_CLIENT_SUPPORT */
2361
2362void
2364 if (c_session && c_session->context && c_session->tls) {
2365 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2366 c_session->tls,
2367 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2368 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2369 c_session->tls = NULL;
2371 }
2372}
2373
2374void
2376 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2377 int ret;
2378
2379 if (g_env)
2380 G_CHECK(gnutls_dtls_set_data_mtu(g_env->g_session,
2381 (unsigned int)c_session->mtu),
2382 "gnutls_dtls_set_data_mtu");
2383fail:
2384 ;;
2385}
2386
2387/*
2388 * return +ve data amount
2389 * 0 no more
2390 * -1 error
2391 */
2392ssize_t
2394 const uint8_t *data, size_t data_len) {
2395 int ret;
2396 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2397
2398 assert(g_env != NULL);
2399
2400 c_session->dtls_event = -1;
2401 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2402 coap_session_str(c_session), (int)data_len);
2403 if (g_env->established) {
2404 ret = gnutls_record_send(g_env->g_session, data, data_len);
2405
2406 if (ret <= 0) {
2407 switch (ret) {
2408 case GNUTLS_E_AGAIN:
2409 ret = 0;
2410 break;
2411 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2412 /* Stop the sending of an alert on closedown */
2413 g_env->sent_alert = 1;
2414 log_last_alert(c_session, g_env->g_session);
2416 ret = -1;
2417 break;
2418 default:
2419 coap_log_debug("coap_dtls_send: gnutls_record_send "
2420 "returned %d: '%s'\n",
2421 ret, gnutls_strerror(ret));
2422 ret = -1;
2423 break;
2424 }
2425 if (ret == -1) {
2426 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2427 }
2428 }
2429 } else {
2430 ret = do_gnutls_handshake(c_session, g_env);
2431 if (ret == 1) {
2432 /* Just connected, so send the data */
2433 return coap_dtls_send(c_session, data, data_len);
2434 }
2435 ret = -1;
2436 }
2437
2438 if (c_session->dtls_event >= 0) {
2439 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2440 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2441 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2443 ret = -1;
2444 }
2445 }
2446
2447 return ret;
2448}
2449
2450int
2452 return 0;
2453}
2454
2456coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2457 return 0;
2458}
2459
2462 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2463
2464 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2465 if (g_env && g_env->g_session) {
2466 unsigned int rem_ms = gnutls_dtls_get_timeout(g_env->g_session);
2467
2468 if (rem_ms == 0) {
2469 /*
2470 * Need to make sure that we do not do this too frequently as some
2471 * versions of gnutls reset retransmit if a spurious packet is received
2472 * (e.g. duplicate Client Hello), but last_transmit does not get updated
2473 * when gnutls_handshake() is called and there is 'nothing' to resend.
2474 */
2475 if (g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS > now)
2476 return g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS;
2477 }
2478 /* Reset for the next time */
2479 g_env->last_timeout = now;
2480 return now + rem_ms;
2481 }
2482
2483 return 0;
2484}
2485
2486/*
2487 * return 1 timed out
2488 * 0 still timing out
2489 */
2490int
2492 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2493
2494 assert(g_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2495 g_env->doing_dtls_timeout = 1;
2496 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2497 (do_gnutls_handshake(c_session, g_env) < 0)) {
2498 /* Too many retries */
2499 g_env->doing_dtls_timeout = 0;
2501 return 1;
2502 } else {
2503 g_env->doing_dtls_timeout = 0;
2504 return 0;
2505 }
2506}
2507
2508/*
2509 * return +ve data amount
2510 * 0 no more
2511 * -1 error
2512 */
2513int
2514coap_dtls_receive(coap_session_t *c_session, const uint8_t *data,
2515 size_t data_len) {
2516 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2517 int ret = 0;
2518 coap_ssl_t *ssl_data = &g_env->coap_ssl_data;
2519
2520 uint8_t pdu[COAP_RXBUFFER_SIZE];
2521
2522 assert(g_env != NULL);
2523
2524 if (ssl_data->pdu_len)
2525 coap_log_err("** %s: Previous data not read %u bytes\n",
2526 coap_session_str(c_session), ssl_data->pdu_len);
2527 ssl_data->pdu = data;
2528 ssl_data->pdu_len = data_len;
2529
2530 c_session->dtls_event = -1;
2531 if (g_env->established) {
2532 if (c_session->state == COAP_SESSION_STATE_HANDSHAKE) {
2534 c_session);
2535 gnutls_transport_set_ptr(g_env->g_session, c_session);
2536 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2537 }
2538 ret = gnutls_record_recv(g_env->g_session, pdu, (int)sizeof(pdu));
2539 if (ret > 0) {
2540 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2541 coap_session_str(c_session), ret);
2542 return coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2543 } else if (ret == 0) {
2545 } else {
2546 switch (ret) {
2547 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2548 /* Stop the sending of an alert on closedown */
2549 g_env->sent_alert = 1;
2550 log_last_alert(c_session, g_env->g_session);
2552 ret = -1;
2553 break;
2554 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2555 log_last_alert(c_session, g_env->g_session);
2556 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2557 ret = 0;
2558 break;
2559 default:
2560 coap_log_warn("coap_dtls_receive: gnutls_record_recv returned %d\n", ret);
2561 ret = -1;
2562 break;
2563 }
2564 }
2565 } else {
2566 ret = do_gnutls_handshake(c_session, g_env);
2567 if (ret == 1) {
2568 coap_session_connected(c_session);
2569 } else {
2570 ret = -1;
2571 if (ssl_data->pdu_len && !g_env->sent_alert) {
2572 /* Do the handshake again incase of internal timeout */
2573 ret = do_gnutls_handshake(c_session, g_env);
2574 if (ret == 1) {
2575 /* Just connected, so send the data */
2576 coap_session_connected(c_session);
2577 }
2578 }
2579 }
2580 }
2581
2582 if (c_session->dtls_event >= 0) {
2583 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2584 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2585 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2586 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2587 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2589 ssl_data = NULL;
2590 ret = -1;
2591 }
2592 }
2593 if (ssl_data && ssl_data->pdu_len) {
2594 /* pdu data is held on stack which will not stay there */
2595 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2596 ssl_data->pdu_len = 0;
2597 ssl_data->pdu = NULL;
2598 }
2599 return ret;
2600}
2601
2602#if COAP_SERVER_SUPPORT
2603/*
2604 * return -1 failure
2605 * 0 not completed
2606 * 1 client hello seen
2607 */
2608int
2610 const uint8_t *data,
2611 size_t data_len
2612 ) {
2613 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2614 coap_ssl_t *ssl_data;
2615 int ret;
2616
2617 if (!g_env) {
2618 g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_SERVER);
2619 if (g_env) {
2620 c_session->tls = g_env;
2621 gnutls_key_generate(&g_env->coap_ssl_data.cookie_key,
2622 GNUTLS_COOKIE_KEY_SIZE);
2623 } else {
2624 /* error should have already been reported */
2625 return -1;
2626 }
2627 }
2628 if (data_len > 0) {
2629 gnutls_dtls_prestate_st prestate;
2630 uint8_t *data_rw;
2631
2632 memset(&prestate, 0, sizeof(prestate));
2633 /* Need to do this to not get a compiler warning about const parameters */
2634 memcpy(&data_rw, &data, sizeof(data_rw));
2635 ret = gnutls_dtls_cookie_verify(&g_env->coap_ssl_data.cookie_key,
2636 &c_session->addr_info,
2637 sizeof(c_session->addr_info),
2638 data_rw, data_len,
2639 &prestate);
2640 if (ret < 0) { /* cookie not valid */
2641 coap_log_debug("Invalid Cookie - sending Hello Verify\n");
2642 gnutls_dtls_cookie_send(&g_env->coap_ssl_data.cookie_key,
2643 &c_session->addr_info,
2644 sizeof(c_session->addr_info),
2645 &prestate,
2646 c_session,
2647 coap_dgram_write);
2648 return 0;
2649 }
2650 gnutls_dtls_prestate_set(g_env->g_session, &prestate);
2651 }
2652
2653 ssl_data = &g_env->coap_ssl_data;
2654 ssl_data->pdu = data;
2655 ssl_data->pdu_len = data_len;
2656
2657 ret = do_gnutls_handshake(c_session, g_env);
2658 if (ret < 0) {
2659 /*
2660 * as the above failed, need to remove g_env to clean up any
2661 * pollution of the information
2662 */
2663 coap_dtls_free_gnutls_env(((coap_gnutls_context_t *)c_session->context->dtls_context),
2664 g_env, COAP_FREE_BYE_NONE);
2665 c_session->tls = NULL;
2666 ssl_data = NULL;
2667 ret = -1;
2668 } else {
2669 /* Client Hello has been seen */
2670 ret = 1;
2671 }
2672
2673 if (ssl_data && ssl_data->pdu_len) {
2674 /* pdu data is held on stack which will not stay there */
2675 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2676 ssl_data->pdu_len = 0;
2677 ssl_data->pdu = NULL;
2678 }
2679 return ret;
2680}
2681#endif /* COAP_SERVER_SUPPORT */
2682
2683unsigned int
2685 return 37;
2686}
2687
2688#if !COAP_DISABLE_TCP
2689/*
2690 * strm
2691 * return +ve data amount
2692 * 0 connection closed
2693 * -1 error (error in errno)
2694 */
2695static ssize_t
2696coap_sock_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
2697 int ret = 0;
2698 coap_session_t *c_session = (coap_session_t *)context;
2699
2700 if (out != NULL) {
2701 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
2702 /* Translate layer returns into what GnuTLS expects */
2703 if (ret == 0) {
2704 errno = EAGAIN;
2705 ret = -1;
2706 }
2707 }
2708 return ret;
2709}
2710
2711/*
2712 * strm
2713 * return +ve data amount
2714 * 0 no more
2715 * -1 error (error in errno)
2716 */
2717static ssize_t
2718coap_sock_write(gnutls_transport_ptr_t context, const void *in, size_t inl) {
2719 int ret = 0;
2720 coap_session_t *c_session = (coap_session_t *)context;
2721
2722 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session, in, inl);
2723 /* Translate layer what returns into what GnuTLS expects */
2724 if (ret < 0) {
2725 if ((c_session->state == COAP_SESSION_STATE_CSM ||
2726 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
2727 (errno == EPIPE || errno == ECONNRESET)) {
2728 /*
2729 * Need to handle a TCP timing window where an agent continues with
2730 * the sending of the next handshake or a CSM.
2731 * However, the peer does not like a certificate and so sends a
2732 * fatal alert and closes the TCP session.
2733 * The sending of the next handshake or CSM may get terminated because
2734 * of the closed TCP session, but there is still an outstanding alert
2735 * to be read in and reported on.
2736 * In this case, pretend that sending the info was fine so that the
2737 * alert can be read (which effectively is what happens with DTLS).
2738 */
2739 ret = inl;
2740 } else {
2741 coap_log_debug("* %s: failed to send %zd bytes (%s) state %d\n",
2742 coap_session_str(c_session), inl, coap_socket_strerror(),
2743 c_session->state);
2744 }
2745 }
2746 if (ret == 0) {
2747 errno = EAGAIN;
2748 ret = -1;
2749 }
2750 return ret;
2751}
2752
2753#if COAP_CLIENT_SUPPORT
2754void *
2756 coap_gnutls_env_t *g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2757 coap_gnutls_context_t *g_context =
2758 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2759#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2760 int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2761#else /* < 3.6.6 */
2762 int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
2763#endif /* < 3.6.6 */
2764 int ret;
2765
2766 if (!g_env) {
2767 return NULL;
2768 }
2769 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2770
2771 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2772
2773 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2774 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2775 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2776 /* So we can track the coap_session_t in callbacks */
2777 gnutls_transport_set_ptr(g_env->g_session, c_session);
2778
2779 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2780 setup_client_ssl_session(c_session, g_env);
2781
2782 gnutls_handshake_set_timeout(g_env->g_session, GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2783
2784 c_session->tls = g_env;
2785 ret = do_gnutls_handshake(c_session, g_env);
2786 if (ret == 1) {
2788 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2789 }
2790 return g_env;
2791
2792fail:
2793 if (g_env)
2794 gnutls_free(g_env);
2795 return NULL;
2796}
2797#endif /* COAP_CLIENT_SUPPORT */
2798
2799#if COAP_SERVER_SUPPORT
2800void *
2802 coap_gnutls_env_t *g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2803 coap_gnutls_context_t *g_context =
2804 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2805#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2806 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2807#else /* < 3.6.6 */
2808 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK;
2809#endif /* < 3.6.6 */
2810 int ret;
2811
2812 if (!g_env)
2813 return NULL;
2814 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2815
2816 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2817
2818 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2819 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2820 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2821 /* So we can track the coap_session_t in callbacks */
2822 gnutls_transport_set_ptr(g_env->g_session, c_session);
2823
2824 setup_server_ssl_session(c_session, g_env);
2825
2826 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2827 gnutls_handshake_set_timeout(g_env->g_session,
2828 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2829
2830 c_session->tls = g_env;
2831 ret = do_gnutls_handshake(c_session, g_env);
2832 if (ret == 1) {
2834 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2835 }
2836 return g_env;
2837
2838fail:
2839 return NULL;
2840}
2841#endif /* COAP_SERVER_SUPPORT */
2842
2843void
2845 coap_dtls_free_session(c_session);
2846 return;
2847}
2848
2849/*
2850 * strm
2851 * return +ve Number of bytes written.
2852 * -1 Error (error in errno).
2853 */
2854ssize_t
2855coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2856 size_t data_len) {
2857 int ret;
2858 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2859
2860 assert(g_env != NULL);
2861
2862 c_session->dtls_event = -1;
2863 if (g_env->established) {
2864 ret = gnutls_record_send(g_env->g_session, data, data_len);
2865
2866 if (ret <= 0) {
2867 switch (ret) {
2868 case GNUTLS_E_AGAIN:
2869 ret = 0;
2870 break;
2871 case GNUTLS_E_PUSH_ERROR:
2872 case GNUTLS_E_PULL_ERROR:
2873 case GNUTLS_E_PREMATURE_TERMINATION:
2875 break;
2876 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2877 /* Stop the sending of an alert on closedown */
2878 g_env->sent_alert = 1;
2879 log_last_alert(c_session, g_env->g_session);
2881 break;
2882 default:
2883 coap_log_warn("coap_tls_write: gnutls_record_send "
2884 "returned %d: '%s'\n",
2885 ret, gnutls_strerror(ret));
2886 ret = -1;
2887 break;
2888 }
2889 if (ret == -1) {
2890 coap_log_info("coap_tls_write: cannot send PDU\n");
2891 }
2892 }
2893 } else {
2894 ret = do_gnutls_handshake(c_session, g_env);
2895 if (ret == 1) {
2897 c_session);
2898 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2899 ret = 0;
2900 } else {
2901 ret = -1;
2902 }
2903 }
2904
2905 if (c_session->dtls_event >= 0) {
2906 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2907 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2908 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2909 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2910 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2912 ret = -1;
2913 }
2914 }
2915
2916 if (ret > 0) {
2917 if (ret == (ssize_t)data_len)
2918 coap_log_debug("* %s: tls: sent %4d bytes\n",
2919 coap_session_str(c_session), ret);
2920 else
2921 coap_log_debug("* %s: tls: sent %4d of %4zd bytes\n",
2922 coap_session_str(c_session), ret, data_len);
2923 }
2924 return ret;
2925}
2926
2927/*
2928 * strm
2929 * return >=0 Number of bytes read.
2930 * -1 Error (error in errno).
2931 */
2932ssize_t
2933coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
2934 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2935 int ret = -1;
2936
2937 if (!g_env) {
2938 errno = ENXIO;
2939 return -1;
2940 }
2941
2942 c_session->dtls_event = -1;
2943 if (!g_env->established && !g_env->sent_alert) {
2944 ret = do_gnutls_handshake(c_session, g_env);
2945 if (ret == 1) {
2947 c_session);
2948 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2949 ret = 0;
2950 }
2951 }
2952 if (c_session->state != COAP_SESSION_STATE_NONE && g_env->established) {
2953 ret = gnutls_record_recv(g_env->g_session, data, (int)data_len);
2954 if (ret <= 0) {
2955 switch (ret) {
2956 case 0:
2958 break;
2959 case GNUTLS_E_AGAIN:
2960 errno = EAGAIN;
2961 ret = 0;
2962 break;
2963 case GNUTLS_E_PULL_ERROR:
2964 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2965 break;
2966 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2967 /* Stop the sending of an alert on closedown */
2968 g_env->sent_alert = 1;
2969 log_last_alert(c_session, g_env->g_session);
2971 break;
2972 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2973 log_last_alert(c_session, g_env->g_session);
2974 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2975 break;
2976 default:
2977 coap_log_warn("coap_tls_read: gnutls_record_recv "
2978 "returned %d: '%s'\n",
2979 ret, gnutls_strerror(ret));
2980 ret = -1;
2981 break;
2982 }
2983 }
2984 }
2985
2986 if (c_session->dtls_event >= 0) {
2987 /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected_lkd() */
2988 if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
2989 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2990 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2991 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2993 ret = -1;
2994 }
2995 }
2996 if (ret > 0) {
2997 coap_log_debug("* %s: tls: recv %4d bytes\n",
2998 coap_session_str(c_session), ret);
2999 }
3000 return ret;
3001}
3002#endif /* !COAP_DISABLE_TCP */
3003
3004#if COAP_SERVER_SUPPORT
3006coap_digest_setup(void) {
3007 gnutls_hash_hd_t digest_ctx;
3008
3009 if (gnutls_hash_init(&digest_ctx, GNUTLS_DIG_SHA256)) {
3010 return NULL;
3011 }
3012 return digest_ctx;
3013}
3014
3015void
3017 if (digest_ctx)
3018 gnutls_hash_deinit(digest_ctx, NULL);
3019}
3020
3021int
3023 const uint8_t *data,
3024 size_t data_len) {
3025 int ret = gnutls_hash(digest_ctx, data, data_len);
3026
3027 return ret == 0;
3028}
3029
3030int
3032 coap_digest_t *digest_buffer) {
3033 gnutls_hash_output(digest_ctx, (uint8_t *)digest_buffer);
3034
3035 coap_digest_free(digest_ctx);
3036 return 1;
3037}
3038#endif /* COAP_SERVER_SUPPORT */
3039
3040#if COAP_WS_SUPPORT
3041/*
3042 * The struct hash_algs and the function get_hash_alg() are used to
3043 * determine which hash type to use for creating the required hash object.
3044 */
3045static struct hash_algs {
3046 cose_alg_t alg;
3047 gnutls_digest_algorithm_t dig_type;
3048 size_t dig_size;
3049} hashs[] = {
3050 {COSE_ALGORITHM_SHA_1, GNUTLS_DIG_SHA1, 20},
3051 {COSE_ALGORITHM_SHA_256_256, GNUTLS_DIG_SHA256, 32},
3052 {COSE_ALGORITHM_SHA_512, GNUTLS_DIG_SHA512, 64},
3053};
3054
3055static gnutls_digest_algorithm_t
3056get_hash_alg(cose_alg_t alg, size_t *hash_len) {
3057 size_t idx;
3058
3059 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
3060 if (hashs[idx].alg == alg) {
3061 *hash_len = hashs[idx].dig_size;
3062 return hashs[idx].dig_type;
3063 }
3064 }
3065 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
3066 return GNUTLS_DIG_UNKNOWN;
3067}
3068
3069int
3071 const coap_bin_const_t *data,
3072 coap_bin_const_t **hash) {
3073 size_t hash_length;
3074 gnutls_digest_algorithm_t dig_type = get_hash_alg(alg, &hash_length);
3075 gnutls_hash_hd_t digest_ctx;
3076 coap_binary_t *dummy = NULL;
3077 int ret;
3078
3079 if (dig_type == GNUTLS_DIG_UNKNOWN) {
3080 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3081 return 0;
3082 }
3083
3084 if (gnutls_hash_init(&digest_ctx, dig_type)) {
3085 return 0;
3086 }
3087 ret = gnutls_hash(digest_ctx, data->s, data->length);
3088 if (ret != 0)
3089 goto error;
3090
3091 dummy = coap_new_binary(hash_length);
3092 if (!dummy)
3093 goto error;
3094 gnutls_hash_output(digest_ctx, dummy->s);
3095
3096 *hash = (coap_bin_const_t *)(dummy);
3097 gnutls_hash_deinit(digest_ctx, NULL);
3098 return 1;
3099
3100error:
3102 gnutls_hash_deinit(digest_ctx, NULL);
3103 return 0;
3104}
3105#endif /* COAP_WS_SUPPORT */
3106
3107#if COAP_OSCORE_SUPPORT
3108int
3110 return 1;
3111}
3112
3113/*
3114 * The struct cipher_algs and the function get_cipher_alg() are used to
3115 * determine which cipher type to use for creating the required cipher
3116 * suite object.
3117 */
3118static struct cipher_algs {
3119 cose_alg_t alg;
3120 gnutls_cipher_algorithm_t cipher_type;
3121} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, GNUTLS_CIPHER_AES_128_CCM_8},
3122 {COSE_ALGORITHM_AES_CCM_16_64_256, GNUTLS_CIPHER_AES_256_CCM_8}
3123};
3124
3125static gnutls_cipher_algorithm_t
3126get_cipher_alg(cose_alg_t alg) {
3127 size_t idx;
3128
3129 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
3130 if (ciphers[idx].alg == alg)
3131 return ciphers[idx].cipher_type;
3132 }
3133 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
3134 return 0;
3135}
3136
3137/*
3138 * The struct hmac_algs and the function get_hmac_alg() are used to
3139 * determine which hmac type to use for creating the required hmac
3140 * suite object.
3141 */
3142static struct hmac_algs {
3143 cose_hmac_alg_t hmac_alg;
3144 gnutls_mac_algorithm_t hmac_type;
3145} hmacs[] = {
3146 {COSE_HMAC_ALG_HMAC256_256, GNUTLS_MAC_SHA256},
3147 {COSE_HMAC_ALG_HMAC512_512, GNUTLS_MAC_SHA512},
3148};
3149
3150static gnutls_mac_algorithm_t
3151get_hmac_alg(cose_hmac_alg_t hmac_alg) {
3152 size_t idx;
3153
3154 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
3155 if (hmacs[idx].hmac_alg == hmac_alg)
3156 return hmacs[idx].hmac_type;
3157 }
3158 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
3159 return 0;
3160}
3161
3162int
3164 return get_cipher_alg(alg);
3165}
3166
3167int
3169 cose_hmac_alg_t hmac_alg;
3170
3171 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3172 return 0;
3173 return get_hmac_alg(hmac_alg);
3174}
3175
3176int
3178 coap_bin_const_t *data,
3179 coap_bin_const_t *aad,
3180 uint8_t *result,
3181 size_t *max_result_len) {
3182 gnutls_aead_cipher_hd_t ctx;
3183 gnutls_datum_t key;
3184 const coap_crypto_aes_ccm_t *ccm;
3185 int ret = 0;
3186 size_t result_len = *max_result_len;
3187 gnutls_cipher_algorithm_t algo;
3188 unsigned tag_size;
3189 uint8_t *key_data_rw;
3190 coap_bin_const_t laad;
3191
3192 if (data == NULL)
3193 return 0;
3194
3195 assert(params != NULL);
3196 if (!params) {
3197 return 0;
3198 }
3199 if ((algo = get_cipher_alg(params->alg)) == 0) {
3200 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
3201 params->alg);
3202 return 0;
3203 }
3204 tag_size = gnutls_cipher_get_tag_size(algo);
3205 ccm = &params->params.aes;
3206
3207 /* Get a RW copy of data */
3208 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3209 key.data = key_data_rw;
3210 key.size = ccm->key.length;
3211
3212 if (aad) {
3213 laad = *aad;
3214 } else {
3215 laad.s = NULL;
3216 laad.length = 0;
3217 }
3218
3219 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3220
3221 G_CHECK(gnutls_aead_cipher_encrypt(ctx,
3222 ccm->nonce,
3223 15 - ccm->l, /* iv */
3224 laad.s,
3225 laad.length, /* ad */
3226 tag_size,
3227 data->s,
3228 data->length, /* input */
3229 result,
3230 &result_len), /* output */
3231 "gnutls_aead_cipher_encrypt");
3232 *max_result_len = result_len;
3233 ret = 1;
3234fail:
3235 gnutls_aead_cipher_deinit(ctx);
3236 return ret == 1 ? 1 : 0;
3237}
3238
3239int
3241 coap_bin_const_t *data,
3242 coap_bin_const_t *aad,
3243 uint8_t *result,
3244 size_t *max_result_len) {
3245 gnutls_aead_cipher_hd_t ctx;
3246 gnutls_datum_t key;
3247 const coap_crypto_aes_ccm_t *ccm;
3248 int ret = 0;
3249 size_t result_len = *max_result_len;
3250 gnutls_cipher_algorithm_t algo;
3251 unsigned tag_size;
3252 uint8_t *key_data_rw;
3253 coap_bin_const_t laad;
3254
3255 if (data == NULL)
3256 return 0;
3257
3258 assert(params != NULL);
3259
3260 if (!params) {
3261 return 0;
3262 }
3263 if ((algo = get_cipher_alg(params->alg)) == 0) {
3264 coap_log_debug("coap_crypto_decrypt: algorithm %d not supported\n",
3265 params->alg);
3266 return 0;
3267 }
3268 tag_size = gnutls_cipher_get_tag_size(algo);
3269 ccm = &params->params.aes;
3270
3271 /* Get a RW copy of data */
3272 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3273 key.data = key_data_rw;
3274 key.size = ccm->key.length;
3275
3276 if (aad) {
3277 laad = *aad;
3278 } else {
3279 laad.s = NULL;
3280 laad.length = 0;
3281 }
3282
3283 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3284
3285 G_CHECK(gnutls_aead_cipher_decrypt(ctx,
3286 ccm->nonce,
3287 15 - ccm->l, /* iv */
3288 laad.s,
3289 laad.length, /* ad */
3290 tag_size,
3291 data->s,
3292 data->length, /* input */
3293 result,
3294 &result_len), /* output */
3295 "gnutls_aead_cipher_decrypt");
3296 *max_result_len = result_len;
3297 ret = 1;
3298fail:
3299 gnutls_aead_cipher_deinit(ctx);
3300 return ret == 1 ? 1 : 0;
3301}
3302
3303int
3305 coap_bin_const_t *key,
3306 coap_bin_const_t *data,
3307 coap_bin_const_t **hmac) {
3308 gnutls_hmac_hd_t ctx;
3309 int ret = 0;
3310 unsigned len;
3311 gnutls_mac_algorithm_t mac_algo;
3312 coap_binary_t *dummy = NULL;
3313
3314 if (data == NULL)
3315 return 0;
3316
3317 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3318 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3319 return 0;
3320 }
3321 len = gnutls_hmac_get_len(mac_algo);
3322 if (len == 0)
3323 return 0;
3324
3325 dummy = coap_new_binary(len);
3326 if (dummy == NULL)
3327 return 0;
3328 G_CHECK(gnutls_hmac_init(&ctx, mac_algo, key->s, key->length),
3329 "gnutls_hmac_init");
3330 G_CHECK(gnutls_hmac(ctx, data->s, data->length), "gnutls_hmac");
3331 gnutls_hmac_output(ctx, dummy->s);
3332 *hmac = (coap_bin_const_t *)dummy;
3333 dummy = NULL;
3334 ret = 1;
3335fail:
3337 gnutls_hmac_deinit(ctx, NULL);
3338 return ret == 1 ? 1 : 0;
3339}
3340
3341#endif /* COAP_OSCORE_SUPPORT */
3342
3343#else /* !COAP_WITH_LIBGNUTLS */
3344
3345#ifdef __clang__
3346/* Make compilers happy that do not like empty modules. As this function is
3347 * never used, we ignore -Wunused-function at the end of compiling this file
3348 */
3349#pragma GCC diagnostic ignored "-Wunused-function"
3350#endif
3351static inline void
3352dummy(void) {
3353}
3354
3355#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:2336
#define COAP_RXBUFFER_SIZE
Definition coap_io.h:29
@ COAP_NACK_TLS_FAILED
Definition coap_io.h:66
@ COAP_LAYER_TLS
Library specific build wrapper for coap_internal.h.
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition coap_notls.c:108
coap_tick_t coap_dtls_get_timeout(coap_session_t *session COAP_UNUSED, coap_tick_t now COAP_UNUSED)
Definition coap_notls.c: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:143
int coap_handle_event_lkd(coap_context_t *context, coap_event_t event, coap_session_t *session)
Invokes the event handler of context for the given event and data.
Definition coap_net.c:4783
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:2793
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:35
coap_tls_version_t * coap_get_tls_library_version(void)
Determine the type and version of the underlying (D)TLS library.
Definition coap_notls.c:100
coap_dtls_role_t
Definition coap_dtls.h:44
#define COAP_DTLS_RPK_CERT_CN
Definition coap_dtls.h:49
coap_tls_library_t
Definition coap_dtls.h:70
@ COAP_PKI_KEY_DEF_PKCS11
The PKI key type is PKCS11 (pkcs11:...).
Definition coap_dtls.h:245
@ COAP_PKI_KEY_DEF_DER_BUF
The PKI key type is DER buffer (ASN.1).
Definition coap_dtls.h:242
@ COAP_PKI_KEY_DEF_PEM_BUF
The PKI key type is PEM buffer.
Definition coap_dtls.h:236
@ COAP_PKI_KEY_DEF_PEM
The PKI key type is PEM file.
Definition coap_dtls.h:234
@ COAP_PKI_KEY_DEF_ENGINE
The PKI key type is to be passed to ENGINE.
Definition coap_dtls.h:251
@ COAP_PKI_KEY_DEF_RPK_BUF
The PKI key type is RPK in buffer.
Definition coap_dtls.h:238
@ COAP_PKI_KEY_DEF_DER
The PKI key type is DER file.
Definition coap_dtls.h:240
@ COAP_PKI_KEY_DEF_PKCS11_RPK
The PKI key type is PKCS11 w/ RPK (pkcs11:...).
Definition coap_dtls.h:248
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition coap_dtls.h:46
@ COAP_DTLS_ROLE_CLIENT
Internal function invoked for client.
Definition coap_dtls.h:45
@ COAP_PKI_KEY_DEFINE
The individual PKI key types are Definable.
Definition coap_dtls.h:172
@ COAP_TLS_LIBRARY_GNUTLS
Using GnuTLS library.
Definition coap_dtls.h:74
@ COAP_EVENT_DTLS_CLOSED
Triggerred when (D)TLS session closed.
Definition coap_event.h:39
@ COAP_EVENT_DTLS_CONNECTED
Triggered when (D)TLS session connected.
Definition coap_event.h:41
@ COAP_EVENT_DTLS_ERROR
Triggered when (D)TLS error occurs.
Definition coap_event.h:45
#define coap_lock_callback_ret(r, c, func)
Dummy for no thread-safe code.
#define coap_log_debug(...)
Definition coap_debug.h:120
coap_log_t
Logging type.
Definition coap_debug.h:50
coap_log_t coap_dtls_get_log_level(void)
Get the current (D)TLS logging.
Definition coap_notls.c:176
#define coap_dtls_log(level,...)
Logging function.
Definition coap_debug.h:300
void coap_dtls_set_log_level(coap_log_t level)
Sets the (D)TLS logging level to the specified level.
Definition coap_notls.c:171
const char * coap_session_str(const coap_session_t *session)
Get session description.
#define coap_log_info(...)
Definition coap_debug.h:108
#define coap_log_warn(...)
Definition coap_debug.h:102
#define coap_log_err(...)
Definition coap_debug.h:96
@ COAP_LOG_EMERG
Definition coap_debug.h:51
@ COAP_LOG_DEBUG
Definition coap_debug.h:58
@ COAP_LOG_WARN
Definition coap_debug.h:55
int coap_netif_available(coap_session_t *session)
Function interface to check whether netif for session is still available.
Definition coap_netif.c:25
int cose_get_hmac_alg_for_hkdf(cose_hkdf_alg_t hkdf_alg, cose_hmac_alg_t *hmac_alg)
cose_hkdf_alg_t
cose_hmac_alg_t
cose_alg_t
@ COSE_HMAC_ALG_HMAC256_256
@ COSE_HMAC_ALG_HMAC512_512
@ COSE_ALGORITHM_SHA_256_256
@ COSE_ALGORITHM_SHA_1
@ COSE_ALGORITHM_AES_CCM_16_64_128
@ COSE_ALGORITHM_SHA_512
@ COSE_ALGORITHM_AES_CCM_16_64_256
@ COAP_PROTO_DTLS
Definition coap_pdu.h:315
@ COAP_PROTO_TLS
Definition coap_pdu.h:317
int coap_session_refresh_psk_hint(coap_session_t *session, const coap_bin_const_t *psk_hint)
Refresh the session's current Identity Hint (PSK).
int coap_session_refresh_psk_key(coap_session_t *session, const coap_bin_const_t *psk_key)
Refresh the session's current pre-shared key (PSK).
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
int coap_session_refresh_psk_identity(coap_session_t *session, const coap_bin_const_t *psk_identity)
Refresh the session's current pre-shared identity (PSK).
void coap_session_disconnected_lkd(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
#define COAP_PROTO_NOT_RELIABLE(p)
@ COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_NONE
coap_binary_t * coap_new_binary(size_t size)
Returns a new binary object with at least size bytes storage allocated.
Definition coap_str.c:77
void coap_delete_binary(coap_binary_t *s)
Deletes the given coap_binary_t object and releases any memory allocated.
Definition coap_str.c:105
int coap_dtls_cid_is_supported(void)
Check whether (D)TLS CID is available.
Definition coap_notls.c:86
int coap_dtls_psk_is_supported(void)
Check whether (D)TLS PSK is available.
Definition coap_notls.c:50
int coap_tls_is_supported(void)
Check whether TLS is available.
Definition coap_notls.c:41
int coap_oscore_is_supported(void)
Check whether OSCORE is available.
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition coap_notls.c:36
int coap_dtls_pki_is_supported(void)
Check whether (D)TLS PKI is available.
Definition coap_notls.c:59
int coap_dtls_rpk_is_supported(void)
Check whether (D)TLS RPK is available.
Definition coap_notls.c:77
int coap_dtls_pkcs11_is_supported(void)
Check whether (D)TLS PKCS11 is available.
Definition coap_notls.c:68
#define COAP_UNUSED
Definition libcoap.h:70
CoAP binary data definition with const data.
Definition coap_str.h:64
size_t length
length of binary data
Definition coap_str.h:65
const uint8_t * s
read-only binary data
Definition coap_str.h:66
CoAP binary data definition.
Definition coap_str.h:56
size_t length
length of binary data
Definition coap_str.h:57
uint8_t * s
binary data
Definition coap_str.h:58
The CoAP stack's global state is stored in a coap_context_t object.
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
The structure that holds the AES Crypto information.
size_t l
The number of bytes in the length field.
const uint8_t * nonce
must be exactly 15 - l bytes
coap_crypto_key_t key
The Key to use.
The common structure that holds the Crypto information.
union coap_crypto_param_t::@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:379
coap_bin_const_t key
Definition coap_dtls.h:381
coap_bin_const_t identity
Definition coap_dtls.h:380
The structure used for defining the Client PSK setup data to be used.
Definition coap_dtls.h:410
uint8_t use_cid
Set to 1 if DTLS Connection ID is to be used.
Definition coap_dtls.h:417
void * ih_call_back_arg
Passed in to the Identity Hint callback function.
Definition coap_dtls.h:434
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:437
coap_dtls_ih_callback_t validate_ih_call_back
Identity Hint check callback function.
Definition coap_dtls.h:433
uint8_t ec_jpake
Set to COAP_DTLS_CPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:415
The structure that holds the PKI key information.
Definition coap_dtls.h:279
coap_pki_key_define_t define
for definable type keys
Definition coap_dtls.h:286
union coap_dtls_key_t::@3 key
coap_pki_key_t key_type
key format type
Definition coap_dtls.h:280
The structure used for defining the PKI setup data to be used.
Definition coap_dtls.h:312
uint8_t allow_no_crl
1 ignore if CRL not there
Definition coap_dtls.h:326
uint8_t cert_chain_validation
1 if to check cert_chain_verify_depth
Definition coap_dtls.h:323
uint8_t use_cid
1 if DTLS Connection ID is to be used (Client only, server always enabled) if supported
Definition coap_dtls.h:333
uint8_t check_cert_revocation
1 if revocation checks wanted
Definition coap_dtls.h:325
uint8_t cert_chain_verify_depth
recommended depth is 3
Definition coap_dtls.h:324
uint8_t allow_expired_certs
1 if expired certs are allowed
Definition coap_dtls.h:322
uint8_t verify_peer_cert
Set to COAP_DTLS_PKI_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:317
char * client_sni
If not NULL, SNI to use in client TLS setup.
Definition coap_dtls.h:368
uint8_t allow_self_signed
1 if self-signed certs are allowed.
Definition coap_dtls.h:320
uint8_t allow_expired_crl
1 if expired crl is allowed
Definition coap_dtls.h:327
uint8_t is_rpk_not_cert
1 is RPK instead of Public Certificate.
Definition coap_dtls.h:330
uint8_t check_common_ca
1 if peer cert is to be signed by the same CA as the local cert
Definition coap_dtls.h:318
coap_dtls_key_t pki_key
PKI key definition.
Definition coap_dtls.h:373
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition coap_dtls.h:450
coap_bin_const_t hint
Definition coap_dtls.h:451
The structure used for defining the Server PSK setup data to be used.
Definition coap_dtls.h:501
coap_dtls_psk_sni_callback_t validate_sni_call_back
SNI check callback function.
Definition coap_dtls.h:530
coap_dtls_id_callback_t validate_id_call_back
Identity check callback function.
Definition coap_dtls.h:522
void * id_call_back_arg
Passed in to the Identity callback function.
Definition coap_dtls.h:523
uint8_t ec_jpake
Set to COAP_DTLS_SPSK_SETUP_VERSION to support this version of the struct.
Definition coap_dtls.h:506
void * sni_call_back_arg
Passed in to the SNI callback function.
Definition coap_dtls.h:531
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition coap_dtls.h:533
coap_layer_read_t l_read
coap_layer_write_t l_write
coap_layer_establish_t l_establish
coap_const_char_ptr_t public_cert
define: Public Cert
Definition coap_dtls.h:261
const char * user_pin
define: User pin to access type PKCS11.
Definition coap_dtls.h:271
coap_const_char_ptr_t private_key
define: Private Key
Definition coap_dtls.h:262
coap_const_char_ptr_t ca
define: Common CA Certificate
Definition coap_dtls.h:260
size_t public_cert_len
define Public Cert length (if needed)
Definition coap_dtls.h:264
size_t ca_len
define CA Cert length (if needed)
Definition coap_dtls.h:263
coap_pki_define_t private_key_def
define: Private Key type definition
Definition coap_dtls.h:268
size_t private_key_len
define Private Key length (if needed)
Definition coap_dtls.h:265
coap_pki_define_t ca_def
define: Common CA type definition
Definition coap_dtls.h:266
coap_pki_define_t public_cert_def
define: Public Cert type definition
Definition coap_dtls.h:267
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
unsigned int dtls_timeout_count
dtls setup retry counter
coap_endpoint_t * endpoint
session's endpoint
coap_socket_t sock
socket object for the session, if any
coap_session_state_t state
current state of relationship with peer
coap_addr_tuple_t addr_info
remote/local address info
coap_proto_t proto
protocol used
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
size_t mtu
path or CSM mtu (xmt)
int dtls_event
Tracking any (D)TLS events on this session.
void * tls
security parameters
uint16_t max_retransmit
maximum re-transmit count (default 4)
coap_context_t * context
session's context
coap_layer_func_t lfunc[COAP_LAYER_LAST]
Layer functions to use.
CoAP string data definition with const data.
Definition coap_str.h:46
const uint8_t * s
read-only string data
Definition coap_str.h:48
size_t length
length of string
Definition coap_str.h:47
The structure used for returning the underlying (D)TLS library information.
Definition coap_dtls.h:83
uint64_t built_version
(D)TLS Built against Library Version
Definition coap_dtls.h:86
coap_tls_library_t type
Library type.
Definition coap_dtls.h:85
uint64_t version
(D)TLS runtime Library Version
Definition coap_dtls.h:84
const char * s_byte
signed char ptr
Definition coap_str.h:73
const uint8_t * u_byte
unsigned char ptr
Definition coap_str.h:74