-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathsession_mbedtls.c
More file actions
2570 lines (2247 loc) · 82.9 KB
/
session_mbedtls.c
File metadata and controls
2570 lines (2247 loc) · 82.9 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
/**
* @file session_mbedtls.c
* @author Roman Janota <janota@cesnet.cz>
* @brief libnetconf2 - wrapped MbedTLS function calls for TLS/asymmetric cryptography support
*
* This file is a wrapper for MbedTLS function calls. The implementation is done
* in such a way that the original libnetconf2 code is not dependent on MbedTLS.
* This file is included in the build process only if MbedTLS is being used.
*
* @copyright
* Copyright (c) 2024 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <curl/curl.h>
#include "compat.h"
#include "config.h"
#include "log_p.h"
#include "session.h"
#include "session_p.h"
#include "session_wrapper.h"
#include <libssh/libssh.h>
#include <mbedtls/base64.h>
#include <mbedtls/bignum.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
#include <mbedtls/error.h>
#include <mbedtls/net_sockets.h>
#include <mbedtls/oid.h>
#include <mbedtls/pem.h>
#include <mbedtls/ssl.h>
#include <mbedtls/x509.h>
#include <mbedtls/x509_crl.h>
#include <mbedtls/x509_crt.h>
/**
* @brief List of supported cipher suites for MbedTLS.
*
* This list is used to populate the operational data for supported cipher suites.
* Obtained from <mbedtls/cipher_suites.h> v4.0.0.
*/
const char *nc_tls_supported_cipher_suites[] = {
"TLS_PSK_WITH_NULL_SHA", "TLS_PSK_WITH_AES_128_CBC_SHA", "TLS_PSK_WITH_AES_256_CBC_SHA",
"TLS_PSK_WITH_AES_128_GCM_SHA256", "TLS_PSK_WITH_AES_256_GCM_SHA384", "TLS_PSK_WITH_AES_128_CBC_SHA256",
"TLS_PSK_WITH_AES_256_CBC_SHA384", "TLS_PSK_WITH_NULL_SHA256", "TLS_PSK_WITH_NULL_SHA384",
"TLS_ECDHE_ECDSA_WITH_NULL_SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_RSA_WITH_NULL_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_PSK_WITH_NULL_SHA", "TLS_ECDHE_PSK_WITH_NULL_SHA256",
"TLS_ECDHE_PSK_WITH_NULL_SHA384", "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384", "TLS_PSK_WITH_ARIA_128_CBC_SHA256", "TLS_PSK_WITH_ARIA_256_CBC_SHA384",
"TLS_PSK_WITH_ARIA_128_GCM_SHA256", "TLS_PSK_WITH_ARIA_256_GCM_SHA384", "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256",
"TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256",
"TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384", "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256",
"TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384", "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256",
"TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384", "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256",
"TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384", "TLS_PSK_WITH_AES_128_CCM", "TLS_PSK_WITH_AES_256_CCM",
"TLS_PSK_WITH_AES_128_CCM_8", "TLS_PSK_WITH_AES_256_CCM_8", "TLS_ECDHE_ECDSA_WITH_AES_128_CCM",
"TLS_ECDHE_ECDSA_WITH_AES_256_CCM", "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8", "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8",
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_PSK_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", NULL
};
/**
* @brief Converts MbedTLS error code to a string and merges it with an arbitrary error message.
*
* @param[in] session NETCONF session.
* @param[in] mbedtls_err_code MbedTLS error code.
* @param[in] orig_err_msg_fmt Original error message format string.
* @param[in] ... Additional arguments for the original error message.
*/
static void
nc_mbedtls_strerr(const struct nc_session *session, int mbedtls_err_code, const char *orig_err_msg_fmt, ...)
{
va_list args;
char *err_buf = NULL, *err_msg_fmt = NULL;
size_t err_buf_len = 0, err_msg_fmt_len = 0;
const char *high_err_str, *low_err_str;
va_start(args, orig_err_msg_fmt);
/* get the length of the error strings */
high_err_str = mbedtls_high_level_strerr(mbedtls_err_code);
low_err_str = mbedtls_low_level_strerr(mbedtls_err_code);
if (high_err_str) {
err_buf_len += strlen(high_err_str);
}
if (low_err_str) {
err_buf_len += strlen(low_err_str);
}
if (!err_buf_len) {
/* just print the original error message */
nc_log_vprintf(session, NC_VERB_ERROR, orig_err_msg_fmt, args);
goto cleanup;
}
if (high_err_str && low_err_str) {
/* for a colon and 2 spaces */
err_buf_len += 3;
}
/* allocate the mbedtls error buffer */
err_buf = malloc(err_buf_len + 1);
if (!err_buf) {
/* just print the original error message */
nc_log_vprintf(session, NC_VERB_ERROR, orig_err_msg_fmt, args);
goto cleanup;
}
/* fill the error buffer and print it */
if (high_err_str && low_err_str) {
snprintf(err_buf, err_buf_len + 1, "%s : %s", high_err_str, low_err_str);
} else if (high_err_str) {
snprintf(err_buf, err_buf_len + 1, "%s", high_err_str);
} else {
snprintf(err_buf, err_buf_len + 1, "%s", low_err_str);
}
/* allocate the new error format string buffer, err_msg = "orig_err_msg (MbedTLS err)." */
err_msg_fmt_len = strlen(orig_err_msg_fmt) + strlen(" (") + strlen(err_buf) + strlen(").");
err_msg_fmt = malloc(err_msg_fmt_len + 1);
if (!err_msg_fmt) {
/* just print the original error message */
nc_log_vprintf(session, NC_VERB_ERROR, orig_err_msg_fmt, args);
goto cleanup;
}
/* fill the new error format string */
snprintf(err_msg_fmt, err_msg_fmt_len + 1, "%s (%s).", orig_err_msg_fmt, err_buf);
/* print the error message */
nc_log_vprintf(session, NC_VERB_ERROR, err_msg_fmt, args);
cleanup:
va_end(args);
free(err_msg_fmt);
free(err_buf);
}
/**
* @brief Converts DN to a string.
*
* @param[in] dn Internal DN representation.
* @return DN string on success, NULL of fail.
*/
static char *
nc_server_tls_dn2str(const mbedtls_x509_name *dn)
{
char *str;
size_t len = 64;
int r;
str = malloc(len);
NC_CHECK_ERRMEM_RET(!str, NULL);
while ((r = mbedtls_x509_dn_gets(str, len, dn)) == MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) {
len <<= 1;
str = nc_realloc(str, len);
NC_CHECK_ERRMEM_RET(!str, NULL);
}
if (r < 1) {
free(str);
nc_mbedtls_strerr(NULL, r, "Failed to convert DN to string");
return NULL;
}
return str;
}
/**
* @brief Create a new random number generator context.
*
* @param[out] ctr_drbg Random bit generator context.
* @param[out] entropy Entropy context.
* @return 0 on success, 1 on failure.
*/
static int
nc_tls_rng_new(mbedtls_ctr_drbg_context **ctr_drbg, mbedtls_entropy_context **entropy)
{
int rc;
*ctr_drbg = NULL;
*entropy = NULL;
*entropy = malloc(sizeof **entropy);
NC_CHECK_ERRMEM_GOTO(!*entropy, , fail);
*ctr_drbg = malloc(sizeof **ctr_drbg);
NC_CHECK_ERRMEM_GOTO(!*ctr_drbg, , fail);
mbedtls_entropy_init(*entropy);
mbedtls_ctr_drbg_init(*ctr_drbg);
rc = mbedtls_ctr_drbg_seed(*ctr_drbg, mbedtls_entropy_func, *entropy, NULL, 0);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Seeding ctr_drbg failed");
goto fail;
}
return 0;
fail:
mbedtls_ctr_drbg_free(*ctr_drbg);
free(*ctr_drbg);
if (*entropy) {
mbedtls_entropy_free(*entropy);
free(*entropy);
}
*ctr_drbg = NULL;
*entropy = NULL;
return 1;
}
/**
* @brief Destroy the random number generator context.
*
* @param[in] ctr_drbg Random bit generator context.
* @param[in] entropy Entropy context.
*/
static void
nc_tls_rng_destroy(mbedtls_ctr_drbg_context *ctr_drbg, mbedtls_entropy_context *entropy)
{
mbedtls_ctr_drbg_free(ctr_drbg);
free(ctr_drbg);
if (entropy) {
mbedtls_entropy_free(entropy);
free(entropy);
}
}
/**
* @brief Get a string representation of the verification error.
*
* @param[in] err Verification error code.
* @return String representation of the error. Caller is responsible for freeing it.
*/
static char *
nc_tls_get_verify_err_str(int err)
{
int ret;
char *err_buf = NULL;
err_buf = malloc(256);
NC_CHECK_ERRMEM_RET(!err_buf, NULL);
ret = mbedtls_x509_crt_verify_info(err_buf, 256, "", err);
if (ret < 0) {
free(err_buf);
return NULL;
}
/* strip the NL */
err_buf[ret - 1] = '\0';
return err_buf;
}
int
nc_tls_backend_init_wrap(void)
{
int r;
r = psa_crypto_init();
if (r) {
nc_mbedtls_strerr(NULL, r, "Failed to initialize PSA crypto");
return -1;
}
return 0;
}
void
nc_tls_backend_destroy_wrap(void)
{
mbedtls_psa_crypto_free();
}
void *
nc_tls_session_new_wrap(void *tls_cfg)
{
int rc;
mbedtls_ssl_context *session;
session = malloc(sizeof *session);
NC_CHECK_ERRMEM_RET(!session, NULL);
mbedtls_ssl_init(session);
rc = mbedtls_ssl_setup(session, tls_cfg);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Setting up TLS session failed");
mbedtls_ssl_free(session);
free(session);
return NULL;
}
return session;
}
void
nc_tls_session_destroy_wrap(void *tls_session)
{
mbedtls_ssl_free(tls_session);
free(tls_session);
}
void *
nc_tls_config_new_wrap(int side)
{
int r;
mbedtls_ssl_config *tls_cfg;
tls_cfg = malloc(sizeof *tls_cfg);
NC_CHECK_ERRMEM_RET(!tls_cfg, NULL);
mbedtls_ssl_config_init(tls_cfg);
/* set default config data */
if (side == NC_SERVER) {
r = mbedtls_ssl_config_defaults(tls_cfg, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
} else {
r = mbedtls_ssl_config_defaults(tls_cfg, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
}
if (r) {
nc_mbedtls_strerr(NULL, r, "Setting default TLS config failed");
mbedtls_ssl_config_free(tls_cfg);
free(tls_cfg);
return NULL;
}
return tls_cfg;
}
void
nc_tls_config_destroy_wrap(void *tls_cfg)
{
if (!tls_cfg) {
return;
}
mbedtls_ssl_config_free(tls_cfg);
free(tls_cfg);
}
void *
nc_tls_cert_new_wrap(void)
{
mbedtls_x509_crt *cert;
cert = malloc(sizeof *cert);
NC_CHECK_ERRMEM_RET(!cert, NULL);
mbedtls_x509_crt_init(cert);
return cert;
}
void
nc_tls_cert_destroy_wrap(void *cert)
{
mbedtls_x509_crt_free(cert);
free(cert);
}
/**
* @brief Create a new private key context.
*
* @return New private key context or NULL.
*/
static void *
nc_tls_pkey_new_wrap(void)
{
mbedtls_pk_context *pkey;
pkey = malloc(sizeof *pkey);
NC_CHECK_ERRMEM_RET(!pkey, NULL);
mbedtls_pk_init(pkey);
return pkey;
}
void
nc_tls_privkey_destroy_wrap(void *pkey)
{
mbedtls_pk_free(pkey);
free(pkey);
}
void *
nc_tls_cert_store_new_wrap(void)
{
/* certificate is the same as a certificate store in MbedTLS */
return nc_tls_cert_new_wrap();
}
void
nc_tls_cert_store_destroy_wrap(void *cert_store)
{
/* certificate is the same as a certificate store in MbedTLS */
nc_tls_cert_destroy_wrap(cert_store);
}
void *
nc_tls_crl_store_new_wrap(void)
{
mbedtls_x509_crl *crl;
crl = malloc(sizeof *crl);
NC_CHECK_ERRMEM_RET(!crl, NULL);
mbedtls_x509_crl_init(crl);
return crl;
}
void
nc_tls_crl_store_destroy_wrap(void *crl_store)
{
mbedtls_x509_crl_free(crl_store);
free(crl_store);
}
void *
nc_tls_pem_to_cert_wrap(const char *cert_data)
{
int rc;
mbedtls_x509_crt *cert;
cert = nc_tls_cert_new_wrap();
if (!cert) {
return NULL;
}
rc = mbedtls_x509_crt_parse(cert, (const unsigned char *)cert_data, strlen(cert_data) + 1);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Parsing certificate data failed");
nc_tls_cert_destroy_wrap(cert);
return NULL;
}
return cert;
}
int
nc_tls_add_cert_to_store_wrap(void *cert, void *cert_store)
{
mbedtls_x509_crt *iter;
/* store is a linked list */
iter = cert_store;
while (iter->next) {
iter = iter->next;
}
iter->next = cert;
return 0;
}
void *
nc_tls_pem_to_privkey_wrap(const char *privkey_data)
{
int rc = 0;
mbedtls_pk_context *pkey = NULL;
mbedtls_ctr_drbg_context *ctr_drbg = NULL;
mbedtls_entropy_context *entropy = NULL;
rc = nc_tls_rng_new(&ctr_drbg, &entropy);
if (rc) {
goto cleanup;
}
pkey = nc_tls_pkey_new_wrap();
if (!pkey) {
rc = 1;
goto cleanup;
}
rc = mbedtls_pk_parse_key(pkey, (const unsigned char *)privkey_data, strlen(privkey_data) + 1, NULL, 0, mbedtls_ctr_drbg_random, ctr_drbg);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Parsing private key data failed");
goto cleanup;
}
cleanup:
if (rc) {
nc_tls_privkey_destroy_wrap(pkey);
pkey = NULL;
}
nc_tls_rng_destroy(ctr_drbg, entropy);
return pkey;
}
int
nc_server_tls_add_crl_to_store_wrap(const unsigned char *crl_data, size_t size, void *crl_store)
{
int rc;
/* try DER first */
rc = mbedtls_x509_crl_parse_der(crl_store, crl_data, size);
if (!rc) {
/* success, it was DER */
return 0;
}
/* DER failed, try PEM */
rc = mbedtls_x509_crl_parse(crl_store, crl_data, size + 1);
if (!rc) {
/* success, it was PEM */
return 0;
}
/* failed to parse it */
ERR(NULL, "Reading downloaded CRL failed.");
return 1;
}
int
nc_server_tls_set_tls_versions_wrap(void *tls_cfg, enum nc_tls_version min, enum nc_tls_version max)
{
/* set the minimum version if any, otherwise leave it to MbedTLS default */
if (min & NC_TLS_VERSION_1_2) {
mbedtls_ssl_conf_min_tls_version(tls_cfg, MBEDTLS_SSL_VERSION_TLS1_2);
} else if (min & NC_TLS_VERSION_1_3) {
mbedtls_ssl_conf_min_tls_version(tls_cfg, MBEDTLS_SSL_VERSION_TLS1_3);
}
/* set the maximum version if any, otherwise leave it to MbedTLS default */
if (max & NC_TLS_VERSION_1_3) {
mbedtls_ssl_conf_max_tls_version(tls_cfg, MBEDTLS_SSL_VERSION_TLS1_3);
} else if (max & NC_TLS_VERSION_1_2) {
mbedtls_ssl_conf_max_tls_version(tls_cfg, MBEDTLS_SSL_VERSION_TLS1_2);
}
return 0;
}
/**
* @brief Duplicates a certificate.
*
* @param[in] cert Certificate to duplicate.
* @return Duplicated certificate or NULL.
*/
static mbedtls_x509_crt *
nc_tls_cert_dup(const mbedtls_x509_crt *cert)
{
mbedtls_x509_crt *new_cert;
new_cert = nc_tls_cert_new_wrap();
if (!new_cert) {
return NULL;
}
if (mbedtls_x509_crt_parse_der(new_cert, cert->raw.p, cert->raw.len)) {
free(new_cert);
return NULL;
}
return new_cert;
}
/**
* @brief Duplicate a certificate and append it to a chain.
*
* @param[in] cert Certificate to duplicate and append.
* @param[in,out] chain Chain to append the certificate to.
* @return 0 on success, -1 on error.
*/
static int
nc_server_tls_append_cert_to_chain(mbedtls_x509_crt *cert, mbedtls_x509_crt **chain)
{
mbedtls_x509_crt *iter, *copy;
copy = nc_tls_cert_dup(cert);
if (!copy) {
return -1;
}
if (!*chain) {
/* first in the list */
*chain = copy;
} else {
/* find the last cert */
iter = *chain;
while (iter->next) {
iter = iter->next;
}
iter->next = copy;
}
return 0;
}
/**
* @brief Verify a certificate.
*
* @param[in] cb_data Callback data (session, opts, data for CTN).
* @param[in] cert Certificate to verify.
* @param[in] depth Certificate depth in the chain.
* @param[in,out] flags Verification flags. Used to propagate errors.
* @return 0 on success (verification result is based on the value of flags), non-zero on fatal-error.
*/
static int
nc_server_tls_verify_cb(void *cb_data, mbedtls_x509_crt *cert, int depth, uint32_t *flags)
{
int ret = 0;
struct nc_tls_verify_cb_data *data = cb_data;
char *err;
/* append to the chain we're building */
ret = nc_server_tls_append_cert_to_chain(cert, (mbedtls_x509_crt **)&data->chain);
if (ret) {
nc_tls_cert_destroy_wrap(data->chain);
return MBEDTLS_ERR_X509_ALLOC_FAILED;
}
if (!*flags) {
/* in-built verification was successful */
ret = nc_server_tls_verify_cert(cert, depth, 1, data);
} else {
/* in-built verification failed, but the client still may be authenticated if:
* 1) the peer cert matches any configured end-entity cert
* 2) the peer cert has a valid chain of trust to any configured certificate authority cert
* otherwise just continue until we reach the peer cert (depth = 0)
*/
if ((depth == 0) && (*flags == MBEDTLS_X509_BADCERT_NOT_TRUSTED)) {
/* not trusted self-signed peer certificate, case 1) */
ret = nc_server_tls_verify_cert(cert, depth, 0, data);
if (!ret) {
*flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
} else if (*flags == MBEDTLS_X509_BADCERT_MISSING) {
/* full chain of trust is invalid, but it may be valid partially, case 2) */
ret = nc_server_tls_verify_cert(cert, depth, 0, data);
if (!ret) {
*flags &= ~MBEDTLS_X509_BADCERT_MISSING;
}
} else {
err = nc_tls_get_verify_err_str(*flags);
ERR(data->session, "Cert verify: fail (%s).", err);
free(err);
ret = 1;
}
}
if ((ret == -1) || (depth == 0)) {
/* free the chain */
nc_tls_cert_destroy_wrap(data->chain);
}
if (ret == -1) {
/* fatal error */
return MBEDTLS_ERR_X509_ALLOC_FAILED;
} else if (!ret) {
/* success */
if ((depth == 0) && (!data->session->opts.server.client_cert)) {
/* copy the client cert */
data->session->opts.server.client_cert = nc_tls_cert_dup(cert);
if (!data->session->opts.server.client_cert) {
return MBEDTLS_ERR_X509_ALLOC_FAILED;
}
}
return 0;
} else {
if (depth > 0) {
/* chain verify failed, but peer cert can still match */
return 0;
} else {
/* failed to verify peer cert, but return 0 so that we can propagate the error via the flags */
if (!*flags) {
*flags |= MBEDTLS_X509_BADCERT_OTHER;
}
return 0;
}
}
}
void
nc_server_tls_set_verify_wrap(void *tls_cfg, struct nc_tls_verify_cb_data *cb_data)
{
mbedtls_ssl_conf_authmode(tls_cfg, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_verify(tls_cfg, nc_server_tls_verify_cb, cb_data);
}
int
nc_client_tls_set_verify_wrap(void *tls_cfg)
{
mbedtls_ssl_conf_authmode(tls_cfg, MBEDTLS_SSL_VERIFY_REQUIRED);
return 0;
}
char *
nc_server_tls_get_subject_wrap(void *cert)
{
return nc_server_tls_dn2str(&(((mbedtls_x509_crt *)cert)->subject));
}
char *
nc_server_tls_get_issuer_wrap(void *cert)
{
return nc_server_tls_dn2str(&(((mbedtls_x509_crt *)cert)->issuer));
}
void *
nc_tls_get_sans_wrap(void *cert)
{
return &(((mbedtls_x509_crt *)cert)->subject_alt_names);
}
void
nc_tls_sans_destroy_wrap(void *UNUSED(sans))
{
return;
}
int
nc_tls_get_num_sans_wrap(void *sans)
{
mbedtls_x509_sequence *iter;
int n = 0;
/* sans are a linked list */
iter = sans;
while (iter) {
++n;
iter = iter->next;
}
return n;
}
int
nc_tls_get_san_value_type_wrap(void *sans, int idx, char **san_value, NC_TLS_CTN_MAPTYPE *san_type)
{
int i, rc, ret = 0;
mbedtls_x509_sequence *iter;
mbedtls_x509_subject_alternative_name san = {0};
const mbedtls_x509_buf *ip;
*san_value = NULL;
*san_type = NC_TLS_CTN_UNKNOWN;
/* find the SAN */
iter = sans;
for (i = 0; i < idx; i++) {
iter = iter->next;
}
/* parse it */
rc = mbedtls_x509_parse_subject_alt_name(&iter->buf, &san);
if (rc && (rc != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE)) {
return -1;
}
/* get its type and value */
switch (san.type) {
case MBEDTLS_X509_SAN_DNS_NAME:
*san_type = NC_TLS_CTN_SAN_DNS_NAME;
*san_value = strndup((const char *)san.san.unstructured_name.p, san.san.unstructured_name.len);
NC_CHECK_ERRMEM_GOTO(!*san_value, ret = -1, cleanup);
break;
case MBEDTLS_X509_SAN_RFC822_NAME:
*san_type = NC_TLS_CTN_SAN_RFC822_NAME;
*san_value = strndup((const char *)san.san.unstructured_name.p, san.san.unstructured_name.len);
NC_CHECK_ERRMEM_GOTO(!*san_value, ret = -1, cleanup);
break;
case MBEDTLS_X509_SAN_IP_ADDRESS:
*san_type = NC_TLS_CTN_SAN_IP_ADDRESS;
ip = &san.san.unstructured_name;
if (ip->len == 4) {
rc = asprintf(san_value, "%d.%d.%d.%d", ip->p[0], ip->p[1], ip->p[2], ip->p[3]) == -1;
NC_CHECK_ERRMEM_GOTO(rc == -1, ret = -1, cleanup);
} else if (ip->len == 16) {
rc = asprintf(san_value, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
ip->p[0], ip->p[1], ip->p[2], ip->p[3], ip->p[4], ip->p[5],
ip->p[6], ip->p[7], ip->p[8], ip->p[9], ip->p[10], ip->p[11],
ip->p[12], ip->p[13], ip->p[14], ip->p[15]);
NC_CHECK_ERRMEM_GOTO(rc == -1, ret = -1, cleanup);
} else {
WRN(NULL, "SAN IP address in an unknown format (length is %d).", ip->len);
ret = 1;
}
break;
default:
/* we dont care about other types */
*san_type = NC_TLS_CTN_UNKNOWN;
ret = 1;
break;
}
cleanup:
mbedtls_x509_free_subject_alt_name(&san);
return ret;
}
int
nc_tls_get_num_certs_wrap(void *chain)
{
mbedtls_x509_crt *iter;
int n = 0;
/* chain is a linked list */
iter = chain;
while (iter) {
++n;
iter = iter->next;
}
return n;
}
void
nc_tls_get_cert_wrap(void *chain, int idx, void **cert)
{
int i;
mbedtls_x509_crt *iter;
iter = chain;
for (i = 0; i < idx; i++) {
iter = iter->next;
}
*cert = iter;
}
int
nc_server_tls_certs_match_wrap(void *cert1, void *cert2)
{
mbedtls_x509_crt *c1 = cert1;
mbedtls_x509_crt *c2 = cert2;
if (!c1 || !c2) {
return 0;
}
/* compare raw DER encoded data */
if (!c1->raw.p || !c2->raw.p || (c1->raw.len != c2->raw.len) ||
memcmp(c1->raw.p, c2->raw.p, c1->raw.len)) {
return 0;
}
return 1;
}
int
nc_server_tls_md5_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_md5(c->raw.p, c->raw.len, buf);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating MD5 digest failed");
return 1;
}
return 0;
}
int
nc_server_tls_sha1_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_sha1(c->raw.p, c->raw.len, buf);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating SHA-1 digest failed");
return 1;
}
return 0;
}
int
nc_server_tls_sha224_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_sha256(c->raw.p, c->raw.len, buf, 1);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating SHA-224 digest failed");
return 1;
}
return 0;
}
int
nc_server_tls_sha256_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_sha256(c->raw.p, c->raw.len, buf, 0);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating SHA-256 digest failed");
return 1;
}
return 0;
}
int
nc_server_tls_sha384_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_sha512(c->raw.p, c->raw.len, buf, 1);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating SHA-384 digest failed");
return 1;
}
return 0;
}
int
nc_server_tls_sha512_wrap(void *cert, unsigned char *buf)
{
int rc;
mbedtls_x509_crt *c = cert;
rc = mbedtls_sha512(c->raw.p, c->raw.len, buf, 0);
if (rc) {
nc_mbedtls_strerr(NULL, rc, "Calculating SHA-512 digest failed");
return 1;
}
return 0;
}
/**
* @brief Callback for sending data.
*
* @param[in] ctx Socket.
* @param[in] buf Data to send.
* @param[in] len Length of the data.
* @return Number of bytes sent or negative value on error.
*/
static int
nc_server_tls_send(void *ctx, const unsigned char *buf, size_t len)
{
int sock, ret;
NC_CHECK_ARG_RET(NULL, ctx, MBEDTLS_ERR_NET_INVALID_CONTEXT);
sock = *(int *)ctx;
ret = send(sock, buf, len, MSG_NOSIGNAL);
if (ret < 0) {
if ((errno == EWOULDBLOCK) || (errno == EAGAIN) || (errno == EINTR)) {
return MBEDTLS_ERR_SSL_WANT_WRITE;
} else if ((errno == EPIPE) || (errno == ECONNRESET)) {
return MBEDTLS_ERR_NET_CONN_RESET;
} else {
return MBEDTLS_ERR_NET_SEND_FAILED;
}
}
return ret;
}
/**
* @brief Callback for receiving data.
*
* @param[in] ctx Socket.
* @param[out] buf Buffer to store the received data.
* @param[in] len Length of the buffer.
* @return Number of bytes received or negative value on error.
*/