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