-
Notifications
You must be signed in to change notification settings - Fork 280
/
mod_openssl.c
3877 lines (3452 loc) · 137 KB
/
mod_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
/*
* mod_openssl - openssl support for lighttpd
*
* Fully-rewritten from original
* Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com All rights reserved
* License: BSD 3-clause (same as lighttpd)
*/
/*
* Note: If session tickets are -not- disabled with
* ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
* mod_openssl rotates server ticket encryption key (STEK) every 8 hours
* and keeps the prior two STEKs around, so ticket lifetime is 24 hours.
* This is fine for use with a single lighttpd instance, but with multiple
* lighttpd workers, no coordinated STEK (server ticket encryption key)
* rotation occurs unless ssl.stek-file is defined and maintained (preferred),
* or if some external job restarts lighttpd. Restarting lighttpd generates a
* new key that is shared by lighttpd workers for the lifetime of the new key.
* If the rotation period expires and lighttpd has not been restarted, and if
* ssl.stek-file is not in use, then lighttpd workers will generate new
* independent keys, making session tickets less effective for session
* resumption, since clients have a lower chance for future connections to
* reach the same lighttpd worker. However, things will still work, and a new
* session will be created if session resumption fails. Admins should plan to
* restart lighttpd at least every 8 hours if session tickets are enabled and
* multiple lighttpd workers are configured. Since that is likely disruptive,
* if multiple lighttpd workers are configured, ssl.stek-file should be
* defined and the file maintained externally.
*/
#include "first.h"
#include <sys/types.h>
#include <sys/stat.h>
#include "sys-time.h"
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/*(not needed)*/
/* correction; needed for:
* SSL_load_client_CA_file()
* X509_STORE_load_locations()
*/
/*#define OPENSSL_NO_STDIO*/
#ifndef USE_OPENSSL_KERBEROS
#ifndef OPENSSL_NO_KRB5
#define OPENSSL_NO_KRB5
#endif
#endif
#ifdef BORINGSSL_API_VERSION
#undef OPENSSL_NO_STDIO /* for X509_STORE_load_locations() */
#endif
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/tls1.h>
#ifndef OPENSSL_NO_DH
#include <openssl/dh.h>
#endif
#ifndef OPENSSL_NO_OCSP
#include <openssl/ocsp.h>
#endif
#ifdef BORINGSSL_API_VERSION
/* BoringSSL purports to have some OCSP support */
#undef OPENSSL_NO_OCSP
#endif
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
#include <openssl/ecdh.h>
#endif
#endif
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
#include <openssl/core_names.h>
#include <openssl/store.h>
#endif
#include "base.h"
#include "ck.h"
#include "fdevent.h"
#include "http_date.h"
#include "http_header.h"
#include "http_kv.h"
#include "log.h"
#include "plugin.h"
typedef struct {
/* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
EVP_PKEY *ssl_pemfile_pkey;
X509 *ssl_pemfile_x509;
STACK_OF(X509) *ssl_pemfile_chain;
buffer *ssl_stapling;
const buffer *ssl_pemfile;
const buffer *ssl_privkey;
const buffer *ssl_stapling_file;
unix_time64_t ssl_stapling_loadts;
unix_time64_t ssl_stapling_nextts;
char must_staple;
char self_issued;
} plugin_cert;
typedef struct {
SSL_CTX *ssl_ctx;
} plugin_ssl_ctx;
typedef struct {
STACK_OF(X509_NAME) *names;
X509_STORE *certs;
} plugin_cacerts;
typedef struct {
SSL_CTX *ssl_ctx; /* output from network_init_ssl() */
/*(used only during startup; not patched)*/
unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
unsigned char ssl_empty_fragments; /* whether to not set SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
unsigned char ssl_use_sslv2;
unsigned char ssl_use_sslv3;
const buffer *ssl_cipher_list;
const buffer *ssl_dh_file;
const buffer *ssl_ec_curve;
array *ssl_conf_cmd;
/*(copied from plugin_data for socket ssl_ctx config)*/
const plugin_cert *pc;
const plugin_cacerts *ssl_ca_file;
STACK_OF(X509_NAME) *ssl_ca_dn_file;
const buffer *ssl_ca_crl_file;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
unsigned char ssl_read_ahead;
unsigned char ssl_disable_client_renegotiation;
} plugin_config_socket; /*(used at startup during configuration)*/
typedef struct {
/* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
plugin_cert *pc;
const plugin_cacerts *ssl_ca_file;
STACK_OF(X509_NAME) *ssl_ca_dn_file;
const buffer *ssl_ca_crl_file;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
unsigned char ssl_verifyclient_export_cert;
unsigned char ssl_read_ahead;
unsigned char ssl_log_noise;
unsigned char ssl_disable_client_renegotiation;
const buffer *ssl_verifyclient_username;
const buffer *ssl_acme_tls_1;
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_ssl_ctx *ssl_ctxs;
plugin_config defaults;
server *srv;
array *cafiles;
const char *ssl_stek_file;
} plugin_data;
static int ssl_is_init;
/* need assigned p->id for deep access of module handler_ctx for connection
* i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
static plugin_data *plugin_data_singleton;
#define LOCAL_SEND_BUFSIZE (16 * 1024)
static char *local_send_buffer;
typedef struct {
SSL *ssl;
request_st *r;
connection *con;
short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
short close_notify;
unsigned short alpn;
plugin_config conf;
buffer *tmp_buf;
log_error_st *errh;
} handler_ctx;
static handler_ctx *
handler_ctx_init (void)
{
handler_ctx *hctx = calloc(1, sizeof(*hctx));
force_assert(hctx);
return hctx;
}
static void
handler_ctx_free (handler_ctx *hctx)
{
if (hctx->ssl) SSL_free(hctx->ssl);
free(hctx);
}
#ifdef TLSEXT_TYPE_session_ticket
/* ssl/ssl_local.h */
#define TLSEXT_KEYNAME_LENGTH 16
#define TLSEXT_TICK_KEY_LENGTH 32
/* openssl has a huge number of interfaces, but not the most useful;
* construct our own session ticket encryption key structure */
typedef struct tlsext_ticket_key_st {
unix_time64_t active_ts; /* tickets not issued w/ key until activation ts*/
unix_time64_t expire_ts; /* key not valid after expiration timestamp */
unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
} tlsext_ticket_key_t;
static tlsext_ticket_key_t session_ticket_keys[4];
static unix_time64_t stek_rotate_ts;
static int
mod_openssl_session_ticket_key_generate (unix_time64_t active_ts, unix_time64_t expire_ts)
{
/* openssl RAND_*bytes() functions are called multiple times since the
* funcs might have a 32-byte limit on number of bytes returned each call
*
* (Note: session ticket encryption key generation is not expected to fail)
*
* 3 keys are stored in session_ticket_keys[]
* The 4th element of session_ticket_keys[] is used for STEK construction
*/
/*(RAND_priv_bytes() not in openssl 1.1.0; introduced in openssl 1.1.1)*/
#if OPENSSL_VERSION_NUMBER < 0x10101000L \
|| defined(BORINGSSL_API_VERSION) \
|| defined(LIBRESSL_VERSION_NUMBER)
#define RAND_priv_bytes(x,sz) RAND_bytes((x),(sz))
#endif
if (RAND_bytes(session_ticket_keys[3].tick_key_name,
TLSEXT_KEYNAME_LENGTH) <= 0
|| RAND_priv_bytes(session_ticket_keys[3].tick_hmac_key,
TLSEXT_TICK_KEY_LENGTH) <= 0
|| RAND_priv_bytes(session_ticket_keys[3].tick_aes_key,
TLSEXT_TICK_KEY_LENGTH) <= 0)
return 0;
session_ticket_keys[3].active_ts = active_ts;
session_ticket_keys[3].expire_ts = expire_ts;
return 1;
}
static void
mod_openssl_session_ticket_key_rotate (void)
{
/* discard oldest key (session_ticket_keys[2]) and put newest key first
* 3 keys are stored in session_ticket_keys[0], [1], [2]
* session_ticket_keys[3] is used to construct and pass new STEK */
session_ticket_keys[2] = session_ticket_keys[1];
session_ticket_keys[1] = session_ticket_keys[0];
/*memmove(session_ticket_keys+1,
session_ticket_keys+0, sizeof(tlsext_ticket_key_t)*2);*/
session_ticket_keys[0] = session_ticket_keys[3];
OPENSSL_cleanse(session_ticket_keys+3, sizeof(tlsext_ticket_key_t));
}
static tlsext_ticket_key_t *
tlsext_ticket_key_get (void)
{
const unix_time64_t cur_ts = log_epoch_secs;
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].active_ts > cur_ts) continue;
if (session_ticket_keys[i].expire_ts < cur_ts) continue;
return &session_ticket_keys[i];
}
return NULL;
}
static tlsext_ticket_key_t *
tlsext_ticket_key_find (unsigned char key_name[16], int *refresh)
{
*refresh = 0;
const unix_time64_t cur_ts = log_epoch_secs;
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].expire_ts < cur_ts) continue;
if (0 == memcmp(session_ticket_keys[i].tick_key_name, key_name, 16))
return &session_ticket_keys[i];
if (session_ticket_keys[i].active_ts <= cur_ts)
*refresh = 1; /* newer active key is available */
}
return NULL;
}
static void
tlsext_ticket_wipe_expired (const unix_time64_t cur_ts)
{
const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
for (int i = 0; i < e; ++i) {
if (session_ticket_keys[i].expire_ts != 0
&& session_ticket_keys[i].expire_ts < cur_ts)
OPENSSL_cleanse(session_ticket_keys+i, sizeof(tlsext_ticket_key_t));
}
}
#if OPENSSL_VERSION_NUMBER < 0x30000000L
/* based on reference implementation from openssl 1.1.1g man page
* man SSL_CTX_set_tlsext_ticket_key_cb
* but mod_openssl code uses EVP_aes_256_cbc() instead of EVP_aes_128_cbc()
*/
static int
ssl_tlsext_ticket_key_cb (SSL *s, unsigned char key_name[16],
unsigned char iv[EVP_MAX_IV_LENGTH],
EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
#else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
/* based on reference implementation from openssl 3.0.0 man page
* man SSL_CTX_set_tlsext_ticket_key_cb
*/
static int
ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16],
unsigned char *iv, EVP_CIPHER_CTX *ctx,
EVP_MAC_CTX *hctx, int enc)
#endif
{
UNUSED(s);
if (enc) { /* create new session */
tlsext_ticket_key_t *k = tlsext_ticket_key_get();
if (NULL == k)
return 0; /* current key does not exist or is not valid */
memcpy(key_name, k->tick_key_name, 16);
if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
return -1; /* insufficient random */
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
#if OPENSSL_VERSION_NUMBER < 0x30000000L
HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
EVP_sha256(), NULL);
#else
OSSL_PARAM params[] = {
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
k->tick_hmac_key, sizeof(k->tick_hmac_key)),
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
"sha256", sizeof("sha256")),
OSSL_PARAM_END
};
EVP_MAC_CTX_set_params(hctx, params);
#endif
return 1;
}
else { /* retrieve session */
int refresh;
tlsext_ticket_key_t *k = tlsext_ticket_key_find(key_name, &refresh);
if (NULL == k)
return 0;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
EVP_sha256(), NULL);
#else
OSSL_PARAM params[] = {
OSSL_PARAM_DEFN(OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
k->tick_hmac_key, sizeof(k->tick_hmac_key)),
OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
"sha256", sizeof("sha256")),
OSSL_PARAM_END
};
EVP_MAC_CTX_set_params(hctx, params);
#endif
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
return refresh ? 2 : 1;
/* 'refresh' will trigger issuing new ticket for session
* even though the current ticket is still valid */
}
}
static int
mod_openssl_session_ticket_key_file (const char *fn)
{
/* session ticket encryption key (STEK)
*
* STEK file should be stored in non-persistent storage,
* e.g. /dev/shm/lighttpd/stek-file (in memory)
* with appropriate permissions set to keep stek-file from being
* read by other users. Where possible, systems should also be
* configured without swap.
*
* admin should schedule an independent job to periodically
* generate new STEK up to 3 times during key lifetime
* (lighttpd stores up to 3 keys)
*
* format of binary file is:
* 4-byte - format version (always 0; for use if format changes)
* 4-byte - activation timestamp
* 4-byte - expiration timestamp
* 16-byte - session ticket key name
* 32-byte - session ticket HMAC encrpytion key
* 32-byte - session ticket AES encrpytion key
*
* STEK file can be created with a command such as:
* dd if=/dev/random bs=1 count=80 status=none | \
* perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
* > STEK-file.$$ && mv STEK-file.$$ STEK-file
*
* The above delays activation time by 5 mins (+300 sec) to allow file to
* be propagated to other machines. (admin must handle this independently)
* If STEK generation is performed immediately prior to starting lighttpd,
* admin should activate keys immediately (without +300).
*/
int buf[23]; /* 92 bytes */
int rc = 0; /*(will retry on next check interval upon any error)*/
if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
return rc;
if (buf[0] == 0) { /*(format version 0)*/
session_ticket_keys[3].active_ts = TIME64_CAST(buf[1]);
session_ticket_keys[3].expire_ts = TIME64_CAST(buf[2]);
#ifndef __COVERITY__ /* intentional; hide from Coverity Scan */
/* intentionally copy 80 bytes into consecutive arrays
* tick_key_name[], tick_hmac_key[], tick_aes_key[] */
memcpy(&session_ticket_keys[3].tick_key_name, buf+3, 80);
#endif
rc = 1;
}
OPENSSL_cleanse(buf, sizeof(buf));
return rc;
}
static void
mod_openssl_session_ticket_key_check (const plugin_data *p, const unix_time64_t cur_ts)
{
static unix_time64_t detect_retrograde_ts;
if (detect_retrograde_ts > cur_ts && detect_retrograde_ts - cur_ts > 28800)
stek_rotate_ts = 0;
detect_retrograde_ts = cur_ts;
int rotate = 0;
if (p->ssl_stek_file) {
struct stat st;
if (0 == stat(p->ssl_stek_file, &st)
&& TIME64_CAST(st.st_mtime) > stek_rotate_ts)
rotate = mod_openssl_session_ticket_key_file(p->ssl_stek_file);
tlsext_ticket_wipe_expired(cur_ts);
}
else if (cur_ts - 28800 >= stek_rotate_ts || 0 == stek_rotate_ts)/*(8 hrs)*/
rotate = mod_openssl_session_ticket_key_generate(cur_ts, cur_ts+86400);
if (rotate) {
mod_openssl_session_ticket_key_rotate();
stek_rotate_ts = cur_ts;
}
}
#endif /* TLSEXT_TYPE_session_ticket */
#ifndef OPENSSL_NO_OCSP
#ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
static int
ssl_tlsext_status_cb(SSL *ssl, void *arg)
{
#ifdef SSL_get_tlsext_status_type
if (TLSEXT_STATUSTYPE_ocsp != SSL_get_tlsext_status_type(ssl))
return SSL_TLSEXT_ERR_NOACK; /* ignore if not client OCSP request */
#endif
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
if (NULL == hctx->conf.pc) return SSL_TLSEXT_ERR_NOACK;/*should not happen*/
buffer *ssl_stapling = hctx->conf.pc->ssl_stapling;
if (NULL == ssl_stapling) return SSL_TLSEXT_ERR_NOACK;
UNUSED(arg);
int len = (int)buffer_clen(ssl_stapling);
/* OpenSSL and LibreSSL require copy (BoringSSL, too, if using compat API)*/
uint8_t *ocsp_resp = OPENSSL_malloc(len);
if (NULL == ocsp_resp)
return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
memcpy(ocsp_resp, ssl_stapling->ptr, len);
if (!SSL_set_tlsext_status_ocsp_resp(ssl, ocsp_resp, len)) {
log_error(hctx->r->conf.errh, __FILE__, __LINE__,
"SSL: failed to set OCSP response for TLS server name %s: %s",
hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
OPENSSL_free(ocsp_resp);
return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
/*return SSL_TLSEXT_ERR_ALERT_FATAL;*/
}
return SSL_TLSEXT_ERR_OK;
}
#endif
#endif
INIT_FUNC(mod_openssl_init)
{
plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
return plugin_data_singleton;
}
static int mod_openssl_init_once_openssl (server *srv)
{
if (ssl_is_init) return 1;
#if OPENSSL_VERSION_NUMBER >= 0x10100000L \
&& (!defined(LIBRESSL_VERSION_NUMBER) \
|| LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
|OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
|OPENSSL_INIT_ADD_ALL_DIGESTS
|OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
#endif
ssl_is_init = 1;
if (0 == RAND_status()) {
log_error(srv->errh, __FILE__, __LINE__,
"SSL: not enough entropy in the pool");
return 0;
}
local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
force_assert(NULL != local_send_buffer);
return 1;
}
static void mod_openssl_free_openssl (void)
{
if (!ssl_is_init) return;
#ifdef TLSEXT_TYPE_session_ticket
OPENSSL_cleanse(session_ticket_keys, sizeof(session_ticket_keys));
stek_rotate_ts = 0;
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L \
&& !defined(LIBRESSL_VERSION_NUMBER)
/*(OpenSSL libraries handle thread init and deinit)
* https://github.com/openssl/openssl/pull/1048 */
#else
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
ERR_remove_thread_state(NULL);
#else
ERR_remove_state(0);
#endif
EVP_cleanup();
#endif
free(local_send_buffer);
ssl_is_init = 0;
}
static void
mod_openssl_free_config (server *srv, plugin_data * const p)
{
array_free(p->cafiles);
if (NULL != p->ssl_ctxs) {
SSL_CTX * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
/* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
for (uint32_t i = 1; i < srv->config_context->used; ++i) {
plugin_ssl_ctx * const s = p->ssl_ctxs + i;
if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope)
SSL_CTX_free(s->ssl_ctx);
}
/* free ssl_ctx from global scope */
if (ssl_ctx_global_scope)
SSL_CTX_free(ssl_ctx_global_scope);
free(p->ssl_ctxs);
}
if (NULL == p->cvlist) return;
/* (init i to 0 if global context; to 1 to skip empty global context) */
for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
for (; -1 != cpv->k_id; ++cpv) {
switch (cpv->k_id) {
case 0: /* ssl.pemfile */
if (cpv->vtype == T_CONFIG_LOCAL) {
plugin_cert *pc = cpv->v.v;
EVP_PKEY_free(pc->ssl_pemfile_pkey);
X509_free(pc->ssl_pemfile_x509);
sk_X509_pop_free(pc->ssl_pemfile_chain, X509_free);
buffer_free(pc->ssl_stapling);
free(pc);
}
break;
case 2: /* ssl.ca-file */
if (cpv->vtype == T_CONFIG_LOCAL) {
plugin_cacerts *cacerts = cpv->v.v;
sk_X509_NAME_pop_free(cacerts->names, X509_NAME_free);
X509_STORE_free(cacerts->certs);
free(cacerts);
}
break;
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
sk_X509_NAME_pop_free(cpv->v.v, X509_NAME_free);
break;
default:
break;
}
}
}
}
/* use memory from openssl secure heap for temporary buffers, returned storage
* (pemfile might contain a private key in addition to certificate chain)
* Interfaces similar to those constructed in include/openssl/pem.h for
* PEM_read_bio_X509(), except this is named PEM_read_bio_X509_secmem().
* Similar for PEM_read_bio_X509_AUX_secmem().
*
* Supporting routine PEM_ASN1_read_bio_secmem() modified from openssl
* crypto/pem/pem_oth.c:PEM_ASN1_read_bio():
* uses PEM_bytes_read_bio_secmem() instead of PEM_bytes_read_bio()
* uses OPENSSL_secure_clear_free() instead of OPENSSL_free()
*
* 'man PEM_bytes_read_bio_secmem()' and see NOTES section for more info
* PEM_bytes_read_bio_secmem() openssl 1.1.1 or later
* OPENSSL_secure_clear_free() openssl 1.1.0g or later
* As this comment is being written, only openssl 1.1.1 is actively maintained.
* Earlier vers of openssl no longer receive security patches from openssl.org.
*/
static void *
PEM_ASN1_read_bio_secmem(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
pem_password_cb *cb, void *u)
{
const unsigned char *p = NULL;
unsigned char *data = NULL;
long len = 0;
char *ret = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x10101000L \
&& !defined(BORINGSSL_API_VERSION) \
&& !defined(LIBRESSL_VERSION_NUMBER)
if (!PEM_bytes_read_bio_secmem(&data, &len, NULL, name, bp, cb, u))
#else
if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
#endif
return NULL;
p = data;
ret = d2i(x, &p, len);
#ifndef BORINGSSL_API_VERSION /* missing PEMerr() macro */
if (ret == NULL)
PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB);
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10101000L \
&& !defined(BORINGSSL_API_VERSION) \
&& !defined(LIBRESSL_VERSION_NUMBER)
OPENSSL_secure_clear_free(data, len);
#else
OPENSSL_cleanse(data, len);
OPENSSL_free(data);
#endif
return ret;
}
static X509 *
PEM_read_bio_X509_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
{
return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509,
PEM_STRING_X509,
bp, (void **)x, cb, u);
}
static X509 *
PEM_read_bio_X509_AUX_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
{
return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509_AUX,
PEM_STRING_X509_TRUSTED,
bp, (void **)x, cb, u);
}
static int
mod_openssl_load_X509_sk (const char *file, log_error_st *errh, STACK_OF(X509) **chain, BIO *in)
{
STACK_OF(X509) *chain_sk = NULL;
for (X509 *ca; (ca = PEM_read_bio_X509_secmem(in,NULL,NULL,NULL)); ) {
if (NULL == chain_sk) /*(allocate only if it will not be empty)*/
chain_sk = sk_X509_new_null();
if (!chain_sk || !sk_X509_push(chain_sk, ca)) {
log_error(errh, __FILE__, __LINE__,
"SSL: couldn't read X509 certificates from '%s'", file);
if (chain_sk) sk_X509_pop_free(chain_sk, X509_free);
X509_free(ca);
return 0;
}
}
*chain = chain_sk;
return 1;
}
static int
mod_openssl_load_X509_STORE (const char *file, log_error_st *errh, X509_STORE **chain, BIO *in)
{
X509_STORE *chain_store = NULL;
for (X509 *ca; (ca = PEM_read_bio_X509(in,NULL,NULL,NULL)); X509_free(ca)) {
if (NULL == chain_store) /*(allocate only if it will not be empty)*/
chain_store = X509_STORE_new();
if (!chain_store || !X509_STORE_add_cert(chain_store, ca)) {
log_error(errh, __FILE__, __LINE__,
"SSL: couldn't read X509 certificates from '%s'", file);
if (chain_store) X509_STORE_free(chain_store);
X509_free(ca);
return 0;
}
}
*chain = chain_store;
return 1;
}
static plugin_cacerts *
mod_openssl_load_cacerts (const buffer *ssl_ca_file, log_error_st *errh)
{
const char *file = ssl_ca_file->ptr;
BIO *in = BIO_new(BIO_s_file());
if (NULL == in) {
log_error(errh, __FILE__, __LINE__,
"SSL: BIO_new(BIO_s_file()) failed");
return NULL;
}
if (BIO_read_filename(in, file) <= 0) {
log_error(errh, __FILE__, __LINE__,
"SSL: BIO_read_filename('%s') failed", file);
BIO_free(in);
return NULL;
}
X509_STORE *chain_store = NULL;
if (!mod_openssl_load_X509_STORE(file, errh, &chain_store, in)) {
BIO_free(in);
return NULL;
}
BIO_free(in);
if (NULL == chain_store) {
log_error(errh, __FILE__, __LINE__,
"SSL: ssl.verifyclient.ca-file is empty %s", file);
return NULL;
}
plugin_cacerts *cacerts = malloc(sizeof(plugin_cacerts));
force_assert(cacerts);
/* (would be more efficient to walk the X509_STORE and build the list,
* but this works for now and matches how ssl.ca-dn-file is handled) */
cacerts->names = SSL_load_client_CA_file(file);
if (NULL == cacerts->names) {
X509_STORE_free(chain_store);
free(cacerts);
return NULL;
}
cacerts->certs = chain_store;
return cacerts;
}
static int
mod_openssl_load_cacrls (X509_STORE *store, const buffer *ssl_ca_crl_file, server *srv)
{
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
if (1 != X509_STORE_load_file(store, ssl_ca_crl_file->ptr))
#else
if (1 != X509_STORE_load_locations(store, ssl_ca_crl_file->ptr, NULL))
#endif
{
log_error(srv->errh, __FILE__, __LINE__,
"SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
ssl_ca_crl_file->ptr);
return 0;
}
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
return 1;
}
#if OPENSSL_VERSION_NUMBER < 0x10002000 \
|| defined(LIBRESSL_VERSION_NUMBER)
static int
mod_openssl_load_verify_locn (SSL_CTX *ssl_ctx, const buffer *b, server *srv)
{
const char *fn = b->ptr;
if (1 == SSL_CTX_load_verify_locations(ssl_ctx, fn, NULL))
return 1;
log_error(srv->errh, __FILE__, __LINE__,
"SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), fn);
return 0;
}
static int
mod_openssl_load_ca_files (SSL_CTX *ssl_ctx, plugin_data *p, server *srv)
{
/* load all ssl.ca-files specified in the config into each SSL_CTX */
for (uint32_t i = 0, used = p->cafiles->used; i < used; ++i) {
const buffer *b = &((data_string *)p->cafiles->data[i])->value;
if (!mod_openssl_load_verify_locn(ssl_ctx, b, srv))
return 0;
}
return 1;
}
#endif
FREE_FUNC(mod_openssl_free)
{
plugin_data *p = p_d;
if (NULL == p->srv) return;
mod_openssl_free_config(p->srv, p);
mod_openssl_free_openssl();
}
static void
mod_openssl_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
{
switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
case 0: /* ssl.pemfile */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->pc = cpv->v.v;
break;
case 1: /* ssl.privkey */
break;
case 2: /* ssl.ca-file */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_file = cpv->v.v;
break;
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_dn_file = cpv->v.v;
break;
case 4: /* ssl.ca-crl-file */
pconf->ssl_ca_crl_file = cpv->v.b;
break;
case 5: /* ssl.read-ahead */
pconf->ssl_read_ahead = (0 != cpv->v.u);
break;
case 6: /* ssl.disable-client-renegotiation */
pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
break;
case 7: /* ssl.verifyclient.activate */
pconf->ssl_verifyclient = (0 != cpv->v.u);
break;
case 8: /* ssl.verifyclient.enforce */
pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
break;
case 9: /* ssl.verifyclient.depth */
pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
break;
case 10:/* ssl.verifyclient.username */
pconf->ssl_verifyclient_username = cpv->v.b;
break;
case 11:/* ssl.verifyclient.exportcert */
pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
break;
case 12:/* ssl.acme-tls-1 */
pconf->ssl_acme_tls_1 = cpv->v.b;
break;
case 13:/* ssl.stapling-file */
break;
case 14:/* debug.log-ssl-noise */
pconf->ssl_log_noise = (0 != cpv->v.u);
break;
#if 0 /*(cpk->k_id remapped in mod_openssl_set_defaults())*/
case 15:/* ssl.verifyclient.ca-file */
case 16:/* ssl.verifyclient.ca-dn-file */
case 17:/* ssl.verifyclient.ca-crl-file */
break;
#endif
default:/* should not happen */
return;
}
}
static void
mod_openssl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
{
do {
mod_openssl_merge_config_cpv(pconf, cpv);
} while ((++cpv)->k_id != -1);
}
static void
mod_openssl_patch_config (request_st * const r, plugin_config * const pconf)
{
plugin_data * const p = plugin_data_singleton;
memcpy(pconf, &p->defaults, sizeof(plugin_config));
for (int i = 1, used = p->nconfig; i < used; ++i) {
if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
mod_openssl_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
}
}
static int
safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
{
BIO *bio = BIO_new(BIO_s_mem());
if (bio) {
int len = X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE);
BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
BIO_free(bio);
return len; /*return value has similar semantics to that of snprintf()*/
}
else {
buf[0] = '\0';
return -1;
}
}
static void
ssl_info_callback (const SSL *ssl, int where, int ret)
{
UNUSED(ret);
if (0 != (where & SSL_CB_HANDSHAKE_START)) {
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
if (hctx->renegotiations >= 0) ++hctx->renegotiations;
}
#ifdef TLS1_3_VERSION
/* https://github.com/openssl/openssl/issues/5721
* "TLSv1.3 unexpected InfoCallback after handshake completed" */
if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
/* SSL_version() is valid after initial handshake completed */
if (SSL_version(ssl) >= TLS1_3_VERSION) {
/* https://wiki.openssl.org/index.php/TLS1.3
* "Renegotiation is not possible in a TLSv1.3 connection" */
handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
hctx->renegotiations = -1;
}
}
#endif
}
/* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
static int
verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
char buf[256];
X509 *err_cert;
int err, depth;
SSL *ssl;
handler_ctx *hctx;
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
hctx = (handler_ctx *) SSL_get_app_data(ssl);
/*
* Catch a too long certificate chain. The depth limit set using
* SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
* that whenever the "depth>verify_depth" condition is met, we
* have violated the limit and want to log this error condition.
* We must do it here, because the CHAIN_TOO_LONG error would not
* be found explicitly; only errors introduced by cutting off the
* additional certificates would be logged.
*/
if (depth > hctx->conf.ssl_verifyclient_depth) {