/
tls-openssl.c
5203 lines (4351 loc) · 146 KB
/
tls-openssl.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
/*************************************************
* Exim - an Internet mail transport agent *
*************************************************/
/* Copyright (c) The Exim Maintainers 2020 - 2022 */
/* Copyright (c) University of Cambridge 1995 - 2019 */
/* See the file NOTICE for conditions of use and distribution. */
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Portions Copyright (c) The OpenSSL Project 1999 */
/* This module provides the TLS (aka SSL) support for Exim using the OpenSSL
library. It is #included into the tls.c file when that library is used. The
code herein is based on a patch that was originally contributed by Steve
Haslam. It was adapted from stunnel, a GPL program by Michal Trojnara.
No cryptographic code is included in Exim. All this module does is to call
functions from the OpenSSL library. */
/* Heading stuff */
#include <openssl/lhash.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_ECDH
# include <openssl/ec.h>
#endif
#ifndef DISABLE_OCSP
# include <openssl/ocsp.h>
#endif
#ifdef SUPPORT_DANE
# include "danessl.h"
#endif
#ifndef DISABLE_OCSP
# define EXIM_OCSP_SKEW_SECONDS (300L)
# define EXIM_OCSP_MAX_AGE (-1L)
#endif
#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
# define EXIM_HAVE_OPENSSL_TLSEXT
#endif
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
# define EXIM_HAVE_RSA_GENKEY_EX
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
# define EXIM_HAVE_OCSP_RESP_COUNT
# define OPENSSL_AUTO_SHA256
# define OPENSSL_MIN_PROTO_VERSION
#else
# define EXIM_HAVE_EPHEM_RSA_KEX
# define EXIM_HAVE_RAND_PSEUDO
#endif
#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
# define EXIM_HAVE_SHA256
#endif
/* X509_check_host provides sane certificate hostname checking, but was added
to OpenSSL late, after other projects forked off the code-base. So in
addition to guarding against the base version number, beware that LibreSSL
does not (at this time) support this function.
If LibreSSL gains a different API, perhaps via libtls, then we'll probably
opt to disentangle and ask a LibreSSL user to provide glue for a third
crypto provider for libtls instead of continuing to tie the OpenSSL glue
into even twistier knots. If LibreSSL gains the same API, we can just
change this guard and punt the issue for a while longer. */
#ifndef LIBRESSL_VERSION_NUMBER
# if OPENSSL_VERSION_NUMBER >= 0x010100000L
# define EXIM_HAVE_OPENSSL_CHECKHOST
# define EXIM_HAVE_OPENSSL_DH_BITS
# define EXIM_HAVE_OPENSSL_TLS_METHOD
# define EXIM_HAVE_OPENSSL_KEYLOG
# define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
# define EXIM_HAVE_SESSION_TICKET
# define EXIM_HAVE_OPESSL_TRACE
# define EXIM_HAVE_OPESSL_GET0_SERIAL
# define EXIM_HAVE_OPESSL_OCSP_RESP_GET0_CERTS
# define EXIM_HAVE_SSL_GET0_VERIFIED_CHAIN
# ifndef DISABLE_OCSP
# define EXIM_HAVE_OCSP
# endif
# define EXIM_HAVE_ALPN /* fail ret from hshake-cb is ignored by LibreSSL */
# else
# define EXIM_NEED_OPENSSL_INIT
# endif
# if OPENSSL_VERSION_NUMBER >= 0x010000000L \
&& (OPENSSL_VERSION_NUMBER & 0x0000ff000L) >= 0x000002000L
# define EXIM_HAVE_OPENSSL_CHECKHOST
# endif
#endif
#if LIBRESSL_VERSION_NUMBER >= 0x3040000fL
# define EXIM_HAVE_OPENSSL_CIPHER_GET_ID
#endif
#if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x030000000L)
# define EXIM_HAVE_EXPORT_CHNL_BNGNG
# define EXIM_HAVE_OPENSSL_X509_STORE_GET1_ALL_CERTS
#endif
#if !defined(LIBRESSL_VERSION_NUMBER) \
|| LIBRESSL_VERSION_NUMBER >= 0x20010000L
# if !defined(OPENSSL_NO_ECDH)
# if OPENSSL_VERSION_NUMBER >= 0x0090800fL
# define EXIM_HAVE_ECDH
# endif
# if OPENSSL_VERSION_NUMBER >= 0x10002000L
# define EXIM_HAVE_OPENSSL_EC_NIST2NID
# endif
# endif
#endif
#ifndef LIBRESSL_VERSION_NUMBER
# if OPENSSL_VERSION_NUMBER >= 0x010101000L
# define OPENSSL_HAVE_KEYLOG_CB
# define OPENSSL_HAVE_NUM_TICKETS
# define EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
# define EXIM_HAVE_EXP_CHNL_BNGNG
# define EXIM_HAVE_OPENSSL_OCSP_RESP_GET0_SIGNER
# define EXIM_HAVE_OPENSSL_SET1_GROUPS
# else
# define OPENSSL_BAD_SRVR_OURCERT
# endif
#endif
#if !defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x010002000L)
# define EXIM_HAVE_EXPORT_CHNL_BNGNG
#endif
#if !defined(EXIM_HAVE_OPENSSL_TLSEXT) && !defined(DISABLE_OCSP)
# warning "OpenSSL library version too old; define DISABLE_OCSP in Makefile"
# define DISABLE_OCSP
#endif
#ifndef DISABLE_TLS_RESUME
# if OPENSSL_VERSION_NUMBER < 0x0101010L
# error OpenSSL version too old for session-resumption
# endif
#endif
#ifdef EXIM_HAVE_OPENSSL_CHECKHOST
# include <openssl/x509v3.h>
#endif
#ifndef EXIM_HAVE_OPENSSL_CIPHER_STD_NAME
# ifndef EXIM_HAVE_OPENSSL_CIPHER_GET_ID
# define SSL_CIPHER_get_id(c) (c->id)
# endif
# ifndef MACRO_PREDEF
# include "tls-cipher-stdname.c"
# endif
#endif
#define TESTSUITE_TICKET_LIFE 10 /* seconds */
/*************************************************
* OpenSSL option parse *
*************************************************/
typedef struct exim_openssl_option {
uschar *name;
long value;
} exim_openssl_option;
/* We could use a macro to expand, but we need the ifdef and not all the
options document which version they were introduced in. Policylet: include
all options unless explicitly for DTLS, let the administrator choose which
to apply.
This list is current as of:
==> 1.1.1c <==
XXX could we autobuild this list, as with predefined-macros?
Seems just parsing ssl.h for SSL_OP_.* would be enough (except to exclude DTLS).
Also allow a numeric literal?
*/
static exim_openssl_option exim_openssl_options[] = {
/* KEEP SORTED ALPHABETICALLY! */
#ifdef SSL_OP_ALL
{ US"all", (long) SSL_OP_ALL },
#endif
#ifdef SSL_OP_ALLOW_NO_DHE_KEX
{ US"allow_no_dhe_kex", SSL_OP_ALLOW_NO_DHE_KEX },
#endif
#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
{ US"allow_unsafe_legacy_renegotiation", SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION },
#endif
#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
{ US"cipher_server_preference", SSL_OP_CIPHER_SERVER_PREFERENCE },
#endif
#ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG
{ US"cryptopro_tlsext_bug", SSL_OP_CRYPTOPRO_TLSEXT_BUG },
#endif
#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
{ US"dont_insert_empty_fragments", SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS },
#endif
#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
{ US"enable_middlebox_compat", SSL_OP_ENABLE_MIDDLEBOX_COMPAT },
#endif
#ifdef SSL_OP_EPHEMERAL_RSA
{ US"ephemeral_rsa", SSL_OP_EPHEMERAL_RSA },
#endif
#ifdef SSL_OP_LEGACY_SERVER_CONNECT
{ US"legacy_server_connect", SSL_OP_LEGACY_SERVER_CONNECT },
#endif
#ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
{ US"microsoft_big_sslv3_buffer", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER },
#endif
#ifdef SSL_OP_MICROSOFT_SESS_ID_BUG
{ US"microsoft_sess_id_bug", SSL_OP_MICROSOFT_SESS_ID_BUG },
#endif
#ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING
{ US"msie_sslv2_rsa_padding", SSL_OP_MSIE_SSLV2_RSA_PADDING },
#endif
#ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG
{ US"netscape_challenge_bug", SSL_OP_NETSCAPE_CHALLENGE_BUG },
#endif
#ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
{ US"netscape_reuse_cipher_change_bug", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG },
#endif
#ifdef SSL_OP_NO_ANTI_REPLAY
{ US"no_anti_replay", SSL_OP_NO_ANTI_REPLAY },
#endif
#ifdef SSL_OP_NO_COMPRESSION
{ US"no_compression", SSL_OP_NO_COMPRESSION },
#endif
#ifdef SSL_OP_NO_ENCRYPT_THEN_MAC
{ US"no_encrypt_then_mac", SSL_OP_NO_ENCRYPT_THEN_MAC },
#endif
#ifdef SSL_OP_NO_RENEGOTIATION
{ US"no_renegotiation", SSL_OP_NO_RENEGOTIATION },
#endif
#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
{ US"no_session_resumption_on_renegotiation", SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION },
#endif
#ifdef SSL_OP_NO_SSLv2
{ US"no_sslv2", SSL_OP_NO_SSLv2 },
#endif
#ifdef SSL_OP_NO_SSLv3
{ US"no_sslv3", SSL_OP_NO_SSLv3 },
#endif
#ifdef SSL_OP_NO_TICKET
{ US"no_ticket", SSL_OP_NO_TICKET },
#endif
#ifdef SSL_OP_NO_TLSv1
{ US"no_tlsv1", SSL_OP_NO_TLSv1 },
#endif
#ifdef SSL_OP_NO_TLSv1_1
# if OPENSSL_VERSION_NUMBER < 0x30000000L
# if SSL_OP_NO_TLSv1_1 == 0x00000400L
/* Error in chosen value in 1.0.1a; see first item in CHANGES for 1.0.1b */
# warning OpenSSL 1.0.1a uses a bad value for SSL_OP_NO_TLSv1_1, ignoring
# define NO_SSL_OP_NO_TLSv1_1
# endif
# endif
# ifndef NO_SSL_OP_NO_TLSv1_1
{ US"no_tlsv1_1", SSL_OP_NO_TLSv1_1 },
# endif
#endif
#ifdef SSL_OP_NO_TLSv1_2
{ US"no_tlsv1_2", SSL_OP_NO_TLSv1_2 },
#endif
#ifdef SSL_OP_NO_TLSv1_3
{ US"no_tlsv1_3", SSL_OP_NO_TLSv1_3 },
#endif
#ifdef SSL_OP_PRIORITIZE_CHACHA
{ US"prioritize_chacha", SSL_OP_PRIORITIZE_CHACHA },
#endif
#ifdef SSL_OP_SAFARI_ECDHE_ECDSA_BUG
{ US"safari_ecdhe_ecdsa_bug", SSL_OP_SAFARI_ECDHE_ECDSA_BUG },
#endif
#ifdef SSL_OP_SINGLE_DH_USE
{ US"single_dh_use", SSL_OP_SINGLE_DH_USE },
#endif
#ifdef SSL_OP_SINGLE_ECDH_USE
{ US"single_ecdh_use", SSL_OP_SINGLE_ECDH_USE },
#endif
#ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG
{ US"ssleay_080_client_dh_bug", SSL_OP_SSLEAY_080_CLIENT_DH_BUG },
#endif
#ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
{ US"sslref2_reuse_cert_type_bug", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG },
#endif
#ifdef SSL_OP_TLS_BLOCK_PADDING_BUG
{ US"tls_block_padding_bug", SSL_OP_TLS_BLOCK_PADDING_BUG },
#endif
#ifdef SSL_OP_TLS_D5_BUG
{ US"tls_d5_bug", SSL_OP_TLS_D5_BUG },
#endif
#ifdef SSL_OP_TLS_ROLLBACK_BUG
{ US"tls_rollback_bug", SSL_OP_TLS_ROLLBACK_BUG },
#endif
#ifdef SSL_OP_TLSEXT_PADDING
{ US"tlsext_padding", SSL_OP_TLSEXT_PADDING },
#endif
};
#ifndef MACRO_PREDEF
static int exim_openssl_options_size = nelem(exim_openssl_options);
static long init_options = 0;
#endif
#ifdef MACRO_PREDEF
void
options_tls(void)
{
uschar buf[64];
for (struct exim_openssl_option * o = exim_openssl_options;
o < exim_openssl_options + nelem(exim_openssl_options); o++)
{
/* Trailing X is workaround for problem with _OPT_OPENSSL_NO_TLSV1
being a ".ifdef _OPT_OPENSSL_NO_TLSV1_3" match */
spf(buf, sizeof(buf), US"_OPT_OPENSSL_%T_X", o->name);
builtin_macro_create(buf);
}
# ifndef DISABLE_TLS_RESUME
builtin_macro_create_var(US"_RESUME_DECODE", RESUME_DECODE_STRING );
# endif
# ifdef SSL_OP_NO_TLSv1_3
builtin_macro_create(US"_HAVE_TLS1_3");
# endif
# ifdef OPENSSL_BAD_SRVR_OURCERT
builtin_macro_create(US"_TLS_BAD_MULTICERT_IN_OURCERT");
# endif
# ifdef EXIM_HAVE_OCSP
builtin_macro_create(US"_HAVE_TLS_OCSP");
builtin_macro_create(US"_HAVE_TLS_OCSP_LIST");
# endif
# ifdef EXIM_HAVE_ALPN
builtin_macro_create(US"_HAVE_TLS_ALPN");
# endif
}
#else
/******************************************************************************/
/* Structure for collecting random data for seeding. */
typedef struct randstuff {
struct timeval tv;
pid_t p;
} randstuff;
/* Local static variables */
static BOOL client_verify_callback_called = FALSE;
static BOOL server_verify_callback_called = FALSE;
static const uschar *sid_ctx = US"exim";
/* We have three different contexts to care about.
Simple case: client, `client_ctx`
As a client, we can be doing a callout or cut-through delivery while receiving
a message. So we have a client context, which should have options initialised
from the SMTP Transport. We may also concurrently want to make TLS connections
to utility daemons, so client-contexts are allocated and passed around in call
args rather than using a gobal.
Server:
There are two cases: with and without ServerNameIndication from the client.
Given TLS SNI, we can be using different keys, certs and various other
configuration settings, because they're re-expanded with $tls_sni set. This
allows vhosting with TLS. This SNI is sent in the handshake.
A client might not send SNI, so we need a fallback, and an initial setup too.
So as a server, we start out using `server_ctx`.
If SNI is sent by the client, then we as server, mid-negotiation, try to clone
`server_sni` from `server_ctx` and then initialise settings by re-expanding
configuration.
*/
typedef struct {
SSL_CTX * ctx;
SSL * ssl;
gstring * corked;
} exim_openssl_client_tls_ctx;
/* static SSL_CTX *server_ctx = NULL; */
/* static SSL *server_ssl = NULL; */
#ifdef EXIM_HAVE_OPENSSL_TLSEXT
static SSL_CTX *server_sni = NULL;
#endif
#ifdef EXIM_HAVE_ALPN
static BOOL server_seen_alpn = FALSE;
#endif
static char ssl_errstring[256];
static int ssl_session_timeout = 7200; /* Two hours */
static BOOL client_verify_optional = FALSE;
static BOOL server_verify_optional = FALSE;
static BOOL reexpand_tls_files_for_sni = FALSE;
typedef struct ocsp_resp {
struct ocsp_resp * next;
OCSP_RESPONSE * resp;
} ocsp_resplist;
typedef struct exim_openssl_state {
exim_tlslib_state lib_state;
#define lib_ctx libdata0
#define lib_ssl libdata1
tls_support * tlsp;
uschar * certificate;
uschar * privatekey;
BOOL is_server;
#ifndef DISABLE_OCSP
union {
struct {
uschar *file;
const uschar *file_expanded;
ocsp_resplist *olist;
STACK_OF(X509) *verify_stack; /* chain for verifying the proof */
} server;
struct {
X509_STORE *verify_store; /* non-null if status requested */
uschar *verify_errstr; /* only if _required */
BOOL verify_required;
} client;
} u_ocsp;
#endif
uschar * dhparam;
/* these are cached from first expand */
uschar * server_cipher_list;
/* only passed down to tls_error: */
host_item * host;
const uschar * verify_cert_hostnames;
#ifndef DISABLE_EVENT
uschar * event_action;
#endif
} exim_openssl_state_st;
/* should figure out a cleanup of API to handle state preserved per
implementation, for various reasons, which can be void * in the APIs.
For now, we hack around it. */
exim_openssl_state_st *client_static_state = NULL; /*XXX should not use static; multiple concurrent clients! */
exim_openssl_state_st state_server = {.is_server = TRUE};
static int
setup_certs(SSL_CTX * sctx, uschar ** certs, uschar * crl, host_item * host,
uschar ** errstr);
/* Callbacks */
#ifndef DISABLE_OCSP
static int tls_server_stapling_cb(SSL *s, void *arg);
static void x509_stack_dump_cert_s_names(const STACK_OF(X509) * sk);
static void x509_store_dump_cert_s_names(X509_STORE * store);
#endif
/* Daemon-called, before every connection, key create/rotate */
#ifndef DISABLE_TLS_RESUME
static void tk_init(void);
static int tls_exdata_idx = -1;
#endif
static void
tls_per_lib_daemon_tick(void)
{
#ifndef DISABLE_TLS_RESUME
tk_init();
#endif
}
/* Called once at daemon startup */
static void
tls_per_lib_daemon_init(void)
{
tls_daemon_creds_reload();
}
/*************************************************
* Handle TLS error *
*************************************************/
/* Called from lots of places when errors occur before actually starting to do
the TLS handshake, that is, while the session is still in clear. Always returns
DEFER for a server and FAIL for a client so that most calls can use "return
tls_error(...)" to do this processing and then give an appropriate return. A
single function is used for both server and client, because it is called from
some shared functions.
Argument:
prefix text to include in the logged error
host NULL if setting up a server;
the connected host if setting up a client
msg error message or NULL if we should ask OpenSSL
errstr pointer to output error message
Returns: OK/DEFER/FAIL
*/
static int
tls_error(uschar * prefix, const host_item * host, uschar * msg, uschar ** errstr)
{
if (!msg)
{
ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
msg = US ssl_errstring;
}
msg = string_sprintf("(%s): %s", prefix, msg);
DEBUG(D_tls) debug_printf("TLS error '%s'\n", msg);
if (errstr) *errstr = msg;
return host ? FAIL : DEFER;
}
/**************************************************
* General library initalisation *
**************************************************/
static BOOL
lib_rand_init(void * addr)
{
randstuff r;
if (!RAND_status()) return TRUE;
gettimeofday(&r.tv, NULL);
r.p = getpid();
RAND_seed(US (&r), sizeof(r));
RAND_seed(US big_buffer, big_buffer_size);
if (addr) RAND_seed(US addr, sizeof(addr));
return RAND_status();
}
static void
tls_openssl_init(void)
{
static BOOL once = FALSE;
if (once) return;
once = TRUE;
#ifdef EXIM_NEED_OPENSSL_INIT
SSL_load_error_strings(); /* basic set up */
OpenSSL_add_ssl_algorithms();
#endif
#if defined(EXIM_HAVE_SHA256) && !defined(OPENSSL_AUTO_SHA256)
/* SHA256 is becoming ever more popular. This makes sure it gets added to the
list of available digests. */
EVP_add_digest(EVP_sha256());
#endif
(void) lib_rand_init(NULL);
(void) tls_openssl_options_parse(openssl_options, &init_options);
}
/*************************************************
* Initialize for DH *
*************************************************/
/* If dhparam is set, expand it, and load up the parameters for DH encryption.
Server only.
Arguments:
sctx The current SSL CTX (inbound or outbound)
dhparam DH parameter file or fixed parameter identity string
errstr error string pointer
Returns: TRUE if OK (nothing to set up, or setup worked)
*/
static BOOL
init_dh(SSL_CTX * sctx, uschar * dhparam, uschar ** errstr)
{
BIO * bio;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
DH * dh;
#else
EVP_PKEY * pkey;
#endif
uschar * dhexpanded;
const char * pem;
int dh_bitsize;
if (!expand_check(dhparam, US"tls_dhparam", &dhexpanded, errstr))
return FALSE;
if (!dhexpanded || !*dhexpanded)
bio = BIO_new_mem_buf(CS std_dh_prime_default(), -1);
else if (dhexpanded[0] == '/')
{
if (!(bio = BIO_new_file(CS dhexpanded, "r")))
{
tls_error(string_sprintf("could not read dhparams file %s", dhexpanded),
NULL, US strerror(errno), errstr);
return FALSE;
}
}
else
{
if (Ustrcmp(dhexpanded, "none") == 0)
{
DEBUG(D_tls) debug_printf("Requested no DH parameters.\n");
return TRUE;
}
if (!(pem = std_dh_prime_named(dhexpanded)))
{
tls_error(string_sprintf("Unknown standard DH prime \"%s\"", dhexpanded),
NULL, US strerror(errno), errstr);
return FALSE;
}
bio = BIO_new_mem_buf(CS pem, -1);
}
if (!(
#if OPENSSL_VERSION_NUMBER < 0x30000000L
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL)
#else
pkey = PEM_read_bio_Parameters_ex(bio, NULL, NULL, NULL)
#endif
) )
{
BIO_free(bio);
tls_error(string_sprintf("Could not read tls_dhparams \"%s\"", dhexpanded),
NULL, NULL, errstr);
return FALSE;
}
/* note: our default limit of 2236 is not a multiple of 8; the limit comes from
an NSS limit, and the GnuTLS APIs handle bit-sizes fine, so we went with 2236.
But older OpenSSL can only report in bytes (octets), not bits. If someone wants
to dance at the edge, then they can raise the limit or use current libraries. */
#if OPENSSL_VERSION_NUMBER < 0x30000000L
# ifdef EXIM_HAVE_OPENSSL_DH_BITS
/* Added in commit 26c79d5641d; `git describe --contains` says OpenSSL_1_1_0-pre1~1022
This predates OpenSSL_1_1_0 (before a, b, ...) so is in all 1.1.0 */
dh_bitsize = DH_bits(dh);
# else
dh_bitsize = 8 * DH_size(dh);
# endif
#else /* 3.0.0 + */
dh_bitsize = EVP_PKEY_get_bits(pkey);
#endif
/* Even if it is larger, we silently return success rather than cause things to
fail out, so that a too-large DH will not knock out all TLS; it's a debatable
choice. Likewise for a failing attempt to set one. */
if (dh_bitsize <= tls_dh_max_bits)
{
if (
#if OPENSSL_VERSION_NUMBER < 0x30000000L
SSL_CTX_set_tmp_dh(sctx, dh)
#else
SSL_CTX_set0_tmp_dh_pkey(sctx, pkey)
#endif
== 0)
{
ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (D-H param setting '%s'): %s",
dhexpanded ? dhexpanded : US"default", ssl_errstring);
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
/* EVP_PKEY_free(pkey); crashes */
#endif
}
else
DEBUG(D_tls)
debug_printf(" Diffie-Hellman initialized from %s with %d-bit prime\n",
dhexpanded ? dhexpanded : US"default", dh_bitsize);
}
else
DEBUG(D_tls)
debug_printf(" dhparams '%s' %d bits, is > tls_dh_max_bits limit of %d\n",
dhexpanded ? dhexpanded : US"default", dh_bitsize, tls_dh_max_bits);
#if OPENSSL_VERSION_NUMBER < 0x30000000L
DH_free(dh);
#endif
/* The EVP_PKEY ownership stays with the ctx; do not free it */
BIO_free(bio);
return TRUE;
}
/*************************************************
* Initialize for ECDH *
*************************************************/
/* "auto" needs to be handled carefully.
OpenSSL < 1.0.2: we do not select anything, but fallback to prime256v1
OpenSSL < 1.1.0: we have to call SSL_CTX_set_ecdh_auto
(openssl/ssl.h defines SSL_CTRL_SET_ECDH_AUTO)
OpenSSL >= 1.1.0: we do not set anything, the libray does autoselection
https://github.com/openssl/openssl/commit/fe6ef2472db933f01b59cad82aa925736935984b
*/
static uschar *
init_ecdh_auto(SSL_CTX * sctx)
{
#if OPENSSL_VERSION_NUMBER < 0x10002000L
DEBUG(D_tls) debug_printf(
" ECDH OpenSSL < 1.0.2: temp key parameter settings: overriding \"auto\" with \"prime256v1\"\n");
return US"prime256v1";
#else
# if defined SSL_CTRL_SET_ECDH_AUTO
DEBUG(D_tls) debug_printf(
" ECDH OpenSSL 1.0.2+: temp key parameter settings: autoselection\n");
SSL_CTX_set_ecdh_auto(sctx, 1);
return NULL;
# else
DEBUG(D_tls) debug_printf(
" ECDH OpenSSL 1.1.0+: temp key parameter settings: library default selection\n");
return NULL;
# endif
#endif
}
/* Load parameters for ECDH encryption. Server only.
For now, we stick to NIST P-256 because: it's simple and easy to configure;
it avoids any patent issues that might bite redistributors; despite events in
the news and concerns over curve choices, we're not cryptographers, we're not
pretending to be, and this is "good enough" to be better than no support,
protecting against most adversaries. Given another year or two, there might
be sufficient clarity about a "right" way forward to let us make an informed
decision, instead of a knee-jerk reaction.
Longer-term, we should look at supporting both various named curves and
external files generated with "openssl ecparam", much as we do for init_dh().
We should also support "none" as a value, to explicitly avoid initialisation.
Patches welcome.
Arguments:
sctx The current SSL CTX (inbound or outbound)
errstr error string pointer
Returns: TRUE if OK (nothing to set up, or setup worked)
*/
static BOOL
init_ecdh(SSL_CTX * sctx, uschar ** errstr)
{
#ifdef OPENSSL_NO_ECDH
return TRUE;
#else
# ifndef EXIM_HAVE_ECDH
DEBUG(D_tls)
debug_printf(" No OpenSSL API to define ECDH parameters, skipping\n");
return TRUE;
# else
uschar * exp_curve;
int ngroups, rc, sep;
const uschar * curves_list, * curve;
# ifdef EXIM_HAVE_OPENSSL_SET1_GROUPS
int nids[16];
# else
int nids[1];
# endif
if (!expand_check(tls_eccurve, US"tls_eccurve", &exp_curve, errstr))
return FALSE;
/* Is the option deliberately empty? */
if (!exp_curve || !*exp_curve)
return TRUE;
/* Limit the list to hardwired array size. Drop out if any element is "suto". */
curves_list = exp_curve;
sep = 0;
for (ngroups = 0;
ngroups < nelem(nids)
&& (curve = string_nextinlist(&curves_list, &sep, NULL, 0));
)
if (Ustrcmp(curve, "auto") == 0)
{
DEBUG(D_tls) if (ngroups > 0)
debug_printf(" tls_eccurve 'auto' item takes precedence\n");
if ((exp_curve = init_ecdh_auto(sctx))) break; /* have a curve name to set */
return TRUE; /* all done */
}
else
ngroups++;
/* Translate to NIDs */
curves_list = exp_curve;
for (ngroups = 0; curve = string_nextinlist(&curves_list, &sep, NULL, 0);
ngroups++)
if ( (nids[ngroups] = OBJ_sn2nid (CCS curve)) == NID_undef
# ifdef EXIM_HAVE_OPENSSL_EC_NIST2NID
&& (nids[ngroups] = EC_curve_nist2nid(CCS curve)) == NID_undef
# endif
)
{
uschar * s = string_sprintf("Unknown curve name in tls_eccurve '%s'", curve);
DEBUG(D_tls) debug_printf("TLS error: %s\n", s);
if (errstr) *errstr = s;
return FALSE;
}
# ifdef EXIM_HAVE_OPENSSL_SET1_GROUPS
/* Set the groups */
if ((rc = SSL_CTX_set1_groups(sctx, nids, ngroups)) == 0)
tls_error(string_sprintf("Error enabling '%s' group(s)", exp_curve), NULL, NULL, errstr);
else
DEBUG(D_tls) debug_printf(" ECDH: enabled '%s' group(s)\n", exp_curve);
# else /* Cannot handle a list; only 1 element nids array */
{
EC_KEY * ecdh;
if (!(ecdh = EC_KEY_new_by_curve_name(nids[0])))
{
tls_error(US"Unable to create ec curve", NULL, NULL, errstr);
return FALSE;
}
/* The "tmp" in the name here refers to setting a temporary key
not to the stability of the interface. */
if ((rc = SSL_CTX_set_tmp_ecdh(sctx, ecdh)) == 0)
tls_error(string_sprintf("Error enabling '%s' curve", exp_curve), NULL, NULL, errstr);
else
DEBUG(D_tls) debug_printf(" ECDH: enabled '%s' curve\n", exp_curve);
EC_KEY_free(ecdh);
}
# endif /*!EXIM_HAVE_OPENSSL_SET1_GROUPS*/
return !!rc;
# endif /*EXIM_HAVE_ECDH*/
#endif /*OPENSSL_NO_ECDH*/
}
/*************************************************
* Expand key and cert file specs *
*************************************************/
#if OPENSSL_VERSION_NUMBER < 0x30000000L
/*
Arguments:
s SSL connection (not used)
export not used
keylength keylength
Returns: pointer to generated key
*/
static RSA *
rsa_callback(SSL *s, int export, int keylength)
{
RSA *rsa_key;
#ifdef EXIM_HAVE_RSA_GENKEY_EX
BIGNUM *bn = BN_new();
#endif
DEBUG(D_tls) debug_printf("Generating %d bit RSA key...\n", keylength);
# ifdef EXIM_HAVE_RSA_GENKEY_EX
if ( !BN_set_word(bn, (unsigned long)RSA_F4)
|| !(rsa_key = RSA_new())
|| !RSA_generate_key_ex(rsa_key, keylength, bn, NULL)
)
# else
if (!(rsa_key = RSA_generate_key(keylength, RSA_F4, NULL, NULL)))
# endif
{
ERR_error_string_n(ERR_get_error(), ssl_errstring, sizeof(ssl_errstring));
log_write(0, LOG_MAIN|LOG_PANIC, "TLS error (RSA_generate_key): %s",
ssl_errstring);
return NULL;
}
return rsa_key;
}
#endif /* pre-3.0.0 */
/* Create and install a selfsigned certificate, for use in server mode */
/*XXX we could arrange to call this during prelo for a null tls_certificate option.
The normal cache inval + relo will suffice.
Just need a timer for inval. */
static int
tls_install_selfsign(SSL_CTX * sctx, uschar ** errstr)
{
X509 * x509 = NULL;
EVP_PKEY * pkey;
X509_NAME * name;
uschar * where;
DEBUG(D_tls) debug_printf("TLS: generating selfsigned server cert\n");
where = US"allocating pkey";
if (!(pkey = EVP_PKEY_new()))
goto err;
where = US"allocating cert";
if (!(x509 = X509_new()))
goto err;
where = US"generating pkey";
#if OPENSSL_VERSION_NUMBER < 0x30000000L
{
RSA * rsa;
if (!(rsa = rsa_callback(NULL, 0, 2048)))
goto err;
where = US"assigning pkey";
if (!EVP_PKEY_assign_RSA(pkey, rsa))
goto err;
}
#else
pkey = EVP_RSA_gen(2048);
#endif
X509_set_version(x509, 2); /* N+1 - version 3 */
ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
X509_gmtime_adj(X509_get_notBefore(x509), 0);
X509_gmtime_adj(X509_get_notAfter(x509), (long)2 * 60 * 60); /* 2 hour */
X509_set_pubkey(x509, pkey);
name = X509_get_subject_name(x509);
X509_NAME_add_entry_by_txt(name, "C",
MBSTRING_ASC, CUS "UK", -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "O",
MBSTRING_ASC, CUS "Exim Developers", -1, -1, 0);
X509_NAME_add_entry_by_txt(name, "CN",
MBSTRING_ASC, CUS smtp_active_hostname, -1, -1, 0);
X509_set_issuer_name(x509, name);
where = US"signing cert";
if (!X509_sign(x509, pkey, EVP_md5()))
goto err;
where = US"installing selfsign cert";
if (!SSL_CTX_use_certificate(sctx, x509))
goto err;
where = US"installing selfsign key";
if (!SSL_CTX_use_PrivateKey(sctx, pkey))
goto err;
return OK;
err:
(void) tls_error(where, NULL, NULL, errstr);
if (x509) X509_free(x509);
if (pkey) EVP_PKEY_free(pkey);
return DEFER;
}
/*************************************************
* Information callback *
*************************************************/
/* The SSL library functions call this from time to time to indicate what they
are doing. We copy the string to the debugging output when TLS debugging has
been requested.
Arguments:
s the SSL connection
where
ret
Returns: nothing