libcoap 4.3.5-develop-f52fada
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(coap_session_t *session, gnutls_session_t g_session,
709 coap_gnutls_certificate_info_t *cert_info, const char *sni_match) {
710 gnutls_x509_crt_t cert;
711 char dn[256];
712 size_t size;
713 int n;
714 char *cn;
715 int ret;
716 unsigned int seq;
717
718#if (GNUTLS_VERSION_NUMBER >= 0x030606)
719 cert_info->certificate_type = gnutls_certificate_type_get2(g_session,
720 GNUTLS_CTYPE_PEERS);
721#else /* < 3.6.6 */
722 cert_info->certificate_type = gnutls_certificate_type_get(g_session);
723#endif /* < 3.6.6 */
724
725 cert_info->san_or_cn = NULL;
726
727 cert_info->cert_list = gnutls_certificate_get_peers(g_session,
728 &cert_info->cert_list_size);
729 if (cert_info->cert_list_size == 0) {
730 return GNUTLS_CRT_UNKNOWN;
731 }
732
733 if (cert_info->certificate_type != GNUTLS_CRT_X509)
734 return cert_info->certificate_type;
735
736 G_CHECK(gnutls_x509_crt_init(&cert), "gnutls_x509_crt_init");
737
738 /* Interested only in first cert in chain */
739 G_CHECK(gnutls_x509_crt_import(cert, &cert_info->cert_list[0],
740 GNUTLS_X509_FMT_DER), "gnutls_x509_crt_import");
741
742 cert_info->self_signed = gnutls_x509_crt_check_issuer(cert, cert);
743
744 /* See if there is a Subject Alt Name first */
745 for (seq = 0; seq < 100; seq++) {
746 size = sizeof(dn) -1;
747 ret = gnutls_x509_crt_get_subject_alt_name(cert, seq, dn, &size, NULL);
748 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
749 /* Reached the end of the SAN list */
750 break;
751 }
752 if (ret >= 0) {
753 dn[size] = '\000';
754 if (sni_match) {
755 if (strlen(sni_match) != size ||
756 memcmp(dn, sni_match, size)) {
757 continue;
758 }
759 }
760 gnutls_x509_crt_deinit(cert);
761 cert_info->san_or_cn = gnutls_strdup(dn);
762 return cert_info->certificate_type;
763 }
764 }
765
766 size = sizeof(dn);
767 G_CHECK(gnutls_x509_crt_get_dn(cert, dn, &size), "gnutls_x509_crt_get_dn");
768
769 /* Need to emulate strcasestr() here. Looking for CN= */
770 n = strlen(dn) - 3;
771 cn = dn;
772 while (n > 0) {
773 if (((cn[0] == 'C') || (cn[0] == 'c')) &&
774 ((cn[1] == 'N') || (cn[1] == 'n')) &&
775 (cn[2] == '=')) {
776 cn += 3;
777 break;
778 }
779 cn++;
780 n--;
781 }
782 if (n > 0) {
783 char *ecn = strchr(cn, ',');
784 if (ecn) {
785 cn[ecn-cn] = '\000';
786 }
787 if (sni_match) {
788 if (!coap_pki_name_match_sni(cn, strlen(cn), sni_match)) {
789 coap_log_debug(" %s: got CN '%s'\n",
790 coap_session_str(session), cn);
791 goto no_match;
792 }
793 }
794
795 gnutls_x509_crt_deinit(cert);
796 cert_info->san_or_cn = gnutls_strdup(cn);
797 return cert_info->certificate_type;
798 }
799no_match:
800 n = 0;
801 for (seq = 0; seq < 100; seq++) {
802 size = sizeof(dn) -1;
803 ret = gnutls_x509_crt_get_subject_alt_name(cert, seq, dn, &size, NULL);
804 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {
805 /* Reached the end of the SAN list */
806 break;
807 }
808 if (ret >= 0) {
809 dn[size] = '\000';
810 coap_log_debug(" %s: got DNS.%d '%s'\n",
811 coap_session_str(session), n + 1, dn);
812
813 }
814 n++;
815 continue;
816 }
817 gnutls_x509_crt_deinit(cert);
818 return GNUTLS_CRT_UNKNOWN;
819
820fail:
821 return GNUTLS_CRT_UNKNOWN;
822}
823
824#if (GNUTLS_VERSION_NUMBER >= 0x030606)
825#define OUTPUT_CERT_NAME (cert_type == GNUTLS_CRT_X509 ? \
826 cert_info.san_or_cn : \
827 cert_type == GNUTLS_CRT_RAW ? \
828 COAP_DTLS_RPK_CERT_CN : "?")
829#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
830#define OUTPUT_CERT_NAME (cert_type == GNUTLS_CRT_X509 ? \
831 cert_info.san_or_cn : "?")
832#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
833
834#if (GNUTLS_VERSION_NUMBER >= 0x030606)
835static int
836check_rpk_cert(coap_gnutls_context_t *g_context,
837 coap_gnutls_certificate_info_t *cert_info,
838 coap_session_t *c_session) {
839 int ret;
840
841 if (g_context->setup_data.validate_cn_call_back) {
842 gnutls_pcert_st pcert;
843 uint8_t der[2048];
844 size_t size;
845
846 G_CHECK(gnutls_pcert_import_rawpk_raw(&pcert, &cert_info->cert_list[0],
847 GNUTLS_X509_FMT_DER, 0, 0),
848 "gnutls_pcert_import_rawpk_raw");
849
850 size = sizeof(der);
851 G_CHECK(gnutls_pubkey_export(pcert.pubkey, GNUTLS_X509_FMT_DER, der, &size),
852 "gnutls_pubkey_export");
853 gnutls_pcert_deinit(&pcert);
855 g_context->setup_data.validate_cn_call_back(COAP_DTLS_RPK_CERT_CN,
856 der,
857 size,
858 c_session,
859 0,
860 1,
861 g_context->setup_data.cn_call_back_arg));
862 if (!ret) {
863 return 0;
864 }
865 }
866 return 1;
867fail:
868 return 0;
869}
870#endif /* >= 3.6.6 */
871
872/*
873 * return 0 failed
874 * 1 passed
875 */
876static int
877cert_verify_gnutls(gnutls_session_t g_session) {
878 unsigned int status = 0;
879 unsigned int fail = 0;
880 coap_session_t *c_session =
881 (coap_session_t *)gnutls_transport_get_ptr(g_session);
882 coap_gnutls_context_t *g_context =
883 (coap_gnutls_context_t *)c_session->context->dtls_context;
884 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
885 int alert = GNUTLS_A_BAD_CERTIFICATE;
886 int ret;
887 coap_gnutls_certificate_info_t cert_info;
888 gnutls_certificate_type_t cert_type;
889
890 memset(&cert_info, 0, sizeof(cert_info));
891 if (!g_context->setup_data.allow_sni_cn_mismatch &&
892 c_session->type == COAP_SESSION_TYPE_CLIENT &&
893 g_context->setup_data.client_sni) {
894 cert_type = get_san_or_cn(c_session, g_session, &cert_info, g_context->setup_data.client_sni);
895 if (cert_type == GNUTLS_CRT_UNKNOWN) {
896 coap_log_info(" %s: SNI '%s' not returned in certificate\n",
897 coap_session_str(c_session), g_context->setup_data.client_sni);
898 alert = GNUTLS_A_ACCESS_DENIED;
899 goto fail;
900 }
901 }
902
903 if (!cert_info.san_or_cn)
904 cert_type = get_san_or_cn(c_session, g_session, &cert_info, NULL);
905#if (GNUTLS_VERSION_NUMBER >= 0x030606)
906 if (cert_type == GNUTLS_CRT_RAW) {
907 if (!check_rpk_cert(g_context, &cert_info, c_session)) {
908 alert = GNUTLS_A_ACCESS_DENIED;
909 goto fail;
910 }
911 goto ok;
912 }
913#endif /* >= 3.6.6 */
914
915 if (cert_info.cert_list_size == 0) {
916 if (!g_context->setup_data.verify_peer_cert)
917 goto ok;
918 else
919 goto fail;
920 }
921
922 G_CHECK(gnutls_certificate_verify_peers(g_session, NULL, 0, &status),
923 "gnutls_certificate_verify_peers");
924
925 coap_dtls_log(COAP_LOG_DEBUG, "error %x cert '%s'\n",
926 status, cert_info.san_or_cn);
927
928 if (g_context->setup_data.validate_cn_call_back) {
929 gnutls_x509_crt_t cert;
930 uint8_t der[2048];
931 size_t size;
932 /* status == 0 indicates that the certificate passed to
933 * setup_data.validate_cn_call_back has been validated. */
934 const int cert_is_trusted = !status;
935
936 G_CHECK(gnutls_x509_crt_init(&cert), "gnutls_x509_crt_init");
937
938 /* Interested only in first cert in chain */
939 G_CHECK(gnutls_x509_crt_import(cert, &cert_info.cert_list[0],
940 GNUTLS_X509_FMT_DER), "gnutls_x509_crt_import");
941
942 size = sizeof(der);
943 G_CHECK(gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, der, &size),
944 "gnutls_x509_crt_export");
945 gnutls_x509_crt_deinit(cert);
947 g_context->setup_data.validate_cn_call_back(OUTPUT_CERT_NAME,
948 der,
949 size,
950 c_session,
951 0,
952 cert_is_trusted,
953 g_context->setup_data.cn_call_back_arg));
954 if (!ret) {
955 alert = GNUTLS_A_ACCESS_DENIED;
956 goto fail;
957 }
958 }
959
960 if (status) {
961 status &= ~(GNUTLS_CERT_INVALID);
962 if (status & (GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED)) {
963 status &= ~(GNUTLS_CERT_NOT_ACTIVATED|GNUTLS_CERT_EXPIRED);
964 if (g_context->setup_data.allow_expired_certs) {
965 coap_log_info(" %s: %s: overridden: '%s'\n",
966 coap_session_str(c_session),
967 "The certificate has an invalid usage date",
968 OUTPUT_CERT_NAME);
969 } else {
970 fail = 1;
971 coap_log_warn(" %s: %s: '%s'\n",
972 coap_session_str(c_session),
973 "The certificate has an invalid usage date",
974 OUTPUT_CERT_NAME);
975 }
976 }
977 if (status & (GNUTLS_CERT_UNEXPECTED_OWNER)) {
978 status &= ~(GNUTLS_CERT_UNEXPECTED_OWNER);
979 if (g_context->setup_data.allow_sni_cn_mismatch) {
980 coap_log_info(" %s: %s: overridden: '%s' v '%s'\n",
981 coap_session_str(c_session),
982 "The SNI does not match the returned CN",
983 g_context->setup_data.client_sni,
984 OUTPUT_CERT_NAME);
985 } else {
986 fail = 1;
987 coap_log_warn(" %s: %s: '%s' v '%s'\n",
988 coap_session_str(c_session),
989 "The SNI does not match the returned CN",
990 g_context->setup_data.client_sni,
991 OUTPUT_CERT_NAME);
992 }
993 }
994 if (status & (GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
995 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE)) {
996 status &= ~(GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED|
997 GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE);
998 if (g_context->setup_data.allow_expired_crl) {
999 coap_log_info(" %s: %s: overridden: '%s'\n",
1000 coap_session_str(c_session),
1001 "The certificate's CRL entry has an invalid usage date",
1002 OUTPUT_CERT_NAME);
1003 } else {
1004 fail = 1;
1005 coap_log_warn(" %s: %s: '%s'\n",
1006 coap_session_str(c_session),
1007 "The certificate's CRL entry has an invalid usage date",
1008 OUTPUT_CERT_NAME);
1009 }
1010 }
1011 if (status & (GNUTLS_CERT_SIGNER_NOT_FOUND)) {
1012 status &= ~(GNUTLS_CERT_SIGNER_NOT_FOUND);
1013 if (cert_info.self_signed) {
1014 if (g_context->setup_data.allow_self_signed &&
1015 !g_context->setup_data.check_common_ca) {
1016 coap_log_info(" %s: %s: overridden: '%s'\n",
1017 coap_session_str(c_session),
1018 "Self-signed",
1019 OUTPUT_CERT_NAME);
1020 } else {
1021 fail = 1;
1022 alert = GNUTLS_A_UNKNOWN_CA;
1023 coap_log_warn(" %s: %s: '%s'\n",
1024 coap_session_str(c_session),
1025 "Self-signed",
1026 OUTPUT_CERT_NAME);
1027 }
1028 } else {
1029 if (!g_context->setup_data.verify_peer_cert) {
1030 coap_log_info(" %s: %s: overridden: '%s'\n",
1031 coap_session_str(c_session),
1032 "The peer certificate's CA is unknown",
1033 OUTPUT_CERT_NAME);
1034 } else {
1035 fail = 1;
1036 alert = GNUTLS_A_UNKNOWN_CA;
1037 coap_log_warn(" %s: %s: '%s'\n",
1038 coap_session_str(c_session),
1039 "The peer certificate's CA is unknown",
1040 OUTPUT_CERT_NAME);
1041 }
1042 }
1043 }
1044 if (status & (GNUTLS_CERT_INSECURE_ALGORITHM)) {
1045 status &= ~(GNUTLS_CERT_INSECURE_ALGORITHM);
1046 fail = 1;
1047 coap_log_warn(" %s: %s: '%s'\n",
1048 coap_session_str(c_session),
1049 "The certificate uses an insecure algorithm",
1050 OUTPUT_CERT_NAME);
1051 }
1052
1053 if (status) {
1054 fail = 1;
1055 coap_log_warn(" %s: gnutls_certificate_verify_peers() status 0x%x: '%s'\n",
1056 coap_session_str(c_session),
1057 status, OUTPUT_CERT_NAME);
1058 }
1059 }
1060
1061 if (fail)
1062 goto fail;
1063
1064 if (g_context->setup_data.additional_tls_setup_call_back) {
1065 /* Additional application setup wanted */
1066 if (!g_context->setup_data.additional_tls_setup_call_back(g_session,
1067 &g_context->setup_data)) {
1068 goto fail;
1069 }
1070 }
1071
1072ok:
1073 if (cert_info.san_or_cn)
1074 gnutls_free(cert_info.san_or_cn);
1075
1076 return 1;
1077
1078fail:
1079 if (cert_info.san_or_cn)
1080 gnutls_free(cert_info.san_or_cn);
1081
1082 if (!g_env->sent_alert) {
1083 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL, alert));
1084 g_env->sent_alert = 1;
1085 }
1087 return 0;
1088}
1089
1090/*
1091 * gnutls_certificate_verify_function return values
1092 * (see gnutls_certificate_set_verify_function())
1093 *
1094 * return -1 failed
1095 * 0 passed
1096 */
1097static int
1098cert_verify_callback_gnutls(gnutls_session_t g_session) {
1099 if (gnutls_auth_get_type(g_session) == GNUTLS_CRD_CERTIFICATE) {
1100 if (cert_verify_gnutls(g_session) == 0) {
1101 return -1;
1102 }
1103 }
1104 return 0;
1105}
1106
1107#ifndef min
1108#define min(a,b) ((a) < (b) ? (a) : (b))
1109#endif
1110
1111static int
1112pin_callback(void *user_data, int attempt,
1113 const char *token_url COAP_UNUSED,
1114 const char *token_label COAP_UNUSED,
1115 unsigned int flags COAP_UNUSED,
1116 char *pin,
1117 size_t pin_max) {
1118 coap_dtls_key_t *key = (coap_dtls_key_t *)user_data;
1119
1120 /* Only do this on first attempt to prevent token lockout */
1121 if (attempt == 0 && key && key->key.define.user_pin) {
1122 int len = min(pin_max - 1, strlen(key->key.define.user_pin));
1123
1124 memcpy(pin, key->key.define.user_pin, len);
1125 pin[len] = 0;
1126 return 0;
1127 }
1128 return -1;
1129}
1130
1131static int
1132check_null_memory(gnutls_datum_t *datum,
1133 const uint8_t *buf, size_t len, int *alloced) {
1134 datum->size = len;
1135 *alloced = 0;
1136 if (buf[len-1] != '\000') {
1137 /* Need to allocate memory, rather than just copying pointers across */
1138 *alloced = 1;
1139 datum->data = gnutls_malloc(len + 1);
1140 if (!datum->data) {
1141 coap_log_err("gnutls_malloc failure\n");
1142 return GNUTLS_E_MEMORY_ERROR;
1143 }
1144 memcpy(datum->data, buf, len);
1145 datum->data[len] = '\000';
1146 datum->size++;
1147 } else {
1148 /* To get around const issue */
1149 memcpy(&datum->data,
1150 &buf, sizeof(datum->data));
1151 }
1152 return 0;
1153}
1154
1155/*
1156 * return 0 Success (GNUTLS_E_SUCCESS)
1157 * neg GNUTLS_E_* error code
1158 */
1159static int
1160setup_pki_credentials(gnutls_certificate_credentials_t *pki_credentials,
1161 gnutls_session_t g_session,
1162 coap_gnutls_context_t *g_context,
1163 coap_dtls_pki_t *setup_data, coap_dtls_role_t role) {
1164 coap_dtls_key_t key;
1165 int ret;
1166 gnutls_datum_t cert;
1167 gnutls_datum_t pkey;
1168 gnutls_datum_t ca;
1169 int alloced_cert_memory = 0;
1170 int alloced_pkey_memory = 0;
1171 int alloced_ca_memory = 0;
1172 int have_done_key = 0;
1173
1174 /* Map over to the new define format to save code duplication */
1175 coap_dtls_map_key_type_to_define(setup_data, &key);
1176
1177 assert(key.key_type == COAP_PKI_KEY_DEFINE);
1178
1179 G_CHECK(gnutls_certificate_allocate_credentials(pki_credentials),
1180 "gnutls_certificate_allocate_credentials");
1181
1182 /*
1183 * Configure the Private Key
1184 */
1185 if (key.key.define.private_key.u_byte &&
1186 key.key.define.private_key.u_byte[0]) {
1187 switch (key.key.define.private_key_def) {
1188 case COAP_PKI_KEY_DEF_PEM: /* define private key */
1189 case COAP_PKI_KEY_DEF_PEM_BUF: /* define private key */
1190 case COAP_PKI_KEY_DEF_DER: /* define private key */
1191 case COAP_PKI_KEY_DEF_DER_BUF: /* define private key */
1192 case COAP_PKI_KEY_DEF_PKCS11: /* define private key */
1193 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define private key */
1194 /* Handled under public key */
1195 break;
1196 case COAP_PKI_KEY_DEF_RPK_BUF: /* define private key */
1197#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1198 /* Handled under public key */
1199 break;
1200#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1201 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1204 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1205#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1206 case COAP_PKI_KEY_DEF_ENGINE: /* define private key */
1207 default:
1210 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1211 }
1212 } else if (role == COAP_DTLS_ROLE_SERVER ||
1214 key.key.define.public_cert.u_byte[0])) {
1217 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1218 }
1219
1220 /*
1221 * Configure the Public Certificate / Key
1222 */
1223 if (key.key.define.public_cert.u_byte &&
1224 key.key.define.public_cert.u_byte[0]) {
1225 /* Both Public and Private keys are handled here and MUST be the same type */
1226 if (!(key.key.define.private_key.s_byte &&
1227 key.key.define.private_key.s_byte[0] &&
1231 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1232 }
1233 switch (key.key.define.public_cert_def) {
1234 case COAP_PKI_KEY_DEF_PEM: /* define public cert */
1235 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1238 GNUTLS_X509_FMT_PEM)) < 0) {
1241 &key, role, ret);
1242 }
1243 break;
1244 case COAP_PKI_KEY_DEF_PEM_BUF: /* define public cert */
1245 if ((ret = check_null_memory(&cert,
1248 &alloced_cert_memory)) < 0) {
1251 &key, role, ret);
1252 }
1253 if ((ret = check_null_memory(&pkey,
1256 &alloced_pkey_memory)) < 0) {
1257 if (alloced_cert_memory)
1258 gnutls_free(cert.data);
1261 &key, role, ret);
1262 }
1263 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1264 &cert,
1265 &pkey,
1266 GNUTLS_X509_FMT_PEM)) < 0) {
1267 if (alloced_cert_memory)
1268 gnutls_free(cert.data);
1269 if (alloced_pkey_memory)
1270 gnutls_free(pkey.data);
1273 &key, role, ret);
1274 }
1275 if (alloced_cert_memory)
1276 gnutls_free(cert.data);
1277 if (alloced_pkey_memory)
1278 gnutls_free(pkey.data);
1279 break;
1280 case COAP_PKI_KEY_DEF_RPK_BUF: /* define public cert */
1281#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1282 if ((ret = check_null_memory(&cert,
1285 &alloced_cert_memory)) < 0) {
1288 &key, role, ret);
1289 }
1290 if ((ret = check_null_memory(&pkey,
1293 &alloced_pkey_memory)) < 0) {
1294 if (alloced_cert_memory)
1295 gnutls_free(cert.data);
1298 &key, role, ret);
1299 }
1300 if (strstr((char *)pkey.data, "-----BEGIN EC PRIVATE KEY-----")) {
1301 gnutls_datum_t der_private;
1302
1303 if (gnutls_pem_base64_decode2("EC PRIVATE KEY", &pkey,
1304 &der_private) == 0) {
1305 coap_binary_t *spki = get_asn1_spki(der_private.data,
1306 der_private.size);
1307
1308 if (spki) {
1309 gnutls_datum_t tspki;
1310
1311 tspki.data = spki->s;
1312 tspki.size = spki->length;
1313 ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1314 &tspki,
1315 &der_private,
1316 GNUTLS_X509_FMT_DER, NULL,
1317 COAP_GNUTLS_KEY_RPK,
1318 NULL, 0, 0);
1319 if (ret >= 0) {
1320 have_done_key = 1;
1321 }
1322 coap_delete_binary(spki);
1323 }
1324 gnutls_free(der_private.data);
1325 }
1326 }
1327 if (!have_done_key) {
1328 if ((ret = gnutls_certificate_set_rawpk_key_mem(*pki_credentials,
1329 &cert,
1330 &pkey,
1331 GNUTLS_X509_FMT_PEM, NULL,
1332 COAP_GNUTLS_KEY_RPK,
1333 NULL, 0, 0)) < 0) {
1334 if (alloced_cert_memory)
1335 gnutls_free(cert.data);
1336 if (alloced_pkey_memory)
1337 gnutls_free(pkey.data);
1340 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1341 }
1342 }
1343 if (alloced_cert_memory)
1344 gnutls_free(cert.data);
1345 if (alloced_pkey_memory)
1346 gnutls_free(pkey.data);
1347 break;
1348#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1349 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1352 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1353#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1354 case COAP_PKI_KEY_DEF_DER: /* define public cert */
1355 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1358 GNUTLS_X509_FMT_DER) < 0)) {
1361 &key, role, ret);
1362 }
1363 break;
1364 case COAP_PKI_KEY_DEF_DER_BUF: /* define public cert */
1365 if ((ret = check_null_memory(&cert,
1368 &alloced_cert_memory)) < 0) {
1371 &key, role, ret);
1372 }
1373 if ((ret = check_null_memory(&pkey,
1376 &alloced_pkey_memory)) < 0) {
1377 if (alloced_cert_memory)
1378 gnutls_free(cert.data);
1381 &key, role, ret);
1382 }
1383 if ((ret = gnutls_certificate_set_x509_key_mem(*pki_credentials,
1384 &cert,
1385 &pkey,
1386 GNUTLS_X509_FMT_DER)) < 0) {
1387 if (alloced_cert_memory)
1388 gnutls_free(cert.data);
1389 if (alloced_pkey_memory)
1390 gnutls_free(pkey.data);
1393 &key, role, ret);
1394 }
1395 if (alloced_cert_memory)
1396 gnutls_free(cert.data);
1397 if (alloced_pkey_memory)
1398 gnutls_free(pkey.data);
1399 break;
1400 case COAP_PKI_KEY_DEF_PKCS11: /* define public cert */
1401 gnutls_pkcs11_set_pin_function(pin_callback, &setup_data->pki_key);
1402 if ((ret = gnutls_certificate_set_x509_key_file(*pki_credentials,
1405 GNUTLS_X509_FMT_DER)) < 0) {
1408 &key, role, ret);
1409 }
1410 break;
1411 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define public cert */
1412#if (GNUTLS_VERSION_NUMBER >= 0x030606)
1413 gnutls_pkcs11_set_pin_function(pin_callback, setup_data);
1414 if ((ret = gnutls_certificate_set_rawpk_key_file(*pki_credentials,
1417 GNUTLS_X509_FMT_PEM, NULL,
1418 COAP_GNUTLS_KEY_RPK,
1419 NULL, 0, GNUTLS_PKCS_PLAIN, 0))) {
1422 &key, role, ret);
1423 }
1424#else /* GNUTLS_VERSION_NUMBER < 0x030606 */
1425 coap_log_err("RPK Support not available (needs gnutls 3.6.6 or later)\n");
1426 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1427#endif /* GNUTLS_VERSION_NUMBER < 0x030606 */
1428 break;
1429 case COAP_PKI_KEY_DEF_ENGINE: /* define public cert */
1430 default:
1433 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1434 }
1435 }
1436
1437 /*
1438 * Configure the CA
1439 */
1440 if (key.key.define.ca.u_byte &&
1441 key.key.define.ca.u_byte[0]) {
1442 switch (key.key.define.ca_def) {
1444 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1445 key.key.define.ca.s_byte,
1446 GNUTLS_X509_FMT_PEM) < 0)) {
1449 &key, role, ret);
1450 }
1451 break;
1452 case COAP_PKI_KEY_DEF_PEM_BUF: /* define ca */
1453 if ((ret = check_null_memory(&ca,
1454 key.key.define.ca.u_byte,
1455 key.key.define.ca_len,
1456 &alloced_ca_memory)) < 0) {
1459 &key, role, ret);
1460 }
1461 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1462 &ca,
1463 GNUTLS_X509_FMT_PEM)) < 0) {
1464 if (alloced_ca_memory)
1465 gnutls_free(ca.data);
1468 &key, role, ret);
1469 }
1470 if (alloced_ca_memory)
1471 gnutls_free(ca.data);
1472 break;
1473 case COAP_PKI_KEY_DEF_RPK_BUF: /* define ca */
1474 /* Ignore if set */
1475 break;
1476 case COAP_PKI_KEY_DEF_DER: /* define ca */
1477 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1478 key.key.define.ca.s_byte,
1479 GNUTLS_X509_FMT_DER) < 0)) {
1482 &key, role, ret);
1483 }
1484 break;
1485 case COAP_PKI_KEY_DEF_DER_BUF: /* define ca */
1486 if ((ret = check_null_memory(&ca,
1487 key.key.define.ca.u_byte,
1488 key.key.define.ca_len,
1489 &alloced_ca_memory)) < 0) {
1492 &key, role, ret);
1493 }
1494 if ((ret = gnutls_certificate_set_x509_trust_mem(*pki_credentials,
1495 &ca,
1496 GNUTLS_X509_FMT_DER)) <= 0) {
1497 if (alloced_ca_memory)
1498 gnutls_free(ca.data);
1501 &key, role, ret);
1502 }
1503 if (alloced_ca_memory)
1504 gnutls_free(ca.data);
1505 break;
1506 case COAP_PKI_KEY_DEF_PKCS11: /* define ca */
1507 if ((ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1508 key.key.define.ca.s_byte,
1509 GNUTLS_X509_FMT_DER)) <= 0) {
1512 &key, role, ret);
1513 }
1514 break;
1515 case COAP_PKI_KEY_DEF_PKCS11_RPK: /* define ca */
1516 /* Ignore if set */
1517 break;
1518 case COAP_PKI_KEY_DEF_ENGINE: /* define ca */
1519 default:
1522 &key, role, GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1523 }
1524 }
1525
1526#if (GNUTLS_VERSION_NUMBER >= 0x030020)
1527 if (g_context->trust_store_defined) {
1528 G_CHECK(gnutls_certificate_set_x509_system_trust(*pki_credentials),
1529 "gnutls_certificate_set_x509_system_trust");
1530 }
1531#endif
1532 if (g_context->root_ca_file) {
1533 ret = gnutls_certificate_set_x509_trust_file(*pki_credentials,
1534 g_context->root_ca_file,
1535 GNUTLS_X509_FMT_PEM);
1536 if (ret == 0) {
1537 coap_log_warn("gnutls_certificate_set_x509_trust_file: Root CA: No certificates found\n");
1538 }
1539 }
1540 if (g_context->root_ca_path) {
1541#if (GNUTLS_VERSION_NUMBER >= 0x030306)
1542 G_CHECK(gnutls_certificate_set_x509_trust_dir(*pki_credentials,
1543 g_context->root_ca_path,
1544 GNUTLS_X509_FMT_PEM),
1545 "gnutls_certificate_set_x509_trust_dir");
1546#endif
1547 }
1548 gnutls_certificate_send_x509_rdn_sequence(g_session,
1549 setup_data->check_common_ca ? 0 : 1);
1550#if (GNUTLS_VERSION_NUMBER >= 0x030020)
1551 if (!(g_context->psk_pki_enabled & IS_PKI) && !g_context->trust_store_defined) {
1552 /* No PKI defined at all - still need a trust set up for 3.6.0 or later */
1553 G_CHECK(gnutls_certificate_set_x509_system_trust(*pki_credentials),
1554 "gnutls_certificate_set_x509_system_trust");
1555 }
1556#endif
1557
1558 /* Verify Peer */
1559 gnutls_certificate_set_verify_function(*pki_credentials,
1560 cert_verify_callback_gnutls);
1561
1562 /* Cert chain checking (can raise GNUTLS_E_CONSTRAINT_ERROR) */
1563 if (setup_data->cert_chain_validation) {
1564 gnutls_certificate_set_verify_limits(*pki_credentials,
1565 0,
1566 setup_data->cert_chain_verify_depth + 2);
1567 }
1568
1569 /*
1570 * Check for self signed
1571 * CRL checking (can raise GNUTLS_CERT_MISSING_OCSP_STATUS)
1572 */
1573 gnutls_certificate_set_verify_flags(*pki_credentials,
1574 (setup_data->check_cert_revocation == 0 ?
1575 GNUTLS_VERIFY_DISABLE_CRL_CHECKS : 0)
1576 );
1577
1578 return GNUTLS_E_SUCCESS;
1579
1580fail:
1581 return ret;
1582}
1583
1584#if COAP_SERVER_SUPPORT
1585/*
1586 * return 0 Success (GNUTLS_E_SUCCESS)
1587 * neg GNUTLS_E_* error code
1588 */
1589static int
1590setup_psk_credentials(gnutls_psk_server_credentials_t *psk_credentials,
1591 coap_gnutls_context_t *g_context COAP_UNUSED,
1592 coap_dtls_spsk_t *setup_data) {
1593 int ret;
1594 char hint[COAP_DTLS_HINT_LENGTH];
1595
1596 G_CHECK(gnutls_psk_allocate_server_credentials(psk_credentials),
1597 "gnutls_psk_allocate_server_credentials");
1598 gnutls_psk_set_server_credentials_function(*psk_credentials,
1599 psk_server_callback);
1600 if (setup_data->psk_info.hint.s) {
1601 snprintf(hint, sizeof(hint), "%.*s", (int)setup_data->psk_info.hint.length,
1602 setup_data->psk_info.hint.s);
1603 G_CHECK(gnutls_psk_set_server_credentials_hint(*psk_credentials, hint),
1604 "gnutls_psk_set_server_credentials_hint");
1605 }
1606
1607 return GNUTLS_E_SUCCESS;
1608
1609fail:
1610 return ret;
1611}
1612
1613/*
1614 * return 0 Success (GNUTLS_E_SUCCESS)
1615 * neg GNUTLS_E_* error code
1616 */
1617static int
1618post_client_hello_gnutls_psk(gnutls_session_t g_session) {
1619 coap_session_t *c_session =
1620 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1621 coap_gnutls_context_t *g_context =
1622 (coap_gnutls_context_t *)c_session->context->dtls_context;
1623 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1624 int ret = GNUTLS_E_SUCCESS;
1625 char *name = NULL;
1626
1627 if (c_session->context->spsk_setup_data.validate_sni_call_back) {
1628 coap_dtls_spsk_t sni_setup_data;
1629 /* DNS names (only type supported) may be at most 256 byte long */
1630 size_t len = 256;
1631 unsigned int type;
1632 unsigned int i;
1633
1634 name = gnutls_malloc(len);
1635 if (name == NULL)
1636 return GNUTLS_E_MEMORY_ERROR;
1637
1638 for (i=0; ;) {
1639 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1640 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1641 char *new_name;
1642 new_name = gnutls_realloc(name, len);
1643 if (new_name == NULL) {
1644 ret = GNUTLS_E_MEMORY_ERROR;
1645 goto end;
1646 }
1647 name = new_name;
1648 continue; /* retry call with same index */
1649 }
1650
1651 /* check if it is the last entry in list */
1652 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1653 break;
1654 i++;
1655 if (ret != GNUTLS_E_SUCCESS)
1656 goto end;
1657 /* unknown types need to be ignored */
1658 if (type != GNUTLS_NAME_DNS)
1659 continue;
1660
1661 }
1662 /* If no extension provided, make it a dummy entry */
1663 if (i == 0) {
1664 name[0] = '\000';
1665 len = 0;
1666 }
1667
1668 /* Is this a cached entry? */
1669 for (i = 0; i < g_context->psk_sni_count; i++) {
1670 if (strcasecmp(name, g_context->psk_sni_entry_list[i].sni) == 0) {
1671 break;
1672 }
1673 }
1674 if (i == g_context->psk_sni_count) {
1675 /*
1676 * New SNI request
1677 */
1678 const coap_dtls_spsk_info_t *new_entry;
1679
1680 coap_lock_callback_ret(new_entry,
1681 c_session->context->spsk_setup_data.validate_sni_call_back(name,
1682 c_session,
1683 c_session->context->spsk_setup_data.sni_call_back_arg));
1684 if (!new_entry) {
1685 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1686 GNUTLS_A_UNRECOGNIZED_NAME));
1687 g_env->sent_alert = 1;
1688 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1689 goto end;
1690 }
1691
1692 g_context->psk_sni_entry_list =
1693 gnutls_realloc(g_context->psk_sni_entry_list,
1694 (i+1)*sizeof(psk_sni_entry));
1695 g_context->psk_sni_entry_list[i].sni = gnutls_strdup(name);
1696 g_context->psk_sni_entry_list[i].psk_info = *new_entry;
1697 sni_setup_data = c_session->context->spsk_setup_data;
1698 sni_setup_data.psk_info = *new_entry;
1699 if ((ret = setup_psk_credentials(
1700 &g_context->psk_sni_entry_list[i].psk_credentials,
1701 g_context,
1702 &sni_setup_data)) < 0) {
1703 int keep_ret = ret;
1704 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1705 GNUTLS_A_BAD_CERTIFICATE));
1706 g_env->sent_alert = 1;
1707 ret = keep_ret;
1708 goto end;
1709 }
1710 g_context->psk_sni_count++;
1711 }
1712 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1713 g_context->psk_sni_entry_list[i].psk_credentials),
1714 "gnutls_credentials_set");
1716 &g_context->psk_sni_entry_list[i].psk_info.hint);
1718 &g_context->psk_sni_entry_list[i].psk_info.key);
1719 }
1720
1721end:
1722 free(name);
1723 return ret;
1724
1725fail:
1726 return ret;
1727}
1728
1729/*
1730 * return 0 Success (GNUTLS_E_SUCCESS)
1731 * neg GNUTLS_E_* error code
1732 */
1733static int
1734post_client_hello_gnutls_pki(gnutls_session_t g_session) {
1735 coap_session_t *c_session =
1736 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1737 coap_gnutls_context_t *g_context =
1738 (coap_gnutls_context_t *)c_session->context->dtls_context;
1739 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
1740 int ret = GNUTLS_E_SUCCESS;
1741 char *name = NULL;
1742
1743 if (g_context->setup_data.validate_sni_call_back) {
1744 /* DNS names (only type supported) may be at most 256 byte long */
1745 size_t len = 256;
1746 unsigned int type;
1747 unsigned int i;
1748 coap_dtls_pki_t sni_setup_data;
1749
1750 name = gnutls_malloc(len);
1751 if (name == NULL)
1752 return GNUTLS_E_MEMORY_ERROR;
1753
1754 for (i=0; ;) {
1755 ret = gnutls_server_name_get(g_session, name, &len, &type, i);
1756 if (ret == GNUTLS_E_SHORT_MEMORY_BUFFER) {
1757 char *new_name;
1758 new_name = gnutls_realloc(name, len);
1759 if (new_name == NULL) {
1760 ret = GNUTLS_E_MEMORY_ERROR;
1761 goto end;
1762 }
1763 name = new_name;
1764 continue; /* retry call with same index */
1765 }
1766
1767 /* check if it is the last entry in list */
1768 if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1769 break;
1770 i++;
1771 if (ret != GNUTLS_E_SUCCESS)
1772 goto end;
1773 /* unknown types need to be ignored */
1774 if (type != GNUTLS_NAME_DNS)
1775 continue;
1776
1777 }
1778 /* If no extension provided, make it a dummy entry */
1779 if (i == 0) {
1780 name[0] = '\000';
1781 len = 0;
1782 }
1783
1784 /* Is this a cached entry? */
1785 for (i = 0; i < g_context->pki_sni_count; i++) {
1786 if (strcasecmp(name, g_context->pki_sni_entry_list[i].sni) == 0) {
1787 break;
1788 }
1789 }
1790 if (i == g_context->pki_sni_count) {
1791 /*
1792 * New SNI request
1793 */
1794 coap_dtls_key_t *new_entry;
1795
1796 coap_lock_callback_ret(new_entry,
1797 g_context->setup_data.validate_sni_call_back(name,
1798 g_context->setup_data.sni_call_back_arg));
1799 if (!new_entry) {
1800 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1801 GNUTLS_A_UNRECOGNIZED_NAME));
1802 g_env->sent_alert = 1;
1803 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
1804 goto end;
1805 }
1806
1807 g_context->pki_sni_entry_list = gnutls_realloc(
1808 g_context->pki_sni_entry_list,
1809 (i+1)*sizeof(pki_sni_entry));
1810 g_context->pki_sni_entry_list[i].sni = gnutls_strdup(name);
1811 g_context->pki_sni_entry_list[i].pki_key = *new_entry;
1812 sni_setup_data = g_context->setup_data;
1813 sni_setup_data.pki_key = *new_entry;
1814 if ((ret = setup_pki_credentials(&g_context->pki_sni_entry_list[i].pki_credentials,
1815 g_session,
1816 g_context,
1817 &sni_setup_data, COAP_DTLS_ROLE_SERVER)) < 0) {
1818 int keep_ret = ret;
1819 G_ACTION(gnutls_alert_send(g_session, GNUTLS_AL_FATAL,
1820 GNUTLS_A_BAD_CERTIFICATE));
1821 g_env->sent_alert = 1;
1822 ret = keep_ret;
1823 goto end;
1824 }
1825 g_context->pki_sni_count++;
1826 }
1827 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1828 g_context->pki_sni_entry_list[i].pki_credentials),
1829 "gnutls_credentials_set");
1830 }
1831
1832end:
1833 free(name);
1834 return ret;
1835
1836fail:
1837 return ret;
1838}
1839#endif /* COAP_SERVER_SUPPORT */
1840
1841#if COAP_CLIENT_SUPPORT
1842/*
1843 * return 0 Success (GNUTLS_E_SUCCESS)
1844 * neg GNUTLS_E_* error code
1845 */
1846static int
1847setup_client_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
1848 coap_gnutls_context_t *g_context =
1849 (coap_gnutls_context_t *)c_session->context->dtls_context;
1850 int ret;
1851
1852 g_context->psk_pki_enabled |= IS_CLIENT;
1853 if (g_context->psk_pki_enabled & IS_PSK) {
1854 coap_dtls_cpsk_t *setup_data = &c_session->cpsk_setup_data;
1855 G_CHECK(gnutls_psk_allocate_client_credentials(&g_env->psk_cl_credentials),
1856 "gnutls_psk_allocate_client_credentials");
1857 gnutls_psk_set_client_credentials_function(g_env->psk_cl_credentials,
1858 psk_client_callback);
1859 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_PSK,
1860 g_env->psk_cl_credentials),
1861 "gnutls_credentials_set");
1862 /* Issue SNI if requested */
1863 if (setup_data->client_sni) {
1864 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1865 setup_data->client_sni,
1866 strlen(setup_data->client_sni)),
1867 "gnutls_server_name_set");
1868 }
1869 if (setup_data->validate_ih_call_back) {
1870 const char *err;
1872
1873 if (tls_version->version >= 0x030604) {
1874 /* Disable TLS1.3 if Identity Hint Callback set */
1875 const char *priority;
1876
1877 if (tls_version->version >= 0x030606) {
1878 priority = VARIANTS_NO_TLS13_3_6_6;
1879 } else {
1880 priority = VARIANTS_NO_TLS13_3_6_4;
1881 }
1882 ret = gnutls_priority_set_direct(g_env->g_session,
1883 priority, &err);
1884 if (ret < 0) {
1885 if (ret == GNUTLS_E_INVALID_REQUEST)
1886 coap_log_warn("gnutls_priority_set_direct: Syntax error at: %s\n", err);
1887 else
1888 coap_log_warn("gnutls_priority_set_direct: %s\n", gnutls_strerror(ret));
1889 goto fail;
1890 }
1891 }
1892 }
1893 }
1894
1895 if ((g_context->psk_pki_enabled & IS_PKI) ||
1896 (g_context->psk_pki_enabled & (IS_PSK | IS_PKI)) == 0) {
1897 /*
1898 * If neither PSK or PKI have been set up, use PKI basics.
1899 * This works providing COAP_PKI_KEY_PEM has a value of 0.
1900 */
1901 coap_dtls_pki_t *setup_data = &g_context->setup_data;
1902
1903 if (!(g_context->psk_pki_enabled & IS_PKI)) {
1904 /* PKI not defined - set up some defaults */
1905 setup_data->verify_peer_cert = 1;
1906 setup_data->check_common_ca = 0;
1907 setup_data->allow_self_signed = 1;
1908 setup_data->allow_expired_certs = 1;
1909 setup_data->cert_chain_validation = 1;
1910 setup_data->cert_chain_verify_depth = 2;
1911 setup_data->check_cert_revocation = 1;
1912 setup_data->allow_no_crl = 1;
1913 setup_data->allow_expired_crl = 1;
1914 setup_data->is_rpk_not_cert = 0;
1915 setup_data->use_cid = 0;
1916 }
1917 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
1918 g_context, setup_data,
1920 "setup_pki_credentials");
1921
1922 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
1923 g_env->pki_credentials),
1924 "gnutls_credentials_set");
1925
1926 if (c_session->proto == COAP_PROTO_TLS)
1927 G_CHECK(gnutls_alpn_set_protocols(g_env->g_session,
1928 &g_context->alpn_proto, 1, 0),
1929 "gnutls_alpn_set_protocols");
1930
1931 /* Issue SNI if requested (only happens if PKI defined) */
1932 if (setup_data->client_sni) {
1933 G_CHECK(gnutls_server_name_set(g_env->g_session, GNUTLS_NAME_DNS,
1934 setup_data->client_sni,
1935 strlen(setup_data->client_sni)),
1936 "gnutls_server_name_set");
1937 }
1938 }
1939 return GNUTLS_E_SUCCESS;
1940
1941fail:
1942 return ret;
1943}
1944#endif /* COAP_CLIENT_SUPPORT */
1945
1946#if COAP_SERVER_SUPPORT
1947/*
1948 * gnutls_psk_server_credentials_function return values
1949 * (see gnutls_psk_set_server_credentials_function())
1950 *
1951 * return -1 failed
1952 * 0 passed
1953 */
1954static int
1955psk_server_callback(gnutls_session_t g_session,
1956 const char *identity,
1957 gnutls_datum_t *key) {
1958 coap_session_t *c_session =
1959 (coap_session_t *)gnutls_transport_get_ptr(g_session);
1960 coap_gnutls_context_t *g_context;
1961 coap_dtls_spsk_t *setup_data;
1962 coap_bin_const_t lidentity;
1963 const coap_bin_const_t *psk_key;
1964
1965 if (c_session == NULL)
1966 return -1;
1967
1968 g_context = (coap_gnutls_context_t *)c_session->context->dtls_context;
1969 if (g_context == NULL)
1970 return -1;
1971 setup_data = &c_session->context->spsk_setup_data;
1972
1973
1974 /* Track the Identity being used */
1975 lidentity.s = identity ? (const uint8_t *)identity : (const uint8_t *)"";
1976 lidentity.length = strlen((const char *)lidentity.s);
1977 coap_session_refresh_psk_identity(c_session, &lidentity);
1978
1979 coap_log_debug("got psk_identity: '%.*s'\n",
1980 (int)lidentity.length, (const char *)lidentity.s);
1981
1982 if (setup_data->validate_id_call_back) {
1983 psk_key = setup_data->validate_id_call_back(&lidentity,
1984 c_session,
1985 setup_data->id_call_back_arg);
1986
1987 coap_session_refresh_psk_key(c_session, psk_key);
1988 } else {
1989 psk_key = coap_get_session_server_psk_key(c_session);
1990 }
1991
1992 if (psk_key == NULL)
1993 return -1;
1994
1995 key->data = gnutls_malloc(psk_key->length);
1996 if (key->data == NULL)
1997 return -1;
1998 memcpy(key->data, psk_key->s, psk_key->length);
1999 key->size = psk_key->length;
2000 return 0;
2001}
2002
2003/*
2004 * return 0 Success (GNUTLS_E_SUCCESS)
2005 * neg GNUTLS_E_* error code
2006 */
2007static int
2008setup_server_ssl_session(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
2009 coap_gnutls_context_t *g_context =
2010 (coap_gnutls_context_t *)c_session->context->dtls_context;
2011 int ret = GNUTLS_E_SUCCESS;
2012
2013 g_context->psk_pki_enabled |= IS_SERVER;
2014 if (g_context->psk_pki_enabled & IS_PSK) {
2015 G_CHECK(setup_psk_credentials(
2016 &g_env->psk_sv_credentials,
2017 g_context,
2018 &c_session->context->spsk_setup_data),
2019 "setup_psk_credentials\n");
2020 G_CHECK(gnutls_credentials_set(g_env->g_session,
2021 GNUTLS_CRD_PSK,
2022 g_env->psk_sv_credentials),
2023 "gnutls_credentials_set\n");
2024 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
2025 post_client_hello_gnutls_psk);
2026 }
2027
2028 if (g_context->psk_pki_enabled & IS_PKI) {
2029 coap_dtls_pki_t *setup_data = &g_context->setup_data;
2030 G_CHECK(setup_pki_credentials(&g_env->pki_credentials, g_env->g_session,
2031 g_context, setup_data,
2033 "setup_pki_credentials");
2034
2035 if (setup_data->verify_peer_cert) {
2036 gnutls_certificate_server_set_request(g_env->g_session,
2037 GNUTLS_CERT_REQUIRE);
2038 } else if (setup_data->is_rpk_not_cert) {
2039 gnutls_certificate_server_set_request(g_env->g_session,
2040 GNUTLS_CERT_REQUEST);
2041 } else {
2042 gnutls_certificate_server_set_request(g_env->g_session,
2043 GNUTLS_CERT_IGNORE);
2044 }
2045
2046 gnutls_handshake_set_post_client_hello_function(g_env->g_session,
2047 post_client_hello_gnutls_pki);
2048
2049 G_CHECK(gnutls_credentials_set(g_env->g_session, GNUTLS_CRD_CERTIFICATE,
2050 g_env->pki_credentials),
2051 "gnutls_credentials_set\n");
2052 }
2053 return GNUTLS_E_SUCCESS;
2054
2055fail:
2056 return ret;
2057}
2058#endif /* COAP_SERVER_SUPPORT */
2059
2060/*
2061 * return +ve data amount
2062 * 0 no more
2063 * -1 error (error in errno)
2064 */
2065static ssize_t
2066coap_dgram_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
2067 ssize_t ret = 0;
2068 coap_session_t *c_session = (coap_session_t *)context;
2069 coap_ssl_t *data;
2070
2071 if (!c_session->tls) {
2072 errno = EAGAIN;
2073 return -1;
2074 }
2075 data = &((coap_gnutls_env_t *)c_session->tls)->coap_ssl_data;
2076
2077 if (out != NULL) {
2078 if (data != NULL && data->pdu_len > 0) {
2079 if (outl < data->pdu_len) {
2080 memcpy(out, data->pdu, outl);
2081 ret = outl;
2082 if (!data->peekmode) {
2083 data->pdu += outl;
2084 data->pdu_len -= outl;
2085 }
2086 } else {
2087 memcpy(out, data->pdu, data->pdu_len);
2088 ret = data->pdu_len;
2089 if (!data->peekmode) {
2090 data->pdu_len = 0;
2091 data->pdu = NULL;
2092 }
2093 }
2094 } else {
2095 errno = EAGAIN;
2096 ret = -1;
2097 }
2098 }
2099 return ret;
2100}
2101
2102/*
2103 * return +ve data amount
2104 * 0 no more
2105 * -1 error (error in errno)
2106 */
2107/* callback function given to gnutls for sending data over socket */
2108static ssize_t
2109coap_dgram_write(gnutls_transport_ptr_t context, const void *send_buffer,
2110 size_t send_buffer_length) {
2111 ssize_t result = -1;
2112 coap_session_t *c_session = (coap_session_t *)context;
2113
2114 if (c_session) {
2115 if (!coap_netif_available(c_session)
2117 && c_session->endpoint == NULL
2118#endif /* COAP_SERVER_SUPPORT */
2119 ) {
2120 /* socket was closed on client due to error */
2121 errno = ECONNRESET;
2122 return -1;
2123 }
2124 result = c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session,
2125 send_buffer, send_buffer_length);
2126 if (result != (int)send_buffer_length) {
2127 int keep_errno = errno;
2128
2129 coap_log_warn("coap_netif_dgrm_write failed (%" PRIdS " != %" PRIuS ")\n",
2130 result, send_buffer_length);
2131 errno = keep_errno;
2132 if (result < 0) {
2133 if (errno == ENOTCONN || errno == ECONNREFUSED)
2134 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2135 return -1;
2136 } else {
2137 result = 0;
2138 }
2139 }
2140 } else {
2141 result = 0;
2142 }
2143 return result;
2144}
2145
2146/*
2147 * return 1 fd has activity
2148 * 0 timeout
2149 * -1 error (error in errno)
2150 */
2151static int
2152receive_timeout(gnutls_transport_ptr_t context, unsigned int ms COAP_UNUSED) {
2153 coap_session_t *c_session = (coap_session_t *)context;
2154
2155 if (c_session) {
2156 fd_set readfds, writefds, exceptfds;
2157 struct timeval tv;
2158#if COAP_SERVER_SUPPORT
2159 coap_fd_t fd = COAP_PROTO_NOT_RELIABLE(c_session->proto) ? c_session->type !=
2160 COAP_SESSION_TYPE_CLIENT ? c_session->endpoint->sock.fd : c_session->sock.fd : c_session->sock.fd;
2161#else /* ! COAP_SERVER_SUPPORT */
2162 coap_fd_t fd = c_session->sock.fd;
2163#endif /* ! COAP_SERVER_SUPPORT */
2164 int nfds = fd + 1;
2165 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2166
2167 /* If data has been read in by libcoap ahead of GnuTLS, say it is there */
2168 if (c_session->proto == COAP_PROTO_DTLS && g_env &&
2169 g_env->coap_ssl_data.pdu_len > 0) {
2170 return 1;
2171 }
2172
2173 FD_ZERO(&readfds);
2174 FD_ZERO(&writefds);
2175 FD_ZERO(&exceptfds);
2176 FD_SET(fd, &readfds);
2177 if (!(g_env && g_env->doing_dtls_timeout)) {
2178 FD_SET(fd, &writefds);
2179 FD_SET(fd, &exceptfds);
2180 }
2181 /* Polling */
2182 tv.tv_sec = 0;
2183 tv.tv_usec = 0;
2184
2185 return select(nfds, &readfds, &writefds, &exceptfds, &tv);
2186 }
2187 return 1;
2188}
2189
2190static coap_gnutls_env_t *
2191coap_dtls_new_gnutls_env(coap_session_t *c_session, int type) {
2192 coap_gnutls_context_t *g_context =
2193 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2194 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2195#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2196 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2197#else /* < 3.6.6 */
2198 int flags = type | GNUTLS_DATAGRAM | GNUTLS_NONBLOCK;
2199#endif /* < 3.6.6 */
2200 int ret;
2201
2202 if (g_env)
2203 return g_env;
2204
2205 g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2206 if (!g_env)
2207 return NULL;
2208
2209 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2210
2211 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2212
2213 gnutls_transport_set_pull_function(g_env->g_session, coap_dgram_read);
2214 gnutls_transport_set_push_function(g_env->g_session, coap_dgram_write);
2215 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2216 /* So we can track the coap_session_t in callbacks */
2217 gnutls_transport_set_ptr(g_env->g_session, c_session);
2218
2219 G_CHECK(gnutls_priority_set(g_env->g_session, g_context->priority_cache),
2220 "gnutls_priority_set");
2221
2222 if (type == GNUTLS_SERVER) {
2223#if COAP_SERVER_SUPPORT
2224 G_CHECK(setup_server_ssl_session(c_session, g_env),
2225 "setup_server_ssl_session");
2226#else /* ! COAP_SERVER_SUPPORT */
2227 goto fail;
2228#endif /* ! COAP_SERVER_SUPPORT */
2229 } else {
2230#if COAP_CLIENT_SUPPORT
2231 G_CHECK(setup_client_ssl_session(c_session, g_env),
2232 "setup_client_ssl_session");
2233#else /* COAP_CLIENT_SUPPORT */
2234 goto fail;
2235#endif /* COAP_CLIENT_SUPPORT */
2236 }
2237
2238 gnutls_handshake_set_timeout(g_env->g_session,
2239 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2240 gnutls_dtls_set_timeouts(g_env->g_session, COAP_DTLS_RETRANSMIT_MS,
2242
2243 return g_env;
2244
2245fail:
2246 if (g_env)
2247 gnutls_free(g_env);
2248 return NULL;
2249}
2250
2251static void
2252coap_dtls_free_gnutls_env(coap_gnutls_context_t *g_context,
2253 coap_gnutls_env_t *g_env,
2254 coap_free_bye_t free_bye) {
2255 if (g_env) {
2256 /* It is suggested not to use GNUTLS_SHUT_RDWR in DTLS
2257 * connections because the peer's closure message might
2258 * be lost */
2259 if (free_bye != COAP_FREE_BYE_NONE && !g_env->sent_alert) {
2260 /* Only do this if appropriate */
2261 gnutls_bye(g_env->g_session, free_bye == COAP_FREE_BYE_AS_UDP ?
2262 GNUTLS_SHUT_WR : GNUTLS_SHUT_RDWR);
2263 }
2264 gnutls_deinit(g_env->g_session);
2265 g_env->g_session = NULL;
2266 if (g_context->psk_pki_enabled & IS_PSK) {
2267 if ((g_context->psk_pki_enabled & IS_CLIENT) &&
2268 g_env->psk_cl_credentials != NULL) {
2269 gnutls_psk_free_client_credentials(g_env->psk_cl_credentials);
2270 g_env->psk_cl_credentials = NULL;
2271 } else {
2272 /* YUK - A memory leak in 3.3.0 (fixed by 3.3.26) of hint */
2273 if (g_env->psk_sv_credentials != NULL)
2274 gnutls_psk_free_server_credentials(g_env->psk_sv_credentials);
2275 g_env->psk_sv_credentials = NULL;
2276 }
2277 }
2278 if ((g_context->psk_pki_enabled & IS_PKI) ||
2279 (g_context->psk_pki_enabled &
2280 (IS_PSK | IS_PKI | IS_CLIENT)) == IS_CLIENT) {
2281 gnutls_certificate_free_credentials(g_env->pki_credentials);
2282 g_env->pki_credentials = NULL;
2283 }
2284 gnutls_free(g_env->coap_ssl_data.cookie_key.data);
2285 gnutls_free(g_env);
2286 }
2287}
2288
2289#if COAP_SERVER_SUPPORT
2290void *
2291coap_dtls_new_server_session(coap_session_t *c_session) {
2292 coap_gnutls_env_t *g_env =
2293 (coap_gnutls_env_t *)c_session->tls;
2294
2295 gnutls_transport_set_ptr(g_env->g_session, c_session);
2296
2297 return g_env;
2298}
2299#endif /* COAP_SERVER_SUPPORT */
2300
2301static void
2302log_last_alert(coap_session_t *c_session,
2303 gnutls_session_t g_session) {
2304#if COAP_MAX_LOGGING_LEVEL > 0
2305 int last_alert = gnutls_alert_get(g_session);
2306
2307 if (last_alert == GNUTLS_A_CLOSE_NOTIFY)
2308 coap_log_debug("***%s: Alert '%d': %s\n",
2309 coap_session_str(c_session),
2310 last_alert, gnutls_alert_get_name(last_alert));
2311 else
2312 coap_log_warn("***%s: Alert '%d': %s\n",
2313 coap_session_str(c_session),
2314 last_alert, gnutls_alert_get_name(last_alert));
2315#else /* COAP_MAX_LOGGING_LEVEL == 0 */
2316 (void)c_session;
2317 (void)g_session;
2318#endif /* COAP_MAX_LOGGING_LEVEL == 0 */
2319}
2320
2321/*
2322 * return -1 failure
2323 * 0 not completed
2324 * 1 established
2325 */
2326static int
2327do_gnutls_handshake(coap_session_t *c_session, coap_gnutls_env_t *g_env) {
2328 int ret;
2329
2330 ret = gnutls_handshake(g_env->g_session);
2331 switch (ret) {
2332 case GNUTLS_E_SUCCESS:
2333 g_env->established = 1;
2334 coap_log_debug("* %s: GnuTLS established\n",
2335 coap_session_str(c_session));
2337 c_session);
2338 gnutls_transport_set_ptr(g_env->g_session, c_session);
2339 c_session->sock.lfunc[COAP_LAYER_TLS].l_establish(c_session);
2340 ret = 1;
2341 break;
2342 case GNUTLS_E_INTERRUPTED:
2343 errno = EINTR;
2344 ret = 0;
2345 break;
2346 case GNUTLS_E_AGAIN:
2347 errno = EAGAIN;
2348 ret = 0;
2349 break;
2350 case GNUTLS_E_INSUFFICIENT_CREDENTIALS:
2351 coap_log_warn("Insufficient credentials provided.\n");
2352 ret = -1;
2353 break;
2354 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2355 /* Stop the sending of an alert on closedown */
2356 g_env->sent_alert = 1;
2357 log_last_alert(c_session, g_env->g_session);
2358 /* Fall through */
2359 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET:
2360 case GNUTLS_E_UNEXPECTED_PACKET:
2362 ret = -1;
2363 break;
2364 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2365 log_last_alert(c_session, g_env->g_session);
2366 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2367 ret = 0;
2368 break;
2369 case GNUTLS_E_NO_CERTIFICATE_FOUND:
2370#if (GNUTLS_VERSION_NUMBER > 0x030606)
2371 case GNUTLS_E_CERTIFICATE_REQUIRED:
2372#endif /* GNUTLS_VERSION_NUMBER > 0x030606 */
2373 coap_log_warn("Client Certificate requested and required, but not provided\n"
2374 );
2375 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2376 GNUTLS_A_BAD_CERTIFICATE));
2377 g_env->sent_alert = 1;
2379 ret = -1;
2380 break;
2381 case GNUTLS_E_DECRYPTION_FAILED:
2382 coap_log_warn("do_gnutls_handshake: session establish "
2383 "returned '%s'\n",
2384 gnutls_strerror(ret));
2385 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2386 GNUTLS_A_DECRYPT_ERROR));
2387 g_env->sent_alert = 1;
2389 ret = -1;
2390 break;
2391 case GNUTLS_E_CERTIFICATE_ERROR:
2392 if (g_env->sent_alert) {
2394 ret = -1;
2395 break;
2396 }
2397 /* Fall through */
2398 case GNUTLS_E_UNKNOWN_CIPHER_SUITE:
2399 case GNUTLS_E_NO_CIPHER_SUITES:
2400 case GNUTLS_E_INVALID_SESSION:
2401 coap_log_warn("do_gnutls_handshake: session establish "
2402 "returned '%s'\n",
2403 gnutls_strerror(ret));
2404 if (!g_env->sent_alert) {
2405 G_ACTION(gnutls_alert_send(g_env->g_session, GNUTLS_AL_FATAL,
2406 GNUTLS_A_HANDSHAKE_FAILURE));
2407 g_env->sent_alert = 1;
2408 }
2410 ret = -1;
2411 break;
2412 case GNUTLS_E_SESSION_EOF:
2413 case GNUTLS_E_PREMATURE_TERMINATION:
2414 case GNUTLS_E_TIMEDOUT:
2415 case GNUTLS_E_PULL_ERROR:
2416 case GNUTLS_E_PUSH_ERROR:
2418 ret = -1;
2419 break;
2420 default:
2421 coap_log_warn("do_gnutls_handshake: session establish "
2422 "returned %d: '%s'\n",
2423 ret, gnutls_strerror(ret));
2424 ret = -1;
2425 break;
2426 }
2427 return ret;
2428}
2429
2430#if COAP_CLIENT_SUPPORT
2431void *
2432coap_dtls_new_client_session(coap_session_t *c_session) {
2433 coap_gnutls_env_t *g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_CLIENT);
2434 int ret;
2435
2436 if (g_env) {
2437 ret = do_gnutls_handshake(c_session, g_env);
2438 if (ret == -1) {
2439 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2440 g_env,
2441 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2442 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2443 return NULL;
2444 }
2445 }
2446 return g_env;
2447}
2448#endif /* COAP_CLIENT_SUPPORT */
2449
2450void
2452 if (c_session && c_session->context && c_session->tls) {
2453 coap_dtls_free_gnutls_env(c_session->context->dtls_context,
2454 c_session->tls,
2455 COAP_PROTO_NOT_RELIABLE(c_session->proto) ?
2456 COAP_FREE_BYE_AS_UDP : COAP_FREE_BYE_AS_TCP);
2457 c_session->tls = NULL;
2459 }
2460}
2461
2462void
2464 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2465 int ret;
2466
2467 if (g_env)
2468 G_CHECK(gnutls_dtls_set_data_mtu(g_env->g_session,
2469 (unsigned int)c_session->mtu),
2470 "gnutls_dtls_set_data_mtu");
2471fail:
2472 ;;
2473}
2474
2475/*
2476 * return +ve data amount
2477 * 0 no more
2478 * -1 error
2479 */
2480ssize_t
2482 const uint8_t *data, size_t data_len) {
2483 int ret;
2484 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2485
2486 if (g_env == NULL) {
2487 return -1;
2488 }
2489
2490 c_session->dtls_event = -1;
2491 coap_log_debug("* %s: dtls: sent %4d bytes\n",
2492 coap_session_str(c_session), (int)data_len);
2493 if (g_env->established) {
2494 ret = gnutls_record_send(g_env->g_session, data, data_len);
2495
2496 if (ret <= 0) {
2497 switch (ret) {
2498 case GNUTLS_E_AGAIN:
2499 ret = 0;
2500 break;
2501 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2502 /* Stop the sending of an alert on closedown */
2503 g_env->sent_alert = 1;
2504 log_last_alert(c_session, g_env->g_session);
2506 ret = -1;
2507 break;
2508 default:
2509 coap_log_debug("coap_dtls_send: gnutls_record_send "
2510 "returned %d: '%s'\n",
2511 ret, gnutls_strerror(ret));
2512 ret = -1;
2513 break;
2514 }
2515 if (ret == -1) {
2516 coap_log_warn("coap_dtls_send: cannot send PDU\n");
2517 }
2518 }
2519 } else {
2520 ret = do_gnutls_handshake(c_session, g_env);
2521 if (ret == 1) {
2522 /* Just connected, so send the data */
2523 return coap_dtls_send(c_session, data, data_len);
2524 }
2525 ret = -1;
2526 }
2527
2528 if (c_session->dtls_event >= 0) {
2529 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2530 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2531 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2532 ret = -1;
2533 }
2534 }
2535
2536 return ret;
2537}
2538
2539int
2541 return 0;
2542}
2543
2545coap_dtls_get_context_timeout(void *dtls_context COAP_UNUSED) {
2546 return 0;
2547}
2548
2551 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2552
2553 assert(c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2554 if (g_env && g_env->g_session) {
2555 unsigned int rem_ms = gnutls_dtls_get_timeout(g_env->g_session);
2556
2557 if (rem_ms == 0) {
2558 /*
2559 * Need to make sure that we do not do this too frequently as some
2560 * versions of gnutls reset retransmit if a spurious packet is received
2561 * (e.g. duplicate Client Hello), but last_transmit does not get updated
2562 * when gnutls_handshake() is called and there is 'nothing' to resend.
2563 */
2564 if (g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS > now)
2565 return g_env->last_timeout + COAP_DTLS_RETRANSMIT_COAP_TICKS;
2566 }
2567 /* Reset for the next time */
2568 g_env->last_timeout = now - rem_ms;
2569 return now + rem_ms;
2570 }
2571
2572 return 0;
2573}
2574
2575/*
2576 * return 1 timed out
2577 * 0 still timing out
2578 */
2579int
2581 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2582
2583 assert(g_env != NULL && c_session->state == COAP_SESSION_STATE_HANDSHAKE);
2584 g_env->doing_dtls_timeout = 1;
2585 if ((++c_session->dtls_timeout_count > c_session->max_retransmit) ||
2586 (do_gnutls_handshake(c_session, g_env) < 0)) {
2587 /* Too many retries */
2588 g_env->doing_dtls_timeout = 0;
2590 return 1;
2591 } else {
2592 g_env->doing_dtls_timeout = 0;
2593 return 0;
2594 }
2595}
2596
2597/*
2598 * return +ve data amount
2599 * 0 no more
2600 * -1 error
2601 */
2602int
2603coap_dtls_receive(coap_session_t *c_session, const uint8_t *data,
2604 size_t data_len) {
2605 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2606 int ret = 0;
2607 coap_ssl_t *ssl_data = &g_env->coap_ssl_data;
2608
2609 uint8_t pdu[COAP_RXBUFFER_SIZE];
2610
2611 assert(g_env != NULL);
2612
2613 if (ssl_data->pdu_len)
2614 coap_log_err("** %s: Previous data not read %u bytes\n",
2615 coap_session_str(c_session), ssl_data->pdu_len);
2616 ssl_data->pdu = data;
2617 ssl_data->pdu_len = data_len;
2618
2619 c_session->dtls_event = -1;
2620 if (g_env->established) {
2621 ret = gnutls_record_recv(g_env->g_session, pdu, (int)sizeof(pdu));
2622 if (ret > 0) {
2623 coap_log_debug("* %s: dtls: recv %4d bytes\n",
2624 coap_session_str(c_session), ret);
2625 return coap_handle_dgram(c_session->context, c_session, pdu, (size_t)ret);
2626 } else if (ret == 0) {
2628 } else {
2629 switch (ret) {
2630 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2631 /* Stop the sending of an alert on closedown */
2632 g_env->sent_alert = 1;
2633 log_last_alert(c_session, g_env->g_session);
2635 ret = -1;
2636 break;
2637 case GNUTLS_E_WARNING_ALERT_RECEIVED:
2638 log_last_alert(c_session, g_env->g_session);
2639 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
2640 ret = 0;
2641 break;
2642 default:
2643 coap_log_warn("coap_dtls_receive: gnutls_record_recv returned %d\n", ret);
2644 ret = -1;
2645 break;
2646 }
2647 }
2648 } else {
2649 ret = do_gnutls_handshake(c_session, g_env);
2650 if (ret == 1) {
2651 coap_session_connected(c_session);
2652 } else {
2653 ret = -1;
2654 if (ssl_data->pdu_len && !g_env->sent_alert) {
2655 /* Do the handshake again incase of internal timeout */
2656 ret = do_gnutls_handshake(c_session, g_env);
2657 if (ret == 1) {
2658 /* Just connected, so send the data */
2659 coap_session_connected(c_session);
2660 }
2661 }
2662 }
2663 }
2664
2665 if (c_session->dtls_event >= 0) {
2666 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2667 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2668 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2670 ssl_data = NULL;
2671 ret = -1;
2672 }
2673 }
2674 if (ssl_data && ssl_data->pdu_len) {
2675 /* pdu data is held on stack which will not stay there */
2676 coap_log_debug("coap_dtls_receive: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2677 ssl_data->pdu_len = 0;
2678 ssl_data->pdu = NULL;
2679 }
2680 return ret;
2681}
2682
2683#if COAP_SERVER_SUPPORT
2684/*
2685 * return -1 failure
2686 * 0 not completed
2687 * 1 client hello seen
2688 */
2689int
2690coap_dtls_hello(coap_session_t *c_session,
2691 const uint8_t *data,
2692 size_t data_len
2693 ) {
2694 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2695 coap_ssl_t *ssl_data;
2696 int ret;
2697
2698 if (!g_env) {
2699 g_env = coap_dtls_new_gnutls_env(c_session, GNUTLS_SERVER);
2700 if (g_env) {
2701 c_session->tls = g_env;
2702 gnutls_key_generate(&g_env->coap_ssl_data.cookie_key,
2703 GNUTLS_COOKIE_KEY_SIZE);
2704 } else {
2705 /* error should have already been reported */
2706 return -1;
2707 }
2708 }
2709 if (data_len > 0) {
2710 gnutls_dtls_prestate_st prestate;
2711 uint8_t *data_rw;
2712
2713 memset(&prestate, 0, sizeof(prestate));
2714 /* Need to do this to not get a compiler warning about const parameters */
2715 memcpy(&data_rw, &data, sizeof(data_rw));
2716 ret = gnutls_dtls_cookie_verify(&g_env->coap_ssl_data.cookie_key,
2717 &c_session->addr_info,
2718 sizeof(c_session->addr_info),
2719 data_rw, data_len,
2720 &prestate);
2721 if (ret < 0) { /* cookie not valid */
2722 coap_log_debug("Invalid Cookie - sending Hello Verify\n");
2723 gnutls_dtls_cookie_send(&g_env->coap_ssl_data.cookie_key,
2724 &c_session->addr_info,
2725 sizeof(c_session->addr_info),
2726 &prestate,
2727 c_session,
2728 coap_dgram_write);
2729 return 0;
2730 }
2731 gnutls_dtls_prestate_set(g_env->g_session, &prestate);
2732 }
2733
2734 ssl_data = &g_env->coap_ssl_data;
2735 ssl_data->pdu = data;
2736 ssl_data->pdu_len = data_len;
2737
2738 ret = do_gnutls_handshake(c_session, g_env);
2739 if (ret < 0) {
2740 /*
2741 * as the above failed, need to remove g_env to clean up any
2742 * pollution of the information
2743 */
2744 coap_dtls_free_gnutls_env(((coap_gnutls_context_t *)c_session->context->dtls_context),
2745 g_env, COAP_FREE_BYE_NONE);
2746 c_session->tls = NULL;
2747 ssl_data = NULL;
2748 ret = -1;
2749 } else {
2750 /* Client Hello has been seen */
2751 ret = 1;
2752 }
2753
2754 if (ssl_data && ssl_data->pdu_len) {
2755 /* pdu data is held on stack which will not stay there */
2756 coap_log_debug("coap_dtls_hello: ret %d: remaining data %u\n", ret, ssl_data->pdu_len);
2757 ssl_data->pdu_len = 0;
2758 ssl_data->pdu = NULL;
2759 }
2760 return ret;
2761}
2762#endif /* COAP_SERVER_SUPPORT */
2763
2764unsigned int
2766 return 37;
2767}
2768
2769#if !COAP_DISABLE_TCP
2770/*
2771 * strm
2772 * return +ve data amount
2773 * 0 connection closed
2774 * -1 error (error in errno)
2775 */
2776static ssize_t
2777coap_sock_read(gnutls_transport_ptr_t context, void *out, size_t outl) {
2778 int ret = 0;
2779 coap_session_t *c_session = (coap_session_t *)context;
2780
2781 if (out != NULL) {
2782 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_read(c_session, out, outl);
2783 /* Translate layer returns into what GnuTLS expects */
2784 if (ret == 0) {
2785 errno = EAGAIN;
2786 ret = -1;
2787 }
2788 }
2789 return ret;
2790}
2791
2792/*
2793 * strm
2794 * return +ve data amount
2795 * 0 no more
2796 * -1 error (error in errno)
2797 */
2798static ssize_t
2799coap_sock_write(gnutls_transport_ptr_t context, const void *in, size_t inl) {
2800 int ret = 0;
2801 coap_session_t *c_session = (coap_session_t *)context;
2802
2803 ret = (int)c_session->sock.lfunc[COAP_LAYER_TLS].l_write(c_session, in, inl);
2804 /* Translate layer what returns into what GnuTLS expects */
2805 if (ret < 0) {
2806 if ((c_session->state == COAP_SESSION_STATE_CSM ||
2807 c_session->state == COAP_SESSION_STATE_HANDSHAKE) &&
2808 (errno == EPIPE || errno == ECONNRESET)) {
2809 /*
2810 * Need to handle a TCP timing window where an agent continues with
2811 * the sending of the next handshake or a CSM.
2812 * However, the peer does not like a certificate and so sends a
2813 * fatal alert and closes the TCP session.
2814 * The sending of the next handshake or CSM may get terminated because
2815 * of the closed TCP session, but there is still an outstanding alert
2816 * to be read in and reported on.
2817 * In this case, pretend that sending the info was fine so that the
2818 * alert can be read (which effectively is what happens with DTLS).
2819 */
2820 ret = inl;
2821 } else {
2822 coap_log_debug("* %s: failed to send %" PRIdS " bytes (%s) state %d\n",
2823 coap_session_str(c_session), inl, coap_socket_strerror(),
2824 c_session->state);
2825 }
2826 }
2827 if (ret == 0) {
2828 errno = EAGAIN;
2829 ret = -1;
2830 }
2831 return ret;
2832}
2833
2834#if COAP_CLIENT_SUPPORT
2835void *
2836coap_tls_new_client_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_CLIENT | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2842#else /* < 3.6.6 */
2843 int flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
2844#endif /* < 3.6.6 */
2845 int ret;
2846
2847 if (!g_env) {
2848 return NULL;
2849 }
2850 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2851
2852 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2853
2854 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2855 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2856 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2857 /* So we can track the coap_session_t in callbacks */
2858 gnutls_transport_set_ptr(g_env->g_session, c_session);
2859
2860 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2861 setup_client_ssl_session(c_session, g_env);
2862
2863 gnutls_handshake_set_timeout(g_env->g_session, 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 if (g_env)
2871 gnutls_free(g_env);
2872 return NULL;
2873}
2874#endif /* COAP_CLIENT_SUPPORT */
2875
2876#if COAP_SERVER_SUPPORT
2877void *
2878coap_tls_new_server_session(coap_session_t *c_session) {
2879 coap_gnutls_env_t *g_env = gnutls_malloc(sizeof(coap_gnutls_env_t));
2880 coap_gnutls_context_t *g_context =
2881 ((coap_gnutls_context_t *)c_session->context->dtls_context);
2882#if (GNUTLS_VERSION_NUMBER >= 0x030606)
2883 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK | GNUTLS_ENABLE_RAWPK;
2884#else /* < 3.6.6 */
2885 int flags = GNUTLS_SERVER | GNUTLS_NONBLOCK;
2886#endif /* < 3.6.6 */
2887 int ret;
2888
2889 if (!g_env)
2890 return NULL;
2891 memset(g_env, 0, sizeof(coap_gnutls_env_t));
2892
2893 G_CHECK(gnutls_init(&g_env->g_session, flags), "gnutls_init");
2894
2895 gnutls_transport_set_pull_function(g_env->g_session, coap_sock_read);
2896 gnutls_transport_set_push_function(g_env->g_session, coap_sock_write);
2897 gnutls_transport_set_pull_timeout_function(g_env->g_session, receive_timeout);
2898 /* So we can track the coap_session_t in callbacks */
2899 gnutls_transport_set_ptr(g_env->g_session, c_session);
2900
2901 setup_server_ssl_session(c_session, g_env);
2902
2903 gnutls_priority_set(g_env->g_session, g_context->priority_cache);
2904 gnutls_handshake_set_timeout(g_env->g_session,
2905 GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
2906
2907 c_session->tls = g_env;
2908 do_gnutls_handshake(c_session, g_env);
2909 return g_env;
2910
2911fail:
2912 return NULL;
2913}
2914#endif /* COAP_SERVER_SUPPORT */
2915
2916void
2918 coap_dtls_free_session(c_session);
2919 return;
2920}
2921
2922/*
2923 * strm
2924 * return +ve Number of bytes written.
2925 * -1 Error (error in errno).
2926 */
2927ssize_t
2928coap_tls_write(coap_session_t *c_session, const uint8_t *data,
2929 size_t data_len) {
2930 int ret;
2931 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
2932
2933 assert(g_env != NULL);
2934
2935 c_session->dtls_event = -1;
2936 if (g_env->established) {
2937 ret = gnutls_record_send(g_env->g_session, data, data_len);
2938
2939 if (ret <= 0) {
2940 switch (ret) {
2941 case GNUTLS_E_AGAIN:
2942 ret = 0;
2943 break;
2944 case GNUTLS_E_PUSH_ERROR:
2945 case GNUTLS_E_PULL_ERROR:
2946 case GNUTLS_E_PREMATURE_TERMINATION:
2948 break;
2949 case GNUTLS_E_FATAL_ALERT_RECEIVED:
2950 /* Stop the sending of an alert on closedown */
2951 g_env->sent_alert = 1;
2952 log_last_alert(c_session, g_env->g_session);
2954 break;
2955 default:
2956 coap_log_warn("coap_tls_write: gnutls_record_send "
2957 "returned %d: '%s'\n",
2958 ret, gnutls_strerror(ret));
2959 ret = -1;
2960 break;
2961 }
2962 if (ret == -1) {
2963 coap_log_info("coap_tls_write: cannot send PDU\n");
2964 }
2965 }
2966 } else {
2967 ret = do_gnutls_handshake(c_session, g_env);
2968 if (ret == 1) {
2969 ret = 0;
2970 } else {
2971 ret = -1;
2972 }
2973 }
2974
2975 if (c_session->dtls_event >= 0) {
2976 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
2977 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
2978 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
2979 ret = -1;
2980 }
2981 }
2982
2983 if (ret > 0) {
2984 if (ret == (ssize_t)data_len)
2985 coap_log_debug("* %s: tls: sent %4d bytes\n",
2986 coap_session_str(c_session), ret);
2987 else
2988 coap_log_debug("* %s: tls: sent %4d of %4" PRIdS " bytes\n",
2989 coap_session_str(c_session), ret, data_len);
2990 }
2991 return ret;
2992}
2993
2994/*
2995 * strm
2996 * return >=0 Number of bytes read.
2997 * -1 Error (error in errno).
2998 */
2999ssize_t
3000coap_tls_read(coap_session_t *c_session, uint8_t *data, size_t data_len) {
3001 coap_gnutls_env_t *g_env = (coap_gnutls_env_t *)c_session->tls;
3002 int ret = -1;
3003
3004 if (!g_env) {
3005 errno = ENOTCONN;
3006 return -1;
3007 }
3008
3009 c_session->dtls_event = -1;
3010 if (!g_env->established && !g_env->sent_alert) {
3011 ret = do_gnutls_handshake(c_session, g_env);
3012 if (ret == 1) {
3013 ret = 0;
3014 }
3015 }
3016 if (c_session->state != COAP_SESSION_STATE_NONE && g_env->established) {
3017 ret = gnutls_record_recv(g_env->g_session, data, (int)data_len);
3018 if (ret <= 0) {
3019 switch (ret) {
3020 case 0:
3022 break;
3023 case GNUTLS_E_AGAIN:
3024 errno = EAGAIN;
3025 ret = 0;
3026 break;
3027 case GNUTLS_E_PULL_ERROR:
3028 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
3029 break;
3030 case GNUTLS_E_FATAL_ALERT_RECEIVED:
3031 /* Stop the sending of an alert on closedown */
3032 g_env->sent_alert = 1;
3033 log_last_alert(c_session, g_env->g_session);
3035 break;
3036 case GNUTLS_E_WARNING_ALERT_RECEIVED:
3037 log_last_alert(c_session, g_env->g_session);
3038 c_session->dtls_event = COAP_EVENT_DTLS_ERROR;
3039 break;
3040 default:
3041 coap_log_warn("coap_tls_read: gnutls_record_recv "
3042 "returned %d: '%s'\n",
3043 ret, gnutls_strerror(ret));
3044 ret = -1;
3045 break;
3046 }
3047 }
3048 }
3049
3050 if (c_session->dtls_event >= 0) {
3051 coap_handle_event_lkd(c_session->context, c_session->dtls_event, c_session);
3052 if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
3053 c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
3055 ret = -1;
3056 }
3057 }
3058 if (ret > 0) {
3059 coap_log_debug("* %s: tls: recv %4d bytes\n",
3060 coap_session_str(c_session), ret);
3061 }
3062 return ret;
3063}
3064#endif /* !COAP_DISABLE_TCP */
3065
3066#if COAP_SERVER_SUPPORT
3067coap_digest_ctx_t *
3068coap_digest_setup(void) {
3069 gnutls_hash_hd_t digest_ctx;
3070
3071 if (gnutls_hash_init(&digest_ctx, GNUTLS_DIG_SHA256)) {
3072 return NULL;
3073 }
3074 return digest_ctx;
3075}
3076
3077void
3078coap_digest_free(coap_digest_ctx_t *digest_ctx) {
3079 if (digest_ctx)
3080 gnutls_hash_deinit(digest_ctx, NULL);
3081}
3082
3083int
3084coap_digest_update(coap_digest_ctx_t *digest_ctx,
3085 const uint8_t *data,
3086 size_t data_len) {
3087 int ret = gnutls_hash(digest_ctx, data, data_len);
3088
3089 return ret == 0;
3090}
3091
3092int
3093coap_digest_final(coap_digest_ctx_t *digest_ctx,
3094 coap_digest_t *digest_buffer) {
3095 gnutls_hash_output(digest_ctx, (uint8_t *)digest_buffer);
3096
3097 coap_digest_free(digest_ctx);
3098 return 1;
3099}
3100#endif /* COAP_SERVER_SUPPORT */
3101
3102#if COAP_WS_SUPPORT
3103/*
3104 * The struct hash_algs and the function get_hash_alg() are used to
3105 * determine which hash type to use for creating the required hash object.
3106 */
3107static struct hash_algs {
3108 cose_alg_t alg;
3109 gnutls_digest_algorithm_t dig_type;
3110 size_t dig_size;
3111} hashs[] = {
3112 {COSE_ALGORITHM_SHA_1, GNUTLS_DIG_SHA1, 20},
3113 {COSE_ALGORITHM_SHA_256_256, GNUTLS_DIG_SHA256, 32},
3114 {COSE_ALGORITHM_SHA_512, GNUTLS_DIG_SHA512, 64},
3115};
3116
3117static gnutls_digest_algorithm_t
3118get_hash_alg(cose_alg_t alg, size_t *hash_len) {
3119 size_t idx;
3120
3121 for (idx = 0; idx < sizeof(hashs) / sizeof(struct hash_algs); idx++) {
3122 if (hashs[idx].alg == alg) {
3123 *hash_len = hashs[idx].dig_size;
3124 return hashs[idx].dig_type;
3125 }
3126 }
3127 coap_log_debug("get_hash_alg: COSE hash %d not supported\n", alg);
3128 return GNUTLS_DIG_UNKNOWN;
3129}
3130
3131int
3133 const coap_bin_const_t *data,
3134 coap_bin_const_t **hash) {
3135 size_t hash_length;
3136 gnutls_digest_algorithm_t dig_type = get_hash_alg(alg, &hash_length);
3137 gnutls_hash_hd_t digest_ctx;
3139 int ret;
3140
3141 if (dig_type == GNUTLS_DIG_UNKNOWN) {
3142 coap_log_debug("coap_crypto_hash: algorithm %d not supported\n", alg);
3143 return 0;
3144 }
3145
3146 if (gnutls_hash_init(&digest_ctx, dig_type)) {
3147 return 0;
3148 }
3149 ret = gnutls_hash(digest_ctx, data->s, data->length);
3150 if (ret != 0)
3151 goto error;
3152
3153 dummy = coap_new_binary(hash_length);
3154 if (!dummy)
3155 goto error;
3156 gnutls_hash_output(digest_ctx, dummy->s);
3157
3158 *hash = (coap_bin_const_t *)(dummy);
3159 gnutls_hash_deinit(digest_ctx, NULL);
3160 return 1;
3161
3162error:
3164 gnutls_hash_deinit(digest_ctx, NULL);
3165 return 0;
3166}
3167#endif /* COAP_WS_SUPPORT */
3168
3169#if COAP_OSCORE_SUPPORT
3170int
3172 return 1;
3173}
3174
3175/*
3176 * The struct cipher_algs and the function get_cipher_alg() are used to
3177 * determine which cipher type to use for creating the required cipher
3178 * suite object.
3179 */
3180static struct cipher_algs {
3181 cose_alg_t alg;
3182 gnutls_cipher_algorithm_t cipher_type;
3183} ciphers[] = {{COSE_ALGORITHM_AES_CCM_16_64_128, GNUTLS_CIPHER_AES_128_CCM_8},
3184 {COSE_ALGORITHM_AES_CCM_16_64_256, GNUTLS_CIPHER_AES_256_CCM_8}
3185};
3186
3187static gnutls_cipher_algorithm_t
3188get_cipher_alg(cose_alg_t alg) {
3189 size_t idx;
3190
3191 for (idx = 0; idx < sizeof(ciphers) / sizeof(struct cipher_algs); idx++) {
3192 if (ciphers[idx].alg == alg)
3193 return ciphers[idx].cipher_type;
3194 }
3195 coap_log_debug("get_cipher_alg: COSE cipher %d not supported\n", alg);
3196 return 0;
3197}
3198
3199/*
3200 * The struct hmac_algs and the function get_hmac_alg() are used to
3201 * determine which hmac type to use for creating the required hmac
3202 * suite object.
3203 */
3204static struct hmac_algs {
3205 cose_hmac_alg_t hmac_alg;
3206 gnutls_mac_algorithm_t hmac_type;
3207} hmacs[] = {
3208 {COSE_HMAC_ALG_HMAC256_256, GNUTLS_MAC_SHA256},
3209 {COSE_HMAC_ALG_HMAC512_512, GNUTLS_MAC_SHA512},
3210};
3211
3212static gnutls_mac_algorithm_t
3213get_hmac_alg(cose_hmac_alg_t hmac_alg) {
3214 size_t idx;
3215
3216 for (idx = 0; idx < sizeof(hmacs) / sizeof(struct hmac_algs); idx++) {
3217 if (hmacs[idx].hmac_alg == hmac_alg)
3218 return hmacs[idx].hmac_type;
3219 }
3220 coap_log_debug("get_hmac_alg: COSE HMAC %d not supported\n", hmac_alg);
3221 return 0;
3222}
3223
3224int
3226 return get_cipher_alg(alg);
3227}
3228
3229int
3231 cose_hmac_alg_t hmac_alg;
3232
3233 if (!cose_get_hmac_alg_for_hkdf(hkdf_alg, &hmac_alg))
3234 return 0;
3235 return get_hmac_alg(hmac_alg);
3236}
3237
3238int
3240 coap_bin_const_t *data,
3241 coap_bin_const_t *aad,
3242 uint8_t *result,
3243 size_t *max_result_len) {
3244 gnutls_aead_cipher_hd_t ctx;
3245 gnutls_datum_t key;
3246 const coap_crypto_aes_ccm_t *ccm;
3247 int ret = 0;
3248 size_t result_len = *max_result_len;
3249 gnutls_cipher_algorithm_t algo;
3250 unsigned tag_size;
3251 uint8_t *key_data_rw;
3252 coap_bin_const_t laad;
3253
3254 if (data == NULL)
3255 return 0;
3256
3257 assert(params != NULL);
3258 if (!params) {
3259 return 0;
3260 }
3261 if ((algo = get_cipher_alg(params->alg)) == 0) {
3262 coap_log_debug("coap_crypto_encrypt: algorithm %d not supported\n",
3263 params->alg);
3264 return 0;
3265 }
3266 tag_size = gnutls_cipher_get_tag_size(algo);
3267 ccm = &params->params.aes;
3268
3269 /* Get a RW copy of data */
3270 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3271 key.data = key_data_rw;
3272 key.size = ccm->key.length;
3273
3274 if (aad) {
3275 laad = *aad;
3276 } else {
3277 laad.s = NULL;
3278 laad.length = 0;
3279 }
3280
3281 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3282
3283 G_CHECK(gnutls_aead_cipher_encrypt(ctx,
3284 ccm->nonce,
3285 15 - ccm->l, /* iv */
3286 laad.s,
3287 laad.length, /* ad */
3288 tag_size,
3289 data->s,
3290 data->length, /* input */
3291 result,
3292 &result_len), /* output */
3293 "gnutls_aead_cipher_encrypt");
3294 *max_result_len = result_len;
3295 ret = 1;
3296fail:
3297 gnutls_aead_cipher_deinit(ctx);
3298 return ret == 1 ? 1 : 0;
3299}
3300
3301int
3303 coap_bin_const_t *data,
3304 coap_bin_const_t *aad,
3305 uint8_t *result,
3306 size_t *max_result_len) {
3307 gnutls_aead_cipher_hd_t ctx;
3308 gnutls_datum_t key;
3309 const coap_crypto_aes_ccm_t *ccm;
3310 int ret = 0;
3311 size_t result_len = *max_result_len;
3312 gnutls_cipher_algorithm_t algo;
3313 unsigned tag_size;
3314 uint8_t *key_data_rw;
3315 coap_bin_const_t laad;
3316
3317 if (data == NULL)
3318 return 0;
3319
3320 assert(params != NULL);
3321
3322 if (!params) {
3323 return 0;
3324 }
3325 if ((algo = get_cipher_alg(params->alg)) == 0) {
3326 coap_log_debug("coap_crypto_decrypt: algorithm %d not supported\n",
3327 params->alg);
3328 return 0;
3329 }
3330 tag_size = gnutls_cipher_get_tag_size(algo);
3331 ccm = &params->params.aes;
3332
3333 /* Get a RW copy of data */
3334 memcpy(&key_data_rw, &ccm->key.s, sizeof(key_data_rw));
3335 key.data = key_data_rw;
3336 key.size = ccm->key.length;
3337
3338 if (aad) {
3339 laad = *aad;
3340 } else {
3341 laad.s = NULL;
3342 laad.length = 0;
3343 }
3344
3345 G_CHECK(gnutls_aead_cipher_init(&ctx, algo, &key), "gnutls_aead_cipher_init");
3346
3347 G_CHECK(gnutls_aead_cipher_decrypt(ctx,
3348 ccm->nonce,
3349 15 - ccm->l, /* iv */
3350 laad.s,
3351 laad.length, /* ad */
3352 tag_size,
3353 data->s,
3354 data->length, /* input */
3355 result,
3356 &result_len), /* output */
3357 "gnutls_aead_cipher_decrypt");
3358 *max_result_len = result_len;
3359 ret = 1;
3360fail:
3361 gnutls_aead_cipher_deinit(ctx);
3362 return ret == 1 ? 1 : 0;
3363}
3364
3365int
3367 coap_bin_const_t *key,
3368 coap_bin_const_t *data,
3369 coap_bin_const_t **hmac) {
3370 gnutls_hmac_hd_t ctx;
3371 int ret = 0;
3372 unsigned len;
3373 gnutls_mac_algorithm_t mac_algo;
3375
3376 if (data == NULL)
3377 return 0;
3378
3379 if ((mac_algo = get_hmac_alg(hmac_alg)) == 0) {
3380 coap_log_debug("coap_crypto_hmac: algorithm %d not supported\n", hmac_alg);
3381 return 0;
3382 }
3383 len = gnutls_hmac_get_len(mac_algo);
3384 if (len == 0)
3385 return 0;
3386
3387 dummy = coap_new_binary(len);
3388 if (dummy == NULL)
3389 return 0;
3390 G_CHECK(gnutls_hmac_init(&ctx, mac_algo, key->s, key->length),
3391 "gnutls_hmac_init");
3392 G_CHECK(gnutls_hmac(ctx, data->s, data->length), "gnutls_hmac");
3393 gnutls_hmac_output(ctx, dummy->s);
3394 *hmac = (coap_bin_const_t *)dummy;
3395 dummy = NULL;
3396 ret = 1;
3397fail:
3399 gnutls_hmac_deinit(ctx, NULL);
3400 return ret == 1 ? 1 : 0;
3401}
3402
3403#endif /* COAP_OSCORE_SUPPORT */
3404
3405#else /* ! COAP_WITH_LIBGNUTLS */
3406
3407#ifdef __clang__
3408/* Make compilers happy that do not like empty modules. As this function is
3409 * never used, we ignore -Wunused-function at the end of compiling this file
3410 */
3411#pragma GCC diagnostic ignored "-Wunused-function"
3412#endif
3413static inline void
3414dummy(void) {
3415}
3416
3417#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:966
#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:5202
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:3097
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:159
int coap_pki_name_match_sni(const char *name_entry, size_t name_length, const char *sni_match)
Check if the PKI name entry is a (wildcard) match for the requested SNI.
Definition coap_dtls.c:288
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::@157113072004166322362146125210066265265052014356 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
union coap_dtls_key_t::@347061073371360224072225335172343174030036152126 key
coap_pki_key_t key_type
key format type
Definition coap_dtls.h:285
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