-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathopenssl.c
More file actions
1746 lines (1466 loc) · 49.3 KB
/
openssl.c
File metadata and controls
1746 lines (1466 loc) · 49.3 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
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2015-2026 The Fluent Bit Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_str.h>
#include <fluent-bit/flb_compat.h>
#include <fluent-bit/tls/flb_tls.h>
#include <fluent-bit/tls/flb_tls_info.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/opensslv.h>
#include <openssl/engine.h>
#include <openssl/x509v3.h>
#ifdef FLB_SYSTEM_MACOS
#include <Security/Security.h>
#include <CoreFoundation/CoreFoundation.h>
#include <unistd.h>
#endif
#ifdef FLB_SYSTEM_WINDOWS
#define strtok_r(str, delimiter, context) \
strtok_s(str, delimiter, context)
#include <wincrypt.h>
#ifndef CERT_FIND_SHA256_HASH
/* Older SDKs may not define this */
#define CERT_FIND_SHA256_HASH 0x0001000d
#endif
#endif
/*
* OPENSSL_VERSION_NUMBER has the following semantics
*
* 0x010100000L M = major F = fix S = status
* MMNNFFPPS N = minor P = patch
*/
#define OPENSSL_1_1_0 0x010100000L
/* OpenSSL library context */
struct tls_context {
int debug_level;
SSL_CTX *ctx;
int mode;
char *alpn;
#if defined(FLB_SYSTEM_WINDOWS)
char *certstore_name;
int use_enterprise_store;
CRYPT_HASH_BLOB *allowed_thumbprints;
size_t allowed_thumbprints_count;
#endif
pthread_mutex_t mutex;
};
struct tls_session {
SSL *ssl;
int fd;
char alpn[FLB_TLS_ALPN_MAX_LENGTH];
int continuation_flag;
struct tls_context *parent; /* parent struct tls_context ref */
};
static int tls_init(void)
{
/*
* Explicit initialization is needed for older versions of
* OpenSSL (before v1.1.0).
*
* https://wiki.openssl.org/index.php/Library_Initialization
*/
#if OPENSSL_VERSION_NUMBER < OPENSSL_1_1_0
OPENSSL_add_all_algorithms_noconf();
SSL_load_error_strings();
SSL_library_init();
#endif
return 0;
}
static void tls_info_callback(const SSL *s, int where, int ret)
{
int w;
int fd;
const char *str;
fd = SSL_get_fd(s);
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) {
str = "SSL_connect";
}
else if (w & SSL_ST_ACCEPT) {
str = "SSL_accept";
}
else {
str = "undefined";
}
if (where & SSL_CB_LOOP) {
flb_debug("[tls] connection #%i %s: %s",
fd, str, SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT) {
str = (where & SSL_CB_READ) ? "read" : "write";
flb_debug("[tls] connection #%i SSL3 alert %s:%s:%s",
fd, str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT) {
if (ret == 0) {
flb_error("[tls] connection #%i %s: failed in %s",
fd, str, SSL_state_string_long(s));
}
else if (ret < 0) {
ret = SSL_get_error(s, ret);
if (ret == SSL_ERROR_WANT_WRITE) {
flb_debug("[tls] connection #%i WANT_WRITE", fd);
}
else if (ret == SSL_ERROR_WANT_READ) {
flb_debug("[tls] connection #%i WANT_READ", fd);
}
else {
flb_error("[tls] connection #%i %s: error in %s",
fd, str, SSL_state_string_long(s));
}
}
}
}
static void tls_context_destroy(void *ctx_backend)
{
struct tls_context *ctx = ctx_backend;
pthread_mutex_lock(&ctx->mutex);
SSL_CTX_free(ctx->ctx);
if (ctx->alpn != NULL) {
flb_free(ctx->alpn);
ctx->alpn = NULL;
}
#if defined(FLB_SYSTEM_WINDOWS)
if (ctx->certstore_name != NULL) {
flb_free(ctx->certstore_name);
ctx->certstore_name = NULL;
}
if (ctx->allowed_thumbprints) {
/* We allocated each blob->pbData; free them too */
for (size_t i = 0; i < ctx->allowed_thumbprints_count; i++) {
if (ctx->allowed_thumbprints[i].pbData) {
flb_free(ctx->allowed_thumbprints[i].pbData);
}
}
flb_free(ctx->allowed_thumbprints);
ctx->allowed_thumbprints = NULL;
ctx->allowed_thumbprints_count = 0;
}
#endif
pthread_mutex_unlock(&ctx->mutex);
flb_free(ctx);
}
static int tls_context_server_alpn_select_callback(SSL *ssl,
const unsigned char **out,
unsigned char *outlen,
const unsigned char *in,
unsigned int inlen,
void *arg)
{
int result;
struct tls_context *ctx;
ctx = (struct tls_context *) arg;
result = SSL_TLSEXT_ERR_NOACK;
if (ctx->alpn != NULL) {
result = SSL_select_next_proto((unsigned char **) out,
outlen,
(const unsigned char *) &ctx->alpn[1],
(unsigned int) ctx->alpn[0],
in,
inlen);
if (result == OPENSSL_NPN_NEGOTIATED) {
result = SSL_TLSEXT_ERR_OK;
}
else if (result == OPENSSL_NPN_NO_OVERLAP) {
result = SSL_TLSEXT_ERR_ALERT_FATAL;
}
}
return result;
}
int tls_context_alpn_set(void *ctx_backend, const char *alpn)
{
size_t wire_format_alpn_index;
size_t wire_format_alpn_length;
size_t alpn_token_length;
unsigned int active_alpn_length;
char *active_alpn;
char *alpn_token_context;
char *alpn_working_copy;
char *new_alpn;
char *wire_format_alpn;
char *alpn_token;
int result;
struct tls_context *ctx;
ctx = (struct tls_context *) ctx_backend;
result = 0;
new_alpn = NULL;
if (alpn != NULL) {
wire_format_alpn = flb_calloc(strlen(alpn) + 3,
sizeof(char));
if (wire_format_alpn == NULL) {
return -1;
}
alpn_working_copy = strdup(alpn);
if (alpn_working_copy == NULL) {
flb_free(wire_format_alpn);
return -1;
}
wire_format_alpn_index = 1;
alpn_token_context = NULL;
alpn_token = strtok_r(alpn_working_copy,
",",
&alpn_token_context);
while (alpn_token != NULL) {
alpn_token_length = strlen(alpn_token);
wire_format_alpn_length = wire_format_alpn_index - 1;
if (alpn_token_length > 255) {
flb_error("[tls] error: alpn token length exceeds 255 bytes");
free(alpn_working_copy);
flb_free(wire_format_alpn);
return -1;
}
if (wire_format_alpn_length + alpn_token_length + 1 > 255) {
flb_error("[tls] error: alpn wire format length exceeds "
"255 bytes");
free(alpn_working_copy);
flb_free(wire_format_alpn);
return -1;
}
wire_format_alpn[wire_format_alpn_index] = \
(char) alpn_token_length;
memcpy(&wire_format_alpn[wire_format_alpn_index + 1],
alpn_token,
alpn_token_length);
wire_format_alpn_index += alpn_token_length + 1;
alpn_token = strtok_r(NULL,
",",
&alpn_token_context);
}
if (wire_format_alpn_index > 1) {
if (wire_format_alpn_index - 1 > 255) {
flb_error("[tls] error: alpn wire format length exceeds "
"255 bytes");
free(alpn_working_copy);
flb_free(wire_format_alpn);
return -1;
}
wire_format_alpn[0] = (char) (wire_format_alpn_index - 1);
new_alpn = wire_format_alpn;
}
else {
flb_free(wire_format_alpn);
}
free(alpn_working_copy);
}
active_alpn = ctx->alpn;
if (alpn != NULL) {
active_alpn = new_alpn;
}
if (ctx->mode == FLB_TLS_SERVER_MODE) {
SSL_CTX_set_alpn_select_cb(
ctx->ctx,
tls_context_server_alpn_select_callback,
ctx);
}
else {
if (active_alpn == NULL) {
result = -1;
}
else {
active_alpn_length =
(unsigned int) ((const unsigned char *) active_alpn)[0];
if (SSL_CTX_set_alpn_protos(
ctx->ctx,
(const unsigned char *) &active_alpn[1],
active_alpn_length) != 0) {
result = -1;
}
}
}
if (result == 0 && alpn != NULL) {
if (ctx->alpn != NULL) {
flb_free(ctx->alpn);
}
ctx->alpn = new_alpn;
new_alpn = NULL;
}
if (new_alpn != NULL) {
flb_free(new_alpn);
}
return result;
}
static int tls_context_set_verify_client(void *ctx_backend, int verify_client)
{
struct tls_context *ctx = ctx_backend;
int mode;
if (ctx->mode == FLB_TLS_SERVER_MODE && verify_client == FLB_TRUE) {
mode = SSL_CTX_get_verify_mode(ctx->ctx);
mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
SSL_CTX_set_verify(ctx->ctx, mode, NULL);
}
return 0;
}
#ifdef _MSC_VER
/* Parse certstore_name prefix like
*
* "My" -> no prefix, leave location untouched
* "CurrentUser\\My" -> CERT_SYSTEM_STORE_CURRENT_USER, "My"
* "HKCU\\My" -> CERT_SYSTEM_STORE_CURRENT_USER, "My"
* "LocalMachine\\My" -> CERT_SYSTEM_STORE_LOCAL_MACHINE, "My"
* "HKLM\\My" -> CERT_SYSTEM_STORE_LOCAL_MACHINE, "My"
* "LocalMachineEnterprise\\My"-> CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE, "My"
* "HKLME\\My" -> CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE, "My"
*
* Also accepts '/' as separator.
*
* If no known prefix is found, *store_name_out is left as-is and *location_flags
* is not modified (so legacy behavior is preserved).
*/
static int windows_resolve_certstore_location(const char *configured_name,
DWORD *location_flags,
const char **store_name_out)
{
const char *name;
const char *sep;
size_t prefix_len;
char prefix_buf[32];
size_t i;
size_t len = 0;
char c;
if (!configured_name || !*configured_name) {
return FLB_FALSE;
}
name = configured_name;
len = strlen(name);
/* Optional "Cert:\" prefix (PowerShell style) */
if (len >= 6 &&
strncasecmp(name, "cert:", 5) == 0 &&
(name[5] == '\\' || name[5] == '/')) {
name += 6;
}
/* Find first '\' or '/' separator */
sep = name;
while (*sep != '\0' && *sep != '\\' && *sep != '/') {
sep++;
}
if (*sep == '\0') {
/* No prefix, only store name (e.g. "My" or "Root")
* -> keep legacy behavior (location_flags unchanged).
*/
*store_name_out = name;
return FLB_FALSE;
}
/* Copy and lowercase prefix into buffer */
prefix_len = (size_t)(sep - name);
if (prefix_len >= sizeof(prefix_buf)) {
prefix_len = sizeof(prefix_buf) - 1;
}
for (i = 0; i < prefix_len; i++) {
c = (char) name[i];
if (c >= 'A' && c <= 'Z') {
c = (char) (c - 'A' + 'a');
}
prefix_buf[i] = c;
}
prefix_buf[prefix_len] = '\0';
/* Default: keep *location_flags as-is */
if (strcmp(prefix_buf, "currentuser") == 0 ||
strcmp(prefix_buf, "hkcu") == 0) {
*location_flags = CERT_SYSTEM_STORE_CURRENT_USER;
}
else if (strcmp(prefix_buf, "localmachine") == 0 ||
strcmp(prefix_buf, "hklm") == 0) {
*location_flags = CERT_SYSTEM_STORE_LOCAL_MACHINE;
}
else if (strcmp(prefix_buf, "localmachineenterprise") == 0 ||
strcmp(prefix_buf, "hklme") == 0) {
*location_flags = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE;
}
else {
/* Unknown prefix -> treat entire string as store name */
*store_name_out = configured_name;
return FLB_FALSE;
}
/* Store name part after the separator "\" or "/" */
*store_name_out = sep + 1;
return FLB_TRUE;
}
static int windows_load_system_certificates(struct tls_context *ctx)
{
int ret;
HANDLE win_store;
unsigned long err;
PCCERT_CONTEXT win_cert = NULL;
const unsigned char *win_cert_data;
X509_STORE *ossl_store = SSL_CTX_get_cert_store(ctx->ctx);
X509 *ossl_cert;
char *configured_name = "Root";
const char *store_name = "Root";
DWORD store_location = CERT_SYSTEM_STORE_CURRENT_USER;
int has_location_prefix = FLB_FALSE;
/* Check if OpenSSL certificate store is available */
if (!ossl_store) {
flb_error("[tls] failed to retrieve openssl certificate store.");
return -1;
}
if (ctx->certstore_name) {
configured_name = ctx->certstore_name;
store_name = ctx->certstore_name;
}
/* First, resolve explicit prefix if present */
has_location_prefix = windows_resolve_certstore_location(configured_name,
&store_location,
&store_name);
/* Backward compatibility:
* If no prefix was given (store_name == configured_name) and
* use_enterprise_store is set, override location accordingly.
*/
if (has_location_prefix == FLB_FALSE && ctx->use_enterprise_store) {
store_location = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE;
}
/* Open the Windows certificate store for the resolved location */
if (store_location == CERT_SYSTEM_STORE_CURRENT_USER) {
/* Keep using CertOpenSystemStoreA for current user to avoid
* changing existing behavior.
*/
win_store = CertOpenSystemStoreA(0, store_name);
}
else {
win_store = CertOpenStore(CERT_STORE_PROV_SYSTEM,
0,
0,
store_location,
store_name);
}
if (win_store == NULL) {
flb_error("[tls] cannot open windows certificate store: %lu", GetLastError());
return -1;
}
if (ctx->allowed_thumbprints_count > 0) {
size_t loaded = 0;
DWORD find_type = 0;
size_t i;
for (i = 0; i < ctx->allowed_thumbprints_count; i++) {
find_type = (ctx->allowed_thumbprints[i].cbData == 20)
? CERT_FIND_SHA1_HASH
: CERT_FIND_SHA256_HASH;
win_cert = NULL;
while ((win_cert = CertFindCertificateInStore(win_store,
X509_ASN_ENCODING,
0,
find_type,
&ctx->allowed_thumbprints[i],
win_cert)) != NULL) {
win_cert_data = win_cert->pbCertEncoded;
ossl_cert = d2i_X509(NULL, &win_cert_data, win_cert->cbCertEncoded);
if (!ossl_cert) {
flb_debug("[tls] parse failed for matched certificate (thumbprint idx %zu)", i);
continue;
}
ret = X509_STORE_add_cert(ossl_store, ossl_cert);
if (ret != 1) {
unsigned long err = ERR_get_error();
if (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
flb_debug("[tls] certificate already present (thumbprint idx %zu).", i);
}
else {
flb_warn("[tls] add_cert failed: %s", ERR_error_string(err, NULL));
}
}
else {
loaded++;
}
X509_free(ossl_cert);
}
}
if (!CertCloseStore(win_store, 0)) {
flb_error("[tls] cannot close windows certificate store: %lu", GetLastError());
return -1;
}
if (loaded == 0) {
flb_warn("[tls] no certificates loaded by thumbprint from '%s'.", configured_name);
}
else {
flb_debug("[tls] loaded %zu certificate(s) by thumbprint from '%s'.", loaded, configured_name);
}
return 0;
}
/* Iterate over certificates in the store */
while ((win_cert = CertEnumCertificatesInStore(win_store, win_cert)) != NULL) {
/* Check if the certificate is encoded in ASN.1 DER format */
if (win_cert->dwCertEncodingType & X509_ASN_ENCODING) {
/*
* Decode the certificate into X509 struct.
*
* The additional pointer variable is necessary per OpenSSL docs because the
* pointer is incremented by d2i_X509.
*/
win_cert_data = win_cert->pbCertEncoded;
ossl_cert = d2i_X509(NULL, &win_cert_data, win_cert->cbCertEncoded);
if (!ossl_cert) {
flb_debug("[tls] cannot parse a certificate, error code: %lu, skipping...", ERR_get_error());
continue;
}
/* Add X509 struct to the openssl cert store */
ret = X509_STORE_add_cert(ossl_store, ossl_cert);
if (!ret) {
err = ERR_get_error();
if (err == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
flb_debug("[tls] certificate already exists in the store, skipping.");
}
else {
flb_warn("[tls] failed to add certificate to openssl store. error code: %lu - %s",
err, ERR_error_string(err, NULL));
}
}
X509_free(ossl_cert);
}
}
/* Check for errors during enumeration */
if (GetLastError() != CRYPT_E_NOT_FOUND) {
flb_error("[tls] error occurred while enumerating certificates: %lu", GetLastError());
CertCloseStore(win_store, 0);
return -1;
}
/* Close the Windows system certificate store */
if (!CertCloseStore(win_store, 0)) {
flb_error("[tls] cannot close windows certificate store: %lu", GetLastError());
return -1;
}
flb_debug("[tls] successfully loaded certificates from windows system %s store.",
configured_name);
return 0;
}
#endif
#ifdef FLB_SYSTEM_MACOS
/* macOS-specific system certificate loading */
static int macos_load_system_certificates(struct tls_context *ctx)
{
X509_STORE *store = NULL;
X509 *x509 = NULL;
SecCertificateRef cert = NULL;
CFArrayRef certs = NULL;
CFDataRef certData = NULL;
CFIndex i = 0;
const unsigned char *data = NULL;
char *subject = NULL;
char *issuer = NULL;
OSStatus status;
unsigned long err;
int ret = -1;
unsigned long loaded_cert_count = 0;
/* Retrieve system certificates from macOS Keychain */
status = SecTrustSettingsCopyCertificates(kSecTrustSettingsDomainSystem, &certs);
if (status != errSecSuccess || !certs) {
flb_debug("[tls] failed to load system certificates from keychain, status: %d", status);
return -1;
}
flb_debug("[tls] attempting to load certificates from system keychain of macOS");
/* Get the SSL context's certificate store */
store = SSL_CTX_get_cert_store(ctx->ctx);
if (!store) {
flb_debug("[tls] failed to get certificate store from SSL context");
CFRelease(certs);
return -1;
}
/* Load each certificate into the X509 store */
for (i = 0; i < CFArrayGetCount(certs); i++) {
cert = (SecCertificateRef) CFArrayGetValueAtIndex(certs, i);
if (!cert) {
flb_debug("[tls] invalid certificate reference at index %ld, skipping", i);
continue;
}
certData = SecCertificateCopyData(cert);
if (!certData) {
flb_debug("[tls] failed to retrieve data for certificate %ld from keychain, skipping", i);
continue;
}
/* Convert certificate data to X509 */
data = CFDataGetBytePtr(certData);
x509 = d2i_X509(NULL, &data, CFDataGetLength(certData));
CFRelease(certData);
if (!x509) {
flb_debug("[tls] failed to parse certificate %ld from keychain, skipping", i);
continue;
}
subject = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(x509), NULL, 0);
if (subject && issuer) {
flb_debug("[tls] certificate %ld details - subject: %s, issuer: %s", i, subject, issuer);
}
/* Attempt to add certificate to trusted store */
ret = X509_STORE_add_cert(store, x509);
if (ret != 1) {
err = ERR_get_error();
if (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
flb_debug("[tls] certificate %ld already exists in the trusted store (duplicate)", i);
} else {
flb_debug("[tls] failed to add certificate %ld to trusted store, error code: %lu", i, err);
}
X509_free(x509);
continue;
}
loaded_cert_count++;
flb_debug("[tls] successfully loaded and added certificate %ld to trusted store", i);
if (subject) {
OPENSSL_free(subject);
}
if (issuer) {
OPENSSL_free(issuer);
}
X509_free(x509);
}
CFRelease(certs);
flb_debug("[tls] finished loading keychain certificates, total loaded: %lu", loaded_cert_count);
return 0;
}
#endif
static int load_system_certificates(struct tls_context *ctx)
{
int ret;
const char *ca_file = FLB_DEFAULT_SEARCH_CA_BUNDLE;
(void) ret;
(void) ca_file;
/* For Windows use specific API to read the certs store */
#ifdef _MSC_VER
return windows_load_system_certificates(ctx);
#elif defined(__APPLE__)
return macos_load_system_certificates(ctx);
#else
if (access(ca_file, R_OK) != 0) {
ca_file = NULL;
}
ret = SSL_CTX_load_verify_locations(ctx->ctx, ca_file, FLB_DEFAULT_CA_DIR);
if (ret != 1) {
ERR_print_errors_fp(stderr);
}
return 0;
#endif
}
#ifdef FLB_HAVE_DEV
/* This is not thread safe */
static void ssl_key_logger(const SSL *ssl, const char *line)
{
char *key_log_filename;
FILE *key_log_file;
key_log_filename = getenv("SSLKEYLOGFILE");
if (key_log_filename == NULL) {
return;
}
key_log_file = fopen(key_log_filename, "a");
if (key_log_file == NULL) {
return;
}
setvbuf(key_log_file, NULL, 0, _IOLBF);
fprintf(key_log_file, "%s\n", line);
fclose(key_log_file);
}
#endif
static void *tls_context_create(int verify,
int debug,
int mode,
const char *vhost,
const char *ca_path,
const char *ca_file,
const char *crt_file,
const char *key_file,
const char *key_passwd)
{
int ret;
SSL_CTX *ssl_ctx;
struct tls_context *ctx;
char err_buf[256];
char *key_log_filename;
/*
* Init library ? based in the documentation on OpenSSL >= 1.1.0 is not longer
* necessary since the library will initialize it self:
*
* https://wiki.openssl.org/index.php/Library_Initialization
*/
/* Create OpenSSL context */
#if OPENSSL_VERSION_NUMBER < OPENSSL_1_1_0
/*
* SSLv23_method() is actually an equivalent of TLS_client_method()
* in OpenSSL v1.0.x.
*
* https://www.openssl.org/docs/man1.0.2/man3/SSLv23_method.html
*/
if (mode == FLB_TLS_SERVER_MODE) {
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
}
else {
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
}
#else
if (mode == FLB_TLS_SERVER_MODE) {
ssl_ctx = SSL_CTX_new(TLS_server_method());
}
else {
ssl_ctx = SSL_CTX_new(TLS_client_method());
}
#endif
if (!ssl_ctx) {
flb_error("[openssl] could not create context");
return NULL;
}
ctx = flb_calloc(1, sizeof(struct tls_context));
if (!ctx) {
flb_errno();
SSL_CTX_free(ssl_ctx);
return NULL;
}
#ifdef FLB_HAVE_DEV
key_log_filename = getenv("SSLKEYLOGFILE");
if (key_log_filename != NULL) {
SSL_CTX_set_keylog_callback(ssl_ctx, ssl_key_logger);
}
#endif
ctx->ctx = ssl_ctx;
ctx->mode = mode;
ctx->alpn = NULL;
ctx->debug_level = debug;
#if defined(FLB_SYSTEM_WINDOWS)
ctx->certstore_name = NULL;
ctx->use_enterprise_store = 0;
ctx->allowed_thumbprints = NULL;
ctx->allowed_thumbprints_count = 0;
#endif
pthread_mutex_init(&ctx->mutex, NULL);
/* Verify peer: by default OpenSSL always verify peer */
if (verify == FLB_FALSE) {
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, NULL);
}
else {
int verify_flags = SSL_VERIFY_PEER;
SSL_CTX_set_verify(ssl_ctx, verify_flags, NULL);
}
/* ca_path | ca_file */
if (ca_path) {
ret = SSL_CTX_load_verify_locations(ctx->ctx, NULL, ca_path);
if (ret != 1) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] ca_path '%s' %lu: %s",
ca_path, ERR_get_error(), err_buf);
goto error;
}
}
else if (ca_file) {
ret = SSL_CTX_load_verify_locations(ctx->ctx, ca_file, NULL);
if (ret != 1) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] ca_file '%s' %lu: %s",
ca_file, ERR_get_error(), err_buf);
goto error;
}
}
else {
load_system_certificates(ctx);
}
/* crt_file */
if (crt_file) {
ret = SSL_CTX_use_certificate_chain_file(ssl_ctx, crt_file);
if (ret != 1) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] crt_file '%s' %lu: %s",
crt_file, ERR_get_error(), err_buf);
goto error;
}
}
/* key_file */
if (key_file) {
if (strncmp(key_file, "pkcs11:", 7) == 0) {
#ifdef OPENSSL_NO_ENGINE
flb_error("[tls] pkcs11_key_file '%s': requires OpenSSL ENGINE support",
key_file);
goto error;
#endif
/* PKCS#11 URI detected */
if (!key_passwd || strlen(key_passwd) == 0) {
flb_warn("[tls] PKCS#11 URI may fail without a PIN/password (tls_key_passwd)");
}
ENGINE *e = ENGINE_by_id("pkcs11");
if (!e) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] failed to load pkcs11 engine: %s", err_buf);
goto error;
}
if (!ENGINE_init(e)) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] failed to initialize pkcs11 engine: %s", err_buf);
ENGINE_free(e);
goto error;
}
EVP_PKEY *pkey = ENGINE_load_private_key(e, key_file, NULL, (void *)key_passwd);
if (!pkey) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] failed to load private key from pkcs11 uri '%s': %s", key_file, err_buf);
ENGINE_finish(e);
ENGINE_free(e);
goto error;
}
if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] failed to use pkcs11 private key '%s': %s", key_file, err_buf);
EVP_PKEY_free(pkey);
ENGINE_finish(e);
ENGINE_free(e);
goto error;
}
EVP_PKEY_free(pkey);
ENGINE_finish(e);
ENGINE_free(e);
}
else
{
if (key_passwd) {
SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx,
(void *) key_passwd);
}
ret = SSL_CTX_use_PrivateKey_file(ssl_ctx, key_file,
SSL_FILETYPE_PEM);
if (ret != 1) {
ERR_error_string_n(ERR_get_error(), err_buf, sizeof(err_buf)-1);
flb_error("[tls] key_file '%s' %lu: %s",
key_file, ERR_get_error(), err_buf);
goto error;
}
}
/* Make sure the key and certificate file match */
if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
flb_error("[tls] private_key '%s' and password don't match",
key_file);
goto error;
}
}
return ctx;
error:
tls_context_destroy(ctx);
return NULL;
}
#if !defined(TLS1_3_VERSION)
# define TLS1_3_VERSION 0x0304
#endif
struct tls_proto_def {
char *name;
int ver;
};
struct tls_proto_options {