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