-
Notifications
You must be signed in to change notification settings - Fork 278
/
mod_gnutls.c
3608 lines (3171 loc) · 128 KB
/
mod_gnutls.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_gnutls - GnuTLS support for lighttpd
*
* Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com All rights reserved
* License: BSD 3-clause (same as lighttpd)
*/
/*
* GnuTLS manual: https://www.gnutls.org/documentation.html
*
* Note: If session tickets are -not- disabled with
* ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
* mod_gnutls rotates server ticket encryption key (STEK) every 18 hours.
* (https://gnutls.org/manual/html_node/Session-resumption.html)
* 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 18 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.
*
* future possible enhancements to lighttpd mod_gnutls:
* - session cache (though session tickets are implemented)
* See gnutls_db_set_store_function() and gnutls_db_set_retrieve_function()
* (and do not enable unless server.feature-flags ssl.session-cache enabled)
*/
#include "first.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h> /* vsnprintf() */
#include <string.h>
#include <gnutls/gnutls.h>
#include <gnutls/ocsp.h>
#include <gnutls/x509.h>
#include <gnutls/x509-ext.h>
#include <gnutls/abstract.h>
#include <gnutls/socket.h>
#ifdef GNUTLS_SKIP_GLOBAL_INIT
GNUTLS_SKIP_GLOBAL_INIT
#endif
#include "base.h"
#include "fdevent.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 */
gnutls_certificate_credentials_t ssl_cred;
char trust_inited;
char must_staple;
gnutls_datum_t *ssl_pemfile_x509;
gnutls_privkey_t ssl_pemfile_pkey;
const buffer *ssl_stapling_file;
unix_time64_t ssl_stapling_loadts;
unix_time64_t ssl_stapling_nextts;
} plugin_cert;
typedef struct {
int8_t ssl_session_ticket;
/*(preserved here for deinit at server shutdown)*/
gnutls_priority_t priority_cache;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} plugin_ssl_ctx;
typedef struct {
plugin_cert *pc;
/*(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;
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)*/
gnutls_priority_t priority_cache;
unsigned char ssl_session_ticket;
unsigned char ssl_verifyclient;
unsigned char ssl_verifyclient_enforce;
unsigned char ssl_verifyclient_depth;
const char *priority_base;
buffer *priority_override;
buffer priority_str;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} 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;
gnutls_datum_t *ssl_ca_file; /* .data is (gnutls_x509_crt_t) */
gnutls_datum_t *ssl_ca_dn_file; /* .data is (gnutls_x509_crt_t) */
gnutls_datum_t *ssl_ca_crl_file;/* .data is (gnutls_x509_crl_t) */
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;
#if GNUTLS_VERSION_NUMBER < 0x030600
gnutls_dh_params_t dh_params;
#endif
} plugin_config;
typedef struct {
PLUGIN_DATA;
plugin_ssl_ctx *ssl_ctxs;
plugin_config defaults;
server *srv;
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 16384 /* DEFAULT_MAX_RECORD_SIZE */
static char *local_send_buffer;
typedef struct {
gnutls_session_t ssl; /* gnutls request/connection context */
request_st *r;
connection *con;
int8_t close_notify;
uint8_t alpn;
int8_t ssl_session_ticket;
int handshake;
size_t pending_write;
plugin_config conf;
unsigned int verify_status;
buffer *tmp_buf;
log_error_st *errh;
gnutls_certificate_credentials_t acme_tls_1_cred;
} 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)
{
gnutls_deinit(hctx->ssl);
if (hctx->acme_tls_1_cred)
gnutls_certificate_free_credentials(hctx->acme_tls_1_cred);
free(hctx);
}
__attribute_cold__
static void elog(log_error_st * const errh,
const char * const file, const int line,
const int rc, const char * const msg)
{
/* error logging convenience function that decodes gnutls result codes */
log_error(errh, file, line, "GnuTLS: %s: (%s) %s",
msg, gnutls_strerror_name(rc), gnutls_strerror(rc));
}
__attribute_cold__
__attribute_format__((__printf__, 5, 6))
static void elogf(log_error_st * const errh,
const char * const file, const int line,
const int rc, const char * const fmt, ...)
{
char msg[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
elog(errh, file, line, rc, msg);
}
/* gnutls func gnutls_load_file() loads file contents into a gnutls_datum_t.
* The data loaded could be sensitive, e.g. a private key included in a pemfile.
* However, gnutls_load_file() is not careful about zeroizing memory on error,
* might use realloc() (which does not guarantee to zeroize memory released),
* and silently continues on short read, so provide our own. Updates to
* gnutls 3.6.14 may be more careful with private key files, but do not
* extend the same care to pemfiles which might contain private keys.
* Related, see also mod_gnutls_datum_wipe() below.
* https://gitlab.com/gnutls/gnutls/-/issues/1001
* https://gitlab.com/gnutls/gnutls/-/issues/1002
* https://gitlab.com/gnutls/gnutls/-/merge_requests/1270
*/
static int
mod_gnutls_load_file (const char * const fn, gnutls_datum_t * const d, log_error_st *errh)
{
#if 0
int rc = gnutls_load_file(fn, d);
if (rc < 0)
elogf(errh, __FILE__, __LINE__, rc, "%s() %s", __func__, fn);
return rc;
#else
off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
char *data = fdevent_load_file(fn, &dlen, errh, gnutls_malloc, gnutls_free);
if (NULL == data) return GNUTLS_E_FILE_ERROR;
d->data = (unsigned char *)data;
d->size = (unsigned int)dlen;
return 0;
#endif
}
/* GnuTLS does not expose _gnutls_free_key_datum() so provide our own */
static void
mod_gnutls_datum_wipe (gnutls_datum_t * const d)
{
if (NULL == d) return;
if (d->data) {
if (d->size) gnutls_memset(d->data, 0, d->size);
gnutls_free(d->data);
d->data = NULL;
}
d->size = 0;
}
/* session tickets
*
* gnutls expects 64 bytes of random data in gnutls_datum_t passed to
* gnutls_session_ticket_enable_server()
*
* (private) session ticket definitions from lib/gnutls_int.h
* #define TICKET_MASTER_KEY_SIZE (TICKET_KEY_NAME_SIZE+TICKET_CIPHER_KEY_SIZE+TICKET_MAC_SECRET_SIZE)
* #define TICKET_KEY_NAME_SIZE 16
* #define TICKET_CIPHER_KEY_SIZE 32
* #define TICKET_MAC_SECRET_SIZE 16
*/
#define TICKET_MASTER_KEY_SIZE 64
#define TLSEXT_KEYNAME_LENGTH 16
#define TLSEXT_TICK_KEY_LENGTH 32
/* construct our own session ticket encryption key structure
* to store keys that are not yet active
* (mirror from mod_openssl, even though not all bits are used here) */
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[1]; /* temp store until active */
static unix_time64_t stek_rotate_ts;
static gnutls_datum_t session_ticket_key;
static void
mod_gnutls_session_ticket_key_free (void)
{
mod_gnutls_datum_wipe(&session_ticket_key);
}
static void
mod_gnutls_session_ticket_key_init (server *srv)
{
int rc = gnutls_session_ticket_key_generate(&session_ticket_key);
if (rc < 0) {
/*(should not happen, but if it does, disable session ticket)*/
session_ticket_key.size = 0;
elog(srv->errh, __FILE__, __LINE__, rc,
"gnutls_session_ticket_key_generate()");
}
}
static void
mod_gnutls_session_ticket_key_rotate (server *srv)
{
mod_gnutls_session_ticket_key_free();
mod_gnutls_session_ticket_key_init(srv);
}
static int
mod_gnutls_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[0].active_ts = TIME64_CAST(buf[1]);
session_ticket_keys[0].expire_ts = TIME64_CAST(buf[2]);
#ifndef __COVERITY__
memcpy(&session_ticket_keys[0].tick_key_name, buf+3, 80);
#else
memcpy(&session_ticket_keys[0].tick_key_name,
buf+3, TLSEXT_KEYNAME_LENGTH);
memcpy(&session_ticket_keys[0].tick_hmac_key,
buf+7, TLSEXT_TICK_KEY_LENGTH);
memcpy(&session_ticket_keys[0].tick_aes_key,
buf+15, TLSEXT_TICK_KEY_LENGTH);
#endif
rc = 1;
}
gnutls_memset(buf, 0, sizeof(buf));
return rc;
}
static void
mod_gnutls_session_ticket_key_check (server *srv, 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;
if (p->ssl_stek_file) {
struct stat st;
if (0 == stat(p->ssl_stek_file, &st)
&& TIME64_CAST(st.st_mtime) > stek_rotate_ts
&& mod_gnutls_session_ticket_key_file(p->ssl_stek_file)) {
stek_rotate_ts = cur_ts;
}
tlsext_ticket_key_t *stek = session_ticket_keys;
if (stek->active_ts != 0 && stek->active_ts - 63 <= cur_ts) {
if (NULL == session_ticket_key.data) {
session_ticket_key.data = gnutls_malloc(TICKET_MASTER_KEY_SIZE);
if (NULL == session_ticket_key.data) return;
session_ticket_key.size = TICKET_MASTER_KEY_SIZE;
}
#ifndef __COVERITY__
memcpy(session_ticket_key.data,
stek->tick_key_name, TICKET_MASTER_KEY_SIZE);
gnutls_memset(stek->tick_key_name, 0, TICKET_MASTER_KEY_SIZE);
#else
char * const data = (char *)session_ticket_key.data;
memcpy(data,
stek->tick_key_name, TLSEXT_KEYNAME_LENGTH);
memcpy(data+TLSEXT_KEYNAME_LENGTH,
stek->tick_hmac_key, TLSEXT_TICK_KEY_LENGTH);
memcpy(data+TLSEXT_KEYNAME_LENGTH+TLSEXT_TICK_KEY_LENGTH,
stek->tick_aes_key,
TICKET_MASTER_KEY_SIZE
- (TLSEXT_KEYNAME_LENGTH + TLSEXT_TICK_KEY_LENGTH));
gnutls_memset(stek->tick_key_name, 0, TLSEXT_KEYNAME_LENGTH);
gnutls_memset(stek->tick_hmac_key, 0, TLSEXT_TICK_KEY_LENGTH);
gnutls_memset(stek->tick_aes_key, 0, TLSEXT_TICK_KEY_LENGTH);
#endif
}
if (stek->expire_ts < cur_ts)
mod_gnutls_session_ticket_key_free();
}
else if (cur_ts - 86400 >= stek_rotate_ts /*(24 hours)*/
|| 0 == stek_rotate_ts) {
mod_gnutls_session_ticket_key_rotate(srv);
stek_rotate_ts = cur_ts;
}
}
INIT_FUNC(mod_gnutls_init)
{
plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
return plugin_data_singleton;
}
static int mod_gnutls_init_once_gnutls (void)
{
if (ssl_is_init) return 1;
ssl_is_init = 1;
/* Note: on systems with support for weak symbols, GNUTLS_SKIP_GLOBAL_INIT
* is set near top of this file to inhibit GnuTLS implicit initialization
* in a library constructor. On systems without support for weak symbols,
* set GNUTLS_NO_EXPLICIT_INIT=1 in the environment before starting lighttpd
* (GnuTLS 3.3.0 or later) */
if (gnutls_global_init() != GNUTLS_E_SUCCESS)
return 0;
local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
force_assert(NULL != local_send_buffer);
return 1;
}
static void mod_gnutls_free_gnutls (void)
{
if (!ssl_is_init) return;
gnutls_memset(session_ticket_keys, 0, sizeof(session_ticket_keys));
mod_gnutls_session_ticket_key_free();
stek_rotate_ts = 0;
gnutls_global_deinit();
free(local_send_buffer);
ssl_is_init = 0;
}
__attribute_noinline__
static void
mod_gnutls_free_config_crts_data (gnutls_datum_t *d)
{
if (NULL == d) return;
gnutls_x509_crt_t *crts = (gnutls_x509_crt_t *)(void *)d->data;
unsigned int u = d->size;
for (unsigned int i = 0; i < u; ++i)
gnutls_x509_crt_deinit(crts[i]);
gnutls_free(crts);
}
static void
mod_gnutls_free_config_crts (gnutls_datum_t *d)
{
mod_gnutls_free_config_crts_data(d);
gnutls_free(d);
}
static void
mod_gnutls_free_config_crls (gnutls_datum_t *d)
{
if (NULL == d) return;
gnutls_x509_crl_t *crls = (gnutls_x509_crl_t *)(void *)d->data;
unsigned int u = d->size;
for (unsigned int i = 0; i < u; ++i)
gnutls_x509_crl_deinit(crls[i]);
gnutls_free(crls);
gnutls_free(d);
}
static int
mod_gnutls_cert_is_active (gnutls_x509_crt_t crt)
{
const time_t before = gnutls_x509_crt_get_activation_time(crt);
const time_t after = gnutls_x509_crt_get_expiration_time(crt);
const unix_time64_t now = log_epoch_secs;
return (before <= now && now <= after);
}
static gnutls_datum_t *
mod_gnutls_load_config_crts (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t));
if (d == NULL) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
d->data = NULL;
d->size = 0;
rc = gnutls_x509_crt_list_import2((gnutls_x509_crt_t **)&d->data, &d->size,
&f, GNUTLS_X509_FMT_PEM,
GNUTLS_X509_CRT_LIST_SORT);
if (rc < 0) {
mod_gnutls_free_config_crts_data(d);
d->data = NULL;
d->size = 0;
if (0 == gnutls_x509_crt_list_import2((gnutls_x509_crt_t **)&d->data,
&d->size, &f, GNUTLS_X509_FMT_DER,
GNUTLS_X509_CRT_LIST_SORT))
rc = 0;
}
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_x509_crt_list_import2() %s", fn);
mod_gnutls_free_config_crts(d);
return NULL;
}
else if (
!mod_gnutls_cert_is_active(((gnutls_x509_crt_t *)(void *)d->data)[0])) {
log_error(errh, __FILE__, __LINE__,
"GnuTLS: inactive/expired X509 certificate '%s'", fn);
}
return d;
}
static gnutls_datum_t *
mod_gnutls_load_config_crls (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t));
if (d == NULL) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
d->data = NULL;
d->size = 0;
rc = gnutls_x509_crl_list_import2((gnutls_x509_crl_t **)&d->data, &d->size,
&f, GNUTLS_X509_FMT_PEM, 0);
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_x509_crl_list_import2() %s", fn);
mod_gnutls_free_config_crls(d);
return NULL;
}
return d;
}
static gnutls_privkey_t
mod_gnutls_load_config_pkey (const char *fn, log_error_st *errh)
{
/*(very similar to other mod_gnutls_load_config_*())*/
if (!mod_gnutls_init_once_gnutls()) return NULL;
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(fn, &f, errh);
if (rc < 0) return NULL;
gnutls_privkey_t pkey;
rc = gnutls_privkey_init(&pkey);
if (rc < 0) {
mod_gnutls_datum_wipe(&f);
return NULL;
}
rc = gnutls_privkey_import_x509_raw(pkey, &f, GNUTLS_X509_FMT_PEM, NULL, 0);
if (rc < 0) {
gnutls_privkey_deinit(pkey);
if (0 == gnutls_privkey_init(&pkey)
&& 0 == gnutls_privkey_import_x509_raw(pkey, &f,
GNUTLS_X509_FMT_DER,NULL,0))
rc = 0;
}
mod_gnutls_datum_wipe(&f);
if (rc < 0) {
elogf(errh, __FILE__, __LINE__, rc,
"gnutls_privkey_import_x509_raw() %s", fn);
gnutls_privkey_deinit(pkey);
return NULL;
}
return pkey;
}
static void
mod_gnutls_free_config (server *srv, plugin_data * const p)
{
if (NULL != p->ssl_ctxs) {
gnutls_priority_t pcache_global_scope = p->ssl_ctxs->priority_cache;
/* free 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->priority_cache && s->priority_cache != pcache_global_scope) {
if (s->priority_cache)
gnutls_priority_deinit(s->priority_cache);
#if GNUTLS_VERSION_NUMBER < 0x030600
if (s->dh_params)
gnutls_dh_params_deinit(s->dh_params);
#endif
}
}
/* free from global scope */
if (pcache_global_scope) {
if (p->ssl_ctxs[0].priority_cache)
gnutls_priority_deinit(p->ssl_ctxs[0].priority_cache);
#if GNUTLS_VERSION_NUMBER < 0x030600
if (p->ssl_ctxs[0].dh_params)
gnutls_dh_params_deinit(p->ssl_ctxs[0].dh_params);
#endif
}
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;
gnutls_certificate_free_credentials(pc->ssl_cred);
mod_gnutls_free_config_crts(pc->ssl_pemfile_x509);
gnutls_privkey_deinit(pc->ssl_pemfile_pkey);
free(pc);
}
break;
case 2: /* ssl.ca-file */
case 3: /* ssl.ca-dn-file */
if (cpv->vtype == T_CONFIG_LOCAL)
mod_gnutls_free_config_crts(cpv->v.v);
break;
case 4: /* ssl.ca-crl-file */
if (cpv->vtype == T_CONFIG_LOCAL)
mod_gnutls_free_config_crls(cpv->v.v);
break;
default:
break;
}
}
}
}
FREE_FUNC(mod_gnutls_free)
{
plugin_data *p = p_d;
if (NULL == p->srv) return;
mod_gnutls_free_config(p->srv, p);
mod_gnutls_free_gnutls();
}
static void
mod_gnutls_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 */
if (cpv->vtype == T_CONFIG_LOCAL)
pconf->ssl_ca_crl_file = cpv->v.v;
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 = (unsigned char)cpv->v.shrt;
break;
#if 0 /*(cpk->k_id remapped in mod_gnutls_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_gnutls_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
{
do {
mod_gnutls_merge_config_cpv(pconf, cpv);
} while ((++cpv)->k_id != -1);
}
static void
mod_gnutls_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_gnutls_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
}
}
static int
mod_gnutls_verify_set_tlist (handler_ctx *hctx, int req)
{
/* XXX GnuTLS interfaces appear to be better for client-side use than for
* server-side use. If gnutls_x509_trust_list_t were available to attach
* to a gnutls_session_t (without copying), then there would not be race
* conditions swapping trust lists on the credential *shared* between
* connections when ssl.ca-dn-file and ssl.ca-file are both set. If both
* are set, current code attempts to set ssl.ca-dn-file right before sending
* client cert request, and sets ssl.ca-file right before client cert verify
*
* Architecture would be cleaner if the trust list for verifying client cert
* (gnutls_x509_trust_list_t) were available to attach to a gnutls_session_t
* instead of attaching to a gnutls_certificate_credentials_t.
*/
if (hctx->conf.pc->trust_inited) return GNUTLS_E_SUCCESS;
gnutls_datum_t *d;
int rc;
/* set trust list using ssl_ca_dn_file, if set, for client cert request
* (when req is true) (for CAs sent by server to client in cert request)
* (trust is later replaced by ssl_ca_file for client cert verification) */
d = req && hctx->conf.ssl_ca_dn_file
? hctx->conf.ssl_ca_dn_file
: hctx->conf.ssl_ca_file;
if (NULL == d) {
log_error(hctx->r->conf.errh, __FILE__, __LINE__,
"GnuTLS: can't verify client without ssl.verifyclient.ca-file "
"for TLS server name %s",
hctx->r->uri.authority.ptr); /*(might not be set yet if no SNI)*/
return GNUTLS_E_INTERNAL_ERROR;
}
gnutls_x509_trust_list_t tlist = NULL;
rc = gnutls_x509_trust_list_init(&tlist, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_init()");
return rc;
}
gnutls_x509_crt_t *clist = (gnutls_x509_crt_t *)(void *)d->data;
rc = gnutls_x509_trust_list_add_cas(tlist, clist, d->size, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_add_cas()");
gnutls_x509_trust_list_deinit(tlist, 0);
return rc;
}
d = hctx->conf.ssl_ca_crl_file;
if (NULL != d && req && hctx->conf.ssl_ca_dn_file) {
/*(check req and ssl_ca_dn_file to see if tlist will be replaced later,
* and, if so, defer setting crls until later)*/
gnutls_x509_crl_t *crl_list = (gnutls_x509_crl_t *)(void *)d->data;
rc = gnutls_x509_trust_list_add_crls(tlist, crl_list, d->size, 0, 0);
if (rc < 0) {
elog(hctx->r->conf.errh, __FILE__, __LINE__, rc,
"gnutls_x509_trust_list_add_crls()");
gnutls_x509_trust_list_deinit(tlist, 0);
return rc;
}
}
/* gnutls limitation; wasteful to have to copy into each cred */
/* (would be better to share list with session, instead of with cred) */
gnutls_certificate_credentials_t ssl_cred = hctx->conf.pc->ssl_cred;
gnutls_certificate_set_trust_list(ssl_cred, tlist, 0); /* transfer tlist */
/* (must flip trust lists back and forth b/w DN names and verify CAs) */
if (NULL == hctx->conf.ssl_ca_dn_file)
hctx->conf.pc->trust_inited = 1;
return GNUTLS_E_SUCCESS;
}
static int
mod_gnutls_verify_cb (gnutls_session_t ssl)
{
handler_ctx * const hctx = gnutls_session_get_ptr(ssl);
if (!hctx->conf.ssl_verifyclient) return 0;
if (gnutls_auth_client_get_type(ssl) != GNUTLS_CRD_CERTIFICATE)
return GNUTLS_E_SUCCESS;
int rc;
/* gnutls limitation; wasteful to have to copy into each cred */
/* (would be better to share list with session, instead of with cred) */
if (hctx->conf.ssl_ca_dn_file) {
rc = mod_gnutls_verify_set_tlist(hctx, 0); /* for client cert verify */
if (rc < 0) return rc;
}
/* gnutls_certificate_verify_peers2() includes processing OCSP staping,
* as well as certificate depth verification before getting internal
* flags and calling gnutls_x509_trust_list_verify_crt2()
* advanced reference:
* gnutls lib/cert-sessions.c:_gnutls_x509_cert_verify_peers()
* XXX: if GnuTLS provided a more advanced interface which permitted
* providing trust list, verify depth, and flags, we could avoid copying
* ca chain and crls into each credential, using
* gnutls_x509_trust_list_add_cas()
* gnutls_x509_trust_list_add_crls()
* gnutls_x509_trust_list_verify_crt2()
* See also GnuTLS manual Section 7.3.4 Advanced certificate verification
*/
rc = gnutls_certificate_verify_peers2(ssl, &hctx->verify_status);
if (rc < 0) return rc;
if (hctx->verify_status == 0 && hctx->conf.ssl_ca_dn_file) {
/* verify that client cert is issued by CA in ssl.ca-dn-file
* if both ssl.ca-dn-file and ssl.ca-file were configured */
gnutls_x509_crt_t *CA_list =
(gnutls_x509_crt_t *)(void *)hctx->conf.ssl_ca_dn_file->data;
unsigned int len = hctx->conf.ssl_ca_dn_file->size;
unsigned int i;
gnutls_x509_dn_t issuer, subject;
unsigned int crt_size = 0;
const gnutls_datum_t *crts;
gnutls_x509_crt_t crt = NULL;
crts = gnutls_certificate_get_peers(ssl, &crt_size);
if (0 == crt_size
|| gnutls_x509_crt_init(&crt) < 0
|| gnutls_x509_crt_import(crt, &crts[0], GNUTLS_X509_FMT_DER) < 0
|| gnutls_x509_crt_get_subject(crt, &issuer) < 0)
len = 0; /*(trigger failure path below)*/
for (i = 0; i < len; ++i) {
if (gnutls_x509_crt_get_subject(CA_list[i], &subject) >= 0
&& 0 == memcmp(&subject, &issuer, sizeof(issuer)))
break;
}
if (i == len)
hctx->verify_status |= GNUTLS_CERT_SIGNER_NOT_CA;
if (crt) gnutls_x509_crt_deinit(crt);
}
if (hctx->verify_status != 0 && hctx->conf.ssl_verifyclient_enforce) {
/* (not looping on GNUTLS_E_INTERRUPTED or GNUTLS_E_AGAIN
* since we do not want to block here (and not expecting to have to))*/
(void)gnutls_alert_send(ssl, GNUTLS_AL_FATAL, GNUTLS_A_ACCESS_DENIED);
return GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR;
}
return GNUTLS_E_SUCCESS;
}
#if GNUTLS_VERSION_NUMBER < 0x030603
static time_t
mod_gnutls_ocsp_next_update (plugin_cert *pc, log_error_st *errh)
{
gnutls_datum_t f = { NULL, 0 };
int rc = mod_gnutls_load_file(pc->ssl_stapling_file->ptr, &f, errh);
if (rc < 0) return (time_t)-1;
gnutls_ocsp_resp_t resp = NULL;
time_t nextupd;
if ( gnutls_ocsp_resp_init(&resp) < 0
|| gnutls_ocsp_resp_import(resp, &f) < 0
|| gnutls_ocsp_resp_get_single(resp, 0, NULL, NULL, NULL, NULL, NULL,
NULL, &nextupd, NULL, NULL) < 0)
nextupd = (time_t)-1;
gnutls_ocsp_resp_deinit(resp);
mod_gnutls_datum_wipe(&f);
return nextupd;
}
#endif
__attribute_cold__
static void
mod_gnutls_expire_stapling_file (server *srv, plugin_cert *pc)
{
#if 0
/* discard expired OCSP stapling response */
/* Does GnuTLS detect expired OCSP response? */
/* or must we rebuild gnutls_certificate_credentials_t ? */
#endif
if (pc->must_staple)
log_error(srv->errh, __FILE__, __LINE__,
"certificate marked OCSP Must-Staple, "
"but OCSP response expired from ssl.stapling-file %s",
pc->ssl_stapling_file->ptr);
}
static int
mod_gnutls_reload_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts)
{
#if GNUTLS_VERSION_NUMBER < 0x030603
/* load file into gnutls_ocsp_resp_t before loading into
* gnutls_certificate_credentials_t for safety. Still ToC-ToU since file
* is loaded twice, but unlikely condition. (GnuTLS limitation does not
* expose access to OCSP response from gnutls_certificate_credentials_t
* before GnuTLS 3.6.3) */
time_t nextupd = mod_gnutls_ocsp_next_update(pc, srv->errh);
#else
UNUSED(srv);
#endif
/* GnuTLS 3.5.6 added the ability to include multiple OCSP responses for
* certificate chain as allowed in TLSv1.3, but that is not utilized here.
* If implemented, it will probably operate on a new directive,
* e.g. ssl.stapling-pemfile
* GnuTLS 3.6.3 added gnutls_certificate_set_ocsp_status_request_file2()
* GnuTLS 3.6.3 added gnutls_certificate_set_ocsp_status_request_mem()
* GnuTLS 3.6.3 added gnutls_certificate_get_ocsp_expiration() */
/* gnutls_certificate_get_ocsp_expiration() code comments:
* Note that the credentials structure should be read-only when in
* use, thus when reloading, either the credentials structure must not
* be in use by any sessions, or a new credentials structure should be
* allocated for new sessions.
* XXX: lighttpd is not threaded, so this is probably not an issue (?)
*/
#if 0
gnutls_certificate_set_flags(pc->ssl_cred,
GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK);
#endif