forked from confluentinc/librdkafka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rdkafka_ssl.c
1903 lines (1575 loc) · 65 KB
/
rdkafka_ssl.c
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
/*
* librdkafka - The Apache Kafka C/C++ library
*
* Copyright (c) 2019-2022, Magnus Edenhill
* 2023, Confluent Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @name OpenSSL integration
*
*/
#include "rdkafka_int.h"
#include "rdkafka_transport_int.h"
#include "rdkafka_cert.h"
#ifdef _WIN32
#include <wincrypt.h>
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#endif
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#if OPENSSL_VERSION_NUMBER >= 0x30000000
#include <openssl/provider.h>
#endif
#include <ctype.h>
#if !_WIN32
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#if WITH_VALGRIND
/* OpenSSL relies on uninitialized memory, which Valgrind will whine about.
* We use in-code Valgrind macros to suppress those warnings. */
#include <valgrind/memcheck.h>
#else
#define VALGRIND_MAKE_MEM_DEFINED(A, B)
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
static mtx_t *rd_kafka_ssl_locks;
static int rd_kafka_ssl_locks_cnt;
#endif
/**
* @brief Close and destroy SSL session
*/
void rd_kafka_transport_ssl_close(rd_kafka_transport_t *rktrans) {
SSL_shutdown(rktrans->rktrans_ssl);
SSL_free(rktrans->rktrans_ssl);
rktrans->rktrans_ssl = NULL;
}
/**
* @brief Clear OpenSSL error queue to get a proper error reporting in case
* the next SSL_*() operation fails.
*/
static RD_INLINE void
rd_kafka_transport_ssl_clear_error(rd_kafka_transport_t *rktrans) {
ERR_clear_error();
#ifdef _WIN32
WSASetLastError(0);
#else
rd_set_errno(0);
#endif
}
/**
* @returns a thread-local single-invocation-use error string for
* the last thread-local error in OpenSSL, or an empty string
* if no error.
*/
const char *rd_kafka_ssl_last_error_str(void) {
static RD_TLS char errstr[256];
unsigned long l;
const char *file, *data, *func;
int line, flags;
#if OPENSSL_VERSION_NUMBER >= 0x30000000
l = ERR_peek_last_error_all(&file, &line, &func, &data, &flags);
#else
l = ERR_peek_last_error_line_data(&file, &line, &data, &flags);
func = ERR_func_error_string(l);
#endif
if (!l)
return "";
rd_snprintf(errstr, sizeof(errstr), "%lu:%s:%s:%s:%d: %s", l,
ERR_lib_error_string(l), func, file, line,
((flags & ERR_TXT_STRING) && data && *data)
? data
: ERR_reason_error_string(l));
return errstr;
}
/**
* Serves the entire OpenSSL error queue and logs each error.
* The last error is not logged but returned in 'errstr'.
*
* If 'rkb' is non-NULL broker-specific logging will be used,
* else it will fall back on global 'rk' debugging.
*/
static char *rd_kafka_ssl_error(rd_kafka_t *rk,
rd_kafka_broker_t *rkb,
char *errstr,
size_t errstr_size) {
unsigned long l;
const char *file, *data, *func;
int line, flags;
int cnt = 0;
if (!rk) {
rd_assert(rkb);
rk = rkb->rkb_rk;
}
while (
#if OPENSSL_VERSION_NUMBER >= 0x30000000
(l = ERR_get_error_all(&file, &line, &func, &data, &flags))
#else
(l = ERR_get_error_line_data(&file, &line, &data, &flags))
#endif
) {
char buf[256];
#if OPENSSL_VERSION_NUMBER < 0x30000000
func = ERR_func_error_string(l);
#endif
if (cnt++ > 0) {
/* Log last message */
if (rkb)
rd_rkb_log(rkb, LOG_ERR, "SSL", "%s", errstr);
else
rd_kafka_log(rk, LOG_ERR, "SSL", "%s", errstr);
}
ERR_error_string_n(l, buf, sizeof(buf));
if (!(flags & ERR_TXT_STRING) || !data || !*data)
data = NULL;
/* Include openssl file:line:func if debugging is enabled */
if (rk->rk_conf.log_level >= LOG_DEBUG)
rd_snprintf(errstr, errstr_size, "%s:%d:%s %s%s%s",
file, line, func, buf, data ? ": " : "",
data ? data : "");
else
rd_snprintf(errstr, errstr_size, "%s%s%s", buf,
data ? ": " : "", data ? data : "");
}
if (cnt == 0)
rd_snprintf(errstr, errstr_size,
"No further error information available");
return errstr;
}
/**
* Set transport IO event polling based on SSL error.
*
* Returns -1 on permanent errors.
*
* Locality: broker thread
*/
static RD_INLINE int
rd_kafka_transport_ssl_io_update(rd_kafka_transport_t *rktrans,
int ret,
char *errstr,
size_t errstr_size) {
int serr = SSL_get_error(rktrans->rktrans_ssl, ret);
int serr2;
switch (serr) {
case SSL_ERROR_WANT_READ:
rd_kafka_transport_poll_set(rktrans, POLLIN);
break;
case SSL_ERROR_WANT_WRITE:
rd_kafka_transport_set_blocked(rktrans, rd_true);
rd_kafka_transport_poll_set(rktrans, POLLOUT);
break;
case SSL_ERROR_SYSCALL:
serr2 = ERR_peek_error();
if (serr2)
rd_kafka_ssl_error(NULL, rktrans->rktrans_rkb, errstr,
errstr_size);
else if (!rd_socket_errno || rd_socket_errno == ECONNRESET)
rd_snprintf(errstr, errstr_size, "Disconnected");
else
rd_snprintf(errstr, errstr_size,
"SSL transport error: %s",
rd_strerror(rd_socket_errno));
return -1;
case SSL_ERROR_ZERO_RETURN:
rd_snprintf(errstr, errstr_size, "Disconnected");
return -1;
default:
rd_kafka_ssl_error(NULL, rktrans->rktrans_rkb, errstr,
errstr_size);
return -1;
}
return 0;
}
ssize_t rd_kafka_transport_ssl_send(rd_kafka_transport_t *rktrans,
rd_slice_t *slice,
char *errstr,
size_t errstr_size) {
ssize_t sum = 0;
const void *p;
size_t rlen;
rd_kafka_transport_ssl_clear_error(rktrans);
while ((rlen = rd_slice_peeker(slice, &p))) {
int r;
size_t r2;
r = SSL_write(rktrans->rktrans_ssl, p, (int)rlen);
if (unlikely(r <= 0)) {
if (rd_kafka_transport_ssl_io_update(rktrans, r, errstr,
errstr_size) == -1)
return -1;
else
return sum;
}
/* Update buffer read position */
r2 = rd_slice_read(slice, NULL, (size_t)r);
rd_assert((size_t)r == r2 &&
*"BUG: wrote more bytes than available in slice");
sum += r;
/* FIXME: remove this and try again immediately and let
* the next SSL_write() call fail instead? */
if ((size_t)r < rlen)
break;
}
return sum;
}
ssize_t rd_kafka_transport_ssl_recv(rd_kafka_transport_t *rktrans,
rd_buf_t *rbuf,
char *errstr,
size_t errstr_size) {
ssize_t sum = 0;
void *p;
size_t len;
while ((len = rd_buf_get_writable(rbuf, &p))) {
int r;
rd_kafka_transport_ssl_clear_error(rktrans);
r = SSL_read(rktrans->rktrans_ssl, p, (int)len);
if (unlikely(r <= 0)) {
if (rd_kafka_transport_ssl_io_update(rktrans, r, errstr,
errstr_size) == -1)
return -1;
else
return sum;
}
VALGRIND_MAKE_MEM_DEFINED(p, r);
/* Update buffer write position */
rd_buf_write(rbuf, NULL, (size_t)r);
sum += r;
/* FIXME: remove this and try again immediately and let
* the next SSL_read() call fail instead? */
if ((size_t)r < len)
break;
}
return sum;
}
/**
* OpenSSL password query callback
*
* Locality: application thread
*/
static int rd_kafka_transport_ssl_passwd_cb(char *buf,
int size,
int rwflag,
void *userdata) {
rd_kafka_t *rk = userdata;
int pwlen;
rd_kafka_dbg(rk, SECURITY, "SSLPASSWD",
"Private key requires password");
if (!rk->rk_conf.ssl.key_password) {
rd_kafka_log(rk, LOG_WARNING, "SSLPASSWD",
"Private key requires password but "
"no password configured (ssl.key.password)");
return -1;
}
pwlen = (int)strlen(rk->rk_conf.ssl.key_password);
memcpy(buf, rk->rk_conf.ssl.key_password, RD_MIN(pwlen, size));
return pwlen;
}
/**
* @brief OpenSSL callback to perform additional broker certificate
* verification and validation.
*
* @return 1 on success when the broker certificate
* is valid and 0 when the certificate is not valid.
*
* @sa SSL_CTX_set_verify()
*/
static int rd_kafka_transport_ssl_cert_verify_cb(int preverify_ok,
X509_STORE_CTX *x509_ctx) {
rd_kafka_transport_t *rktrans = rd_kafka_curr_transport;
rd_kafka_broker_t *rkb;
rd_kafka_t *rk;
X509 *cert;
char *buf = NULL;
int buf_size;
int depth;
int x509_orig_error, x509_error;
char errstr[512];
int ok;
rd_assert(rktrans != NULL);
rkb = rktrans->rktrans_rkb;
rk = rkb->rkb_rk;
cert = X509_STORE_CTX_get_current_cert(x509_ctx);
if (!cert) {
rd_rkb_log(rkb, LOG_ERR, "SSLCERTVRFY",
"Failed to get current certificate to verify");
return 0;
}
depth = X509_STORE_CTX_get_error_depth(x509_ctx);
x509_orig_error = x509_error = X509_STORE_CTX_get_error(x509_ctx);
buf_size = i2d_X509(cert, (unsigned char **)&buf);
if (buf_size < 0 || !buf) {
rd_rkb_log(rkb, LOG_ERR, "SSLCERTVRFY",
"Unable to convert certificate to X509 format");
return 0;
}
*errstr = '\0';
/* Call application's verification callback. */
ok = rk->rk_conf.ssl.cert_verify_cb(
rk, rkb->rkb_nodename, rkb->rkb_nodeid, &x509_error, depth, buf,
(size_t)buf_size, errstr, sizeof(errstr), rk->rk_conf.opaque);
OPENSSL_free(buf);
if (!ok) {
char subject[128];
char issuer[128];
X509_NAME_oneline(X509_get_subject_name(cert), subject,
sizeof(subject));
X509_NAME_oneline(X509_get_issuer_name(cert), issuer,
sizeof(issuer));
rd_rkb_log(rkb, LOG_ERR, "SSLCERTVRFY",
"Certificate (subject=%s, issuer=%s) verification "
"callback failed: %s",
subject, issuer, errstr);
X509_STORE_CTX_set_error(x509_ctx, x509_error);
return 0; /* verification failed */
}
/* Clear error */
if (x509_orig_error != 0 && x509_error == 0)
X509_STORE_CTX_set_error(x509_ctx, 0);
return 1; /* verification successful */
}
/**
* @brief Set TLSEXT hostname for SNI and optionally enable
* SSL endpoint identification verification.
*
* @returns 0 on success or -1 on error.
*/
static int rd_kafka_transport_ssl_set_endpoint_id(rd_kafka_transport_t *rktrans,
char *errstr,
size_t errstr_size) {
char name[RD_KAFKA_NODENAME_SIZE];
char *t;
rd_kafka_broker_lock(rktrans->rktrans_rkb);
rd_snprintf(name, sizeof(name), "%s",
rktrans->rktrans_rkb->rkb_nodename);
rd_kafka_broker_unlock(rktrans->rktrans_rkb);
/* Remove ":9092" port suffix from nodename */
if ((t = strrchr(name, ':')))
*t = '\0';
#if (OPENSSL_VERSION_NUMBER >= 0x0090806fL) && !defined(OPENSSL_NO_TLSEXT)
/* If non-numerical hostname, send it for SNI */
if (!(/*ipv6*/ (strchr(name, ':') &&
strspn(name, "0123456789abcdefABCDEF:.[]%") ==
strlen(name)) ||
/*ipv4*/ strspn(name, "0123456789.") == strlen(name)) &&
!SSL_set_tlsext_host_name(rktrans->rktrans_ssl, name))
goto fail;
#endif
if (rktrans->rktrans_rkb->rkb_rk->rk_conf.ssl.endpoint_identification ==
RD_KAFKA_SSL_ENDPOINT_ID_NONE)
return 0;
#if OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(OPENSSL_IS_BORINGSSL)
if (!SSL_set1_host(rktrans->rktrans_ssl, name))
goto fail;
#elif OPENSSL_VERSION_NUMBER >= 0x1000200fL /* 1.0.2 */
{
X509_VERIFY_PARAM *param;
param = SSL_get0_param(rktrans->rktrans_ssl);
if (!X509_VERIFY_PARAM_set1_host(param, name, 0))
goto fail;
}
#else
rd_snprintf(errstr, errstr_size,
"Endpoint identification not supported on this "
"OpenSSL version (0x%lx)",
OPENSSL_VERSION_NUMBER);
return -1;
#endif
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY, "ENDPOINT",
"Enabled endpoint identification using hostname %s", name);
return 0;
fail:
rd_kafka_ssl_error(NULL, rktrans->rktrans_rkb, errstr, errstr_size);
return -1;
}
/**
* @brief Set up SSL for a newly connected connection
*
* @returns -1 on failure, else 0.
*/
int rd_kafka_transport_ssl_connect(rd_kafka_broker_t *rkb,
rd_kafka_transport_t *rktrans,
char *errstr,
size_t errstr_size) {
int r;
rktrans->rktrans_ssl = SSL_new(rkb->rkb_rk->rk_conf.ssl.ctx);
if (!rktrans->rktrans_ssl)
goto fail;
if (!SSL_set_fd(rktrans->rktrans_ssl, (int)rktrans->rktrans_s))
goto fail;
if (rd_kafka_transport_ssl_set_endpoint_id(rktrans, errstr,
errstr_size) == -1)
return -1;
rd_kafka_transport_ssl_clear_error(rktrans);
r = SSL_connect(rktrans->rktrans_ssl);
if (r == 1) {
/* Connected, highly unlikely since this is a
* non-blocking operation. */
rd_kafka_transport_connect_done(rktrans, NULL);
return 0;
}
if (rd_kafka_transport_ssl_io_update(rktrans, r, errstr, errstr_size) ==
-1)
return -1;
return 0;
fail:
rd_kafka_ssl_error(NULL, rkb, errstr, errstr_size);
return -1;
}
static RD_UNUSED int
rd_kafka_transport_ssl_io_event(rd_kafka_transport_t *rktrans, int events) {
int r;
char errstr[512];
if (events & POLLOUT) {
rd_kafka_transport_ssl_clear_error(rktrans);
r = SSL_write(rktrans->rktrans_ssl, NULL, 0);
if (rd_kafka_transport_ssl_io_update(rktrans, r, errstr,
sizeof(errstr)) == -1)
goto fail;
}
return 0;
fail:
/* Permanent error */
rd_kafka_broker_fail(rktrans->rktrans_rkb, LOG_ERR,
RD_KAFKA_RESP_ERR__TRANSPORT, "%s", errstr);
return -1;
}
/**
* @brief Verify SSL handshake was valid.
*/
static int rd_kafka_transport_ssl_verify(rd_kafka_transport_t *rktrans) {
long int rl;
X509 *cert;
if (!rktrans->rktrans_rkb->rkb_rk->rk_conf.ssl.enable_verify)
return 0;
#if OPENSSL_VERSION_NUMBER >= 0x30000000
cert = SSL_get1_peer_certificate(rktrans->rktrans_ssl);
#else
cert = SSL_get_peer_certificate(rktrans->rktrans_ssl);
#endif
X509_free(cert);
if (!cert) {
rd_kafka_broker_fail(rktrans->rktrans_rkb, LOG_ERR,
RD_KAFKA_RESP_ERR__SSL,
"Broker did not provide a certificate");
return -1;
}
if ((rl = SSL_get_verify_result(rktrans->rktrans_ssl)) != X509_V_OK) {
rd_kafka_broker_fail(rktrans->rktrans_rkb, LOG_ERR,
RD_KAFKA_RESP_ERR__SSL,
"Failed to verify broker certificate: %s",
X509_verify_cert_error_string(rl));
return -1;
}
rd_rkb_dbg(rktrans->rktrans_rkb, SECURITY, "SSLVERIFY",
"Broker SSL certificate verified");
return 0;
}
/**
* @brief SSL handshake handling.
* Call repeatedly (based on IO events) until handshake is done.
*
* @returns -1 on error, 0 if handshake is still in progress,
* or 1 on completion.
*/
int rd_kafka_transport_ssl_handshake(rd_kafka_transport_t *rktrans) {
rd_kafka_broker_t *rkb = rktrans->rktrans_rkb;
char errstr[512];
int r;
r = SSL_do_handshake(rktrans->rktrans_ssl);
if (r == 1) {
/* SSL handshake done. Verify. */
if (rd_kafka_transport_ssl_verify(rktrans) == -1)
return -1;
rd_kafka_transport_connect_done(rktrans, NULL);
return 1;
} else if (rd_kafka_transport_ssl_io_update(rktrans, r, errstr,
sizeof(errstr)) == -1) {
const char *extra = "";
rd_kafka_resp_err_t err = RD_KAFKA_RESP_ERR__SSL;
if (strstr(errstr, "unexpected message"))
extra =
": client SSL authentication might be "
"required (see ssl.key.location and "
"ssl.certificate.location and consult the "
"broker logs for more information)";
else if (strstr(errstr,
"tls_process_server_certificate:"
"certificate verify failed") ||
strstr(errstr, "error:0A000086") /*openssl3*/ ||
strstr(errstr,
"get_server_certificate:"
"certificate verify failed"))
extra =
": broker certificate could not be verified, "
"verify that ssl.ca.location is correctly "
"configured or root CA certificates are "
"installed"
#ifdef __APPLE__
" (brew install openssl)"
#elif defined(_WIN32)
" (add broker's CA certificate to the Windows "
"Root certificate store)"
#else
" (install ca-certificates package)"
#endif
;
else if (!strcmp(errstr, "Disconnected")) {
extra = ": connecting to a PLAINTEXT broker listener?";
/* Disconnects during handshake are most likely
* not due to SSL, but rather at the transport level */
err = RD_KAFKA_RESP_ERR__TRANSPORT;
}
rd_kafka_broker_fail(rkb, LOG_ERR, err,
"SSL handshake failed: %s%s", errstr,
extra);
return -1;
}
return 0;
}
/**
* @brief Parse a PEM-formatted string into an EVP_PKEY (PrivateKey) object.
*
* @param str Input PEM string, nul-terminated
*
* @remark This method does not provide automatic addition of PEM
* headers and footers.
*
* @returns a new EVP_PKEY on success or NULL on error.
*/
static EVP_PKEY *rd_kafka_ssl_PKEY_from_string(rd_kafka_t *rk,
const char *str) {
BIO *bio = BIO_new_mem_buf((void *)str, -1);
EVP_PKEY *pkey;
pkey = PEM_read_bio_PrivateKey(bio, NULL,
rd_kafka_transport_ssl_passwd_cb, rk);
BIO_free(bio);
return pkey;
}
/**
* @brief Parse a PEM-formatted string into an X509 object.
*
* @param str Input PEM string, nul-terminated
*
* @returns a new X509 on success or NULL on error.
*/
static X509 *rd_kafka_ssl_X509_from_string(rd_kafka_t *rk, const char *str) {
BIO *bio = BIO_new_mem_buf((void *)str, -1);
X509 *x509;
x509 =
PEM_read_bio_X509(bio, NULL, rd_kafka_transport_ssl_passwd_cb, rk);
BIO_free(bio);
return x509;
}
#ifdef _WIN32
/**
* @brief Attempt load CA certificates from a Windows Certificate store.
*/
static int rd_kafka_ssl_win_load_cert_store(rd_kafka_t *rk,
SSL_CTX *ctx,
const char *store_name) {
HCERTSTORE w_store;
PCCERT_CONTEXT w_cctx = NULL;
X509_STORE *store;
int fail_cnt = 0, cnt = 0;
char errstr[256];
wchar_t *wstore_name;
size_t wsize = 0;
errno_t werr;
/* Convert store_name to wide-char */
werr = mbstowcs_s(&wsize, NULL, 0, store_name, strlen(store_name));
if (werr || wsize < 2 || wsize > 1000) {
rd_kafka_log(rk, LOG_ERR, "CERTSTORE",
"Invalid Windows certificate store name: %.*s%s",
30, store_name,
wsize < 2 ? " (empty)" : " (truncated)");
return -1;
}
wstore_name = rd_alloca(sizeof(*wstore_name) * wsize);
werr = mbstowcs_s(NULL, wstore_name, wsize, store_name,
strlen(store_name));
rd_assert(!werr);
w_store = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,
CERT_SYSTEM_STORE_CURRENT_USER |
CERT_STORE_READONLY_FLAG |
CERT_STORE_OPEN_EXISTING_FLAG,
wstore_name);
if (!w_store) {
rd_kafka_log(
rk, LOG_ERR, "CERTSTORE",
"Failed to open Windows certificate "
"%s store: %s",
store_name,
rd_strerror_w32(GetLastError(), errstr, sizeof(errstr)));
return -1;
}
/* Get the OpenSSL trust store */
store = SSL_CTX_get_cert_store(ctx);
/* Enumerate the Windows certs */
while ((w_cctx = CertEnumCertificatesInStore(w_store, w_cctx))) {
X509 *x509;
/* Parse Windows cert: DER -> X.509 */
x509 = d2i_X509(NULL,
(const unsigned char **)&w_cctx->pbCertEncoded,
(long)w_cctx->cbCertEncoded);
if (!x509) {
fail_cnt++;
continue;
}
/* Add cert to OpenSSL's trust store */
if (!X509_STORE_add_cert(store, x509))
fail_cnt++;
else
cnt++;
X509_free(x509);
}
if (w_cctx)
CertFreeCertificateContext(w_cctx);
CertCloseStore(w_store, 0);
rd_kafka_dbg(rk, SECURITY, "CERTSTORE",
"%d certificate(s) successfully added from "
"Windows Certificate %s store, %d failed",
cnt, store_name, fail_cnt);
if (cnt == 0 && fail_cnt > 0)
return -1;
return cnt;
}
/**
* @brief Load certs from the configured CSV list of Windows Cert stores.
*
* @returns the number of successfully loaded certificates, or -1 on error.
*/
static int rd_kafka_ssl_win_load_cert_stores(rd_kafka_t *rk,
SSL_CTX *ctx,
const char *store_names) {
char *s;
int cert_cnt = 0, fail_cnt = 0;
if (!store_names || !*store_names)
return 0;
rd_strdupa(&s, store_names);
/* Parse CSV list ("Root,CA, , ,Something") and load
* each store in order. */
while (*s) {
char *t;
const char *store_name;
int r;
while (isspace((int)*s) || *s == ',')
s++;
if (!*s)
break;
store_name = s;
t = strchr(s, (int)',');
if (t) {
*t = '\0';
s = t + 1;
for (; t >= store_name && isspace((int)*t); t--)
*t = '\0';
} else {
s = "";
}
r = rd_kafka_ssl_win_load_cert_store(rk, ctx, store_name);
if (r != -1)
cert_cnt += r;
else
fail_cnt++;
}
if (cert_cnt == 0 && fail_cnt > 0)
return -1;
return cert_cnt;
}
#endif /* MSC_VER */
/**
* @brief Probe for the system's CA certificate location and if found set it
* on the \p CTX.
*
* @returns 0 if CA location was set, else -1.
*/
static int rd_kafka_ssl_probe_and_set_default_ca_location(rd_kafka_t *rk,
SSL_CTX *ctx) {
#if _WIN32
/* No standard location on Windows, CA certs are in the ROOT store. */
return -1;
#else
/* The probe paths are based on:
* https://www.happyassassin.net/posts/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
* Golang's crypto probing paths:
* https://golang.org/search?q=certFiles and certDirectories
*/
static const char *paths[] = {
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/certs/ca-bundle.crt",
"/etc/pki/tls/certs/ca-bundle.trust.crt",
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
"/etc/ssl/ca-bundle.pem",
"/etc/pki/tls/cacert.pem",
"/etc/ssl/cert.pem",
"/etc/ssl/cacert.pem",
"/etc/certs/ca-certificates.crt",
"/etc/ssl/certs/ca-certificates.crt",
"/etc/ssl/certs",
"/usr/local/etc/ssl/cert.pem",
"/usr/local/etc/ssl/cacert.pem",
"/usr/local/etc/ssl/certs/cert.pem",
"/usr/local/etc/ssl/certs/cacert.pem",
/* BSD */
"/usr/local/share/certs/ca-root-nss.crt",
"/etc/openssl/certs/ca-certificates.crt",
#ifdef __APPLE__
"/private/etc/ssl/cert.pem",
"/private/etc/ssl/certs",
"/usr/local/etc/[email protected]/cert.pem",
"/usr/local/etc/[email protected]/cert.pem",
"/usr/local/etc/openssl/certs",
"/System/Library/OpenSSL",
#endif
#ifdef _AIX
"/var/ssl/certs/ca-bundle.crt",
#endif
NULL,
};
const char *path = NULL;
int i;
for (i = 0; (path = paths[i]); i++) {
struct stat st;
rd_bool_t is_dir;
int r;
if (stat(path, &st) != 0)
continue;
is_dir = S_ISDIR(st.st_mode);
if (is_dir && rd_kafka_dir_is_empty(path))
continue;
rd_kafka_dbg(rk, SECURITY, "CACERTS",
"Setting default CA certificate location "
"to %s, override with ssl.ca.location",
path);
r = SSL_CTX_load_verify_locations(ctx, is_dir ? NULL : path,
is_dir ? path : NULL);
if (r != 1) {
char errstr[512];
/* Read error and clear the error stack */
rd_kafka_ssl_error(rk, NULL, errstr, sizeof(errstr));
rd_kafka_dbg(rk, SECURITY, "CACERTS",
"Failed to set default CA certificate "
"location to %s %s: %s: skipping",
is_dir ? "directory" : "file", path,
errstr);
continue;
}
return 0;
}
rd_kafka_dbg(rk, SECURITY, "CACERTS",
"Unable to find any standard CA certificate"
"paths: is the ca-certificates package installed?");
return -1;
#endif
}
/**
* @brief Registers certificates, keys, etc, on the SSL_CTX
*
* @returns -1 on error, or 0 on success.
*/
static int rd_kafka_ssl_set_certs(rd_kafka_t *rk,
SSL_CTX *ctx,
char *errstr,
size_t errstr_size) {
rd_bool_t ca_probe = rd_true;
rd_bool_t check_pkey = rd_false;
int r;
/*
* ssl_ca, ssl.ca.location, or Windows cert root store,
* or default paths.
*/
if (rk->rk_conf.ssl.ca) {
/* CA certificate chain set with conf_set_ssl_cert() */
rd_kafka_dbg(rk, SECURITY, "SSL",
"Loading CA certificate(s) from memory");
SSL_CTX_set_cert_store(ctx, rk->rk_conf.ssl.ca->store);
/* OpenSSL takes ownership of the store */
rk->rk_conf.ssl.ca->store = NULL;
ca_probe = rd_false;
} else {
if (rk->rk_conf.ssl.ca_location &&
strcmp(rk->rk_conf.ssl.ca_location, "probe")) {
/* CA certificate location, either file or directory. */
int is_dir =
rd_kafka_path_is_dir(rk->rk_conf.ssl.ca_location);