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