-
Notifications
You must be signed in to change notification settings - Fork 471
Expand file tree
/
Copy pathcoap_openhitls.c
More file actions
3180 lines (2849 loc) · 98 KB
/
Copy pathcoap_openhitls.c
File metadata and controls
3180 lines (2849 loc) · 98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* coap_openhitls.c -- openHiTLS Datagram Transport Layer Support for libcoap
*
* Copyright (C) 2026 openHiTLS Project.
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
/**
* @file coap_openhitls.c
* @brief openHiTLS specific interface functions.
*/
#include "coap3/coap_libcoap_build.h"
#if COAP_WITH_LIBOPENHITLS || COAP_WITH_LIBOPENHITLS_OSCORE
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#ifdef COAP_EPOLL_SUPPORT
#include <sys/epoll.h>
#endif /* COAP_EPOLL_SUPPORT */
#include <hitls/bsl/bsl_err.h>
#include <hitls/bsl/bsl_errno.h>
#include <hitls/bsl/bsl_sal.h>
#include <hitls/bsl/bsl_uio.h>
#include <hitls/bsl/bsl_version.h>
#include <hitls/crypto/crypt_eal_cipher.h>
#include <hitls/crypto/crypt_eal_init.h>
#include <hitls/crypto/crypt_eal_mac.h>
#include <hitls/crypto/crypt_eal_md.h>
#include <hitls/crypto/crypt_eal_pkey.h>
#include <hitls/crypto/crypt_errno.h>
#if COAP_WITH_LIBOPENHITLS
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif /* defined(__GNUC__) */
#include <hitls/bsl/bsl_list.h>
#include <hitls/pki/hitls_pki_cert.h>
#include <hitls/pki/hitls_pki_errno.h>
#include <hitls/pki/hitls_pki_types.h>
#include <hitls/pki/hitls_pki_utils.h>
#include <hitls/pki/hitls_pki_x509.h>
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif /* defined(__GNUC__) */
#include <hitls/tls/hitls.h>
#include <hitls/tls/hitls_alpn.h>
#include <hitls/tls/hitls_cert.h>
#include <hitls/tls/hitls_cert_init.h>
#include <hitls/tls/hitls_config.h>
#include <hitls/tls/hitls_cookie.h>
#include <hitls/tls/hitls_crypt_init.h>
#include <hitls/tls/hitls_debug.h>
#include <hitls/tls/hitls_error.h>
#include <hitls/tls/hitls_psk.h>
#include <hitls/tls/hitls_sni.h>
#endif /* COAP_WITH_LIBOPENHITLS */
#if COAP_WITH_LIBOPENHITLS
#define IS_PSK 0x01
#define IS_PKI 0x02
#define COAP_HITLS_DTLS_OVERHEAD 37
#define COAP_HITLS_IPV4_UDP_OVERHEAD 28
#define COAP_HITLS_IPV6_UDP_OVERHEAD 48
#define COAP_HITLS_COOKIE_SECRET_LEN 32
#define COAP_HITLS_COOKIE_LEN 32
/* +1 converts libcoap verify_depth to the intermediate-CA limit.
* +2 adds the leaf certificate and trust anchor for openHiTLS maxDepth.
*/
#define COAP_HITLS_VERIFY_DEPTH_TO_MAX_CHAIN_DEPTH(depth) \
((depth) + 1 + 2)
typedef struct coap_hitls_context_t {
coap_context_t *coap_context;
coap_dtls_pki_t setup_data;
char *root_ca_file;
char *root_ca_dir;
int psk_pki_enabled;
int trust_store_defined;
int cookie_secret_set;
uint8_t cookie_secret[COAP_HITLS_COOKIE_SECRET_LEN];
} coap_hitls_context_t;
typedef struct coap_hitls_env_t {
HITLS_Ctx *ctx;
BSL_UIO *uio;
BSL_UIO_Method *method;
const uint8_t *pdu;
size_t pdu_len;
coap_session_t *session;
int established;
coap_dtls_role_t role;
coap_proto_t proto;
int hello_verify_sent;
int mtu_exceeded;
int had_fatal;
coap_tick_t last_timeout;
} coap_hitls_env_t;
static coap_log_t dtls_log_level = COAP_LOG_EMERG;
#endif /* COAP_WITH_LIBOPENHITLS */
static int coap_hitls_started = 0;
#if COAP_WITH_LIBOPENHITLS
static const uint8_t coap_hitls_alpn[] = { 4, 'c', 'o', 'a', 'p' };
static const uint16_t coap_hitls_psk_cipher_suites[] = {
HITLS_PSK_WITH_AES_128_GCM_SHA256,
HITLS_PSK_WITH_AES_256_GCM_SHA384,
HITLS_PSK_WITH_AES_256_CCM,
HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256
};
static const uint16_t coap_hitls_pki_cipher_suites[] = {
HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384
};
static const uint16_t coap_hitls_psk_pki_cipher_suites[] = {
HITLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
HITLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
HITLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
HITLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
HITLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
HITLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
HITLS_PSK_WITH_AES_128_GCM_SHA256,
HITLS_PSK_WITH_AES_256_GCM_SHA384,
HITLS_PSK_WITH_AES_256_CCM,
HITLS_PSK_WITH_CHACHA20_POLY1305_SHA256
};
static void
coap_hitls_get_cipher_suites(int enabled, const uint16_t **cipher_suites,
uint32_t *cipher_suites_count) {
if ((enabled & IS_PSK) && (enabled & IS_PKI)) {
*cipher_suites = coap_hitls_psk_pki_cipher_suites;
*cipher_suites_count =
(uint32_t)(sizeof(coap_hitls_psk_pki_cipher_suites) /
sizeof(coap_hitls_psk_pki_cipher_suites[0]));
} else if (enabled & IS_PKI) {
*cipher_suites = coap_hitls_pki_cipher_suites;
*cipher_suites_count =
(uint32_t)(sizeof(coap_hitls_pki_cipher_suites) /
sizeof(coap_hitls_pki_cipher_suites[0]));
} else {
*cipher_suites = coap_hitls_psk_cipher_suites;
*cipher_suites_count =
(uint32_t)(sizeof(coap_hitls_psk_cipher_suites) /
sizeof(coap_hitls_psk_cipher_suites[0]));
}
}
static void
coap_hitls_mark_fatal(coap_session_t *session) {
coap_hitls_env_t *env = session ? (coap_hitls_env_t *)session->tls : NULL;
if (env)
env->had_fatal = 1;
}
static void
coap_hitls_log_err_stack(const coap_session_t *session) {
int32_t e;
while ((e = BSL_ERR_GetError()) != BSL_SUCCESS)
coap_dtls_log(COAP_LOG_WARN, "* %s: openHiTLS error 0x%08x\n",
coap_session_str(session), (unsigned int)e);
}
static void
coap_hitls_log_fatal_err_stack(coap_session_t *session) {
coap_hitls_mark_fatal(session);
coap_hitls_log_err_stack(session);
}
/* TLS alert levels and descriptions as defined by RFC 5246 / RFC 8446. */
enum {
ALERT_LEVEL_WARNING = 1,
ALERT_LEVEL_FATAL = 2,
ALERT_CLOSE_NOTIFY = 0,
ALERT_UNEXPECTED_MESSAGE = 10,
ALERT_BAD_RECORD_MAC = 20,
ALERT_RECORD_OVERFLOW = 22,
ALERT_HANDSHAKE_FAILURE = 40,
ALERT_BAD_CERTIFICATE = 42,
ALERT_UNSUPPORTED_CERTIFICATE = 43,
ALERT_CERTIFICATE_REVOKED = 44,
ALERT_CERTIFICATE_EXPIRED = 45,
ALERT_ILLEGAL_PARAMETER = 47,
ALERT_UNKNOWN_CA = 48,
ALERT_DECODE_ERROR = 50,
ALERT_DECRYPT_ERROR = 51,
ALERT_PROTOCOL_VERSION = 70,
ALERT_INSUFFICIENT_SECURITY = 71,
ALERT_INTERNAL_ERROR = 80,
ALERT_INAPPROPRIATE_FALLBACK = 86,
ALERT_NO_RENEGOTIATION = 100,
ALERT_MISSING_EXTENSION = 109,
ALERT_UNSUPPORTED_EXTENSION = 110,
ALERT_UNRECOGNIZED_NAME = 112,
ALERT_CERTIFICATE_REQUIRED = 116,
ALERT_NO_APPLICATION_PROTOCOL = 120
};
static const char *
coap_hitls_alert_desc(int desc) {
switch (desc) {
case ALERT_CLOSE_NOTIFY:
return "close_notify";
case ALERT_UNEXPECTED_MESSAGE:
return "unexpected_message";
case ALERT_BAD_RECORD_MAC:
return "bad_record_mac";
case ALERT_RECORD_OVERFLOW:
return "record_overflow";
case ALERT_HANDSHAKE_FAILURE:
return "handshake_failure";
case ALERT_BAD_CERTIFICATE:
return "bad_certificate";
case ALERT_UNSUPPORTED_CERTIFICATE:
return "unsupported_certificate";
case ALERT_CERTIFICATE_REVOKED:
return "certificate_revoked";
case ALERT_CERTIFICATE_EXPIRED:
return "certificate_expired";
case ALERT_ILLEGAL_PARAMETER:
return "illegal_parameter";
case ALERT_UNKNOWN_CA:
return "unknown_ca";
case ALERT_DECODE_ERROR:
return "decode_error";
case ALERT_DECRYPT_ERROR:
return "decrypt_error";
case ALERT_PROTOCOL_VERSION:
return "protocol_version";
case ALERT_INSUFFICIENT_SECURITY:
return "insufficient_security";
case ALERT_INTERNAL_ERROR:
return "internal_error";
case ALERT_INAPPROPRIATE_FALLBACK:
return "inappropriate_fallback";
case ALERT_NO_RENEGOTIATION:
return "no_renegotiation";
case ALERT_MISSING_EXTENSION:
return "missing_extension";
case ALERT_UNSUPPORTED_EXTENSION:
return "unsupported_extension";
case ALERT_UNRECOGNIZED_NAME:
return "unrecognized_name";
case ALERT_CERTIFICATE_REQUIRED:
return "certificate_required";
case ALERT_NO_APPLICATION_PROTOCOL:
return "no_application_protocol";
default:
return "unknown";
}
}
/* The info callback packs the alert as (level << 8) | description. */
static void
coap_hitls_info_cb(const HITLS_Ctx *ctx, int32_t event_type, int32_t value) {
coap_session_t *session = (coap_session_t *)HITLS_GetUserData(ctx);
int alert_level = (value >> 8) & 0xff;
int alert_desc = value & 0xff;
const char *dir;
if ((event_type & INDICATE_EVENT_ALERT) == 0 || !session)
return;
dir = (event_type & INDICATE_EVENT_READ) ? "received" : "sent";
if (alert_level == ALERT_LEVEL_FATAL && alert_desc != ALERT_CLOSE_NOTIFY)
coap_log_warn("* %s: openHiTLS %s fatal alert: %s (%d)\n",
coap_session_str(session), dir,
coap_hitls_alert_desc(alert_desc), alert_desc);
else
coap_log_info("* %s: openHiTLS %s alert: %s (%d)\n",
coap_session_str(session), dir,
coap_hitls_alert_desc(alert_desc), alert_desc);
}
static const char *
coap_hitls_verify_err_str(int32_t err) {
switch (err) {
case HITLS_X509_ERR_TIME_EXPIRED:
case HITLS_X509_ERR_VFY_NOTAFTER_EXPIRED:
return "certificate expired";
case HITLS_X509_ERR_TIME_FUTURE:
case HITLS_X509_ERR_VFY_NOTBEFORE_IN_FUTURE:
return "certificate not yet valid";
case HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND:
return "issuer certificate not found";
case HITLS_X509_ERR_ROOT_CERT_NOT_FOUND:
return "self-signed or root CA not found";
case HITLS_X509_ERR_VFY_CRL_NOT_FOUND:
return "CRL not found";
case HITLS_X509_ERR_VFY_THISUPDATE_IN_FUTURE:
case HITLS_X509_ERR_VFY_NEXTUPDATE_EXPIRED:
return "CRL expired or not yet valid";
case HITLS_X509_ERR_VFY_CHECK_SECBITS:
return "certificate security strength too low";
case HITLS_X509_ERR_VFY_HOSTNAME_FAIL:
return "hostname mismatch";
case HITLS_X509_ERR_VFY_GET_NOTBEFORE_FAIL:
return "cannot read certificate validity start";
case HITLS_X509_ERR_VFY_GET_NOTAFTER_FAIL:
return "cannot read certificate validity end";
case BSL_SAL_TIME_SYS_ERROR:
return "system time unavailable";
default:
return "certificate verification failed";
}
}
#endif /* COAP_WITH_LIBOPENHITLS */
static int
coap_hitls_startup(void) {
if (!coap_hitls_started) {
int32_t ret = CRYPT_EAL_Init(CRYPT_EAL_INIT_ALL);
if (ret != CRYPT_SUCCESS) {
coap_log_err("CRYPT_EAL_Init() returned 0x%x\n", (unsigned int)ret);
return 0;
}
#if COAP_WITH_LIBOPENHITLS
ret = HITLS_CertMethodInit();
if (ret != HITLS_SUCCESS) {
coap_log_err("HITLS_CertMethodInit() returned 0x%x\n",
(unsigned int)ret);
CRYPT_EAL_Cleanup(CRYPT_EAL_INIT_ALL);
return 0;
}
HITLS_CryptMethodInit();
#endif /* COAP_WITH_LIBOPENHITLS */
coap_hitls_started = 1;
}
return coap_hitls_started;
}
#if COAP_WITH_LIBOPENHITLS
static char *
coap_hitls_strdup(const char *s) {
size_t len;
char *copy;
if (!s)
return NULL;
len = strlen(s);
copy = (char *)coap_malloc_type(COAP_STRING, len + 1);
if (!copy)
return NULL;
memcpy(copy, s, len + 1);
return copy;
}
static uint8_t *
coap_hitls_read_file(const char *file, uint32_t *buf_len) {
FILE *fp;
long file_len;
uint8_t *buf = NULL;
size_t read_len;
if (!file || !buf_len)
return NULL;
fp = fopen(file, "rb");
if (!fp)
return NULL;
if (fseek(fp, 0, SEEK_END) != 0)
goto fail;
file_len = ftell(fp);
if (file_len <= 0 || (uintmax_t)file_len > UINT32_MAX)
goto fail;
if (fseek(fp, 0, SEEK_SET) != 0)
goto fail;
buf = (uint8_t *)coap_malloc_type(COAP_STRING, (size_t)file_len);
if (!buf)
goto fail;
read_len = fread(buf, 1, (size_t)file_len, fp);
if (read_len != (size_t)file_len) {
coap_free_type(COAP_STRING, buf);
buf = NULL;
goto fail;
}
fclose(fp);
*buf_len = (uint32_t)read_len;
return buf;
fail:
fclose(fp);
return NULL;
}
static size_t
coap_hitls_strnlen(const uint8_t *s, size_t max_len) {
size_t len = 0;
if (!s)
return 0;
while (len < max_len && s[len])
len++;
return len;
}
static uint32_t
coap_hitls_copy_bin(uint8_t *dst, uint32_t dst_len,
const coap_bin_const_t *src, int add_nul) {
size_t extra = add_nul ? 1 : 0;
if (!dst || !src || !src->s ||
extra > (size_t)dst_len || src->length > (size_t)dst_len - extra)
return 0;
memcpy(dst, src->s, src->length);
if (add_nul)
dst[src->length] = '\000';
return (uint32_t)src->length;
}
#if COAP_SERVER_SUPPORT
static int
coap_hitls_cookie_mac(coap_session_t *session, uint8_t *cookie,
uint32_t *cookie_len) {
static const uint8_t cookie_label[] = "libcoap openhitls dtls cookie";
coap_hitls_context_t *context;
CRYPT_EAL_MacCtx *ctx = NULL;
uint32_t out_len;
int ret = 0;
if (!session || !session->context || !cookie || !cookie_len ||
*cookie_len < COAP_HITLS_COOKIE_LEN ||
session->addr_info.local.size == 0 ||
session->addr_info.remote.size == 0)
return 0;
context = (coap_hitls_context_t *)session->context->dtls_context;
if (!context || !context->cookie_secret_set)
return 0;
ctx = CRYPT_EAL_MacNewCtx(CRYPT_MAC_HMAC_SHA256);
if (!ctx)
return 0;
out_len = *cookie_len;
if (CRYPT_EAL_MacInit(ctx, context->cookie_secret,
COAP_HITLS_COOKIE_SECRET_LEN) != CRYPT_SUCCESS)
goto finish;
if (CRYPT_EAL_MacUpdate(ctx, cookie_label,
(uint32_t)sizeof(cookie_label) - 1) != CRYPT_SUCCESS)
goto finish;
if (CRYPT_EAL_MacUpdate(ctx,
(const uint8_t *)&session->addr_info.local.addr,
(uint32_t)session->addr_info.local.size) != CRYPT_SUCCESS)
goto finish;
if (CRYPT_EAL_MacUpdate(ctx,
(const uint8_t *)&session->addr_info.remote.addr,
(uint32_t)session->addr_info.remote.size) != CRYPT_SUCCESS)
goto finish;
if (CRYPT_EAL_MacFinal(ctx, cookie, &out_len) != CRYPT_SUCCESS ||
out_len != COAP_HITLS_COOKIE_LEN)
goto finish;
*cookie_len = out_len;
ret = 1;
finish:
CRYPT_EAL_MacFreeCtx(ctx);
return ret;
}
static int
coap_hitls_cookie_equal(const uint8_t *a, const uint8_t *b, uint32_t len) {
uint8_t diff = 0;
uint32_t i;
for (i = 0; i < len; i++)
diff |= (uint8_t)(a[i] ^ b[i]);
return diff == 0;
}
static int32_t
coap_hitls_cookie_gen_cb(HITLS_Ctx *ctx, uint8_t *cookie,
uint32_t *cookie_len) {
coap_session_t *session = (coap_session_t *)HITLS_GetUserData(ctx);
return coap_hitls_cookie_mac(session, cookie, cookie_len) ?
HITLS_COOKIE_GENERATE_SUCCESS : HITLS_COOKIE_GENERATE_ERROR;
}
static int32_t
coap_hitls_cookie_verify_cb(HITLS_Ctx *ctx, const uint8_t *cookie,
uint32_t cookie_len) {
uint8_t expected[COAP_HITLS_COOKIE_LEN];
uint32_t expected_len = sizeof(expected);
coap_session_t *session = (coap_session_t *)HITLS_GetUserData(ctx);
if (!cookie || cookie_len != COAP_HITLS_COOKIE_LEN ||
!coap_hitls_cookie_mac(session, expected, &expected_len) ||
expected_len != cookie_len ||
!coap_hitls_cookie_equal(cookie, expected, cookie_len))
return HITLS_COOKIE_VERIFY_ERROR;
return HITLS_COOKIE_VERIFY_SUCCESS;
}
static uint32_t
coap_hitls_u24(const uint8_t *p) {
return ((uint32_t)p[0] << 16) | ((uint32_t)p[1] << 8) | p[2];
}
static int
coap_hitls_client_hello_cookie_valid(coap_session_t *session,
const uint8_t *data, size_t data_len) {
uint8_t expected[COAP_HITLS_COOKIE_LEN];
uint32_t expected_len = sizeof(expected);
size_t body_offset = 13 + 12;
size_t body_end;
size_t offset;
uint32_t record_len;
uint32_t hs_len;
uint32_t frag_offset;
uint32_t frag_len;
uint8_t session_id_len;
uint8_t cookie_len;
if (!data || data_len < body_offset || data[0] != 22 || data[13] != 1)
return -1;
record_len = ((uint32_t)data[11] << 8) | data[12];
hs_len = coap_hitls_u24(&data[14]);
frag_offset = coap_hitls_u24(&data[19]);
frag_len = coap_hitls_u24(&data[22]);
if (record_len > data_len - 13 || hs_len > record_len - 12 ||
frag_offset != 0 || frag_len != hs_len)
return -1;
body_end = body_offset + hs_len;
if (body_end > data_len || body_end < body_offset + 35)
return -1;
offset = body_offset + 34;
session_id_len = data[offset++];
if (offset + session_id_len + 1 > body_end)
return -1;
offset += session_id_len;
cookie_len = data[offset++];
if (cookie_len == 0)
return 0;
if (offset + cookie_len > body_end ||
cookie_len != COAP_HITLS_COOKIE_LEN ||
!coap_hitls_cookie_mac(session, expected, &expected_len) ||
expected_len != cookie_len)
return -1;
return coap_hitls_cookie_equal(&data[offset], expected, cookie_len) ? 1 : -1;
}
#endif /* COAP_SERVER_SUPPORT */
static int
coap_hitls_pki_len(const uint8_t *buf, size_t len, HITLS_ParseFormat format,
uint32_t *out_len) {
if (!buf)
return 0;
if (format == TLS_PARSE_FORMAT_PEM && len && buf[len - 1] == '\000')
len--;
if (len > UINT32_MAX)
return 0;
*out_len = (uint32_t)len;
return 1;
}
static int
coap_hitls_key_define_supported(coap_pki_define_t define) {
switch (define) {
case COAP_PKI_KEY_DEF_PEM:
case COAP_PKI_KEY_DEF_PEM_BUF:
case COAP_PKI_KEY_DEF_DER:
case COAP_PKI_KEY_DEF_DER_BUF:
return 1;
case COAP_PKI_KEY_DEF_RPK_BUF:
case COAP_PKI_KEY_DEF_PKCS11:
case COAP_PKI_KEY_DEF_PKCS11_RPK:
case COAP_PKI_KEY_DEF_ENGINE:
default:
return 0;
}
}
static int
coap_hitls_check_define_key(coap_dtls_key_t *key, coap_define_issue_key_t type,
coap_pki_define_t define,
const coap_dtls_role_t role) {
if (coap_hitls_key_define_supported(define))
return 1;
return coap_dtls_define_issue(type, COAP_DEFINE_FAIL_NOT_SUPPORTED, key,
role, 0);
}
static int
coap_hitls_check_pki_key_supported(const coap_dtls_pki_t *setup_data,
const coap_dtls_role_t role) {
coap_dtls_key_t key;
if (setup_data->is_rpk_not_cert) {
coap_log_warn("openHiTLS backend has no RPK support\n");
return 0;
}
if (setup_data->pki_key.key_type == COAP_PKI_KEY_PKCS11) {
coap_log_warn("openHiTLS backend has no PKCS11 support\n");
return 0;
}
coap_dtls_map_key_type_to_define(setup_data, &key);
if (key.key_type != COAP_PKI_KEY_DEFINE)
return 0;
return coap_hitls_check_define_key(&key, COAP_DEFINE_KEY_CA,
key.key.define.ca_def, role) &&
coap_hitls_check_define_key(&key, COAP_DEFINE_KEY_PUBLIC,
key.key.define.public_cert_def, role) &&
coap_hitls_check_define_key(&key, COAP_DEFINE_KEY_PRIVATE,
key.key.define.private_key_def, role);
}
static int
coap_hitls_verify_error_allowed(const coap_dtls_pki_t *setup_data,
int32_t err_code) {
if (err_code == HITLS_PKI_SUCCESS)
return 1;
if (!setup_data || !setup_data->verify_peer_cert)
return 1;
switch (err_code) {
case HITLS_X509_ERR_TIME_EXPIRED:
case HITLS_X509_ERR_TIME_FUTURE:
case HITLS_X509_ERR_VFY_NOTBEFORE_IN_FUTURE:
case HITLS_X509_ERR_VFY_NOTAFTER_EXPIRED:
return setup_data->allow_expired_certs;
case HITLS_X509_ERR_VFY_CRL_NOT_FOUND:
return !setup_data->check_cert_revocation || setup_data->allow_no_crl;
case HITLS_X509_ERR_VFY_THISUPDATE_IN_FUTURE:
case HITLS_X509_ERR_VFY_NEXTUPDATE_EXPIRED:
return !setup_data->check_cert_revocation ||
setup_data->allow_expired_crl;
default:
return 0;
}
}
static int
coap_hitls_get_verify_session(HITLS_CERT_StoreCtx *store_ctx,
coap_session_t **session) {
HITLS_Ctx *ctx = NULL;
if (!store_ctx || !session)
return 0;
*session = NULL;
if (HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store_ctx,
HITLS_X509_STORECTX_GET_USR_DATA,
&ctx, sizeof(ctx)) != HITLS_PKI_SUCCESS ||
!ctx)
return 0;
*session = (coap_session_t *)HITLS_GetUserData(ctx);
return *session != NULL;
}
static int
coap_hitls_get_verify_cert(HITLS_CERT_StoreCtx *store_ctx,
HITLS_X509_Cert **cert, int32_t *depth) {
if (!store_ctx || !cert || !depth)
return 0;
*cert = NULL;
*depth = 0;
(void)HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store_ctx,
HITLS_X509_STORECTX_GET_CUR_DEPTH,
depth, sizeof(*depth));
return HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store_ctx,
HITLS_X509_STORECTX_GET_CUR_CERT,
cert, sizeof(*cert)) == HITLS_PKI_SUCCESS &&
*cert;
}
static int
coap_hitls_cert_is_self_signed(HITLS_X509_Cert *cert) {
bool self_signed = false;
return cert &&
HITLS_X509_CertCtrl(cert, HITLS_X509_IS_SELF_SIGNED,
&self_signed,
sizeof(self_signed)) == HITLS_PKI_SUCCESS &&
self_signed;
}
/*
* The self-signed override bypasses the library chain verification, which is
* where the validity period is normally checked. Apply the same check here,
* using the library time helpers, so an expired or not-yet-valid self-signed
* leaf is not accepted. Returns HITLS_PKI_SUCCESS or a specific failure code.
*/
static int32_t
coap_hitls_cert_time_valid(HITLS_X509_Cert *cert) {
BSL_TIME not_before;
BSL_TIME not_after;
int64_t start;
int64_t end;
int64_t now = BSL_SAL_CurrentSysTimeGet();
if (now <= 0)
return BSL_SAL_TIME_SYS_ERROR;
if (HITLS_X509_CertCtrl(cert, HITLS_X509_GET_BEFORE_TIME, ¬_before,
sizeof(not_before)) != HITLS_PKI_SUCCESS ||
BSL_SAL_DateToUtcTimeConvert(¬_before, &start) != BSL_SUCCESS)
return HITLS_X509_ERR_VFY_GET_NOTBEFORE_FAIL;
if (start > now)
return HITLS_X509_ERR_VFY_NOTBEFORE_IN_FUTURE;
if (HITLS_X509_CertCtrl(cert, HITLS_X509_GET_AFTER_TIME, ¬_after,
sizeof(not_after)) != HITLS_PKI_SUCCESS ||
BSL_SAL_DateToUtcTimeConvert(¬_after, &end) != BSL_SUCCESS)
return HITLS_X509_ERR_VFY_GET_NOTAFTER_FAIL;
if (end < now)
return HITLS_X509_ERR_VFY_NOTAFTER_EXPIRED;
return HITLS_PKI_SUCCESS;
}
static int
coap_hitls_get_peer_leaf_cert(HITLS_CERT_StoreCtx *store_ctx,
HITLS_X509_Cert **cert,
int32_t *chain_count) {
HITLS_X509_List *peer_chain = NULL;
if (!store_ctx || !cert || !chain_count)
return 0;
*cert = NULL;
*chain_count = 0;
if (HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store_ctx,
HITLS_X509_STORECTX_GET_PEER_CERT_CHAIN,
&peer_chain,
sizeof(peer_chain)) != HITLS_PKI_SUCCESS ||
!peer_chain)
return 0;
*chain_count = BSL_LIST_COUNT(peer_chain);
*cert = (HITLS_X509_Cert *)BSL_LIST_FIRST_ELMT(peer_chain);
return *cert != NULL;
}
static int
coap_hitls_self_signed_leaf_allowed(const coap_dtls_pki_t *setup_data,
HITLS_CERT_StoreCtx *store_ctx,
HITLS_X509_Cert **leaf_cert) {
HITLS_X509_Cert *cert = NULL;
int32_t chain_count = 0;
if (leaf_cert)
*leaf_cert = NULL;
if (!setup_data || !setup_data->allow_self_signed ||
setup_data->check_common_ca)
return 0;
if (!coap_hitls_get_peer_leaf_cert(store_ctx, &cert, &chain_count) ||
chain_count != 1 || !coap_hitls_cert_is_self_signed(cert))
return 0;
if (leaf_cert)
*leaf_cert = cert;
return 1;
}
static int
coap_hitls_verify_cb_self_signed_allowed(const coap_dtls_pki_t *setup_data,
HITLS_CERT_StoreCtx *store_ctx) {
HITLS_X509_Cert *cert = NULL;
int32_t depth = 0;
return setup_data && setup_data->allow_self_signed &&
!setup_data->check_common_ca &&
coap_hitls_get_verify_cert(store_ctx, &cert, &depth) &&
depth == 0 && coap_hitls_cert_is_self_signed(cert);
}
static char *
coap_hitls_copy_name(const uint8_t *data, uint32_t data_len) {
char *copy;
size_t len = (size_t)data_len;
if (data_len && !data)
return NULL;
copy = (char *)coap_malloc_type(COAP_STRING, len + 1);
if (!copy)
return NULL;
if (len)
memcpy(copy, data, len);
copy[len] = '\000';
return copy;
}
static char *
coap_hitls_get_san_from_cert(coap_session_t *session, HITLS_X509_Cert *cert,
const char *sni_match, int report_san) {
HITLS_X509_ExtSan san = {0};
char *dns_name = NULL;
if (HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_SAN, &san,
sizeof(san)) == HITLS_PKI_SUCCESS &&
san.names) {
int n = 0;
for (BslListNode *name_node = BSL_LIST_FirstNode(san.names);
name_node != NULL;
name_node = BSL_LIST_GetNextNode(san.names, name_node)) {
const HITLS_X509_GeneralName *name =
(const HITLS_X509_GeneralName *)BSL_LIST_GetData(name_node);
if (!name || name->type != HITLS_X509_GN_DNS)
continue;
if (name->value.dataLen &&
memchr(name->value.data, '\000', name->value.dataLen))
continue;
if (report_san) {
coap_log_debug(" %s: got DNS.%d '%*.*s'\n",
coap_session_str(session), n + 1, (int)name->value.dataLen, (int)name->value.dataLen,
name->value.data);
n++;
continue;
}
if (sni_match) {
if (strlen(sni_match) != name->value.dataLen ||
memcmp(name->value.data, sni_match, name->value.dataLen)) {
continue;
}
}
dns_name = coap_hitls_copy_name(name->value.data, name->value.dataLen);
break;
}
}
HITLS_X509_ClearSubjectAltName(&san);
return dns_name;
}
static char *
coap_hitls_get_cn_from_cert(coap_session_t *session, HITLS_X509_Cert *cert, const char *sni_match) {
BSL_Buffer cn = {0};
char *cn_name = NULL;
if (HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SUBJECT_CN_STR,
&cn, sizeof(cn)) == HITLS_PKI_SUCCESS) {
if (cn.data && coap_pki_name_match_sni((char *)cn.data, cn.dataLen, sni_match)) {
cn_name = coap_hitls_copy_name(cn.data, cn.dataLen);
}
}
if (cn.data && !cn_name) {
coap_log_debug(" %s: got CN '%*.*s'\n",
coap_session_str(session), (int)cn.dataLen, (int)cn.dataLen, cn.data);
}
if (cn.data)
BSL_SAL_Free(cn.data);
return cn_name;
}
static char *
coap_hitls_get_san_or_cn_from_cert(coap_session_t *session, HITLS_X509_Cert *cert,
const char *sni_match) {
char *name;
if (!cert)
return NULL;
name = coap_hitls_get_san_from_cert(session, cert, sni_match, 0);
if (name)
return name;
name = coap_hitls_get_cn_from_cert(session, cert, sni_match);
if (!name) {
name = coap_hitls_get_san_from_cert(session, cert, sni_match, 1);
}
return name;
}
static int
coap_hitls_validate_cn_cert(coap_session_t *session,
const coap_dtls_pki_t *setup_data,
HITLS_X509_Cert *cert,
unsigned depth,
int validated,
char **san_or_cn) {
uint8_t *der = NULL;
uint32_t der_len = 0;
int ret = 1;
(void)HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODELEN,
&der_len, sizeof(der_len));
if (der_len)
(void)HITLS_X509_CertCtrl(cert, HITLS_X509_GET_ENCODE,
&der, sizeof(der));
if (!*san_or_cn)
*san_or_cn = coap_hitls_get_san_or_cn_from_cert(session, cert, NULL);
if (setup_data->validate_cn_call_back) {
coap_lock_callback_ret(ret,
setup_data->validate_cn_call_back(
*san_or_cn ? *san_or_cn : "",
der, der_len, session, depth, validated,
setup_data->cn_call_back_arg));
}
return ret;
}
static int
coap_hitls_verify_cb(int32_t err_code, HITLS_CERT_StoreCtx *store_ctx) {
coap_session_t *session = NULL;
coap_hitls_context_t *context;
coap_dtls_pki_t *setup_data;
HITLS_X509_Cert *cert;
int32_t depth;
int allowed;
char *san_or_cn = NULL;
if (!coap_hitls_get_verify_session(store_ctx, &session) ||
!session->context || !session->context->dtls_context)
return err_code;
context = (coap_hitls_context_t *)session->context->dtls_context;
setup_data = &context->setup_data;
if (!coap_hitls_get_verify_cert(store_ctx, &cert, &depth)) {
return err_code;
}
if (!setup_data->allow_sni_cn_mismatch && depth <= 0 &&
session->type == COAP_SESSION_TYPE_CLIENT && setup_data->client_sni) {
san_or_cn = coap_hitls_get_san_or_cn_from_cert(session, cert, setup_data->client_sni);
if (!san_or_cn) {
/* No match on returned Cert for requested host */
coap_log_warn("* %s: SNI '%s' not returned in certificate\n",
coap_session_str(session),
setup_data->client_sni);
return HITLS_X509_ERR_VFY_HOSTNAME_FAIL;
}
}
if (setup_data->validate_cn_call_back) {
if (!coap_hitls_validate_cn_cert(session, setup_data, cert,
depth < 0 ? 0 : (unsigned)depth,
err_code == HITLS_PKI_SUCCESS, &san_or_cn)) {
coap_log_warn("* %s: certificate verification failed: %s\n",
coap_session_str(session),
coap_hitls_verify_err_str(HITLS_X509_ERR_VFY_HOSTNAME_FAIL));
if (san_or_cn)
coap_free_type(COAP_STRING, san_or_cn);
return HITLS_X509_ERR_VFY_HOSTNAME_FAIL;
}
}
if (san_or_cn)
coap_free_type(COAP_STRING, san_or_cn);
if (err_code == HITLS_X509_ERR_ISSUE_CERT_NOT_FOUND ||
err_code == HITLS_X509_ERR_ROOT_CERT_NOT_FOUND) {
allowed = coap_hitls_verify_cb_self_signed_allowed(setup_data,
store_ctx);
} else {
allowed = coap_hitls_verify_error_allowed(setup_data, err_code);
}
if (!allowed) {
coap_log_warn("* %s: certificate verification failed: %s (0x%x)\n",
coap_session_str(session),
coap_hitls_verify_err_str(err_code), (unsigned int)err_code);
return err_code;
}
return HITLS_PKI_SUCCESS;
}
static int32_t
coap_hitls_app_verify_cb(HITLS_CERT_StoreCtx *store_ctx,
void *arg COAP_UNUSED) {
coap_session_t *session = NULL;
coap_hitls_context_t *context;
coap_dtls_pki_t *setup_data;
HITLS_X509_List *peer_chain = NULL;
HITLS_X509_Cert *leaf_cert = NULL;
int32_t ret;
if (!coap_hitls_get_verify_session(store_ctx, &session) ||
!session->context || !session->context->dtls_context)
return HITLS_X509_ERR_INVALID_PARAM;
if (HITLS_X509_StoreCtxCtrl((HITLS_X509_StoreCtx *)store_ctx,
HITLS_X509_STORECTX_GET_PEER_CERT_CHAIN,
&peer_chain,
sizeof(peer_chain)) != HITLS_PKI_SUCCESS ||
!peer_chain)
return HITLS_X509_ERR_INVALID_PARAM;