xref: /lighttpd1.4/src/mod_openssl.c (revision 9570cc2f)
1 /*
2  * mod_openssl - openssl support for lighttpd
3  *
4  * Fully-rewritten from original
5  * Copyright(c) 2016 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
6  * License: BSD 3-clause (same as lighttpd)
7  */
8 /*
9  * future possible enhancements: OCSP stapling
10  *
11  * Note: If session tickets are -not- disabled with
12  *     ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
13  *   mod_openssl rotates server ticket encryption key (STEK) every 24 hours.
14  *   This is fine for use with a single lighttpd instance, but with multiple
15  *   lighttpd workers, no coordinated STEK (server ticket encryption key)
16  *   rotation occurs other than by (some external job) restarting lighttpd.
17  *   Restarting lighttpd generates a new key that is shared by lighttpd workers
18  *   for the lifetime of the new key.  If the rotation period expires and
19  *   lighttpd has not been restarted, lighttpd workers will generate new
20  *   independent keys, making session tickets less effective for session
21  *   resumption, since clients have a lower chance for future connections to
22  *   reach the same lighttpd worker.  However, things will still work, and a new
23  *   session will be created if session resumption fails.  Admins should plan to
24  *   restart lighttpd at least every 24 hours if session tickets are enabled and
25  *   multiple lighttpd workers are configured.
26  */
27 #include "first.h"
28 
29 #include <errno.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 
34 /*(not needed)*/
35 #define OPENSSL_NO_STDIO
36 
37 #ifndef USE_OPENSSL_KERBEROS
38 #ifndef OPENSSL_NO_KRB5
39 #define OPENSSL_NO_KRB5
40 #endif
41 #endif
42 
43 #include "sys-crypto.h"
44 
45 #include <openssl/ssl.h>
46 #include <openssl/bio.h>
47 #include <openssl/bn.h>
48 #include <openssl/err.h>
49 #include <openssl/objects.h>
50 #include <openssl/pem.h>
51 #include <openssl/rand.h>
52 #ifndef OPENSSL_NO_DH
53 #include <openssl/dh.h>
54 #endif
55 
56 #if ! defined OPENSSL_NO_TLSEXT && ! defined SSL_CTRL_SET_TLSEXT_HOSTNAME
57 #define OPENSSL_NO_TLSEXT
58 #endif
59 
60 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
61 #ifndef OPENSSL_NO_ECDH
62 #include <openssl/ecdh.h>
63 #endif
64 #endif
65 
66 #include "base.h"
67 #include "http_header.h"
68 #include "log.h"
69 #include "plugin.h"
70 
71 typedef struct {
72     /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
73     EVP_PKEY *ssl_pemfile_pkey;
74     X509 *ssl_pemfile_x509;
75     STACK_OF(X509) *ssl_pemfile_chain;
76     const buffer *ssl_pemfile;
77     const buffer *ssl_privkey;
78 } plugin_cert;
79 
80 typedef struct {
81     SSL_CTX *ssl_ctx;
82 } plugin_ssl_ctx;
83 
84 typedef struct {
85     STACK_OF(X509_NAME) *names;
86     X509_STORE *certs;
87 } plugin_cacerts;
88 
89 typedef struct {
90     SSL_CTX *ssl_ctx; /* output from network_init_ssl() */
91 
92     /*(used only during startup; not patched)*/
93     unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
94     unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
95     unsigned char ssl_empty_fragments; /* whether to not set SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
96     unsigned char ssl_use_sslv2;
97     unsigned char ssl_use_sslv3;
98     const buffer *ssl_cipher_list;
99     const buffer *ssl_dh_file;
100     const buffer *ssl_ec_curve;
101     array *ssl_conf_cmd;
102 
103     /*(copied from plugin_data for socket ssl_ctx config)*/
104     const plugin_cert *pc;
105     const plugin_cacerts *ssl_ca_file;
106     STACK_OF(X509_NAME) *ssl_ca_dn_file;
107     const buffer *ssl_ca_crl_file;
108     unsigned char ssl_verifyclient;
109     unsigned char ssl_verifyclient_enforce;
110     unsigned char ssl_verifyclient_depth;
111     unsigned char ssl_read_ahead;
112     unsigned char ssl_disable_client_renegotiation;
113 } plugin_config_socket; /*(used at startup during configuration)*/
114 
115 typedef struct {
116     /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
117     plugin_cert *pc;
118     const plugin_cacerts *ssl_ca_file;
119     STACK_OF(X509_NAME) *ssl_ca_dn_file;
120     const buffer *ssl_ca_crl_file;
121 
122     unsigned char ssl_verifyclient;
123     unsigned char ssl_verifyclient_enforce;
124     unsigned char ssl_verifyclient_depth;
125     unsigned char ssl_verifyclient_export_cert;
126     unsigned char ssl_read_ahead;
127     unsigned char ssl_log_noise;
128     unsigned char ssl_disable_client_renegotiation;
129     const buffer *ssl_verifyclient_username;
130     const buffer *ssl_acme_tls_1;
131 } plugin_config;
132 
133 typedef struct {
134     PLUGIN_DATA;
135     plugin_ssl_ctx *ssl_ctxs;
136     plugin_config defaults;
137     server *srv;
138     array *cafiles;
139 } plugin_data;
140 
141 static int ssl_is_init;
142 /* need assigned p->id for deep access of module handler_ctx for connection
143  *   i.e. handler_ctx *hctx = r->plugin_ctx[plugin_data_singleton->id]; */
144 static plugin_data *plugin_data_singleton;
145 #define LOCAL_SEND_BUFSIZE (16 * 1024)
146 static char *local_send_buffer;
147 
148 typedef struct {
149     SSL *ssl;
150     request_st *r;
151     connection *con;
152     short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
153     short close_notify;
154     unsigned short request_env_patched;
155     unsigned short alpn;
156     plugin_config conf;
157     buffer *tmp_buf;
158 } handler_ctx;
159 
160 
161 static handler_ctx *
162 handler_ctx_init (void)
163 {
164     handler_ctx *hctx = calloc(1, sizeof(*hctx));
165     force_assert(hctx);
166     return hctx;
167 }
168 
169 
170 static void
171 handler_ctx_free (handler_ctx *hctx)
172 {
173     if (hctx->ssl) SSL_free(hctx->ssl);
174     free(hctx);
175 }
176 
177 
178 #ifdef TLSEXT_TYPE_session_ticket
179 static time_t stek_rotate_ts;
180 
181 static void
182 mod_openssl_session_ticket_key_rotate (server * const srv, const plugin_data * const p)
183 {
184     /* server ticket encryption key (STEK) is *per-SSL_CTX* in openssl
185      *   and keys are initially created in SSL_CTX_new()
186      * SSL_CTX_set_tlsext_ticket_keys() is an openssl interface,
187      *   but how to construct its arguments is not well documented.
188      * See openssl ssl/s3_lib.c
189      *   case SSL_CTRL_SET_TLSEXT_TICKET_KEYS:
190      * In openssl 1.1.x
191      *   ssl/ssl_local.h
192      *     TLSEXT_KEYNAME_LENGTH  16
193      *     TLSEXT_TICK_KEY_LENGTH 32
194      *   private SSL_CTX data members:
195      *     ssl_ctx->ext.tick_key_name          TLSEXT_KEYNAME_LENGTH
196      *     ssl_ctx->ext.secure->tick_hmac_key  TLSEXT_TICK_KEY_LENGTH
197      *     ssl_ctx->ext.secure->tick_aes_key   TLSEXT_TICK_KEY_LENGTH
198      * In openssl 1.0.x, each element is 16 bytes (TLSEXT_TICK_KEY_LENGTH 16)
199      *
200      * openssl RAND_*bytes() functions are called multiple times since the
201      * funcs might have a 32-byte limit on number of bytes returned each call
202      *
203      * (Note: session ticket encryption key rotation is not expected to fail)
204      */
205     int rc = 1;
206   #if OPENSSL_VERSION_NUMBER < 0x10100000L
207     unsigned char keys[16+16+16];
208     if (RAND_bytes(keys,16) <= 0
209         || RAND_bytes(keys+16,16) <= 0
210         || RAND_bytes(keys+16+16,16) <= 0)
211   #else
212     /*(RAND_priv_bytes() not in openssl 1.1.0; introduced in openssl 1.1.1)*/
213     #if OPENSSL_VERSION_NUMBER < 0x10101000L
214     #define RAND_priv_bytes(x,sz) RAND_bytes((x),(sz))
215     #endif
216     unsigned char keys[16+32+32];
217     if (RAND_bytes(keys,16) <= 0
218         || RAND_priv_bytes(keys+16,32) <= 0
219         || RAND_priv_bytes(keys+16+32,32) <= 0)
220   #endif
221         rc = 0;
222 
223     const size_t sz = sizeof(keys);
224 
225     for (uint32_t i = 0; i < srv->config_context->used; ++i) {
226         plugin_ssl_ctx * const s = p->ssl_ctxs + i;
227         if (!s->ssl_ctx) continue;
228         if (SSL_CTX_get_options(s->ssl_ctx) & SSL_OP_NO_TICKET) continue;
229         if (!rc || 1 != SSL_CTX_set_tlsext_ticket_keys(s->ssl_ctx, keys, sz)) {
230             /*(disable session tickets rather than continue to use aging keys)*/
231             long opts = SSL_CTX_get_options(s->ssl_ctx) | SSL_OP_NO_TICKET;
232             SSL_CTX_set_options(s->ssl_ctx, opts);
233             log_error(srv->errh, __FILE__, __LINE__,
234               "SSL: STEK rotation failed; disabling session tickets");
235         }
236     }
237 
238     OPENSSL_cleanse(keys, sizeof(keys));
239 }
240 #endif /* TLSEXT_TYPE_session_ticket */
241 
242 
243 INIT_FUNC(mod_openssl_init)
244 {
245     plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
246   #ifdef DEBUG_WOLFSSL
247     wolfSSL_Debugging_ON();
248   #endif
249     return plugin_data_singleton;
250 }
251 
252 
253 static int mod_openssl_init_once_openssl (server *srv)
254 {
255     if (ssl_is_init) return 1;
256 
257   #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
258    && !defined(LIBRESSL_VERSION_NUMBER)
259     OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
260                     |OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
261     OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
262                        |OPENSSL_INIT_ADD_ALL_DIGESTS
263                        |OPENSSL_INIT_LOAD_CONFIG, NULL);
264   #else
265     SSL_load_error_strings();
266     SSL_library_init();
267     OpenSSL_add_all_algorithms();
268   #endif
269     ssl_is_init = 1;
270 
271     if (0 == RAND_status()) {
272         log_error(srv->errh, __FILE__, __LINE__,
273           "SSL: not enough entropy in the pool");
274         return 0;
275     }
276 
277     local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
278     force_assert(NULL != local_send_buffer);
279 
280     return 1;
281 }
282 
283 
284 static void mod_openssl_free_openssl (void)
285 {
286     if (!ssl_is_init) return;
287 
288   #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
289    && !defined(LIBRESSL_VERSION_NUMBER)
290     /*(OpenSSL libraries handle thread init and deinit)
291      * https://github.com/openssl/openssl/pull/1048 */
292   #else
293     CRYPTO_cleanup_all_ex_data();
294     ERR_free_strings();
295    #if OPENSSL_VERSION_NUMBER >= 0x10000000L
296     ERR_remove_thread_state(NULL);
297    #else
298     ERR_remove_state(0);
299    #endif
300     EVP_cleanup();
301   #endif
302 
303     free(local_send_buffer);
304     ssl_is_init = 0;
305 }
306 
307 
308 static void
309 mod_openssl_free_config (server *srv, plugin_data * const p)
310 {
311     array_free(p->cafiles);
312 
313     if (NULL != p->ssl_ctxs) {
314         SSL_CTX * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
315         /* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
316         for (uint32_t i = 1; i < srv->config_context->used; ++i) {
317             plugin_ssl_ctx * const s = p->ssl_ctxs + i;
318             if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope)
319                 SSL_CTX_free(s->ssl_ctx);
320         }
321         /* free ssl_ctx from global scope */
322         if (ssl_ctx_global_scope)
323             SSL_CTX_free(ssl_ctx_global_scope);
324         free(p->ssl_ctxs);
325     }
326 
327     if (NULL == p->cvlist) return;
328     /* (init i to 0 if global context; to 1 to skip empty global context) */
329     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
330         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
331         for (; -1 != cpv->k_id; ++cpv) {
332             switch (cpv->k_id) {
333               case 0: /* ssl.pemfile */
334                 if (cpv->vtype == T_CONFIG_LOCAL) {
335                     plugin_cert *pc = cpv->v.v;
336                     EVP_PKEY_free(pc->ssl_pemfile_pkey);
337                     X509_free(pc->ssl_pemfile_x509);
338                     sk_X509_pop_free(pc->ssl_pemfile_chain, X509_free);
339                 }
340                 break;
341               case 2: /* ssl.ca-file */
342                 if (cpv->vtype == T_CONFIG_LOCAL) {
343                     plugin_cacerts *cacerts = cpv->v.v;
344                     sk_X509_NAME_pop_free(cacerts->names, X509_NAME_free);
345                     X509_STORE_free(cacerts->certs);
346                     free(cacerts);
347                 }
348                 break;
349               case 3: /* ssl.ca-dn-file */
350                 if (cpv->vtype == T_CONFIG_LOCAL)
351                     sk_X509_NAME_pop_free(cpv->v.v, X509_NAME_free);
352                 break;
353               default:
354                 break;
355             }
356         }
357     }
358 }
359 
360 
361 /* openssl BIO_s_file() employs system stdio
362  * system stdio buffers reads and does not guarantee to clear buffer memory
363  * 'man PEM_bytes_read_bio_secmem()' and see NOTES section for more info
364  */
365 
366 #ifdef OPENSSL_NO_POSIX_IO
367 
368 #include <stdio.h>
369 static BIO *
370 BIO_new_rdonly_file (const char *file)
371 {
372 
373     BIO *in = BIO_new(BIO_s_file());
374     if (NULL == in)
375         return NULL;
376 
377     if (BIO_read_filename(in, file) <= 0) {
378         BIO_free(in);
379         return NULL;
380     }
381 
382     /* set I/O stream unbuffered (best-effort; not fatal)
383      * system stdio buffers reads and does not guarantee to clear buffer memory.
384      * Alternative: provide buffer (e.g. 8k) and clear after use (in caller) */
385     FILE *fp = NULL;
386     if (BIO_get_fp(in, &fp))
387         setvbuf(fp, NULL, _IONBF, 0);
388 
389     return in;
390 }
391 
392 #else  /* !OPENSSL_NO_POSIX_IO */
393 
394 #include <fcntl.h>
395 #include "fdevent.h"
396 static BIO *
397 BIO_new_rdonly_file (const char *file)
398 {
399     /* unbuffered fd; not using system stdio */
400     int fd = fdevent_open_cloexec(file, 1, O_RDONLY, 0);
401     if (fd < 0)
402         return NULL;
403 
404     BIO *in = BIO_new_fd(fd, BIO_CLOSE);
405     if (NULL == in) {
406         close(fd);
407         return NULL;
408     }
409 
410     return in;
411 }
412 
413 #endif /* !OPENSSL_NO_POSIX_IO */
414 
415 
416 /* use memory from openssl secure heap for temporary buffers, returned storage
417  * (pemfile might contain a private key in addition to certificate chain)
418  * Interfaces similar to those constructed in include/openssl/pem.h for
419  * PEM_read_bio_X509(), except this is named PEM_read_bio_X509_secmem().
420  * Similar for PEM_read_bio_X509_AUX_secmem().
421  *
422  * Supporting routine PEM_ASN1_read_bio_secmem() modified from openssl
423  * crypto/pem/pem_oth.c:PEM_ASN1_read_bio():
424  *   uses PEM_bytes_read_bio_secmem() instead of PEM_bytes_read_bio()
425  *   uses OPENSSL_secure_clear_free() instead of OPENSSL_free()
426  *
427  * PEM_bytes_read_bio_secmem() openssl 1.1.1 or later
428  * OPENSSL_secure_clear_free() openssl 1.1.0g or later
429  * As this comment is being written, only openssl 1.1.1 is actively maintained.
430  * Earlier vers of openssl no longer receive security patches from openssl.org.
431  */
432 static void *
433 PEM_ASN1_read_bio_secmem(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
434                          pem_password_cb *cb, void *u)
435 {
436     const unsigned char *p = NULL;
437     unsigned char *data = NULL;
438     long len = 0;
439     char *ret = NULL;
440 
441   #if OPENSSL_VERSION_NUMBER >= 0x10101000L
442     if (!PEM_bytes_read_bio_secmem(&data, &len, NULL, name, bp, cb, u))
443   #else
444     if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
445   #endif
446         return NULL;
447     p = data;
448     ret = d2i(x, &p, len);
449     if (ret == NULL)
450         PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB);
451   #if OPENSSL_VERSION_NUMBER >= 0x10101000L
452     OPENSSL_secure_clear_free(data, len);
453   #else
454     OPENSSL_cleanse(data, len);
455     OPENSSL_free(data);
456   #endif
457     return ret;
458 }
459 
460 
461 static X509 *
462 PEM_read_bio_X509_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
463 {
464     return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509,
465                                     PEM_STRING_X509,
466                                     bp, (void **)x, cb, u);
467 }
468 
469 
470 static X509 *
471 PEM_read_bio_X509_AUX_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
472 {
473     return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509_AUX,
474                                     PEM_STRING_X509_TRUSTED,
475                                     bp, (void **)x, cb, u);
476 }
477 
478 
479 static int
480 mod_openssl_load_X509_sk (const char *file, log_error_st *errh, STACK_OF(X509) **chain, BIO *in)
481 {
482     STACK_OF(X509) *chain_sk = NULL;
483     for (X509 *ca; (ca = PEM_read_bio_X509_secmem(in,NULL,NULL,NULL)); ) {
484         if (NULL == chain_sk) /*(allocate only if it will not be empty)*/
485             chain_sk = sk_X509_new_null();
486         if (!chain_sk || !sk_X509_push(chain_sk, ca)) {
487             log_error(errh, __FILE__, __LINE__,
488               "SSL: couldn't read X509 certificates from '%s'", file);
489             if (chain_sk) sk_X509_pop_free(chain_sk, X509_free);
490             X509_free(ca);
491             return 0;
492         }
493     }
494     *chain = chain_sk;
495     return 1;
496 }
497 
498 
499 static int
500 mod_openssl_load_X509_STORE (const char *file, log_error_st *errh, X509_STORE **chain, BIO *in)
501 {
502     X509_STORE *chain_store = NULL;
503     for (X509 *ca; (ca = PEM_read_bio_X509(in,NULL,NULL,NULL)); X509_free(ca)) {
504         if (NULL == chain_store) /*(allocate only if it will not be empty)*/
505             chain_store = X509_STORE_new();
506         if (!chain_store || !X509_STORE_add_cert(chain_store, ca)) {
507             log_error(errh, __FILE__, __LINE__,
508               "SSL: couldn't read X509 certificates from '%s'", file);
509             if (chain_store) X509_STORE_free(chain_store);
510             X509_free(ca);
511             return 0;
512         }
513     }
514     *chain = chain_store;
515     return 1;
516 }
517 
518 
519 static plugin_cacerts *
520 mod_openssl_load_cacerts (const buffer *ssl_ca_file, log_error_st *errh)
521 {
522     const char *file = ssl_ca_file->ptr;
523     BIO *in = BIO_new(BIO_s_file());
524     if (NULL == in) {
525         log_error(errh, __FILE__, __LINE__,
526           "SSL: BIO_new(BIO_s_file()) failed");
527         return NULL;
528     }
529 
530     if (BIO_read_filename(in, file) <= 0) {
531         log_error(errh, __FILE__, __LINE__,
532           "SSL: BIO_read_filename('%s') failed", file);
533         BIO_free(in);
534         return NULL;
535     }
536 
537     X509_STORE *chain_store = NULL;
538     if (!mod_openssl_load_X509_STORE(file, errh, &chain_store, in)) {
539         BIO_free(in);
540         return NULL;
541     }
542 
543     BIO_free(in);
544 
545     if (NULL == chain_store) {
546         log_error(errh, __FILE__, __LINE__,
547           "SSL: ssl.ca-file is empty %s", file);
548         return NULL;
549     }
550 
551     plugin_cacerts *cacerts = malloc(sizeof(plugin_cacerts));
552     force_assert(cacerts);
553 
554     /* (would be more efficient to walk the X509_STORE and build the list,
555      *  but this works for now and matches how ssl.ca-dn-file is handled) */
556     cacerts->names = SSL_load_client_CA_file(file);
557     if (NULL == cacerts->names) {
558         X509_STORE_free(chain_store);
559         free(cacerts);
560         return NULL;
561     }
562 
563     cacerts->certs = chain_store;
564     return cacerts;
565 }
566 
567 
568 static int
569 mod_openssl_load_cacrls (X509_STORE *store, const buffer *ssl_ca_crl_file, server *srv)
570 {
571     if (1 != X509_STORE_load_locations(store, ssl_ca_crl_file->ptr, NULL)) {
572         log_error(srv->errh, __FILE__, __LINE__,
573           "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
574           ssl_ca_crl_file->ptr);
575         return 0;
576     }
577     X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
578     return 1;
579 }
580 
581 
582 #if OPENSSL_VERSION_NUMBER < 0x10002000
583 static int
584 mod_openssl_load_verify_locn (SSL_CTX *ssl_ctx, const buffer *b, server *srv)
585 {
586     const char *fn = b->ptr;
587     if (1 == SSL_CTX_load_verify_locations(ssl_ctx, fn, NULL))
588         return 1;
589 
590     log_error(srv->errh, __FILE__, __LINE__,
591       "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), fn);
592     return 0;
593 }
594 
595 
596 static int
597 mod_openssl_load_ca_files (SSL_CTX *ssl_ctx, plugin_data *p, server *srv)
598 {
599     /* load all ssl.ca-files specified in the config into each SSL_CTX */
600 
601     for (uint32_t i = 0, used = p->cafiles->used; i < used; ++i) {
602         const buffer *b = &((data_string *)p->cafiles->data[i])->value;
603         if (!mod_openssl_load_verify_locn(ssl_ctx, b, srv))
604             return 0;
605     }
606     return 1;
607 }
608 #endif
609 
610 
611 FREE_FUNC(mod_openssl_free)
612 {
613     plugin_data *p = p_d;
614     if (NULL == p->srv) return;
615     mod_openssl_free_config(p->srv, p);
616     mod_openssl_free_openssl();
617 }
618 
619 
620 static void
621 mod_openssl_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
622 {
623     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
624       case 0: /* ssl.pemfile */
625         if (cpv->vtype == T_CONFIG_LOCAL)
626             pconf->pc = cpv->v.v;
627         break;
628       case 1: /* ssl.privkey */
629         break;
630       case 2: /* ssl.ca-file */
631         if (cpv->vtype == T_CONFIG_LOCAL)
632             pconf->ssl_ca_file = cpv->v.v;
633         break;
634       case 3: /* ssl.ca-dn-file */
635         if (cpv->vtype == T_CONFIG_LOCAL)
636             pconf->ssl_ca_dn_file = cpv->v.v;
637         break;
638       case 4: /* ssl.ca-crl-file */
639         pconf->ssl_ca_crl_file = cpv->v.b;
640         break;
641       case 5: /* ssl.read-ahead */
642         pconf->ssl_read_ahead = (0 != cpv->v.u);
643         break;
644       case 6: /* ssl.disable-client-renegotiation */
645         pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
646         break;
647       case 7: /* ssl.verifyclient.activate */
648         pconf->ssl_verifyclient = (0 != cpv->v.u);
649         break;
650       case 8: /* ssl.verifyclient.enforce */
651         pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
652         break;
653       case 9: /* ssl.verifyclient.depth */
654         pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
655         break;
656       case 10:/* ssl.verifyclient.username */
657         pconf->ssl_verifyclient_username = cpv->v.b;
658         break;
659       case 11:/* ssl.verifyclient.exportcert */
660         pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
661         break;
662       case 12:/* ssl.acme-tls-1 */
663         pconf->ssl_acme_tls_1 = cpv->v.b;
664         break;
665       case 13:/* debug.log-ssl-noise */
666         pconf->ssl_log_noise = (0 != cpv->v.u);
667         break;
668       default:/* should not happen */
669         return;
670     }
671 }
672 
673 
674 static void
675 mod_openssl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
676 {
677     do {
678         mod_openssl_merge_config_cpv(pconf, cpv);
679     } while ((++cpv)->k_id != -1);
680 }
681 
682 
683 static void
684 mod_openssl_patch_config (request_st * const r, plugin_config * const pconf)
685 {
686     plugin_data * const p = plugin_data_singleton;
687     memcpy(pconf, &p->defaults, sizeof(plugin_config));
688     for (int i = 1, used = p->nconfig; i < used; ++i) {
689         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
690             mod_openssl_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
691     }
692 }
693 
694 
695 static int
696 safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
697 {
698     BIO *bio = BIO_new(BIO_s_mem());
699     if (bio) {
700         int len = X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE);
701         BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
702         BIO_free(bio);
703         return len; /*return value has similar semantics to that of snprintf()*/
704     }
705     else {
706         buf[0] = '\0';
707         return -1;
708     }
709 }
710 
711 
712 static void
713 ssl_info_callback (const SSL *ssl, int where, int ret)
714 {
715     UNUSED(ret);
716 
717     if (0 != (where & SSL_CB_HANDSHAKE_START)) {
718         handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
719         if (hctx->renegotiations >= 0) ++hctx->renegotiations;
720     }
721   #ifdef TLS1_3_VERSION
722     /* https://github.com/openssl/openssl/issues/5721
723      * "TLSv1.3 unexpected InfoCallback after handshake completed" */
724     if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
725         /* SSL_version() is valid after initial handshake completed */
726         if (SSL_version(ssl) >= TLS1_3_VERSION) {
727             /* https://wiki.openssl.org/index.php/TLS1.3
728              * "Renegotiation is not possible in a TLSv1.3 connection" */
729             handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
730             hctx->renegotiations = -1;
731         }
732     }
733   #endif
734 }
735 
736 /* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
737 static int
738 verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
739 {
740     char buf[256];
741     X509 *err_cert;
742     int err, depth;
743     SSL *ssl;
744     handler_ctx *hctx;
745 
746     err = X509_STORE_CTX_get_error(ctx);
747     depth = X509_STORE_CTX_get_error_depth(ctx);
748 
749     /*
750      * Retrieve the pointer to the SSL of the connection currently treated
751      * and the application specific data stored into the SSL object.
752      */
753     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
754     hctx = (handler_ctx *) SSL_get_app_data(ssl);
755 
756     /*
757      * Catch a too long certificate chain. The depth limit set using
758      * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
759      * that whenever the "depth>verify_depth" condition is met, we
760      * have violated the limit and want to log this error condition.
761      * We must do it here, because the CHAIN_TOO_LONG error would not
762      * be found explicitly; only errors introduced by cutting off the
763      * additional certificates would be logged.
764      */
765     if (depth > hctx->conf.ssl_verifyclient_depth) {
766         preverify_ok = 0;
767         err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
768         X509_STORE_CTX_set_error(ctx, err);
769     }
770 
771     if (preverify_ok && 0 == depth && NULL != hctx->conf.ssl_ca_dn_file) {
772         /* verify that client cert is issued by CA in ssl.ca-dn-file
773          * if both ssl.ca-dn-file and ssl.ca-file were configured */
774         STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file;
775         X509_NAME *issuer;
776       #if OPENSSL_VERSION_NUMBER >= 0x10002000L
777         err_cert = X509_STORE_CTX_get_current_cert(ctx);
778       #else
779         err_cert = ctx->current_cert;
780       #endif
781         if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
782         issuer = X509_get_issuer_name(err_cert);
783       #if 0 /*(?desirable/undesirable to have cert_names sorted?)*/
784         if (-1 != sk_X509_NAME_find(cert_names, issuer))
785             return preverify_ok; /* match */
786       #else
787         for (int i = 0, len = sk_X509_NAME_num(cert_names); i < len; ++i) {
788             if (0 == X509_NAME_cmp(sk_X509_NAME_value(cert_names, i), issuer))
789                 return preverify_ok; /* match */
790         }
791       #endif
792 
793         preverify_ok = 0;
794         err = X509_V_ERR_CERT_REJECTED;
795         X509_STORE_CTX_set_error(ctx, err);
796     }
797 
798     if (preverify_ok) {
799         return preverify_ok;
800     }
801 
802   #if OPENSSL_VERSION_NUMBER >= 0x10002000L
803     err_cert = X509_STORE_CTX_get_current_cert(ctx);
804   #else
805     err_cert = ctx->current_cert;
806   #endif
807     if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
808     safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf));
809     log_error_st *errh = hctx->r->conf.errh;
810     log_error(errh, __FILE__, __LINE__,
811       "SSL: verify error:num=%d:%s:depth=%d:subject=%s",
812       err, X509_verify_cert_error_string(err), depth, buf);
813 
814     /*
815      * At this point, err contains the last verification error. We can use
816      * it for something special
817      */
818     if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
819                           err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
820         safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf));
821         log_error(errh, __FILE__, __LINE__, "SSL: issuer=%s", buf);
822     }
823 
824     return !hctx->conf.ssl_verifyclient_enforce;
825 }
826 
827 static int
828 mod_openssl_cert_cb (SSL *ssl, void *arg)
829 {
830     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
831     plugin_cert *pc = hctx->conf.pc;
832     UNUSED(arg);
833 
834     if (NULL == pc->ssl_pemfile_x509 || NULL == pc->ssl_pemfile_pkey) {
835         /* x509/pkey available <=> pemfile was set <=> pemfile got patched:
836          * so this should never happen, unless you nest $SERVER["socket"] */
837         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
838           "SSL: no certificate/private key for TLS server name %s",
839           hctx->r->uri.authority.ptr);
840         return 0;
841     }
842 
843     /* first set certificate!
844      * setting private key checks whether certificate matches it */
845     if (1 != SSL_use_certificate(ssl, pc->ssl_pemfile_x509)) {
846         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
847           "SSL: failed to set certificate for TLS server name %s: %s",
848           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
849         return 0;
850     }
851 
852   #if OPENSSL_VERSION_NUMBER >= 0x10002000
853     if (pc->ssl_pemfile_chain)
854         SSL_set1_chain(ssl, pc->ssl_pemfile_chain);
855     else if (hctx->conf.ssl_ca_file) {
856         /* preserve legacy behavior whereby openssl will reuse CAs trusted for
857          * certificate verification (set by SSL_CTX_load_verify_locations() in
858          * SSL_CTX) in order to build certificate chain for server certificate
859          * sent to client */
860         SSL_set1_chain_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
861 
862         if (1 != SSL_build_cert_chain(ssl,
863                                         SSL_BUILD_CHAIN_FLAG_NO_ROOT
864                                       | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR
865                                       | SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)) {
866             log_error(hctx->r->conf.errh, __FILE__, __LINE__,
867               "SSL: building cert chain for TLS server name %s: %s",
868               hctx->r->uri.authority.ptr,
869               ERR_error_string(ERR_get_error(), NULL));
870             return 0;
871         }
872         else { /* copy chain for future reuse */
873             STACK_OF(X509) *chain = NULL;
874             SSL_get0_chain_certs(ssl, &chain);
875             pc->ssl_pemfile_chain = X509_chain_up_ref(chain);
876             SSL_set1_chain_cert_store(ssl, NULL);
877         }
878     }
879   #endif
880 
881     if (1 != SSL_use_PrivateKey(ssl, pc->ssl_pemfile_pkey)) {
882         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
883           "SSL: failed to set private key for TLS server name %s: %s",
884           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
885         return 0;
886     }
887 
888     if (hctx->conf.ssl_verifyclient) {
889         if (NULL == hctx->conf.ssl_ca_file) {
890             log_error(hctx->r->conf.errh, __FILE__, __LINE__,
891               "SSL: can't verify client without ssl.ca-file "
892               "for TLS server name %s", hctx->r->uri.authority.ptr);
893             return 0;
894         }
895       #if OPENSSL_VERSION_NUMBER >= 0x10002000
896         SSL_set1_verify_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
897       #endif
898         /* WTH openssl?  SSL_set_client_CA_list() calls set0_CA_list(),
899          * but there is no set1_CA_list() to simply up the reference count
900          * (without needing to duplicate the list) */
901         STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file
902           ? hctx->conf.ssl_ca_dn_file
903           : hctx->conf.ssl_ca_file->names;
904         SSL_set_client_CA_list(ssl, SSL_dup_CA_list(cert_names));
905         int mode = SSL_VERIFY_PEER;
906         if (hctx->conf.ssl_verifyclient_enforce)
907             mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
908         SSL_set_verify(ssl, mode, verify_callback);
909         SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
910     }
911     else {
912         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
913     }
914 
915     return 1;
916 }
917 
918 #ifndef OPENSSL_NO_TLSEXT
919 static int
920 mod_openssl_SNI (handler_ctx *hctx, const char *servername, size_t len)
921 {
922     request_st * const r = hctx->r;
923     if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
924         log_error(r->conf.errh, __FILE__, __LINE__,
925                   "SSL: SNI name too long %.*s", (int)len, servername);
926         return SSL_TLSEXT_ERR_ALERT_FATAL;
927     }
928 
929     /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
930     buffer_copy_string_len(&r->uri.authority, servername, len);
931     buffer_to_lower(&r->uri.authority);
932   #if 0
933     /*(r->uri.authority used below for configuration before request read;
934      * revisit for h2)*/
935     if (0 != http_request_host_policy(&r->uri.authority,
936                                       r->conf.http_parseopts, 443))
937         return SSL_TLSEXT_ERR_ALERT_FATAL;
938   #endif
939 
940     r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
941                             |  (1 << COMP_HTTP_HOST);
942     mod_openssl_patch_config(r, &hctx->conf);
943     /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
944     /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
945     /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
946     /*buffer_clear(&r->uri.authority);*/
947 
948   #if OPENSSL_VERSION_NUMBER >= 0x10002000L
949     return SSL_TLSEXT_ERR_OK;
950   #else
951     return (mod_openssl_cert_cb(hctx->ssl, NULL) == 1)
952       ? SSL_TLSEXT_ERR_OK
953       : SSL_TLSEXT_ERR_ALERT_FATAL;
954   #endif
955 }
956 
957 #ifdef SSL_CLIENT_HELLO_SUCCESS
958 static int
959 mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv)
960 {
961     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
962     buffer_copy_string(&hctx->r->uri.scheme, "https");
963     UNUSED(srv);
964 
965     const unsigned char *name;
966     size_t len, slen;
967     if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) {
968         return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */
969     }
970 
971     /* expecting single element in the server_name extension; parse first one */
972     if (len > 5
973         && (size_t)((name[0] << 8) + name[1]) == len-2
974         && name[2] == TLSEXT_TYPE_server_name
975         && (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/
976         int read_ahead = hctx->conf.ssl_read_ahead;
977         int rc = mod_openssl_SNI(hctx, (const char *)name+5, slen);
978         if (!read_ahead && hctx->conf.ssl_read_ahead)
979             SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
980         if (rc == SSL_TLSEXT_ERR_OK)
981             return SSL_CLIENT_HELLO_SUCCESS;
982     }
983 
984     *al = TLS1_AD_UNRECOGNIZED_NAME;
985     return SSL_CLIENT_HELLO_ERROR;
986 }
987 #else
988 static int
989 network_ssl_servername_callback (SSL *ssl, int *al, void *srv)
990 {
991     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
992     buffer_copy_string(&hctx->r->uri.scheme, "https");
993     UNUSED(al);
994     UNUSED(srv);
995 
996     const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
997     if (NULL == servername)
998         return SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */
999     int read_ahead = hctx->conf.ssl_read_ahead;
1000     int rc = mod_openssl_SNI(hctx, servername, strlen(servername));
1001     if (!read_ahead && hctx->conf.ssl_read_ahead)
1002         SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
1003     return rc;
1004 }
1005 #endif
1006 #endif
1007 
1008 
1009 static X509 *
1010 mod_openssl_load_pem_file (const char *file, log_error_st *errh, STACK_OF(X509) **chain)
1011 {
1012     *chain = NULL;
1013 
1014     BIO *in = BIO_new_rdonly_file(file);
1015     if (NULL == in) {
1016         log_error(errh, __FILE__, __LINE__,
1017           "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1018         return NULL;
1019     }
1020 
1021     X509 *x = PEM_read_bio_X509_AUX_secmem(in, NULL, NULL, NULL);
1022     if (NULL == x) {
1023         log_error(errh, __FILE__, __LINE__,
1024           "SSL: couldn't read X509 certificate from '%s'", file);
1025     }
1026     else if (!mod_openssl_load_X509_sk(file, errh, chain, in)) {
1027         X509_free(x);
1028         x = NULL;
1029     }
1030 
1031     BIO_free(in);
1032     return x;
1033 }
1034 
1035 
1036 static EVP_PKEY *
1037 mod_openssl_evp_pkey_load_pem_file (const char *file, log_error_st *errh)
1038 {
1039     BIO *in = BIO_new_rdonly_file(file);
1040     if (NULL == in) {
1041         log_error(errh, __FILE__, __LINE__,
1042           "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1043         return NULL;
1044     }
1045 
1046     EVP_PKEY *x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
1047     BIO_free(in);
1048     if (NULL == x)
1049         log_error(errh, __FILE__, __LINE__,
1050           "SSL: couldn't read private key from '%s'", file);
1051 
1052     return x;
1053 }
1054 
1055 
1056 static plugin_cert *
1057 network_openssl_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey)
1058 {
1059     if (!mod_openssl_init_once_openssl(srv)) return NULL;
1060 
1061     STACK_OF(X509) *ssl_pemfile_chain = NULL;
1062     X509 *ssl_pemfile_x509 =
1063       mod_openssl_load_pem_file(pemfile->ptr, srv->errh, &ssl_pemfile_chain);
1064     if (NULL == ssl_pemfile_x509)
1065         return NULL;
1066 
1067     EVP_PKEY *ssl_pemfile_pkey =
1068       mod_openssl_evp_pkey_load_pem_file(privkey->ptr, srv->errh);
1069     if (NULL == ssl_pemfile_pkey) {
1070         X509_free(ssl_pemfile_x509);
1071         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1072         return NULL;
1073     }
1074 
1075     if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1076         log_error(srv->errh, __FILE__, __LINE__, "SSL:"
1077           "Private key does not match the certificate public key, "
1078           "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
1079           pemfile->ptr, privkey->ptr);
1080         EVP_PKEY_free(ssl_pemfile_pkey);
1081         X509_free(ssl_pemfile_x509);
1082         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1083         return NULL;
1084     }
1085 
1086     plugin_cert *pc = malloc(sizeof(plugin_cert));
1087     force_assert(pc);
1088     pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
1089     pc->ssl_pemfile_x509 = ssl_pemfile_x509;
1090     pc->ssl_pemfile_chain= ssl_pemfile_chain;
1091     pc->ssl_pemfile = pemfile;
1092     pc->ssl_privkey = privkey;
1093     return pc;
1094 }
1095 
1096 
1097 #ifndef OPENSSL_NO_TLSEXT
1098 
1099 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1100 
1101 static int
1102 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
1103 {
1104     buffer * const b = hctx->tmp_buf;
1105     const buffer * const name = &hctx->r->uri.authority;
1106     log_error_st * const errh = hctx->r->conf.errh;
1107     X509 *ssl_pemfile_x509 = NULL;
1108     STACK_OF(X509) *ssl_pemfile_chain = NULL;
1109     EVP_PKEY *ssl_pemfile_pkey = NULL;
1110     size_t len;
1111     int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
1112 
1113     /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
1114     if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
1115         return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
1116     buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
1117     buffer_append_slash(b);
1118 
1119     /* check if SNI set server name (required for acme-tls/1 protocol)
1120      * and perform simple path checks for no '/'
1121      * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
1122     if (buffer_string_is_empty(name))   return rc;
1123     if (NULL != strchr(name->ptr, '/')) return rc;
1124     if (name->ptr[0] == '.')            return rc;
1125   #if 0
1126     if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443))
1127         return rc;
1128   #endif
1129     buffer_append_string_buffer(b, name);
1130     len = buffer_string_length(b);
1131 
1132     do {
1133         buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
1134         ssl_pemfile_x509 =
1135           mod_openssl_load_pem_file(b->ptr, errh, &ssl_pemfile_chain);
1136         if (NULL == ssl_pemfile_x509) {
1137             log_error(errh, __FILE__, __LINE__,
1138               "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1139             break;
1140         }
1141 
1142         buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
1143         buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
1144         ssl_pemfile_pkey = mod_openssl_evp_pkey_load_pem_file(b->ptr, errh);
1145         if (NULL == ssl_pemfile_pkey) {
1146             log_error(errh, __FILE__, __LINE__,
1147               "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1148             break;
1149         }
1150 
1151       #if 0 /* redundant with below? */
1152         if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1153             log_error(errh, __FILE__, __LINE__,
1154                "SSL: Private key does not match acme-tls/1 "
1155                "certificate public key, reason: %s %s"
1156                ERR_error_string(ERR_get_error(), NULL), b->ptr);
1157             break;
1158         }
1159       #endif
1160 
1161         /* first set certificate!
1162          * setting private key checks whether certificate matches it */
1163         if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
1164             log_error(errh, __FILE__, __LINE__,
1165               "SSL: failed to set acme-tls/1 certificate for TLS server "
1166               "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1167             break;
1168         }
1169 
1170         if (ssl_pemfile_chain) {
1171             SSL_set0_chain(ssl, ssl_pemfile_chain);
1172             ssl_pemfile_chain = NULL;
1173         }
1174 
1175         if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
1176             log_error(errh, __FILE__, __LINE__,
1177               "SSL: failed to set acme-tls/1 private key for TLS server "
1178               "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1179             break;
1180         }
1181 
1182         hctx->conf.ssl_verifyclient_enforce = 0;
1183         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1184         rc = SSL_TLSEXT_ERR_OK;
1185     } while (0);
1186 
1187     if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
1188     if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
1189     if (ssl_pemfile_chain)
1190         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1191 
1192     return rc;
1193 }
1194 
1195 enum {
1196   MOD_OPENSSL_ALPN_HTTP11      = 1
1197  ,MOD_OPENSSL_ALPN_HTTP10      = 2
1198  ,MOD_OPENSSL_ALPN_H2          = 3
1199  ,MOD_OPENSSL_ALPN_ACME_TLS_1  = 4
1200 };
1201 
1202 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
1203 static int
1204 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
1205 {
1206     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1207     unsigned short proto;
1208     UNUSED(arg);
1209 
1210     for (unsigned int i = 0, n; i < inlen; i += n) {
1211         n = in[i++];
1212         if (i+n > inlen || 0 == n) break;
1213         switch (n) {
1214          #if 0
1215           case 2:  /* "h2" */
1216             if (in[i] == 'h' && in[i+1] == '2') {
1217                 proto = MOD_OPENSSL_ALPN_H2;
1218                 break;
1219             }
1220             continue;
1221          #endif
1222           case 8:  /* "http/1.1" "http/1.0" */
1223             if (0 == memcmp(in+i, "http/1.", 7)) {
1224                 if (in[i+7] == '1') {
1225                     proto = MOD_OPENSSL_ALPN_HTTP11;
1226                     break;
1227                 }
1228                 if (in[i+7] == '0') {
1229                     proto = MOD_OPENSSL_ALPN_HTTP10;
1230                     break;
1231                 }
1232             }
1233             continue;
1234           case 10: /* "acme-tls/1" */
1235             if (0 == memcmp(in+i, "acme-tls/1", 10)) {
1236                 int rc = mod_openssl_acme_tls_1(ssl, hctx);
1237                 if (rc == SSL_TLSEXT_ERR_OK) {
1238                     proto = MOD_OPENSSL_ALPN_ACME_TLS_1;
1239                     break;
1240                 }
1241                 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */
1242                 if (rc == SSL_TLSEXT_ERR_NOACK) continue;
1243                 return rc;
1244             }
1245             continue;
1246           default:
1247             continue;
1248         }
1249 
1250         hctx->alpn = proto;
1251         *out = in+i;
1252         *outlen = n;
1253         return SSL_TLSEXT_ERR_OK;
1254     }
1255 
1256   #if OPENSSL_VERSION_NUMBER < 0x10100000L
1257     return SSL_TLSEXT_ERR_NOACK;
1258   #else
1259     return SSL_TLSEXT_ERR_ALERT_FATAL;
1260   #endif
1261 }
1262 
1263 #endif /* TLSEXT_TYPE_application_layer_protocol_negotiation */
1264 
1265 #endif /* OPENSSL_NO_TLSEXT */
1266 
1267 
1268 static int
1269 network_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s)
1270 {
1271   #ifdef SSL_CONF_FLAG_CMDLINE
1272 
1273     int rc = 0;
1274     const data_string *ds;
1275     SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new();
1276     SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx);
1277     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE
1278                                | SSL_CONF_FLAG_SERVER
1279                                | SSL_CONF_FLAG_SHOW_ERRORS
1280                                | SSL_CONF_FLAG_CERTIFICATE);
1281 
1282     /* always disable null and export ciphers */
1283     ds = (const data_string *)
1284       array_get_element_klen(s->ssl_conf_cmd,
1285                              CONST_STR_LEN("CipherString"));
1286     if (NULL != ds) {
1287         buffer *cipher_string =
1288           array_get_buf_ptr(s->ssl_conf_cmd, CONST_STR_LEN("CipherString"));
1289         buffer_append_string_len(cipher_string,
1290                                  CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
1291     }
1292 
1293     for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
1294         ds = (data_string *)s->ssl_conf_cmd->data[i];
1295         ERR_clear_error();
1296         if (SSL_CONF_cmd(cctx, ds->key.ptr, ds->value.ptr) <= 0) {
1297             log_error(srv->errh, __FILE__, __LINE__,
1298               "SSL: SSL_CONF_cmd %s %s: %s", ds->key.ptr, ds->value.ptr,
1299               ERR_error_string(ERR_get_error(), NULL));
1300             rc = -1;
1301             break;
1302         }
1303     }
1304 
1305     if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) {
1306         log_error(srv->errh, __FILE__, __LINE__,
1307           "SSL: SSL_CONF_CTX_finish(): %s",
1308           ERR_error_string(ERR_get_error(), NULL));
1309         rc = -1;
1310     }
1311 
1312     SSL_CONF_CTX_free(cctx);
1313     return rc;
1314 
1315   #else
1316 
1317     UNUSED(s);
1318     log_error(srv->errh, __FILE__, __LINE__,
1319       "SSL: ssl.openssl.ssl-conf-cmd not available; ignored");
1320     return 0;
1321 
1322   #endif
1323 }
1324 
1325 
1326 #ifndef OPENSSL_NO_DH
1327 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1328  || defined(LIBRESSL_VERSION_NUMBER)
1329 #define DH_set0_pqg(dh, dh_p, NULL, dh_g) \
1330         ((dh)->p = (dh_p), (dh)->g = (dh_g), (dh_p) != NULL && (dh_g != NULL))
1331 #endif
1332 /* https://tools.ietf.org/html/rfc7919#appendix-A.1
1333  * A.1.  ffdhe2048
1334  *
1335  * https://ssl-config.mozilla.org/ffdhe2048.txt
1336  * C code generated with: openssl dhparam -C -in ffdhe2048.txt
1337  */
1338 static DH *get_dh2048(void)
1339 {
1340     static unsigned char dhp_2048[] = {
1341         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8,
1342         0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, 0xAF, 0xDC, 0x56, 0x20,
1343         0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D,
1344         0x36, 0x95, 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
1345         0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, 0x7D, 0x2F,
1346         0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02,
1347         0xAE, 0xC4, 0x61, 0x7A, 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD,
1348         0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
1349         0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57,
1350         0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, 0x98, 0x4F, 0x0C, 0x70,
1351         0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF,
1352         0xE8, 0x72, 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
1353         0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, 0xBC, 0x0A,
1354         0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B,
1355         0xB2, 0xC8, 0xE3, 0xFB, 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7,
1356         0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
1357         0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07,
1358         0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, 0x9E, 0x02, 0xFC, 0xE1,
1359         0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34,
1360         0x2F, 0x61, 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
1361         0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, 0xC3, 0xFE,
1362         0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC,
1363         0x2E, 0xC2, 0x20, 0x05, 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16,
1364         0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
1365         0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, 0xFF, 0xFF,
1366         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
1367     };
1368     static unsigned char dhg_2048[] = {
1369         0x02
1370     };
1371     DH *dh = DH_new();
1372     BIGNUM *p, *g;
1373 
1374     if (dh == NULL)
1375         return NULL;
1376     p = BN_bin2bn(dhp_2048, sizeof(dhp_2048), NULL);
1377     g = BN_bin2bn(dhg_2048, sizeof(dhg_2048), NULL);
1378     if (p == NULL || g == NULL || !DH_set0_pqg(dh, p, NULL, g)) {
1379         DH_free(dh);
1380         BN_free(p);
1381         BN_free(g);
1382         return NULL;
1383     }
1384     return dh;
1385 }
1386 #endif
1387 
1388 
1389 static int
1390 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p)
1391 {
1392     /* load SSL certificates */
1393 
1394       #ifndef SSL_OP_NO_COMPRESSION
1395       #define SSL_OP_NO_COMPRESSION 0
1396       #endif
1397       #ifndef SSL_MODE_RELEASE_BUFFERS    /* OpenSSL >= 1.0.0 */
1398       #define SSL_MODE_RELEASE_BUFFERS 0
1399       #endif
1400         long ssloptions = SSL_OP_ALL
1401                         | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1402                         | SSL_OP_NO_COMPRESSION;
1403 
1404       #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1405         s->ssl_ctx = (!s->ssl_use_sslv2 && !s->ssl_use_sslv3)
1406           ? SSL_CTX_new(TLS_server_method())
1407           : SSL_CTX_new(SSLv23_server_method());
1408       #else
1409         s->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
1410       #endif
1411         if (NULL == s->ssl_ctx) {
1412             log_error(srv->errh, __FILE__, __LINE__,
1413               "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
1414             return -1;
1415         }
1416 
1417       #ifdef SSL_OP_NO_RENEGOTIATION /* openssl 1.1.0 */
1418         if (s->ssl_disable_client_renegotiation)
1419             ssloptions |= SSL_OP_NO_RENEGOTIATION;
1420       #endif
1421 
1422         /* completely useless identifier;
1423          * required for client cert verification to work with sessions */
1424         if (0 == SSL_CTX_set_session_id_context(
1425                    s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){
1426             log_error(srv->errh, __FILE__, __LINE__,
1427               "SSL: failed to set session context: %s",
1428               ERR_error_string(ERR_get_error(), NULL));
1429             return -1;
1430         }
1431 
1432         if (s->ssl_empty_fragments) {
1433           #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
1434             ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1435           #else
1436             ssloptions &= ~0x00000800L; /* hardcode constant */
1437             log_error(srv->errh, __FILE__, __LINE__,
1438               "WARNING: SSL: 'insert empty fragments' not supported by the "
1439               "openssl version used to compile lighttpd with");
1440           #endif
1441         }
1442 
1443         SSL_CTX_set_options(s->ssl_ctx, ssloptions);
1444         SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback);
1445 
1446       #ifndef HAVE_WOLFSSL_SSL_H /*(wolfSSL does not support SSLv2)*/
1447         if (!s->ssl_use_sslv2 && 0 != SSL_OP_NO_SSLv2) {
1448             /* disable SSLv2 */
1449             if ((SSL_OP_NO_SSLv2
1450                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2))
1451                 != SSL_OP_NO_SSLv2) {
1452                 log_error(srv->errh, __FILE__, __LINE__,
1453                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
1454                 return -1;
1455             }
1456         }
1457       #endif
1458 
1459         if (!s->ssl_use_sslv3 && 0 != SSL_OP_NO_SSLv3) {
1460             /* disable SSLv3 */
1461             if ((SSL_OP_NO_SSLv3
1462                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3))
1463                 != SSL_OP_NO_SSLv3) {
1464                 log_error(srv->errh, __FILE__, __LINE__,
1465                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
1466                 return -1;
1467             }
1468         }
1469 
1470         if (!buffer_string_is_empty(s->ssl_cipher_list)) {
1471             /* Disable support for low encryption ciphers */
1472             if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){
1473                 log_error(srv->errh, __FILE__, __LINE__,
1474                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
1475                 return -1;
1476             }
1477 
1478             if (s->ssl_honor_cipher_order) {
1479                 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE);
1480             }
1481         }
1482 
1483       #ifndef OPENSSL_NO_DH
1484       {
1485         DH *dh;
1486         /* Support for Diffie-Hellman key exchange */
1487         if (!buffer_string_is_empty(s->ssl_dh_file)) {
1488             /* DH parameters from file */
1489             BIO *bio;
1490             bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r");
1491             if (bio == NULL) {
1492                 log_error(srv->errh, __FILE__, __LINE__,
1493                   "SSL: Unable to open file %s", s->ssl_dh_file->ptr);
1494                 return -1;
1495             }
1496             dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1497             BIO_free(bio);
1498             if (dh == NULL) {
1499                 log_error(srv->errh, __FILE__, __LINE__,
1500                   "SSL: PEM_read_bio_DHparams failed %s", s->ssl_dh_file->ptr);
1501                 return -1;
1502             }
1503         } else {
1504             dh = get_dh2048();
1505             if (dh == NULL) {
1506                 log_error(srv->errh, __FILE__, __LINE__,
1507                   "SSL: get_dh2048() failed");
1508                 return -1;
1509             }
1510         }
1511         SSL_CTX_set_tmp_dh(s->ssl_ctx,dh);
1512         SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE);
1513         DH_free(dh);
1514       }
1515       #else
1516         if (!buffer_string_is_empty(s->ssl_dh_file)) {
1517             log_error(srv->errh, __FILE__, __LINE__,
1518               "SSL: openssl compiled without DH support, "
1519               "can't load parameters from %s", s->ssl_dh_file->ptr);
1520         }
1521       #endif
1522 
1523       #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1524       #ifndef OPENSSL_NO_ECDH
1525       {
1526         int nid = 0;
1527         /* Support for Elliptic-Curve Diffie-Hellman key exchange */
1528         if (!buffer_string_is_empty(s->ssl_ec_curve)) {
1529             /* OpenSSL only supports the "named curves"
1530              * from RFC 4492, section 5.1.1. */
1531             nid = OBJ_sn2nid((char *) s->ssl_ec_curve->ptr);
1532             if (nid == 0) {
1533                 log_error(srv->errh, __FILE__, __LINE__,
1534                   "SSL: Unknown curve name %s", s->ssl_ec_curve->ptr);
1535                 return -1;
1536             }
1537         } else {
1538           #if OPENSSL_VERSION_NUMBER < 0x10002000
1539             /* Default curve */
1540             nid = OBJ_sn2nid("prime256v1");
1541           #elif OPENSSL_VERSION_NUMBER < 0x10100000L \
1542              || defined(LIBRESSL_VERSION_NUMBER)
1543             if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) {
1544                 log_error(srv->errh, __FILE__, __LINE__,
1545                   "SSL: SSL_CTX_set_ecdh_auto() failed");
1546             }
1547           #endif
1548         }
1549         if (nid) {
1550             EC_KEY *ecdh;
1551             ecdh = EC_KEY_new_by_curve_name(nid);
1552             if (ecdh == NULL) {
1553                 log_error(srv->errh, __FILE__, __LINE__,
1554                   "SSL: Unable to create curve %s", s->ssl_ec_curve->ptr);
1555                 return -1;
1556             }
1557             SSL_CTX_set_tmp_ecdh(s->ssl_ctx,ecdh);
1558             SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_ECDH_USE);
1559             EC_KEY_free(ecdh);
1560         }
1561       }
1562       #endif
1563       #endif
1564 
1565       #if OPENSSL_VERSION_NUMBER >= 0x10002000
1566 
1567         SSL_CTX_set_cert_cb(s->ssl_ctx, mod_openssl_cert_cb, NULL);
1568         UNUSED(p);
1569 
1570       #else /* OPENSSL_VERSION_NUMBER < 0x10002000 */
1571 
1572         /* load all ssl.ca-files specified in the config into each SSL_CTX
1573          * XXX: This might be a bit excessive, but are all trusted CAs
1574          *      TODO: prefer to load on-demand in mod_openssl_cert_cb()
1575          *            for openssl >= 1.0.2 */
1576         if (!mod_openssl_load_ca_files(s->ssl_ctx, p, srv))
1577             return -1;
1578 
1579         if (s->ssl_verifyclient) {
1580             if (NULL == s->ssl_ca_file) {
1581                 log_error(srv->errh, __FILE__, __LINE__,
1582                   "SSL: You specified ssl.verifyclient.activate "
1583                   "but no ssl.ca-file");
1584                 return -1;
1585             }
1586             /* WTH openssl?  SSL_CTX_set_client_CA_list() calls set0_CA_list(),
1587              * but there is no set1_CA_list() to simply up the reference count
1588              * (without needing to duplicate the list) */
1589             STACK_OF(X509_NAME) * const cert_names = s->ssl_ca_dn_file
1590               ? s->ssl_ca_dn_file
1591               : s->ssl_ca_file->names;
1592             SSL_CTX_set_client_CA_list(s->ssl_ctx, SSL_dup_CA_list(cert_names));
1593             int mode = SSL_VERIFY_PEER;
1594             if (s->ssl_verifyclient_enforce) {
1595                 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1596             }
1597             SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback);
1598             SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1);
1599             if (!buffer_string_is_empty(s->ssl_ca_crl_file)) {
1600                 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx);
1601                 if (!mod_openssl_load_cacrls(store, s->ssl_ca_crl_file, srv))
1602                     return -1;
1603             }
1604         }
1605 
1606         if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx,
1607                                                     s->pc->ssl_pemfile->ptr)) {
1608             log_error(srv->errh, __FILE__, __LINE__,
1609               "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
1610               s->pc->ssl_pemfile->ptr);
1611             return -1;
1612         }
1613 
1614         if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->pc->ssl_pemfile_pkey)) {
1615             log_error(srv->errh, __FILE__, __LINE__,
1616               "SSL: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
1617               s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
1618             return -1;
1619         }
1620 
1621         if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) {
1622             log_error(srv->errh, __FILE__, __LINE__,
1623               "SSL: Private key does not match the certificate public key, "
1624               "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
1625               s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
1626             return -1;
1627         }
1628 
1629       #endif /* OPENSSL_VERSION_NUMBER < 0x10002000 */
1630 
1631         SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead);
1632         SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx)
1633                                    | SSL_MODE_ENABLE_PARTIAL_WRITE
1634                                    | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
1635                                    | SSL_MODE_RELEASE_BUFFERS);
1636 
1637       #ifndef OPENSSL_NO_TLSEXT
1638        #ifdef SSL_CLIENT_HELLO_SUCCESS
1639         SSL_CTX_set_client_hello_cb(s->ssl_ctx,mod_openssl_client_hello_cb,srv);
1640        #else
1641         if (!SSL_CTX_set_tlsext_servername_callback(
1642                s->ssl_ctx, network_ssl_servername_callback) ||
1643             !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) {
1644             log_error(srv->errh, __FILE__, __LINE__,
1645               "SSL: failed to initialize TLS servername callback, "
1646               "openssl library does not support TLS servername extension");
1647             return -1;
1648         }
1649        #endif
1650 
1651        #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1652         SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL);
1653        #endif
1654       #endif
1655 
1656         if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) {
1657             if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1;
1658         }
1659 
1660         return 0;
1661 }
1662 
1663 
1664 static int
1665 mod_openssl_set_defaults_sockets(server *srv, plugin_data *p)
1666 {
1667     static const config_plugin_keys_t cpk[] = {
1668       { CONST_STR_LEN("ssl.engine"),
1669         T_CONFIG_BOOL,
1670         T_CONFIG_SCOPE_CONNECTION }
1671      ,{ CONST_STR_LEN("ssl.cipher-list"),
1672         T_CONFIG_STRING,
1673         T_CONFIG_SCOPE_CONNECTION }
1674      ,{ CONST_STR_LEN("ssl.honor-cipher-order"),
1675         T_CONFIG_BOOL,
1676         T_CONFIG_SCOPE_CONNECTION }
1677      ,{ CONST_STR_LEN("ssl.dh-file"),
1678         T_CONFIG_STRING,
1679         T_CONFIG_SCOPE_CONNECTION }
1680      ,{ CONST_STR_LEN("ssl.ec-curve"),
1681         T_CONFIG_STRING,
1682         T_CONFIG_SCOPE_CONNECTION }
1683      ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"),
1684         T_CONFIG_ARRAY_KVSTRING,
1685         T_CONFIG_SCOPE_CONNECTION }
1686      ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */
1687         T_CONFIG_STRING,
1688         T_CONFIG_SCOPE_CONNECTION }
1689      ,{ CONST_STR_LEN("ssl.empty-fragments"),
1690         T_CONFIG_BOOL,
1691         T_CONFIG_SCOPE_CONNECTION }
1692      ,{ CONST_STR_LEN("ssl.use-sslv2"),
1693         T_CONFIG_BOOL,
1694         T_CONFIG_SCOPE_CONNECTION }
1695      ,{ CONST_STR_LEN("ssl.use-sslv3"),
1696         T_CONFIG_BOOL,
1697         T_CONFIG_SCOPE_CONNECTION }
1698      ,{ NULL, 0,
1699         T_CONFIG_UNSET,
1700         T_CONFIG_SCOPE_UNSET }
1701     };
1702     static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 };
1703 
1704     p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx));
1705     force_assert(p->ssl_ctxs);
1706 
1707     int rc = HANDLER_GO_ON;
1708     plugin_data_base srvplug;
1709     memset(&srvplug, 0, sizeof(srvplug));
1710     plugin_data_base * const ps = &srvplug;
1711     if (!config_plugin_values_init(srv, ps, cpk, "mod_openssl"))
1712         return HANDLER_ERROR;
1713 
1714     plugin_config_socket defaults;
1715     memset(&defaults, 0, sizeof(defaults));
1716     defaults.ssl_honor_cipher_order = 1;
1717     defaults.ssl_cipher_list = &default_ssl_cipher_list;
1718 
1719     /* process and validate config directives for global and $SERVER["socket"]
1720      * (init i to 0 if global context; to 1 to skip empty global context) */
1721     for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) {
1722         config_cond_info cfginfo;
1723         config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id);
1724         int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET);
1725         int count_not_engine = 0;
1726 
1727         plugin_config_socket conf;
1728         memcpy(&conf, &defaults, sizeof(conf));
1729 
1730         /*(preserve prior behavior; not inherited)*/
1731         /*(forcing inheritance might break existing configs where SSL is enabled
1732          * by default in the global scope, but not $SERVER["socket"]=="*:80") */
1733         conf.ssl_enabled = 0;
1734 
1735         config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0];
1736         for (; -1 != cpv->k_id; ++cpv) {
1737             /* ignore ssl.pemfile (k_id=6); included to process global scope */
1738             if (!is_socket_scope && cpv->k_id != 6) {
1739                 log_error(srv->errh, __FILE__, __LINE__,
1740                   "%s is valid only in global scope or "
1741                   "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k);
1742                 continue;
1743             }
1744             ++count_not_engine;
1745             switch (cpv->k_id) {
1746               case 0: /* ssl.engine */
1747                 conf.ssl_enabled = (0 != cpv->v.u);
1748                 --count_not_engine;
1749                 break;
1750               case 1: /* ssl.cipher-list */
1751                 conf.ssl_cipher_list = cpv->v.b;
1752                 break;
1753               case 2: /* ssl.honor-cipher-order */
1754                 conf.ssl_honor_cipher_order = (0 != cpv->v.u);
1755                 break;
1756               case 3: /* ssl.dh-file */
1757                 conf.ssl_dh_file = cpv->v.b;
1758                 break;
1759               case 4: /* ssl.ec-curve */
1760                 conf.ssl_ec_curve = cpv->v.b;
1761                 break;
1762               case 5: /* ssl.openssl.ssl-conf-cmd */
1763                 *(const array **)&conf.ssl_conf_cmd = cpv->v.a;
1764                 break;
1765               case 6: /* ssl.pemfile */
1766                 /* ignore here; included to process global scope when
1767                  * ssl.pemfile is set, but ssl.engine is not "enable" */
1768                 break;
1769               case 7: /* ssl.empty-fragments */
1770                 conf.ssl_empty_fragments = (0 != cpv->v.u);
1771                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
1772                   "ssl.empty-fragments is deprecated and will soon be "
1773                   "removed.  If needed, use: ssl.openssl.ssl-conf-cmd = "
1774                   "(\"Options\" => \"EmptyFragments\")");
1775                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
1776                   "ssl.empty-fragments is a "
1777                   "counter-measure against a SSL 3.0/TLS 1.0 protocol "
1778                   "vulnerability affecting CBC ciphers, which cannot be handled"
1779                   " by some broken (Microsoft) SSL implementations.");
1780                 break;
1781               case 8: /* ssl.use-sslv2 */
1782                 conf.ssl_use_sslv2 = (0 != cpv->v.u);
1783                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
1784                   "ssl.use-sslv2 is deprecated and will soon be removed.  "
1785                   "Many modern TLS libraries no longer support SSLv2.");
1786                 break;
1787               case 9: /* ssl.use-sslv3 */
1788                 conf.ssl_use_sslv3 = (0 != cpv->v.u);
1789                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
1790                   "ssl.use-sslv3 is deprecated and will soon be removed.  "
1791                   "Many modern TLS libraries no longer support SSLv3.  "
1792                   "If needed, use: "
1793                   "ssl.openssl.ssl-conf-cmd = (\"MinProtocol\" => \"SSLv3\")");
1794                 break;
1795               default:/* should not happen */
1796                 break;
1797             }
1798         }
1799         if (HANDLER_GO_ON != rc) break;
1800         if (0 == i) memcpy(&defaults, &conf, sizeof(conf));
1801 
1802         if (0 != i && !conf.ssl_enabled) continue;
1803 
1804         /* fill plugin_config_socket with global context then $SERVER["socket"]
1805          * only for directives directly in current $SERVER["socket"] condition*/
1806 
1807         /*conf.pc                     = p->defaults.pc;*/
1808         conf.ssl_ca_file              = p->defaults.ssl_ca_file;
1809         conf.ssl_ca_dn_file           = p->defaults.ssl_ca_dn_file;
1810         conf.ssl_ca_crl_file          = p->defaults.ssl_ca_crl_file;
1811         conf.ssl_verifyclient         = p->defaults.ssl_verifyclient;
1812         conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce;
1813         conf.ssl_verifyclient_depth   = p->defaults.ssl_verifyclient_depth;
1814         conf.ssl_read_ahead           = p->defaults.ssl_read_ahead;
1815 
1816         int sidx = ps->cvlist[i].k_id;
1817         for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) {
1818             if (p->cvlist[j].k_id != sidx) continue;
1819             /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/
1820             cpv = p->cvlist + p->cvlist[j].v.u2[0];
1821             for (; -1 != cpv->k_id; ++cpv) {
1822                 ++count_not_engine;
1823                 switch (cpv->k_id) {
1824                   case 0: /* ssl.pemfile */
1825                     if (cpv->vtype == T_CONFIG_LOCAL)
1826                         conf.pc = cpv->v.v;
1827                     break;
1828                   case 2: /* ssl.ca-file */
1829                     if (cpv->vtype == T_CONFIG_LOCAL)
1830                         conf.ssl_ca_file = cpv->v.v;
1831                     break;
1832                   case 3: /* ssl.ca-dn-file */
1833                     if (cpv->vtype == T_CONFIG_LOCAL)
1834                         conf.ssl_ca_dn_file = cpv->v.v;
1835                     break;
1836                   case 4: /* ssl.ca-crl-file */
1837                     conf.ssl_ca_crl_file = cpv->v.b;
1838                     break;
1839                   case 5: /* ssl.read-ahead */
1840                     conf.ssl_read_ahead = (0 != cpv->v.u);
1841                     break;
1842                   case 6: /* ssl.disable-client-renegotiation */
1843                     conf.ssl_disable_client_renegotiation = (0 != cpv->v.u);
1844                     break;
1845                   case 7: /* ssl.verifyclient.activate */
1846                     conf.ssl_verifyclient = (0 != cpv->v.u);
1847                     break;
1848                   case 8: /* ssl.verifyclient.enforce */
1849                     conf.ssl_verifyclient_enforce = (0 != cpv->v.u);
1850                     break;
1851                   case 9: /* ssl.verifyclient.depth */
1852                     conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
1853                     break;
1854                   default:
1855                     break;
1856                 }
1857             }
1858             break;
1859         }
1860 
1861         if (NULL == conf.pc) {
1862             if (0 == i && !conf.ssl_enabled) continue;
1863             if (0 != i) {
1864                 /* inherit ssl settings from global scope
1865                  * (if only ssl.engine = "enable" and no other ssl.* settings)
1866                  * (This is for convenience when defining both IPv4 and IPv6
1867                  *  and desiring to inherit the ssl config from global context
1868                  *  without having to duplicate the directives)*/
1869                 if (count_not_engine) {
1870                     log_error(srv->errh, __FILE__, __LINE__,
1871                       "ssl.pemfile has to be set in same $SERVER[\"socket\"] scope "
1872                       "as other ssl.* directives, unless only ssl.engine is set, "
1873                       "inheriting ssl.* from global scope");
1874                     rc = HANDLER_ERROR;
1875                     continue;
1876                 }
1877                 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
1878                 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/
1879                 continue;
1880             }
1881             /* PEM file is required */
1882             log_error(srv->errh, __FILE__, __LINE__,
1883               "ssl.pemfile has to be set when ssl.engine = \"enable\"");
1884             rc = HANDLER_ERROR;
1885             continue;
1886         }
1887 
1888         /* configure ssl_ctx for socket */
1889 
1890         /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/
1891         if (0 == network_init_ssl(srv, &conf, p)) {
1892             plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
1893             s->ssl_ctx = conf.ssl_ctx;
1894         }
1895         else {
1896             SSL_CTX_free(conf.ssl_ctx);
1897             rc = HANDLER_ERROR;
1898         }
1899     }
1900 
1901   #ifdef TLSEXT_TYPE_session_ticket
1902     if (rc == HANDLER_GO_ON) {
1903         mod_openssl_session_ticket_key_rotate(srv, p);
1904         stek_rotate_ts = log_epoch_secs;
1905     }
1906   #endif
1907 
1908     free(srvplug.cvlist);
1909     return rc;
1910 }
1911 
1912 
1913 SETDEFAULTS_FUNC(mod_openssl_set_defaults)
1914 {
1915     static const config_plugin_keys_t cpk[] = {
1916       { CONST_STR_LEN("ssl.pemfile"),
1917         T_CONFIG_STRING,
1918         T_CONFIG_SCOPE_CONNECTION }
1919      ,{ CONST_STR_LEN("ssl.privkey"),
1920         T_CONFIG_STRING,
1921         T_CONFIG_SCOPE_CONNECTION }
1922      ,{ CONST_STR_LEN("ssl.ca-file"),
1923         T_CONFIG_STRING,
1924         T_CONFIG_SCOPE_CONNECTION }
1925      ,{ CONST_STR_LEN("ssl.ca-dn-file"),
1926         T_CONFIG_STRING,
1927         T_CONFIG_SCOPE_CONNECTION }
1928      ,{ CONST_STR_LEN("ssl.ca-crl-file"),
1929         T_CONFIG_STRING,
1930         T_CONFIG_SCOPE_CONNECTION }
1931      ,{ CONST_STR_LEN("ssl.read-ahead"),
1932         T_CONFIG_BOOL,
1933         T_CONFIG_SCOPE_CONNECTION }
1934      ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"),
1935         T_CONFIG_BOOL,
1936         T_CONFIG_SCOPE_CONNECTION }
1937      ,{ CONST_STR_LEN("ssl.verifyclient.activate"),
1938         T_CONFIG_BOOL,
1939         T_CONFIG_SCOPE_CONNECTION }
1940      ,{ CONST_STR_LEN("ssl.verifyclient.enforce"),
1941         T_CONFIG_BOOL,
1942         T_CONFIG_SCOPE_CONNECTION }
1943      ,{ CONST_STR_LEN("ssl.verifyclient.depth"),
1944         T_CONFIG_SHORT,
1945         T_CONFIG_SCOPE_CONNECTION }
1946      ,{ CONST_STR_LEN("ssl.verifyclient.username"),
1947         T_CONFIG_STRING,
1948         T_CONFIG_SCOPE_CONNECTION }
1949      ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"),
1950         T_CONFIG_BOOL,
1951         T_CONFIG_SCOPE_CONNECTION }
1952      ,{ CONST_STR_LEN("ssl.acme-tls-1"),
1953         T_CONFIG_STRING,
1954         T_CONFIG_SCOPE_CONNECTION }
1955      ,{ CONST_STR_LEN("debug.log-ssl-noise"),
1956         T_CONFIG_BOOL,
1957         T_CONFIG_SCOPE_CONNECTION }
1958      ,{ NULL, 0,
1959         T_CONFIG_UNSET,
1960         T_CONFIG_SCOPE_UNSET }
1961     };
1962 
1963     plugin_data * const p = p_d;
1964     p->srv = srv;
1965     p->cafiles = array_init(0);
1966     if (!config_plugin_values_init(srv, p, cpk, "mod_openssl"))
1967         return HANDLER_ERROR;
1968 
1969     const buffer *default_ssl_ca_crl_file = NULL;
1970 
1971     /* process and validate config directives
1972      * (init i to 0 if global context; to 1 to skip empty global context) */
1973     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
1974         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1975         config_plugin_value_t *pemfile = NULL;
1976         config_plugin_value_t *privkey = NULL;
1977         const buffer *ssl_ca_file = NULL;
1978         const buffer *ssl_ca_dn_file = NULL;
1979         const buffer *ssl_ca_crl_file = NULL;
1980         X509_STORE *ca_store = NULL;
1981         for (; -1 != cpv->k_id; ++cpv) {
1982             switch (cpv->k_id) {
1983               case 0: /* ssl.pemfile */
1984                 if (!buffer_string_is_empty(cpv->v.b)) pemfile = cpv;
1985                 break;
1986               case 1: /* ssl.privkey */
1987                 if (!buffer_string_is_empty(cpv->v.b)) privkey = cpv;
1988                 break;
1989               case 2: /* ssl.ca-file */
1990                 if (buffer_string_is_empty(cpv->v.b)) break;
1991                 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
1992                 ssl_ca_file = cpv->v.b;
1993                 cpv->v.v = mod_openssl_load_cacerts(ssl_ca_file, srv->errh);
1994                 if (NULL != cpv->v.v) {
1995                     cpv->vtype = T_CONFIG_LOCAL;
1996                     ca_store = ((plugin_cacerts *)cpv->v.v)->certs;
1997                 }
1998                 else {
1999                     log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2000                       ERR_error_string(ERR_get_error(), NULL),
2001                       ssl_ca_file->ptr);
2002                     return HANDLER_ERROR;
2003                 }
2004                 break;
2005               case 3: /* ssl.ca-dn-file */
2006                 if (buffer_string_is_empty(cpv->v.b)) break;
2007                 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
2008                 ssl_ca_dn_file = cpv->v.b;
2009                 cpv->v.v = SSL_load_client_CA_file(ssl_ca_dn_file->ptr);
2010                 if (NULL != cpv->v.v) {
2011                     cpv->vtype = T_CONFIG_LOCAL;
2012                 }
2013                 else {
2014                     log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2015                       ERR_error_string(ERR_get_error(), NULL),
2016                       ssl_ca_dn_file->ptr);
2017                     return HANDLER_ERROR;
2018                 }
2019                 break;
2020               case 4: /* ssl.ca-crl-file */
2021                 if (buffer_string_is_empty(cpv->v.b)) break;
2022                 ssl_ca_crl_file = cpv->v.b;
2023                 if (0 == i) default_ssl_ca_crl_file = cpv->v.b;
2024                 break;
2025               case 5: /* ssl.read-ahead */
2026               case 6: /* ssl.disable-client-renegotiation */
2027               case 7: /* ssl.verifyclient.activate */
2028               case 8: /* ssl.verifyclient.enforce */
2029                 break;
2030               case 9: /* ssl.verifyclient.depth */
2031                 if (cpv->v.shrt > 255) {
2032                     log_error(srv->errh, __FILE__, __LINE__,
2033                       "%s is absurdly large (%hu); limiting to 255",
2034                       cpk[cpv->k_id].k, cpv->v.shrt);
2035                     cpv->v.shrt = 255;
2036                 }
2037                 break;
2038               case 10:/* ssl.verifyclient.username */
2039               case 11:/* ssl.verifyclient.exportcert */
2040               case 12:/* ssl.acme-tls-1 */
2041               case 13:/* debug.log-ssl-noise */
2042                 break;
2043               default:/* should not happen */
2044                 break;
2045             }
2046         }
2047 
2048       #if OPENSSL_VERSION_NUMBER < 0x10002000 /* p->cafiles for legacy only */
2049         /* load all ssl.ca-files into a single chain */
2050         /*(certificate load order might matter)*/
2051         if (ssl_ca_dn_file)
2052             array_insert_value(p->cafiles, CONST_BUF_LEN(ssl_ca_dn_file));
2053         if (ssl_ca_file)
2054             array_insert_value(p->cafiles, CONST_BUF_LEN(ssl_ca_file));
2055         UNUSED(ca_store);
2056         UNUSED(ssl_ca_crl_file);
2057         UNUSED(default_ssl_ca_crl_file);
2058       #else
2059         if (NULL == ca_store && ssl_ca_crl_file && i != 0) {
2060             log_error(srv->errh, __FILE__, __LINE__,
2061               "ssl.ca-crl-file (%s) ignored unless issued with ssl.ca-file",
2062               ssl_ca_crl_file->ptr);
2063         }
2064         else if (ca_store && (ssl_ca_crl_file || default_ssl_ca_crl_file)) {
2065             /* prior behavior in lighttpd allowed ssl.ca-crl-file only in global
2066              * scope or $SERVER["socket"], so this inheritence from global scope
2067              * is reasonable.  This code does not implement inheritance of
2068              * ssl.ca-crl-file from $SERVER["socket"] into nested $HTTP["host"],
2069              * but the solution is to repeat ssl.ca-crl-file where ssl.ca-file
2070              * is issued (and to not unnecessarily repeat ssl.ca-file)
2071              * Alternative: write code to load ssl.ca-crl-file into (X509_CRL *)
2072              * using PEM_read_bio_X509_CRL() and in mod_openssl_cert_cb(),
2073              * create a new (X509_STORE *) which merges with CA (X509_STORE *)
2074              * using X509_STORE_add_cert() and X509_STORE_add_crl(), and keeps
2075              * the result in our (plugin_cert *) for reuse */
2076             if (NULL == ssl_ca_crl_file)
2077                 ssl_ca_crl_file = default_ssl_ca_crl_file;
2078             if (!mod_openssl_load_cacrls(ca_store, ssl_ca_crl_file, srv))
2079                 return HANDLER_ERROR;
2080         }
2081       #endif
2082 
2083         if (pemfile) {
2084           #ifdef OPENSSL_NO_TLSEXT
2085             config_cond_info cfginfo;
2086             uint32_t j = (uint32_t)p->cvlist[i].k_id;
2087             config_get_config_cond_info(&cfginfo, j);
2088             if (j > 0 && (COMP_SERVER_SOCKET != cfginfo.comp
2089                           || cfginfo.cond != CONFIG_COND_EQ)) {
2090                 if (COMP_HTTP_HOST == cfginfo.comp)
2091                     log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2092                       "can't use ssl.pemfile with $HTTP[\"host\"], "
2093                       "as openssl version does not support TLS extensions");
2094                 else
2095                     log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2096                       "ssl.pemfile only works in SSL socket binding context "
2097                       "as openssl version does not support TLS extensions");
2098                 return HANDLER_ERROR;
2099             }
2100           #endif
2101             if (NULL == privkey) privkey = pemfile;
2102             pemfile->v.v =
2103               network_openssl_load_pemfile(srv, pemfile->v.b, privkey->v.b);
2104             if (pemfile->v.v)
2105                 pemfile->vtype = T_CONFIG_LOCAL;
2106             else
2107                 return HANDLER_ERROR;
2108         }
2109     }
2110 
2111     p->defaults.ssl_verifyclient = 0;
2112     p->defaults.ssl_verifyclient_enforce = 1;
2113     p->defaults.ssl_verifyclient_depth = 9;
2114     p->defaults.ssl_verifyclient_export_cert = 0;
2115     p->defaults.ssl_disable_client_renegotiation = 1;
2116     p->defaults.ssl_read_ahead = 0;
2117 
2118     /* initialize p->defaults from global config context */
2119     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
2120         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
2121         if (-1 != cpv->k_id)
2122             mod_openssl_merge_config(&p->defaults, cpv);
2123     }
2124 
2125     return mod_openssl_set_defaults_sockets(srv, p);
2126 }
2127 
2128 
2129 static int
2130 load_next_chunk (request_st * const r, chunkqueue * const cq, off_t max_bytes,
2131                  const char ** const data, size_t * const data_len)
2132 {
2133     chunk *c = cq->first;
2134 
2135     /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
2136      *
2137      * it has to stay at the same location all the time to satisfy the needs
2138      * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE
2139      *
2140      * buffer is allocated once, is NOT realloced (note: not thread-safe)
2141      *
2142      * (Note: above restriction no longer true since SSL_CTX_set_mode() is
2143      *        called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
2144      * */
2145 
2146     force_assert(NULL != c);
2147 
2148     switch (c->type) {
2149     case MEM_CHUNK:
2150         *data = NULL;
2151         *data_len = 0;
2152         do {
2153             size_t have;
2154 
2155             force_assert(c->offset >= 0
2156                          && c->offset <= (off_t)buffer_string_length(c->mem));
2157 
2158             have = buffer_string_length(c->mem) - c->offset;
2159 
2160             /* copy small mem chunks into single large buffer before SSL_write()
2161              * to reduce number times write() called underneath SSL_write() and
2162              * potentially reduce number of packets generated if TCP_NODELAY */
2163             if (*data_len) {
2164                 size_t space = LOCAL_SEND_BUFSIZE - *data_len;
2165                 if (have > space)
2166                     have = space;
2167                 if (have > (size_t)max_bytes - *data_len)
2168                     have = (size_t)max_bytes - *data_len;
2169                 if (*data != local_send_buffer) {
2170                     memcpy(local_send_buffer, *data, *data_len);
2171                     *data = local_send_buffer;
2172                 }
2173                 memcpy(local_send_buffer+*data_len,c->mem->ptr+c->offset,have);
2174                 *data_len += have;
2175                 continue;
2176             }
2177 
2178             if ((off_t) have > max_bytes) have = max_bytes;
2179 
2180             *data = c->mem->ptr + c->offset;
2181             *data_len = have;
2182         } while ((c = c->next) && c->type == MEM_CHUNK
2183                  && *data_len < LOCAL_SEND_BUFSIZE
2184                  && (off_t) *data_len < max_bytes);
2185         return 0;
2186 
2187     case FILE_CHUNK:
2188         if (0 != chunkqueue_open_file_chunk(cq, r->conf.errh)) return -1;
2189 
2190         {
2191             off_t offset, toSend;
2192 
2193             force_assert(c->offset >= 0 && c->offset <= c->file.length);
2194             offset = c->file.start + c->offset;
2195             toSend = c->file.length - c->offset;
2196 
2197             if (toSend > LOCAL_SEND_BUFSIZE) toSend = LOCAL_SEND_BUFSIZE;
2198             if (toSend > max_bytes) toSend = max_bytes;
2199 
2200             if (-1 == lseek(c->file.fd, offset, SEEK_SET)) {
2201                 log_perror(r->conf.errh, __FILE__, __LINE__, "lseek");
2202                 return -1;
2203             }
2204             if (-1 == (toSend = read(c->file.fd, local_send_buffer, toSend))) {
2205                 log_perror(r->conf.errh, __FILE__, __LINE__, "read");
2206                 return -1;
2207             }
2208 
2209             *data = local_send_buffer;
2210             *data_len = toSend;
2211         }
2212         return 0;
2213     }
2214 
2215     return -1;
2216 }
2217 
2218 
2219 static int
2220 mod_openssl_close_notify(handler_ctx *hctx);
2221 
2222 
2223 static int
2224 connection_write_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
2225 {
2226     request_st * const r = &con->request;
2227     handler_ctx *hctx = r->plugin_ctx[plugin_data_singleton->id];
2228     SSL *ssl = hctx->ssl;
2229 
2230     if (0 != hctx->close_notify) return mod_openssl_close_notify(hctx);
2231 
2232     chunkqueue_remove_finished_chunks(cq);
2233 
2234     while (max_bytes > 0 && NULL != cq->first) {
2235         const char *data;
2236         size_t data_len;
2237         int wr;
2238 
2239         if (0 != load_next_chunk(r, cq, max_bytes, &data, &data_len)) return -1;
2240 
2241         /**
2242          * SSL_write man-page
2243          *
2244          * WARNING
2245          *        When an SSL_write() operation has to be repeated because of
2246          *        SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be
2247          *        repeated with the same arguments.
2248          */
2249 
2250         ERR_clear_error();
2251         wr = SSL_write(ssl, data, data_len);
2252 
2253         if (hctx->renegotiations > 1
2254             && hctx->conf.ssl_disable_client_renegotiation) {
2255             log_error(r->conf.errh, __FILE__, __LINE__,
2256               "SSL: renegotiation initiated by client, killing connection");
2257             return -1;
2258         }
2259 
2260         if (wr <= 0) {
2261             int ssl_r;
2262             unsigned long err;
2263 
2264             switch ((ssl_r = SSL_get_error(ssl, wr))) {
2265             case SSL_ERROR_WANT_READ:
2266                 con->is_readable = -1;
2267                 return 0; /* try again later */
2268             case SSL_ERROR_WANT_WRITE:
2269                 con->is_writable = -1;
2270                 return 0; /* try again later */
2271             case SSL_ERROR_SYSCALL:
2272                 /* perhaps we have error waiting in our error-queue */
2273                 if (0 != (err = ERR_get_error())) {
2274                     do {
2275                         log_error(r->conf.errh, __FILE__, __LINE__,
2276                           "SSL: %d %d %s",ssl_r,wr,ERR_error_string(err,NULL));
2277                     } while((err = ERR_get_error()));
2278                 } else if (wr == -1) {
2279                     /* no, but we have errno */
2280                     switch(errno) {
2281                     case EPIPE:
2282                     case ECONNRESET:
2283                         return -2;
2284                     default:
2285                         log_perror(r->conf.errh, __FILE__, __LINE__,
2286                           "SSL: %d %d", ssl_r, wr);
2287                         break;
2288                     }
2289                 } else {
2290                     /* neither error-queue nor errno ? */
2291                     log_perror(r->conf.errh, __FILE__, __LINE__,
2292                       "SSL (error): %d %d", ssl_r, wr);
2293                 }
2294                 break;
2295 
2296             case SSL_ERROR_ZERO_RETURN:
2297                 /* clean shutdown on the remote side */
2298 
2299                 if (wr == 0) return -2;
2300 
2301                 /* fall through */
2302             default:
2303                 while((err = ERR_get_error())) {
2304                     log_error(r->conf.errh, __FILE__, __LINE__,
2305                       "SSL: %d %d %s", ssl_r, wr, ERR_error_string(err, NULL));
2306                 }
2307                 break;
2308             }
2309             return -1;
2310         }
2311 
2312         chunkqueue_mark_written(cq, wr);
2313         max_bytes -= wr;
2314 
2315         if ((size_t) wr < data_len) break; /* try again later */
2316     }
2317 
2318     return 0;
2319 }
2320 
2321 
2322 static int
2323 connection_read_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
2324 {
2325     request_st * const r = &con->request;
2326     handler_ctx *hctx = r->plugin_ctx[plugin_data_singleton->id];
2327     int len;
2328     char *mem = NULL;
2329     size_t mem_len = 0;
2330 
2331     UNUSED(max_bytes);
2332 
2333     if (0 != hctx->close_notify) return mod_openssl_close_notify(hctx);
2334 
2335     ERR_clear_error();
2336     do {
2337         len = SSL_pending(hctx->ssl);
2338         mem_len = len < 2048 ? 2048 : (size_t)len;
2339         chunk * const ckpt = cq->last;
2340         mem = chunkqueue_get_memory(cq, &mem_len);
2341 
2342         len = SSL_read(hctx->ssl, mem, mem_len);
2343         if (len > 0) {
2344             chunkqueue_use_memory(cq, ckpt, len);
2345             con->bytes_read += len;
2346         } else {
2347             chunkqueue_use_memory(cq, ckpt, 0);
2348         }
2349 
2350         if (hctx->renegotiations > 1
2351             && hctx->conf.ssl_disable_client_renegotiation) {
2352             log_error(r->conf.errh, __FILE__, __LINE__,
2353               "SSL: renegotiation initiated by client, killing connection");
2354             return -1;
2355         }
2356 
2357       #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2358         if (hctx->alpn) {
2359             if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) {
2360                 chunkqueue_reset(cq);
2361                 /* initiate handshake in order to send ServerHello.
2362                  * Once TLS handshake is complete, return -1 to result in
2363                  * CON_STATE_ERROR so that socket connection is quickly closed*/
2364                 if (1 == SSL_do_handshake(hctx->ssl)) return -1;
2365                 len = -1;
2366                 break;
2367             }
2368             hctx->alpn = 0;
2369         }
2370       #endif
2371     } while (len > 0
2372              && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0));
2373 
2374     if (len < 0) {
2375         int oerrno = errno;
2376         int rc, ssl_err;
2377         switch ((rc = SSL_get_error(hctx->ssl, len))) {
2378         case SSL_ERROR_WANT_WRITE:
2379             con->is_writable = -1;
2380             /* fall through */
2381         case SSL_ERROR_WANT_READ:
2382             con->is_readable = 0;
2383 
2384             /* the manual says we have to call SSL_read with the same arguments
2385              * next time.  we ignore this restriction; no one has complained
2386              * about it in 1.5 yet, so it probably works anyway.
2387              */
2388 
2389             return 0;
2390         case SSL_ERROR_SYSCALL:
2391             /**
2392              * man SSL_get_error()
2393              *
2394              * SSL_ERROR_SYSCALL
2395              *   Some I/O error occurred.  The OpenSSL error queue may contain
2396              *   more information on the error.  If the error queue is empty
2397              *   (i.e. ERR_get_error() returns 0), ret can be used to find out
2398              *   more about the error: If ret == 0, an EOF was observed that
2399              *   violates the protocol.  If ret == -1, the underlying BIO
2400              *   reported an I/O error (for socket I/O on Unix systems, consult
2401              *   errno for details).
2402              *
2403              */
2404             while((ssl_err = ERR_get_error())) {
2405                 /* get all errors from the error-queue */
2406                 log_error(r->conf.errh, __FILE__, __LINE__,
2407                   "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL));
2408             }
2409 
2410             switch(oerrno) {
2411             case ECONNRESET:
2412                 if (!hctx->conf.ssl_log_noise) break;
2413                 /* fall through */
2414             default:
2415                 /* (oerrno should be something like ECONNABORTED not 0
2416                  *  if client disconnected before anything was sent
2417                  *  (e.g. TCP connection probe), but it does not appear
2418                  *  that openssl provides such notification, not even
2419                  *  something like SSL_R_SSL_HANDSHAKE_FAILURE) */
2420                 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise)
2421                     break;
2422 
2423                 log_error(r->conf.errh, __FILE__, __LINE__,
2424                   "SSL: %d %d %d %s", len, rc, oerrno, strerror(oerrno));
2425                 break;
2426             }
2427 
2428             break;
2429         case SSL_ERROR_ZERO_RETURN:
2430             /* clean shutdown on the remote side */
2431 
2432             if (rc == 0) {
2433                 /* FIXME: later */
2434             }
2435 
2436             /* fall through */
2437         default:
2438             while((ssl_err = ERR_get_error())) {
2439                 switch (ERR_GET_REASON(ssl_err)) {
2440                 case SSL_R_SSL_HANDSHAKE_FAILURE:
2441               #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
2442                 case SSL_R_UNEXPECTED_EOF_WHILE_READING:
2443               #endif
2444               #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA
2445                 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
2446               #endif
2447               #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN
2448                 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
2449               #endif
2450               #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
2451                 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
2452               #endif
2453                     if (!hctx->conf.ssl_log_noise) continue;
2454                     break;
2455                 default:
2456                     break;
2457                 }
2458                 /* get all errors from the error-queue */
2459                 log_error(r->conf.errh, __FILE__, __LINE__,
2460                   "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL));
2461             }
2462             break;
2463         }
2464         return -1;
2465     } else if (len == 0) {
2466         con->is_readable = 0;
2467         /* the other end close the connection -> KEEP-ALIVE */
2468 
2469         return -2;
2470     } else {
2471         return 0;
2472     }
2473 }
2474 
2475 
2476 CONNECTION_FUNC(mod_openssl_handle_con_accept)
2477 {
2478     server_socket *srv_sock = con->srv_socket;
2479     if (!srv_sock->is_ssl) return HANDLER_GO_ON;
2480 
2481     plugin_data *p = p_d;
2482     handler_ctx * const hctx = handler_ctx_init();
2483     request_st * const r = &con->request;
2484     hctx->r = r;
2485     hctx->con = con;
2486     hctx->tmp_buf = con->srv->tmp_buf;
2487     r->plugin_ctx[p->id] = hctx;
2488 
2489     plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx;
2490     hctx->ssl = SSL_new(s->ssl_ctx);
2491     if (NULL != hctx->ssl
2492         && SSL_set_app_data(hctx->ssl, hctx)
2493         && SSL_set_fd(hctx->ssl, con->fd)) {
2494         SSL_set_accept_state(hctx->ssl);
2495         con->network_read = connection_read_cq_ssl;
2496         con->network_write = connection_write_cq_ssl;
2497         con->proto_default_port = 443; /* "https" */
2498         mod_openssl_patch_config(r, &hctx->conf);
2499         return HANDLER_GO_ON;
2500     }
2501     else {
2502         log_error(r->conf.errh, __FILE__, __LINE__,
2503           "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2504         return HANDLER_ERROR;
2505     }
2506 }
2507 
2508 
2509 static void
2510 mod_openssl_detach(handler_ctx *hctx)
2511 {
2512     /* step aside from further SSL processing
2513      * (used after handle_connection_shut_wr hook) */
2514     /* future: might restore prior network_read and network_write fn ptrs */
2515     hctx->con->is_ssl_sock = 0;
2516     /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
2517     if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
2518     hctx->close_notify = 1;
2519 }
2520 
2521 
2522 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)
2523 {
2524     request_st * const r = &con->request;
2525     plugin_data *p = p_d;
2526     handler_ctx *hctx = r->plugin_ctx[p->id];
2527     if (NULL == hctx) return HANDLER_GO_ON;
2528 
2529     hctx->close_notify = -2;
2530     if (SSL_is_init_finished(hctx->ssl)) {
2531         mod_openssl_close_notify(hctx);
2532     }
2533     else {
2534         mod_openssl_detach(hctx);
2535     }
2536 
2537     return HANDLER_GO_ON;
2538 }
2539 
2540 
2541 static int
2542 mod_openssl_close_notify(handler_ctx *hctx)
2543 {
2544         int ret, ssl_r;
2545         unsigned long err;
2546         log_error_st *errh;
2547 
2548         if (1 == hctx->close_notify) return -2;
2549 
2550         ERR_clear_error();
2551         switch ((ret = SSL_shutdown(hctx->ssl))) {
2552         case 1:
2553             mod_openssl_detach(hctx);
2554             return -2;
2555         case 0:
2556             /* Drain SSL read buffers in case pending records need processing.
2557              * Limit to reading next record to avoid denial of service when CPU
2558              * processing TLS is slower than arrival speed of TLS data packets.
2559              * (unless hctx->conf.ssl_read_ahead is set)
2560              *
2561              * references:
2562              *
2563              * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection"
2564              * https://github.com/openssl/openssl/issues/6262
2565              *
2566              * The peer is still allowed to send data after receiving the
2567              * "close notify" event. If the peer did send data it need to be
2568              * processed by calling SSL_read() before calling SSL_shutdown() a
2569              * second time. SSL_read() will indicate the end of the peer data by
2570              * returning <= 0 and SSL_get_error() returning
2571              * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read()
2572              * between SSL_shutdown() calls.
2573              *
2574              * Additional discussion in "Auto retry in shutdown"
2575              * https://github.com/openssl/openssl/pull/6340
2576              */
2577             ssl_r = SSL_pending(hctx->ssl);
2578             if (ssl_r) {
2579                 do {
2580                     char buf[4096];
2581                     ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf));
2582                 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret)));
2583             }
2584 
2585             ERR_clear_error();
2586             switch ((ret = SSL_shutdown(hctx->ssl))) {
2587             case 1:
2588                 mod_openssl_detach(hctx);
2589                 return -2;
2590             case 0:
2591                 hctx->close_notify = -1;
2592                 return 0;
2593             default:
2594                 break;
2595             }
2596 
2597             /* fall through */
2598         default:
2599 
2600             if (!SSL_is_init_finished(hctx->ssl)) {
2601                 mod_openssl_detach(hctx);
2602                 return -2;
2603             }
2604 
2605             switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) {
2606             case SSL_ERROR_ZERO_RETURN:
2607             case SSL_ERROR_WANT_WRITE:
2608             case SSL_ERROR_WANT_READ:
2609                 hctx->close_notify = -1;
2610                 return 0; /* try again later */
2611             case SSL_ERROR_SYSCALL:
2612                 /* perhaps we have error waiting in our error-queue */
2613                 errh = hctx->r->conf.errh;
2614                 if (0 != (err = ERR_get_error())) {
2615                     do {
2616                         log_error(errh, __FILE__, __LINE__,
2617                           "SSL: %d %d %s",ssl_r,ret,ERR_error_string(err,NULL));
2618                     } while((err = ERR_get_error()));
2619                 } else if (errno != 0) {
2620                     /*ssl bug (see lighttpd ticket #2213): sometimes errno==0*/
2621                     switch(errno) {
2622                     case EPIPE:
2623                     case ECONNRESET:
2624                         break;
2625                     default:
2626                         log_perror(errh, __FILE__, __LINE__,
2627                           "SSL (error): %d %d", ssl_r, ret);
2628                         break;
2629                     }
2630                 }
2631 
2632                 break;
2633             default:
2634                 errh = hctx->r->conf.errh;
2635                 while((err = ERR_get_error())) {
2636                     log_error(errh, __FILE__, __LINE__,
2637                       "SSL: %d %d %s", ssl_r, ret, ERR_error_string(err, NULL));
2638                 }
2639 
2640                 break;
2641             }
2642         }
2643         ERR_clear_error();
2644         hctx->close_notify = -1;
2645         return ret;
2646 }
2647 
2648 
2649 CONNECTION_FUNC(mod_openssl_handle_con_close)
2650 {
2651     request_st * const r = &con->request;
2652     plugin_data *p = p_d;
2653     handler_ctx *hctx = r->plugin_ctx[p->id];
2654     if (NULL != hctx) {
2655         handler_ctx_free(hctx);
2656         r->plugin_ctx[p->id] = NULL;
2657     }
2658 
2659     return HANDLER_GO_ON;
2660 }
2661 
2662 
2663 static void
2664 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx)
2665 {
2666     buffer * const tb = r->tmp_buf;
2667     X509 *xs;
2668     X509_NAME *xn;
2669     int i, nentries;
2670 
2671     long vr = SSL_get_verify_result(hctx->ssl);
2672     if (vr != X509_V_OK) {
2673         char errstr[256];
2674         ERR_error_string_n(vr, errstr, sizeof(errstr));
2675         buffer_copy_string_len(tb, CONST_STR_LEN("FAILED:"));
2676         buffer_append_string(tb, errstr);
2677         http_header_env_set(r,
2678                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2679                             CONST_BUF_LEN(tb));
2680         return;
2681     } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) {
2682         http_header_env_set(r,
2683                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2684                             CONST_STR_LEN("NONE"));
2685         return;
2686     } else {
2687         http_header_env_set(r,
2688                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2689                             CONST_STR_LEN("SUCCESS"));
2690     }
2691 
2692     xn = X509_get_subject_name(xs);
2693     {
2694         char buf[256];
2695         int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf));
2696         if (len > 0) {
2697             if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1;
2698             http_header_env_set(r,
2699                                 CONST_STR_LEN("SSL_CLIENT_S_DN"),
2700                                 buf, (size_t)len);
2701         }
2702     }
2703     buffer_copy_string_len(tb, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
2704     for (i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) {
2705         int xobjnid;
2706         const char * xobjsn;
2707         X509_NAME_ENTRY *xe;
2708 
2709         if (!(xe = X509_NAME_get_entry(xn, i))) {
2710             continue;
2711         }
2712         xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe));
2713         xobjsn = OBJ_nid2sn(xobjnid);
2714         if (xobjsn) {
2715             buffer_string_set_length(tb, sizeof("SSL_CLIENT_S_DN_")-1);
2716             buffer_append_string(tb, xobjsn);
2717             http_header_env_set(r,
2718                                 CONST_BUF_LEN(tb),
2719                                 (const char*)X509_NAME_ENTRY_get_data(xe)->data,
2720                                 X509_NAME_ENTRY_get_data(xe)->length);
2721         }
2722     }
2723 
2724     {
2725         ASN1_INTEGER *xsn = X509_get_serialNumber(xs);
2726         BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL);
2727         char *serialHex = BN_bn2hex(serialBN);
2728         http_header_env_set(r,
2729                             CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
2730                             serialHex, strlen(serialHex));
2731         OPENSSL_free(serialHex);
2732         BN_free(serialBN);
2733     }
2734 
2735     if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
2736         /* pick one of the exported values as "REMOTE_USER", for example
2737          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
2738          * or
2739          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
2740          */
2741         const buffer *varname = hctx->conf.ssl_verifyclient_username;
2742         const buffer *vb = http_header_env_get(r, CONST_BUF_LEN(varname));
2743         if (vb) { /* same as http_auth.c:http_auth_setenv() */
2744             http_header_env_set(r,
2745                                 CONST_STR_LEN("REMOTE_USER"),
2746                                 CONST_BUF_LEN(vb));
2747             http_header_env_set(r,
2748                                 CONST_STR_LEN("AUTH_TYPE"),
2749                                 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
2750         }
2751     }
2752 
2753     if (hctx->conf.ssl_verifyclient_export_cert) {
2754         BIO *bio;
2755         if (NULL != (bio = BIO_new(BIO_s_mem()))) {
2756             PEM_write_bio_X509(bio, xs);
2757             const int n = BIO_pending(bio);
2758 
2759             buffer_string_prepare_copy(tb, n);
2760             BIO_read(bio, tb->ptr, n);
2761             BIO_free(bio);
2762             buffer_commit(tb, n);
2763             http_header_env_set(r,
2764                                 CONST_STR_LEN("SSL_CLIENT_CERT"),
2765                                 CONST_BUF_LEN(tb));
2766         }
2767     }
2768     X509_free(xs);
2769 }
2770 
2771 
2772 static void
2773 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx)
2774 {
2775     const char *s;
2776     const SSL_CIPHER *cipher;
2777 
2778     s = SSL_get_version(hctx->ssl);
2779     http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s));
2780 
2781     if ((cipher = SSL_get_current_cipher(hctx->ssl))) {
2782         int usekeysize, algkeysize;
2783         char buf[LI_ITOSTRING_LENGTH];
2784         s = SSL_CIPHER_get_name(cipher);
2785         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s));
2786         usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize);
2787         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
2788                             buf, li_itostrn(buf, sizeof(buf), usekeysize));
2789         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
2790                             buf, li_itostrn(buf, sizeof(buf), algkeysize));
2791     }
2792 }
2793 
2794 
2795 REQUEST_FUNC(mod_openssl_handle_request_env)
2796 {
2797     plugin_data *p = p_d;
2798     handler_ctx *hctx = r->plugin_ctx[p->id];
2799     if (NULL == hctx) return HANDLER_GO_ON;
2800     if (hctx->request_env_patched) return HANDLER_GO_ON;
2801     hctx->request_env_patched = 1;
2802 
2803     http_cgi_ssl_env(r, hctx);
2804     if (hctx->conf.ssl_verifyclient) {
2805         https_add_ssl_client_entries(r, hctx);
2806     }
2807 
2808     return HANDLER_GO_ON;
2809 }
2810 
2811 
2812 REQUEST_FUNC(mod_openssl_handle_uri_raw)
2813 {
2814     /* mod_openssl must be loaded prior to mod_auth
2815      * if mod_openssl is configured to set REMOTE_USER based on client cert */
2816     /* mod_openssl must be loaded after mod_extforward
2817      * if mod_openssl config is based on lighttpd.conf remote IP conditional
2818      * using remote IP address set by mod_extforward, *unless* PROXY protocol
2819      * is enabled with extforward.hap-PROXY = "enable", in which case the
2820      * reverse is true: mod_extforward must be loaded after mod_openssl */
2821     plugin_data *p = p_d;
2822     handler_ctx *hctx = r->plugin_ctx[p->id];
2823     if (NULL == hctx) return HANDLER_GO_ON;
2824 
2825     mod_openssl_patch_config(r, &hctx->conf);
2826     if (hctx->conf.ssl_verifyclient) {
2827         mod_openssl_handle_request_env(r, p);
2828     }
2829 
2830     return HANDLER_GO_ON;
2831 }
2832 
2833 
2834 REQUEST_FUNC(mod_openssl_handle_request_reset)
2835 {
2836     plugin_data *p = p_d;
2837     handler_ctx *hctx = r->plugin_ctx[p->id];
2838     if (NULL == hctx) return HANDLER_GO_ON;
2839 
2840     hctx->request_env_patched = 0;
2841     return HANDLER_GO_ON;
2842 }
2843 
2844 
2845 TRIGGER_FUNC(mod_openssl_handle_trigger) {
2846     const plugin_data * const p = p_d;
2847     const time_t cur_ts = log_epoch_secs;
2848     if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/
2849     UNUSED(srv);
2850     UNUSED(p);
2851 
2852   #ifdef TLSEXT_TYPE_session_ticket
2853     if (cur_ts - 86400 >= stek_rotate_ts) {  /*(24 hours)*/
2854         mod_openssl_session_ticket_key_rotate(srv, p);
2855         stek_rotate_ts = cur_ts;
2856     }
2857   #endif
2858 
2859     return HANDLER_GO_ON;
2860 }
2861 
2862 
2863 int mod_openssl_plugin_init (plugin *p);
2864 int mod_openssl_plugin_init (plugin *p)
2865 {
2866     p->version      = LIGHTTPD_VERSION_ID;
2867     p->name         = "openssl";
2868     p->init         = mod_openssl_init;
2869     p->cleanup      = mod_openssl_free;
2870     p->priv_defaults= mod_openssl_set_defaults;
2871 
2872     p->handle_connection_accept  = mod_openssl_handle_con_accept;
2873     p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr;
2874     p->handle_connection_close   = mod_openssl_handle_con_close;
2875     p->handle_uri_raw            = mod_openssl_handle_uri_raw;
2876     p->handle_request_env        = mod_openssl_handle_request_env;
2877     p->connection_reset          = mod_openssl_handle_request_reset;
2878     p->handle_trigger            = mod_openssl_handle_trigger;
2879 
2880     return 0;
2881 }
2882