-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgtm_tls_impl.c
More file actions
2408 lines (2297 loc) · 85.7 KB
/
gtm_tls_impl.c
File metadata and controls
2408 lines (2297 loc) · 85.7 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
/****************************************************************
* *
* Copyright (c) 2013-2023 Fidelity National Information *
* Services, Inc. and/or its subsidiaries. All rights reserved. *
* *
* Copyright (c) 2018-2025 YottaDB LLC and/or its subsidiaries. *
* All rights reserved. *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/time.h>
#include <dlfcn.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <libconfig.h>
#include "gtmxc_types.h"
#include "gtmcrypt_util.h"
#include "ydb_tls_interface.h"
#include "gtm_tls_impl.h"
#include "gtm_tls_externalcalls.h"
#include "ydb_getenv.h"
#ifdef DEBUG
#include <stdlib.h>
#include <assert.h> /* Use "assert" macro to check assertions in DEBUG builds */
#endif
GBLDEF int tls_errno;
GBLDEF gtmtls_passwd_list_t *gtmtls_passwd_listhead;
STATICDEF config_t gtm_tls_cfg;
STATICDEF gtm_tls_ctx_t *gtm_tls_ctx = NULL;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
STATICDEF DH *dh512, *dh1024; /* Diffie-Hellman structures for Ephemeral Diffie-Hellman key exchange. */
#endif
#ifdef DEBUG
STATICDEF char *wbox_enable = NULL, *wbox_tls_check = NULL,
*wbox_count = NULL, *wbox_test_count = NULL;
STATICDEF int wbox_count_val = 0, wbox_test_count_val = 0, wbox_enable_val = 0, wbox_tls_check_val = 0;
#define TRUE 1
#define FALSE 0
#define WBTEST_REPL_TLS_RECONN 169
#endif
#define MAX_CONFIG_LOOKUP_PATHLEN 64
/* Older, but still commonly used, OpenSSL versions don't have macros for TLSv1.1, TLSv1.2 and TLSv1.3 versions.
* They are hard coded. So, define them here for use in gtm_tls_get_conn_info.
*/
#ifndef TLS1_1_VERSION
#define TLS1_1_VERSION 0x0302
#endif
#ifndef TLS1_2_VERSION
#define TLS1_2_VERSION 0x0303
#endif
#ifndef TLS1_3_VERSION
#define TLS1_3_VERSION 0x0304
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
#define PHA_MACROS_ENABLED (SSL_VERIFY_PEER | SSL_VERIFY_POST_HANDSHAKE)
#endif
/* Below template translates to: Arrange ciphers in increasing order of strength after excluding the following:
* ADH: Anonymous Diffie-Hellman Key Exchange (Since we want both encryption and authentication and ADH provides only former).
* LOW: Low strength ciphers.
* EXP: Export Ciphers.
* MD5 : MD5 message digest.
*/
#define REPL_CIPHER_LIST "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"
#define GTM_DEFAULT_CIPHER_LIST "DEFAULT:!SRP"
#define CIPHER_LIST_SIZE 4096
#define ERR_STR_SIZE 2048
#define OPTIONEND ':'
#define OPTIONENDSTR ":"
#define OPTIONNOT '!'
#define DEFINE_SSL_OP(OP_DEF) { #OP_DEF , OP_DEF }
/* Macros for the external call function input parameters */
#define TLS1_2_STR "tls1_2"
#define TLS1_3_STR "tls1_3"
#define SOCKET_STR "SOCKET"
#define REPLICATION_STR "REPLICATION"
#define COMPILE_TIME_STR "compile-time"
#define RUN_TIME_STR "run-time"
#define SET_AND_APPEND_OPENSSL_ERROR(...) \
{ \
char *errptr, *end; \
int rv; \
\
rv = gtm_tls_set_error(NULL, __VA_ARGS__); \
end = errptr = (char *)gtm_tls_get_error(NULL); \
end += MAX_GTMCRYPT_ERR_STRLEN; \
errptr += rv; \
if (end > errptr) \
{ \
rv = snprintf(errptr, end - errptr, "%s", " Reason: "); \
if (0 <= rv) \
errptr += rv; \
} \
if (end > errptr) \
{ \
rv = ERR_get_error(); \
ERR_error_string_n(rv, errptr, end - errptr); \
} \
}
struct gtm_ssl_options
{
const char *opt_str;
long opt_val;
};
STATICDEF struct gtm_ssl_options gtm_ssl_verify_level_list[]=
{
{ "CHECK", GTMTLS_OP_VERIFY_LEVEL_CHECK },
{NULL, 0}
};
STATICDEF struct gtm_ssl_options gtm_ssl_verify_mode_list[] =
{
#include "gen_tls_verify_options.h"
{NULL, 0}
};
STATICDEF struct gtm_ssl_options gtm_ssl_options_list[] =
{
#include "gen_tls_options.h"
#ifndef SSL_OP_NO_TLSv1_3
/* Special case: define this option so that pre OpenSSL 1.1.1 recognize it */
# define SSL_OP_NO_TLSv1_3 0x0
DEFINE_SSL_OP(SSL_OP_NO_TLSv1_3),
#endif
{NULL, 0}
};
#ifdef SSL_OP_NO_TLSv1
#define GTM_NO_TLSv1 | SSL_OP_NO_TLSv1
#else
#define GTM_NO_TLSv1
#endif
#ifdef SSL_OP_NO_TLSv1_1
#define GTM_NO_TLSv1_1 | SSL_OP_NO_TLSv1_1
#else
#define GTM_NO_TLSv1_1
#endif
/* Deprecate all SSL/TLS Protocols before TLS v1.2 */
#define DEPRECATED_SSLTLS_PROTOCOLS (SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 GTM_NO_TLSv1 GTM_NO_TLSv1_1)
/* Static function definitions */
STATICFNDEF char *parse_SSL_options(struct gtm_ssl_options *opt_table, size_t opt_table_size, const char *options, long *current,
long *clear);
STATICFNDEF int gtm_tls_set_error(gtm_tls_socket_t *tlssocket, const char *format, ...);
STATICFNDEF void gtm_tls_copy_gcerror(gtm_tls_socket_t *tlssocket);
STATICFNDEF char *parse_SSL_options(struct gtm_ssl_options *opt_table, size_t opt_table_size, const char *options, long *current,
long *clear)
{
size_t num_options, index, optionlen;
long bitmask;
const char *charptr, *optionend;
if (NULL == options)
return 0;
bitmask = *current;
num_options = opt_table_size/SIZEOF(struct gtm_ssl_options);
for (charptr = options; *charptr; charptr = optionend)
{
int negate;
if (OPTIONEND == *charptr)
if ('\0' == *++charptr)
break;
optionend = strstr((const char *)charptr, OPTIONENDSTR);
if (NULL == optionend)
optionend = charptr + strlen(charptr);
if (OPTIONNOT == *charptr)
{
negate = TRUE;
charptr++;
} else
negate = FALSE;
optionlen = optionend - charptr;
for (index = 0; num_options > index ; index++)
{
if (NULL == opt_table[index].opt_str)
break;
if ((optionlen == strlen(opt_table[index].opt_str))
&& (0 == strncmp(opt_table[index].opt_str, charptr, optionlen)))
{
if (negate)
{
bitmask &= ~opt_table[index].opt_val;
if (NULL != clear)
*clear |= opt_table[index].opt_val;
} else
bitmask |= opt_table[index].opt_val;
break;
}
}
if ((num_options - 1) <= index) /* last option is NULL */
return (char *)charptr; /* option not known */
}
*current = bitmask;
return NULL;
}
#ifdef DEBUG_SSL
#define SSL_DPRINT(FP, ...) {fprintf(FP, __VA_ARGS__); fflush(FP);} /* BYPASSOK -- cannot use FFLUSH. */
#define DEBUG_SSL_ONLY(X) X
#else
#define SSL_DPRINT(FP, ...)
#define DEBUG_SSL_ONLY(X)
#endif
/* In PRO builds (where DEBUG macro is not defined), define assert(x) to be no-op.
* In DEBUG builds, use system assert defined by <assert.h>.
*/
#ifndef DEBUG
#define assert(X)
#endif
/* OpenSSL doesn't provide an easy way to convert an ASN1 time to a string format unless BIOs are used. So, use a memory BIO to
* write the string representation of ASN1_TIME in the said buffer.
*/
STATICFNDEF int format_ASN1_TIME(ASN1_TIME *tm, char *buf, int maxlen)
{
BIO *memfp;
int len;
if (NULL == (memfp = BIO_new(BIO_s_mem())))
return -1;
ASN1_TIME_print(memfp, tm);
len = BIO_pending(memfp);
len = len < maxlen ? len : maxlen;
if (0 >= BIO_read(memfp, buf, len))
return -1;
if (0 >= BIO_free(memfp))
return -1;
buf[len] = '\0';
return 0;
}
STATICFNDEF int ssl_error(gtm_tls_socket_t *tls_sock, int err, long verify_result)
{
int ssl_error_code, reason_code, err_lib, error_code2;
unsigned long error_code;
char *errptr, *end;
SSL *ssl;
#ifdef DEBUG
int is_wb = FALSE;
#endif
ssl = tls_sock->ssl;
ssl_error_code = SSL_get_error(ssl, err); /* generic error code */
#ifdef DEBUG
/* Change the error code to induce error in case of
* WBTEST_REPL_TLS_RECONN white box.
*/
if ((1 == wbox_enable_val) && (WBTEST_REPL_TLS_RECONN == wbox_tls_check_val)
&& (wbox_test_count_val == wbox_count_val))
{
SSL_DPRINT(stderr, "Prev code: %d setting code to: %d\n",
ssl_error_code,SSL_ERROR_SSL);
is_wb = TRUE;
ssl_error_code = SSL_ERROR_SSL;
}
#endif
switch (ssl_error_code)
{
case SSL_ERROR_ZERO_RETURN:
/* SSL/TLS connection has been closed gracefully. The underlying TCP/IP connection is not yet closed. The
* caller should take necessary action to close the underlying transport
*/
tls_errno = ECONNRESET;
break;
/* Below is from https://www.openssl.org/docs/man3.0/man3/SSL_get_error.html.
*
* (1) On an unexpected EOF, versions before OpenSSL 3.0 returned SSL_ERROR_SYSCALL, nothing was added
* to the error stack, and errno was 0.
* (2) Since OpenSSL 3.0 the returned error is SSL_ERROR_SSL with a meaningful error on the error stack.
*
* This is taken care of by setting tls_errno to ECONNRESET through the OPENSSL_VERSION_MAJOR checks below.
*/
case SSL_ERROR_SYSCALL:
tls_errno = errno;
# if OPENSSL_VERSION_MAJOR < 3
if (0 == tls_errno) /* If no error at underlying socket, consider a connection reset */
tls_errno = ECONNRESET; /* This handles (1) in the above ECONNRESET comment block */
# else
assert(tls_errno); /* A 0 value of errno in the SSL_ERROR_SYSCALL case should not happen with
* OpenSSL 3 per (2) above. Hence this assert.
*/
# endif
tls_sock->flags |= GTMTLS_OP_NOSHUTDOWN;
break;
case SSL_ERROR_WANT_WRITE:
return GTMTLS_WANT_WRITE;
case SSL_ERROR_WANT_READ:
return GTMTLS_WANT_READ;
case SSL_ERROR_SSL:
case SSL_ERROR_NONE:
errptr = (char *)gtm_tls_get_error(tls_sock);
assert(errptr != NULL);
end = errptr + MAX_GTMCRYPT_ERR_STRLEN;
tls_errno = -1;
if ((GTMTLS_OP_VERIFY_LEVEL_CHECK & tls_sock->flags) && (X509_V_OK != verify_result))
{
gtm_tls_set_error(tls_sock, "certificate verification error: %s",
X509_verify_cert_error_string(verify_result));
return -1;
} else if (SSL_ERROR_NONE == ssl_error_code)
{ /* we are ignoring verify result and no other error */
tls_errno = 0;
/* Return the orginal return value from the prev SSL call,
* since SSL_ERROR_NONE is only returned when ret > 0
*/
return err;
} else if (SSL_ERROR_SSL == ssl_error_code)
{
SSL_DPRINT(stderr, "Resetting the err code\n");
/* Check the first error in the queue */
error_code = ERR_peek_error();
#ifdef DEBUG
assert(error_code || ((1 == wbox_enable_val) && (WBTEST_REPL_TLS_RECONN
== wbox_tls_check_val)));
#endif
err_lib = ERR_GET_LIB(error_code);
reason_code = ERR_GET_REASON(error_code);
#ifdef DEBUG
if (is_wb)
{
reason_code = SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC;
err_lib = ERR_LIB_SSL;
}
#endif
/* Change the returned error only for replication
* and if the error comes from SSL library
*/
if (!(tls_sock->flags & GTMTLS_OP_SOCKET_DEV) && !(tls_sock->flags & GTMTLS_OP_DM_AUDIT)
&& (ERR_LIB_SSL == err_lib) &&
((SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC == reason_code) ||
(SSL_R_SSLV3_ALERT_BAD_RECORD_MAC == reason_code)))
tls_errno = ECONNRESET;
tls_sock->flags |= GTMTLS_OP_NOSHUTDOWN;
}
do
{
error_code2 = ERR_get_error();
# if OPENSSL_VERSION_MAJOR >= 3
if ((SSL_ERROR_SSL == ssl_error_code) && (0x0A000126 == error_code2)) /* 167772454 in decimal */
tls_errno = ECONNRESET; /* This handles (2) in the above ECONNRESET comment block */
# endif
if (0 == error_code2)
{
if (errptr == tls_sock->errstr)
{
/* Very first call to ERR_get_error returned 0. This is very unlikely. Nevertheless
* handle this by updating the error string with a generic error.
*/
gtm_tls_set_error(tls_sock, "Unknown SSL/TLS protocol error.");
return -1;
}
break;
} else if ((errptr < end) && (errptr != tls_sock->errstr))
*errptr++ = ';';
if (errptr >= end)
continue; /* We could break here, but we want to clear the OpenSSL error stack. */
ERR_error_string_n(error_code2, errptr, end - errptr);
errptr += STRLEN(errptr);
} while (TRUE);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_CONNECT:
default:
tls_errno = -1;
gtm_tls_set_error(tls_sock, "Unknown error: %d returned by `SSL_get_error'", ssl_error_code);
assert(FALSE);
break;
}
return -1;
}
/* This callback function is called whenever OpenSSL wants to decrypt the private key (e.g., SSL_CTX_check_private_key()). More
* importantly, when OpenSSL calls this callback function, it passes a userdata which provides the callback a hint as to which
* private key this callback function corresponds to. In our case, this hint is equivalent to the TLSID passed to the plugin when
* gtm_tls_socket is called.
*/
STATICFNDEF int passwd_callback(char *buf, int size, int rwflag, void *userdata)
{
passwd_entry_t *pwent;
int len;
pwent = (passwd_entry_t *)userdata;
assert(NULL != pwent);
assert(NULL != pwent->passwd);
len = STRLEN(pwent->passwd);
strncpy(buf, pwent->passwd, size);
if (len >= size)
{
buf[size] = '\0';
len = size - 1;
}
return len;
}
/* The below callback is invoked whenever OpenSSL creates a new session (either because the old session expired or because of a
* renegotiation). Store the session back into the API's socket structure.
*/
STATICFNDEF int new_session_callback(SSL *ssl, SSL_SESSION *session)
{
gtm_tls_socket_t *socket;
/* See SSL_set_app_data for details on why we need to use the compatibility interface: SSL_get_app_data/SSL_set_app_data. */
socket = SSL_get_app_data(ssl);
assert(NULL != socket);
/* Free up the old session. */
SSL_DPRINT(stderr, "new_session_callback: references=%d\n", session->references);
if (socket->session)
SSL_SESSION_free(socket->session);
/* Add the new session to the `socket' structure. */
socket->session = session;
return 1;
}
#if OPENSSL_VERSION_NUMBER < 0x30000000L
STATICFNDEF DH *read_dhparams(const char *dh_fn)
{
BIO *bio;
DH *dh;
if (NULL == (bio = BIO_new_file(dh_fn, "r")))
{
SET_AND_APPEND_OPENSSL_ERROR("Unable to load Diffie-Hellman parameter file: %s.", dh_fn);
return NULL;
}
if (NULL == (dh = (PEM_read_bio_DHparams(bio, NULL, NULL, NULL))))
{
SET_AND_APPEND_OPENSSL_ERROR("Unable to load Diffie-Hellman parameter file: %s.", dh_fn);
return NULL;
}
return dh;
}
STATICFNDEF int init_dhparams(void)
{
int rv1, rv2;
const char *dh512_fn, *dh1024_fn;
if (dh1024)
return 0; /* already have */
rv1 = config_lookup_string(>m_tls_cfg, "tls.dh512", &dh512_fn);
rv2 = config_lookup_string(>m_tls_cfg, "tls.dh1024", &dh1024_fn);
if (!rv1 && !rv2)
return 0; /* No Diffie-Hellman parameters specified in the config file. */
if (!rv1)
{
gtm_tls_set_error(NULL, "Configuration parameter `tls.dh512' not specified.");
return -1;
}
if (!rv2)
{
gtm_tls_set_error(NULL, "Configuration parameter `tls.dh1024' not specified.");
return -1;
}
if (NULL == (dh512 = read_dhparams(dh512_fn)))
return -1;
if (NULL == (dh1024 = read_dhparams(dh1024_fn)))
return -1;
return 0;
}
STATICFNDEF DH *tmp_dh_callback(SSL *ssl, int is_export, int keylength)
{
assert(dh512 && dh1024 && ((512 == keylength) || (1024 == keylength)));
return (512 == keylength) ? dh512 : dh1024;
}
#endif
int gtm_tls_errno(void)
{
return tls_errno;
}
/* Interlude to snprintf that uses the appropriate buffer. Function can return bytes written for callers that care */
STATICFNDEF int gtm_tls_set_error(gtm_tls_socket_t *tlssocket, const char *format, ...)
{
char *errstr = NULL;
va_list var;
int ret = 0;
assert(NULL != gtmtls_err_string);
if (NULL != tlssocket)
{ /* Separate DB and network error strings */
if (NULL == tlssocket->errstr)
{
errstr = tlssocket->errstr = malloc(MAX_GTMCRYPT_ERR_STRLEN);
if (NULL != errstr)
errstr[0] = '\0';
}
assert(NULL != tlssocket->errstr);
}
if (NULL == errstr)
errstr = (NULL != gtmtls_err_string)? gtmtls_err_string : gtmcrypt_err_string;
va_start(var, format);
ret = vsnprintf(errstr, MAX_GTMCRYPT_ERR_STRLEN, format, var);
va_end(var);
return ret;
}
/* Copies error messages set by the DB encryption routines shared by the SSL/TLS reference implementation. */
STATICFNDEF void gtm_tls_copy_gcerror(gtm_tls_socket_t *tlssocket)
{
assert(strlen(gtmcrypt_err_string)); /* If no error why copy? */
if ((NULL != tlssocket) && (NULL != tlssocket->errstr)) /* socket specific error string present */
memcpy(tlssocket->errstr, gtmcrypt_err_string, MAX_GTMCRYPT_ERR_STRLEN);
else if (gtmtls_err_string) /* TLS implementation's general error string */
memcpy(gtmtls_err_string, gtmcrypt_err_string, MAX_GTMCRYPT_ERR_STRLEN);
}
const char *gtm_tls_get_error(gtm_tls_socket_t *tlssocket)
{
if ((NULL != tlssocket) && (NULL != tlssocket->errstr))
return tlssocket->errstr; /* socket specific error string present */
if (gtmtls_err_string)
return gtmtls_err_string; /* TLS implementation's general error string */
return gtmcrypt_err_string; /* DB encryption error string */
}
int gtm_tls_version(int caller_version)
{
return GTM_TLS_API_VERSION;
}
gtm_tls_ctx_t *gtm_tls_init(int version, int flags)
{
const char *CAfile = NULL, *CApath = NULL, *crl, *CAptr, *cipher_list, *options_string, *verify_mode_string;
const char *verify_level_string;
char *config_env, *parse_ptr, *optionendptr;
int rv, rv1, rv2, fips_requested, fips_enabled, verify_mode, parse_len, verify_level;
# if (((LIBCONFIG_VER_MAJOR == 1) && (LIBCONFIG_VER_MINOR >= 4)) || (LIBCONFIG_VER_MAJOR > 1))
int verify_depth, session_timeout;
# else
long int verify_depth, session_timeout;
# endif
long options_mask, options_current, options_clear, verify_long, level_long, level_clear;
SSL_CTX *ctx;
X509_STORE *store;
X509_LOOKUP *lookup;
config_t *cfg;
if (NULL != gtm_tls_ctx) /* Non-null implies a repeat call which is possible when using the external call interface */
return gtm_tls_ctx;
assert(GTM_TLS_API_VERSION >= version); /* Make sure the caller is using the right API version */
if (NULL == (gtmtls_err_string = malloc(MAX_GTMCRYPT_ERR_STRLEN + 1)))
{
gtm_tls_set_error(NULL, "Unable to allocate error buffer for libgtmtls.so plugin");
return NULL;
} else
gtmtls_err_string[0] = '\0';
if (GTM_TLS_API_VERSION < version)
{
gtm_tls_set_error(NULL, "Version of libgtmtls.so plugin (%d) older than needed by caller (%d).",
GTM_TLS_API_VERSION, version);
return NULL;
}
/* Setup function pointers to symbols exported by libyottadb.so. */
if (0 != gc_load_yottadb_symbols())
return NULL;
/* Initialize OpenSSL library */
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/* The following options are initialzied by default:
* OPENSSL_INIT_LOAD_CRYPTO_STRINGS
* OPENSSL_INIT_ADD_ALL_CIPHERS
* OPENSSL_INIT_ADD_ALL_DIGESTS
* OPENSSL_INIT_LOAD_CONFIG as of 1.1.1 - second parameter is path to file; NULL means OS default
* OPENSSL_INIT_ASYNC
*
* The following are manually added:
* OPENSSL_INIT_NO_ATEXIT - suppress OpenSSL's "atexit" handler (new OpenSSL 3.0)
*/
# ifndef OPENSSL_INIT_NO_ATEXIT
# define OPENSSL_INIT_NO_ATEXIT 0
# endif
# define GTMTLS_STARTUP_OPTIONS (OPENSSL_INIT_NO_ATEXIT)
if (!OPENSSL_init_ssl(GTMTLS_STARTUP_OPTIONS, NULL))
{ /* Can't use SET_AND_APPEND_OPENSSL_ERROR which needs the above to initialize error reporting functions */
gtm_tls_set_error(NULL, "OpenSSL library initialization failed");
return NULL;
}
#else
/* Initialize the SSL/TLS library, the algorithms/cipher suite and error strings. */
SSL_library_init();
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
#endif
/* Turn on FIPS mode if requested. */
fips_enabled = FALSE; /* most common case. */
IS_FIPS_MODE_REQUESTED(fips_requested);
if (fips_requested)
{
ENABLE_FIPS_MODE(rv, fips_enabled);
if (-1 == rv)
return NULL; /* Relevant error detail populated in the above macro. */
}
/* Setup a SSL context that allows TLSv1.x but no SSLv[23] (which is deprecated due to a great number of security
* vulnerabilities).
*/
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (NULL == (ctx = SSL_CTX_new(TLS_method())))
#else
if (NULL == (ctx = SSL_CTX_new(SSLv23_method())))
#endif
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to create an SSL context.");
return NULL;
}
SSL_CTX_set_options(ctx, DEPRECATED_SSLTLS_PROTOCOLS);
/* Read the configuration file for more configuration parameters. */
cfg = >m_tls_cfg;
config_init(cfg);
if (NULL == (config_env = ydb_getenv(YDBENVINDX_CRYPT_CONFIG, NULL_SUFFIX, NULL_IS_YDB_ENV_MATCH)))
{
if (!(GTMTLS_OP_INTERACTIVE_MODE & flags))
{ /* allow no config file if interactive for simple client usage */
gtm_tls_set_error(NULL, ENV_UNDEF_ERROR, "ydb_crypt_config/gtmcrypt_config");
SSL_CTX_free(ctx);
return NULL;
} else
flags |= GTMTLS_OP_ABSENT_CONFIG;
} else if (!config_read_file(cfg, config_env))
{
gtm_tls_set_error(NULL, "Failed to read config file: %s. At line: %d, %s.", config_env, config_error_line(cfg),
config_error_text(cfg));
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
if (!(GTMTLS_OP_ABSENT_CONFIG & flags))
{ /* check for tls section */
if (NULL == config_lookup(cfg, "tls"))
{
if ((GTMTLS_OP_INTERACTIVE_MODE & flags))
flags |= GTMTLS_OP_ABSENT_CONFIG;
else
{
gtm_tls_set_error(NULL, "No tls: section in config file: %s", config_env);
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
}
}
/* Get global SSL configuration parameters */
if (config_lookup_int(cfg, "tls.verify-depth", &verify_depth))
SSL_CTX_set_verify_depth(ctx, verify_depth);
if (CONFIG_TRUE == config_lookup_string(cfg, "tls.verify-mode", &verify_mode_string))
{
verify_long = 0;
parse_ptr = parse_SSL_options(>m_ssl_verify_mode_list[0], SIZEOF(gtm_ssl_verify_mode_list),
verify_mode_string, &verify_long, NULL);
if (NULL != parse_ptr)
{
optionendptr = strstr((const char *)parse_ptr, OPTIONENDSTR);
if (NULL == optionendptr)
parse_len = strlen(parse_ptr);
else
parse_len = optionendptr - parse_ptr;
gtm_tls_set_error(NULL, "Unknown verify-mode option: %.*s", parse_len, parse_ptr);
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
verify_mode = (int)verify_long;
SSL_CTX_set_verify(ctx, verify_mode, NULL);
} else
flags |= GTMTLS_OP_ABSENT_VERIFYMODE;
if (CONFIG_TRUE == config_lookup_string(cfg, "tls.verify-level", &verify_level_string))
{
level_long = GTMTLS_OP_VERIFY_LEVEL_MASK & flags;
level_clear = 0;
parse_ptr = parse_SSL_options(>m_ssl_verify_level_list[0], SIZEOF(gtm_ssl_verify_level_list),
verify_level_string, &level_long, &level_clear);
if (NULL != parse_ptr)
{
optionendptr = strstr((const char *)parse_ptr, OPTIONENDSTR);
if (NULL == optionendptr)
parse_len = strlen(parse_ptr);
else
parse_len = optionendptr - parse_ptr;
gtm_tls_set_error(NULL, "Unknown verify-level option: %.*s", parse_len, parse_ptr);
return NULL;
}
if (0 != level_clear)
{
verify_level = (int)level_clear;
flags &= ~verify_level;
}
verify_level = (int)level_long;
flags = (GTMTLS_OP_VERIFY_LEVEL_CMPLMNT & flags) | verify_level;
} else
flags |= GTMTLS_OP_VERIFY_LEVEL_DEFAULT;
rv1 = config_lookup_string(cfg, "tls.CAfile", &CAfile);
rv2 = config_lookup_string(cfg, "tls.CApath", &CApath);
/* Setup trust locations for peer verifications. This adds on to any trust locations that was previously loaded. */
if ((rv1 || rv2) && !SSL_CTX_load_verify_locations(ctx, CAfile, CApath))
{
if (rv1 && rv2)
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to load CA verification locations (CAfile = %s; CApath = %s).",
CAfile, CApath);
} else
{
CAptr = rv1 ? CAfile : CApath;
SET_AND_APPEND_OPENSSL_ERROR("Failed to load CA verification location: %s.", CAptr);
}
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
if (rv1 || rv2)
flags |= GTMTLS_OP_CA_LOADED;
/* Load the default verification paths as well. On most Unix distributions, the default path is set to /etc/ssl/certs. */
if (!SSL_CTX_set_default_verify_paths(ctx))
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to load default CA verification locations.");
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
/* If a CRL is specified in the configuration file, add it to the cert store. */
if (config_lookup_string(cfg, "tls.crl", &crl))
{
if (NULL == (store = SSL_CTX_get_cert_store(ctx)))
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to get handle to internal certificate store.");
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
if (NULL == (lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file())))
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to get handle to internal certificate store.");
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
if (0 == X509_LOOKUP_load_file(lookup, (char *)crl, X509_FILETYPE_PEM))
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to add Certificate Revocation List %s to internal certificate store.",
crl);
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
}
SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
/* Set callbacks to called whenever a SSL session is added. */
SSL_CTX_sess_set_new_cb(ctx, new_session_callback);
/* Set session timeout value (in seconds). If the current time is greater than the session creation time + session
* timeout, the session is not reused. This is useful only on the server.
*/
if (config_lookup_int(cfg, "tls.session-timeout", &session_timeout))
{
if (0 >= session_timeout)
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
else
SSL_CTX_set_timeout(ctx, session_timeout);
} else
SSL_CTX_set_timeout(ctx, DEFAULT_SESSION_TIMEOUT);
if (CONFIG_FALSE == config_lookup_string(cfg, "tls.cipher-list", &cipher_list))
cipher_list = NULL;
else if (('\0' != cipher_list[0]) && (0 >= SSL_CTX_set_cipher_list(ctx, cipher_list))
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
&& (0 >= SSL_CTX_set_ciphersuites(ctx, cipher_list))
#endif
)
{
SET_AND_APPEND_OPENSSL_ERROR("Failed to add Cipher-List command string: %s.", cipher_list);
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
} /* use OpenSSL default */
if (CONFIG_TRUE == config_lookup_string(cfg, "tls.ssl-options", &options_string))
{
options_mask = options_current = SSL_CTX_get_options(ctx);
options_clear = 0;
parse_ptr = parse_SSL_options(>m_ssl_options_list[0], SIZEOF(gtm_ssl_options_list), options_string,
&options_mask, &options_clear);
if (NULL != parse_ptr)
{
optionendptr = strstr((const char *)parse_ptr, OPTIONENDSTR);
if (NULL == optionendptr)
parse_len = strlen(parse_ptr);
else
parse_len = optionendptr - parse_ptr;
gtm_tls_set_error(NULL, "Unknown ssl-options option: %.*s", parse_len, parse_ptr);
SSL_CTX_free(ctx);
config_destroy(cfg);
return NULL;
}
if (options_current != options_mask)
options_mask = SSL_CTX_set_options(ctx, options_mask);
if (0 != options_clear)
options_mask = SSL_CTX_clear_options(ctx, options_clear);
}
/* Support for ECDHE Ciphers was added in OpenSSL 1.0.2 with the below.
* OpenSSL 1.1.0 made this the default and made the function a no-op
*/
SSL_CTX_set_ecdh_auto(ctx, 1);
gtm_tls_ctx = MALLOC(SIZEOF(gtm_tls_ctx_t));
gtm_tls_ctx->ctx = ctx;
if (NULL == cipher_list)
flags |= GTMTLS_OP_ABSENT_CIPHER;
else if ('\0' == cipher_list[0])
flags |= GTMTLS_OP_DEFAULT_CIPHER;
gtm_tls_ctx->flags = flags;
gtm_tls_ctx->fips_mode = fips_enabled;
gtm_tls_ctx->compile_time_version = OPENSSL_VERSION_NUMBER;
gtm_tls_ctx->runtime_version = SSLeay();
gtm_tls_ctx->version = version; /* GTM_TLS_API_VERSION of caller */
if (GTM_TLS_API_VERSION_NONBLOCK <= version)
gtm_tls_ctx->plugin_version = GTM_TLS_API_VERSION;
return gtm_tls_ctx;
}
STATICFNDEF gtmtls_passwd_list_t *gtm_tls_find_pwent(char *input_suffix)
{
gtmtls_passwd_list_t *pwent_node;
char *suffix;
int suffixlen, input_suffixlen;
input_suffixlen = (NULL != input_suffix) ? STRLEN(input_suffix) : 0;
for (pwent_node = gtmtls_passwd_listhead; NULL != pwent_node; pwent_node = pwent_node->next)
{ /* Lookup to see if we already have a password for the tlsid. */
suffix = pwent_node->pwent->suffix;
suffixlen = STRLEN(suffix);
if ((suffixlen == input_suffixlen) && (0 == strcmp(input_suffix, suffix)))
break; /* We already have a password for the tlsid. */
}
return pwent_node;
}
int gtm_tls_store_passwd(gtm_tls_ctx_t *tls_ctx, const char *tlsid, const char *obs_passwd)
{
size_t obs_len;
gtmtls_passwd_list_t *pwent_node;
passwd_entry_t *pwent;
assert(tls_ctx);
if (!(GTMTLS_OP_INTERACTIVE_MODE & tls_ctx->flags))
return 0; /* Not running in an interactive mode. */
assert(NULL != tlsid);
assert(0 < STRLEN(tlsid));
obs_len = STRLEN(obs_passwd);
pwent_node = gtm_tls_find_pwent((char *)tlsid);
if (NULL != pwent_node)
{
pwent = pwent_node->pwent;
if ((obs_len == ((size_t)pwent->passwd_len * 2)) && (0 == strncmp(obs_passwd, pwent->passwd, obs_len)))
return 1; /* already on the list */
}
/* Either no entry for tlsid or need to replace with new value */
pwent = MALLOC(SIZEOF(passwd_entry_t));
assert(NULL != pwent);
pwent->envindx = YDBENVINDX_TLS_PASSWD_PREFIX;
SNPRINTF(pwent->suffix, SIZEOF(pwent->suffix), "%s", tlsid);
pwent->env_value = MALLOC(obs_len + 1);
memcpy(pwent->env_value, obs_passwd, obs_len + 1); /* include null */
pwent->passwd = NULL;
pwent->passwd_len = 0;
if (0 == gc_update_passwd(YDBENVINDX_TLS_PASSWD_PREFIX, (char *)tlsid, &pwent, NULL, GTMTLS_OP_NOPWDENVVAR))
{
pwent_node = MALLOC(SIZEOF(gtmtls_passwd_list_t));
pwent_node->next = gtmtls_passwd_listhead;
pwent_node->pwent = pwent;
gtmtls_passwd_listhead = pwent_node;
} else
{
gtm_tls_copy_gcerror(NULL);
return -1; /* gc_update_passwd freed pwent */
}
return 1;
}
void gtm_tls_prefetch_passwd(gtm_tls_ctx_t *tls_ctx, char *env_name)
{
char *env_name_ptr, *env_value, prompt[GTM_PASSPHRASE_MAX_ASCII + 1];
gtmtls_passwd_list_t *pwent_node;
passwd_entry_t *pwent;
assert(FALSE); /* This assert replaces the below assert which is commented since this code is currently
* not invoked by anyone (which is what the new assert checks) but if/when this code
* is invoked, the above "getenv" call needs to be converted to an appropriate "ydb_getenv" call.
*/
# ifdef GTM_SOCKET_SSL_SUPPORT
assert((NULL != (env_value = getenv(env_name))) && (0 == STRLEN(env_value)));
if (!(GTMTLS_OP_INTERACTIVE_MODE & tls_ctx->flags))
return; /* Not running in an interactive mode. Cannot prompt for password. */
env_name_ptr = (char *)env_name;
assert(PASSPHRASE_ENVNAME_MAX > STRLEN(env_name_ptr));
assert(SIZEOF(GTMTLS_PASSWD_ENV_PREFIX) - 1 < STRLEN(env_name_ptr));
env_name_ptr += (SIZEOF(GTMTLS_PASSWD_ENV_PREFIX) - 1);
SNPRINTF(prompt, GTM_PASSPHRASE_MAX_ASCII, "Enter passphrase for TLSID %s: ", env_name_ptr);
pwent = NULL;
assert(FALSE); /* this is for the NULL use in the 2nd parameter below. It needs to be a non-null suffix string
* but not sure what that is now since this is unused code. Fix it if/when this assert fails.
*/
if (0 == gc_update_passwd(YDBENVINDX_TLS_PASSWD_PREFIX, NULL, &pwent, prompt, TRUE))
{
pwent_node = MALLOC(SIZEOF(gtmtls_passwd_list_t));
pwent_node->next = gtmtls_passwd_listhead;
pwent_node->pwent = pwent;
gtmtls_passwd_listhead = pwent_node;
} else /* Later, gtm_tls_socket makes another attempt to acquire the password. Keep the error just in case */
gtm_tls_copy_gcerror(NULL);
# endif
}
static int copy_tlsid_elem(const config_t *tmpcfg, config_t *cfg, config_setting_t *tlsid, const char *idstr, const char *elemname,
int type);
static int copy_tlsid_elem(const config_t *tmpcfg, config_t *cfg, config_setting_t *tlsid, const char *idstr, const char *elemname,
int type)
{
config_setting_t *srcelem, *elem;
char cfg_path[MAX_CONFIG_LOOKUP_PATHLEN];
SNPRINTF(cfg_path, MAX_CONFIG_LOOKUP_PATHLEN, "tls.%s.%s", idstr, elemname);
srcelem = config_lookup(tmpcfg, cfg_path);
if (NULL != srcelem)
{
elem = config_lookup(cfg, cfg_path);
if (NULL == elem)
{ /* option not currently in tls.idstr so create */
elem = config_setting_add(tlsid, elemname, type);
if (NULL == elem)
{
gtm_tls_set_error(NULL, "Failed to add TLSID: %s item %s to config file: %s",
idstr, elemname, config_error_text(cfg));
return -1;
}
}
if (CONFIG_TYPE_STRING == type)
config_setting_set_string(elem, config_setting_get_string(srcelem));
else if (CONFIG_TYPE_INT == type)
{
config_setting_set_int(elem, config_setting_get_int(srcelem));
config_setting_set_format(elem, config_setting_get_format(srcelem));
} else
{
gtm_tls_set_error(NULL, "gtm_tls_impl.c/copy_tlsid_elem: Unexpected CONFIG_TYPE %d for item %s",
type, elemname);
return -1;
}
}
return 0;
}
int gtm_tls_add_config(gtm_tls_ctx_t *tls_ctx, const char *idstr, const char *configstr)
{
# ifndef LIBCONFIG_VER_MAJOR
gtm_tls_set_error(NULL, "TLSID: %s: libconfig 1.4.x is needed to support adding config information", idstr);
return -1;
# else
config_t *cfg, tmpcfg;
config_setting_t *tlsid, *tlssect;
char cfg_path[MAX_CONFIG_LOOKUP_PATHLEN];
config_init(&tmpcfg);
if (CONFIG_FALSE == config_read_string(&tmpcfg, configstr))