xref: /lighttpd1.4/src/mod_openssl.c (revision 4933a225)
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  * Note: If session tickets are -not- disabled with
10  *     ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket")
11  *   mod_openssl rotates server ticket encryption key (STEK) every 8 hours
12  *   and keeps the prior two STEKs around, so ticket lifetime is 24 hours.
13  *   This is fine for use with a single lighttpd instance, but with multiple
14  *   lighttpd workers, no coordinated STEK (server ticket encryption key)
15  *   rotation occurs unless ssl.stek-file is defined and maintained (preferred),
16  *   or if some external job restarts lighttpd.  Restarting lighttpd generates a
17  *   new key that is shared by lighttpd workers for the lifetime of the new key.
18  *   If the rotation period expires and lighttpd has not been restarted, and if
19  *   ssl.stek-file is not in use, then 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 8 hours if session tickets are enabled and
25  *   multiple lighttpd workers are configured.  Since that is likely disruptive,
26  *   if multiple lighttpd workers are configured, ssl.stek-file should be
27  *   defined and the file maintained externally.
28  */
29 #include "first.h"
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <string.h>
38 
39 /*(not needed)*/
40 /* correction; needed for:
41  *   SSL_load_client_CA_file()
42  *   X509_STORE_load_locations()
43  */
44 /*#define OPENSSL_NO_STDIO*/
45 
46 #ifndef USE_OPENSSL_KERBEROS
47 #ifndef OPENSSL_NO_KRB5
48 #define OPENSSL_NO_KRB5
49 #endif
50 #endif
51 
52 #ifdef BORINGSSL_API_VERSION
53 #undef OPENSSL_NO_STDIO /* for X509_STORE_load_locations() */
54 #endif
55 
56 #include <openssl/ssl.h>
57 #include <openssl/bio.h>
58 #include <openssl/bn.h>
59 #include <openssl/err.h>
60 #include <openssl/objects.h>
61 #include <openssl/pem.h>
62 #include <openssl/rand.h>
63 #include <openssl/tls1.h>
64 #ifndef OPENSSL_NO_DH
65 #include <openssl/dh.h>
66 #endif
67 #ifndef OPENSSL_NO_OCSP
68 #include <openssl/ocsp.h>
69 #endif
70 #ifdef BORINGSSL_API_VERSION
71 /* BoringSSL purports to have some OCSP support */
72 #undef OPENSSL_NO_OCSP
73 #endif
74 
75 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
76 #ifndef OPENSSL_NO_ECDH
77 #include <openssl/ecdh.h>
78 #endif
79 #endif
80 
81 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
82 #include <openssl/core_names.h>
83 #endif
84 
85 #include "base.h"
86 #include "fdevent.h"
87 #include "http_header.h"
88 #include "http_kv.h"
89 #include "log.h"
90 #include "plugin.h"
91 #include "safe_memclear.h"
92 
93 typedef struct {
94     /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
95     EVP_PKEY *ssl_pemfile_pkey;
96     X509 *ssl_pemfile_x509;
97     STACK_OF(X509) *ssl_pemfile_chain;
98     buffer *ssl_stapling;
99     const buffer *ssl_pemfile;
100     const buffer *ssl_privkey;
101     const buffer *ssl_stapling_file;
102     time_t ssl_stapling_loadts;
103     time_t ssl_stapling_nextts;
104     char must_staple;
105 } plugin_cert;
106 
107 typedef struct {
108     SSL_CTX *ssl_ctx;
109 } plugin_ssl_ctx;
110 
111 typedef struct {
112     STACK_OF(X509_NAME) *names;
113     X509_STORE *certs;
114 } plugin_cacerts;
115 
116 typedef struct {
117     SSL_CTX *ssl_ctx; /* output from network_init_ssl() */
118 
119     /*(used only during startup; not patched)*/
120     unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
121     unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
122     unsigned char ssl_empty_fragments; /* whether to not set SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
123     unsigned char ssl_use_sslv2;
124     unsigned char ssl_use_sslv3;
125     const buffer *ssl_cipher_list;
126     const buffer *ssl_dh_file;
127     const buffer *ssl_ec_curve;
128     array *ssl_conf_cmd;
129 
130     /*(copied from plugin_data for socket ssl_ctx config)*/
131     const plugin_cert *pc;
132     const plugin_cacerts *ssl_ca_file;
133     STACK_OF(X509_NAME) *ssl_ca_dn_file;
134     const buffer *ssl_ca_crl_file;
135     unsigned char ssl_verifyclient;
136     unsigned char ssl_verifyclient_enforce;
137     unsigned char ssl_verifyclient_depth;
138     unsigned char ssl_read_ahead;
139     unsigned char ssl_disable_client_renegotiation;
140 } plugin_config_socket; /*(used at startup during configuration)*/
141 
142 typedef struct {
143     /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
144     plugin_cert *pc;
145     const plugin_cacerts *ssl_ca_file;
146     STACK_OF(X509_NAME) *ssl_ca_dn_file;
147     const buffer *ssl_ca_crl_file;
148 
149     unsigned char ssl_verifyclient;
150     unsigned char ssl_verifyclient_enforce;
151     unsigned char ssl_verifyclient_depth;
152     unsigned char ssl_verifyclient_export_cert;
153     unsigned char ssl_read_ahead;
154     unsigned char ssl_log_noise;
155     unsigned char ssl_disable_client_renegotiation;
156     const buffer *ssl_verifyclient_username;
157     const buffer *ssl_acme_tls_1;
158 } plugin_config;
159 
160 typedef struct {
161     PLUGIN_DATA;
162     plugin_ssl_ctx *ssl_ctxs;
163     plugin_config defaults;
164     server *srv;
165     array *cafiles;
166     const char *ssl_stek_file;
167 } plugin_data;
168 
169 static int ssl_is_init;
170 /* need assigned p->id for deep access of module handler_ctx for connection
171  *   i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
172 static plugin_data *plugin_data_singleton;
173 #define LOCAL_SEND_BUFSIZE (16 * 1024)
174 static char *local_send_buffer;
175 
176 typedef struct {
177     SSL *ssl;
178     request_st *r;
179     connection *con;
180     short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
181     short close_notify;
182     unsigned short alpn;
183     plugin_config conf;
184     buffer *tmp_buf;
185     log_error_st *errh;
186 } handler_ctx;
187 
188 
189 static handler_ctx *
190 handler_ctx_init (void)
191 {
192     handler_ctx *hctx = calloc(1, sizeof(*hctx));
193     force_assert(hctx);
194     return hctx;
195 }
196 
197 
198 static void
199 handler_ctx_free (handler_ctx *hctx)
200 {
201     if (hctx->ssl) SSL_free(hctx->ssl);
202     free(hctx);
203 }
204 
205 
206 #ifdef TLSEXT_TYPE_session_ticket
207 /* ssl/ssl_local.h */
208 #define TLSEXT_KEYNAME_LENGTH  16
209 #define TLSEXT_TICK_KEY_LENGTH 32
210 
211 /* openssl has a huge number of interfaces, but not the most useful;
212  * construct our own session ticket encryption key structure */
213 typedef struct tlsext_ticket_key_st {
214     time_t active_ts; /* tickets not issued w/ key until activation timestamp */
215     time_t expire_ts; /* key not valid after expiration timestamp */
216     unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH];
217     unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH];
218     unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH];
219 } tlsext_ticket_key_t;
220 
221 static tlsext_ticket_key_t session_ticket_keys[4];
222 static time_t stek_rotate_ts;
223 
224 
225 static int
226 mod_openssl_session_ticket_key_generate (time_t active_ts, time_t expire_ts)
227 {
228     /* openssl RAND_*bytes() functions are called multiple times since the
229      * funcs might have a 32-byte limit on number of bytes returned each call
230      *
231      * (Note: session ticket encryption key generation is not expected to fail)
232      *
233      * 3 keys are stored in session_ticket_keys[]
234      * The 4th element of session_ticket_keys[] is used for STEK construction
235      */
236     /*(RAND_priv_bytes() not in openssl 1.1.0; introduced in openssl 1.1.1)*/
237   #if OPENSSL_VERSION_NUMBER < 0x10101000L \
238    || defined(LIBRESSL_VERSION_NUMBER)
239   #define RAND_priv_bytes(x,sz) RAND_bytes((x),(sz))
240   #endif
241     if (RAND_bytes(session_ticket_keys[3].tick_key_name,
242                    TLSEXT_KEYNAME_LENGTH) <= 0
243         || RAND_priv_bytes(session_ticket_keys[3].tick_hmac_key,
244                            TLSEXT_TICK_KEY_LENGTH) <= 0
245         || RAND_priv_bytes(session_ticket_keys[3].tick_aes_key,
246                            TLSEXT_TICK_KEY_LENGTH) <= 0)
247         return 0;
248     session_ticket_keys[3].active_ts = active_ts;
249     session_ticket_keys[3].expire_ts = expire_ts;
250     return 1;
251 }
252 
253 
254 static void
255 mod_openssl_session_ticket_key_rotate (void)
256 {
257     /* discard oldest key (session_ticket_keys[2]) and put newest key first
258      * 3 keys are stored in session_ticket_keys[0], [1], [2]
259      * session_ticket_keys[3] is used to construct and pass new STEK */
260 
261     session_ticket_keys[2] = session_ticket_keys[1];
262     session_ticket_keys[1] = session_ticket_keys[0];
263     /*memmove(session_ticket_keys+1,
264               session_ticket_keys+0, sizeof(tlsext_ticket_key_t)*2);*/
265     session_ticket_keys[0] = session_ticket_keys[3];
266 
267     OPENSSL_cleanse(session_ticket_keys+3, sizeof(tlsext_ticket_key_t));
268 }
269 
270 
271 static tlsext_ticket_key_t *
272 tlsext_ticket_key_get (void)
273 {
274     const time_t cur_ts = log_epoch_secs;
275     const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
276     for (int i = 0; i < e; ++i) {
277         if (session_ticket_keys[i].active_ts > cur_ts) continue;
278         if (session_ticket_keys[i].expire_ts < cur_ts) continue;
279         return &session_ticket_keys[i];
280     }
281     return NULL;
282 }
283 
284 
285 static tlsext_ticket_key_t *
286 tlsext_ticket_key_find (unsigned char key_name[16], int *refresh)
287 {
288     *refresh = 0;
289     const time_t cur_ts = log_epoch_secs;
290     const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
291     for (int i = 0; i < e; ++i) {
292         if (session_ticket_keys[i].expire_ts < cur_ts) continue;
293         if (0 == memcmp(session_ticket_keys[i].tick_key_name, key_name, 16))
294             return &session_ticket_keys[i];
295         if (session_ticket_keys[i].active_ts <= cur_ts)
296             *refresh = 1; /* newer active key is available */
297     }
298     return NULL;
299 }
300 
301 
302 static void
303 tlsext_ticket_wipe_expired (const time_t cur_ts)
304 {
305     const int e = sizeof(session_ticket_keys)/sizeof(*session_ticket_keys) - 1;
306     for (int i = 0; i < e; ++i) {
307         if (session_ticket_keys[i].expire_ts != 0
308             && session_ticket_keys[i].expire_ts < cur_ts)
309             OPENSSL_cleanse(session_ticket_keys+i, sizeof(tlsext_ticket_key_t));
310     }
311 }
312 
313 
314 #if OPENSSL_VERSION_NUMBER < 0x30000000L
315 /* based on reference implementation from openssl 1.1.1g man page
316  *   man SSL_CTX_set_tlsext_ticket_key_cb
317  * but mod_openssl code uses EVP_aes_256_cbc() instead of EVP_aes_128_cbc()
318  */
319 static int
320 ssl_tlsext_ticket_key_cb (SSL *s, unsigned char key_name[16],
321                           unsigned char iv[EVP_MAX_IV_LENGTH],
322                           EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
323 #else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
324 /* based on reference implementation from openssl 3.0.0 man page
325  *   man SSL_CTX_set_tlsext_ticket_key_cb
326  */
327 static int
328 ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16],
329                          unsigned char *iv, EVP_CIPHER_CTX *ctx,
330                          EVP_MAC_CTX *hctx, int enc)
331 #endif
332 {
333     UNUSED(s);
334     if (enc) { /* create new session */
335         tlsext_ticket_key_t *k = tlsext_ticket_key_get();
336         if (NULL == k)
337             return 0; /* current key does not exist or is not valid */
338         memcpy(key_name, k->tick_key_name, 16);
339         if (RAND_bytes(iv, EVP_MAX_IV_LENGTH) <= 0)
340             return -1; /* insufficient random */
341         EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
342       #if OPENSSL_VERSION_NUMBER < 0x30000000L
343         HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
344                      EVP_sha256(), NULL);
345       #else
346         OSSL_PARAM params[] = {
347           OSSL_PARAM_DEFN(OSSL_MAC_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
348                           k->tick_hmac_key, sizeof(k->tick_hmac_key)),
349           OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
350                           "sha256", sizeof("sha256")),
351           OSSL_PARAM_END
352         };
353         EVP_MAC_CTX_set_params(hctx, params);
354       #endif
355         return 1;
356     }
357     else { /* retrieve session */
358         int refresh;
359         tlsext_ticket_key_t *k = tlsext_ticket_key_find(key_name, &refresh);
360         if (NULL == k)
361             return 0;
362       #if OPENSSL_VERSION_NUMBER < 0x30000000L
363         HMAC_Init_ex(hctx, k->tick_hmac_key, sizeof(k->tick_hmac_key),
364                      EVP_sha256(), NULL);
365       #else
366         OSSL_PARAM params[] = {
367           OSSL_PARAM_DEFN(OSSL_KDF_PARAM_KEY, OSSL_PARAM_OCTET_STRING,
368                           k->tick_hmac_key, sizeof(k->tick_hmac_key)),
369           OSSL_PARAM_DEFN(OSSL_MAC_PARAM_DIGEST, OSSL_PARAM_UTF8_STRING,
370                           "sha256", sizeof("sha256")),
371           OSSL_PARAM_END
372         };
373         EVP_MAC_CTX_set_params(hctx, params);
374       #endif
375         EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, k->tick_aes_key, iv);
376         return refresh ? 2 : 1;
377         /* 'refresh' will trigger issuing new ticket for session
378          * even though the current ticket is still valid */
379     }
380 }
381 
382 
383 static int
384 mod_openssl_session_ticket_key_file (const char *fn)
385 {
386     /* session ticket encryption key (STEK)
387      *
388      * STEK file should be stored in non-persistent storage,
389      *   e.g. /dev/shm/lighttpd/stek-file  (in memory)
390      * with appropriate permissions set to keep stek-file from being
391      * read by other users.  Where possible, systems should also be
392      * configured without swap.
393      *
394      * admin should schedule an independent job to periodically
395      *   generate new STEK up to 3 times during key lifetime
396      *   (lighttpd stores up to 3 keys)
397      *
398      * format of binary file is:
399      *    4-byte - format version (always 0; for use if format changes)
400      *    4-byte - activation timestamp
401      *    4-byte - expiration timestamp
402      *   16-byte - session ticket key name
403      *   32-byte - session ticket HMAC encrpytion key
404      *   32-byte - session ticket AES encrpytion key
405      *
406      * STEK file can be created with a command such as:
407      *   dd if=/dev/random bs=1 count=80 status=none | \
408      *     perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \
409      *     > STEK-file.$$ && mv STEK-file.$$ STEK-file
410      *
411      * The above delays activation time by 5 mins (+300 sec) to allow file to
412      * be propagated to other machines.  (admin must handle this independently)
413      * If STEK generation is performed immediately prior to starting lighttpd,
414      * admin should activate keys immediately (without +300).
415      */
416     int buf[23]; /* 92 bytes */
417     int rc = 0; /*(will retry on next check interval upon any error)*/
418     if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL))
419         return rc;
420     if (buf[0] == 0) { /*(format version 0)*/
421         session_ticket_keys[3].active_ts = buf[1];
422         session_ticket_keys[3].expire_ts = buf[2];
423       #ifndef __COVERITY__ /* intentional; hide from Coverity Scan */
424         /* intentionally copy 80 bytes into consecutive arrays
425          * tick_key_name[], tick_hmac_key[], tick_aes_key[] */
426         memcpy(&session_ticket_keys[3].tick_key_name, buf+3, 80);
427       #endif
428         rc = 1;
429     }
430 
431     OPENSSL_cleanse(buf, sizeof(buf));
432     return rc;
433 }
434 
435 
436 static void
437 mod_openssl_session_ticket_key_check (const plugin_data *p, const time_t cur_ts)
438 {
439     int rotate = 0;
440     if (p->ssl_stek_file) {
441         struct stat st;
442         if (0 == stat(p->ssl_stek_file, &st) && st.st_mtime > stek_rotate_ts)
443             rotate = mod_openssl_session_ticket_key_file(p->ssl_stek_file);
444         tlsext_ticket_wipe_expired(cur_ts);
445     }
446     else if (cur_ts - 28800 >= stek_rotate_ts)     /*(8 hours)*/
447         rotate = mod_openssl_session_ticket_key_generate(cur_ts, cur_ts+86400);
448 
449     if (rotate) {
450         mod_openssl_session_ticket_key_rotate();
451         stek_rotate_ts = cur_ts;
452     }
453 }
454 
455 #endif /* TLSEXT_TYPE_session_ticket */
456 
457 
458 #ifndef OPENSSL_NO_OCSP
459 #ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
460 static int
461 ssl_tlsext_status_cb(SSL *ssl, void *arg)
462 {
463   #ifdef SSL_get_tlsext_status_type
464     if (TLSEXT_STATUSTYPE_ocsp != SSL_get_tlsext_status_type(ssl))
465         return SSL_TLSEXT_ERR_NOACK; /* ignore if not client OCSP request */
466   #endif
467 
468     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
469     buffer *ssl_stapling = hctx->conf.pc->ssl_stapling;
470     if (NULL == ssl_stapling) return SSL_TLSEXT_ERR_NOACK;
471     UNUSED(arg);
472 
473     int len = (int)buffer_string_length(ssl_stapling);
474 
475     /* OpenSSL and LibreSSL require copy (BoringSSL, too, if using compat API)*/
476     uint8_t *ocsp_resp = OPENSSL_malloc(len);
477     if (NULL == ocsp_resp)
478         return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
479     memcpy(ocsp_resp, ssl_stapling->ptr, len);
480 
481     if (!SSL_set_tlsext_status_ocsp_resp(ssl, ocsp_resp, len)) {
482         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
483           "SSL: failed to set OCSP response for TLS server name %s: %s",
484           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
485         OPENSSL_free(ocsp_resp);
486         return SSL_TLSEXT_ERR_NOACK; /* ignore OCSP request if error occurs */
487         /*return SSL_TLSEXT_ERR_ALERT_FATAL;*/
488     }
489     return SSL_TLSEXT_ERR_OK;
490 }
491 #endif
492 #endif
493 
494 
495 INIT_FUNC(mod_openssl_init)
496 {
497     plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
498     return plugin_data_singleton;
499 }
500 
501 
502 static int mod_openssl_init_once_openssl (server *srv)
503 {
504     if (ssl_is_init) return 1;
505 
506   #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
507    && (!defined(LIBRESSL_VERSION_NUMBER) \
508        || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
509     OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
510                     |OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
511     OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
512                        |OPENSSL_INIT_ADD_ALL_DIGESTS
513                        |OPENSSL_INIT_LOAD_CONFIG, NULL);
514   #else
515     SSL_load_error_strings();
516     SSL_library_init();
517     OpenSSL_add_all_algorithms();
518   #endif
519     ssl_is_init = 1;
520 
521     if (0 == RAND_status()) {
522         log_error(srv->errh, __FILE__, __LINE__,
523           "SSL: not enough entropy in the pool");
524         return 0;
525     }
526 
527     local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
528     force_assert(NULL != local_send_buffer);
529 
530     return 1;
531 }
532 
533 
534 static void mod_openssl_free_openssl (void)
535 {
536     if (!ssl_is_init) return;
537 
538   #ifdef TLSEXT_TYPE_session_ticket
539     OPENSSL_cleanse(session_ticket_keys, sizeof(session_ticket_keys));
540     stek_rotate_ts = 0;
541   #endif
542 
543   #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
544    && !defined(LIBRESSL_VERSION_NUMBER)
545     /*(OpenSSL libraries handle thread init and deinit)
546      * https://github.com/openssl/openssl/pull/1048 */
547   #else
548     CRYPTO_cleanup_all_ex_data();
549     ERR_free_strings();
550    #if OPENSSL_VERSION_NUMBER >= 0x10000000L
551     ERR_remove_thread_state(NULL);
552    #else
553     ERR_remove_state(0);
554    #endif
555     EVP_cleanup();
556   #endif
557 
558     free(local_send_buffer);
559     ssl_is_init = 0;
560 }
561 
562 
563 static void
564 mod_openssl_free_config (server *srv, plugin_data * const p)
565 {
566     array_free(p->cafiles);
567 
568     if (NULL != p->ssl_ctxs) {
569         SSL_CTX * const ssl_ctx_global_scope = p->ssl_ctxs->ssl_ctx;
570         /* free ssl_ctx from $SERVER["socket"] (if not copy of global scope) */
571         for (uint32_t i = 1; i < srv->config_context->used; ++i) {
572             plugin_ssl_ctx * const s = p->ssl_ctxs + i;
573             if (s->ssl_ctx && s->ssl_ctx != ssl_ctx_global_scope)
574                 SSL_CTX_free(s->ssl_ctx);
575         }
576         /* free ssl_ctx from global scope */
577         if (ssl_ctx_global_scope)
578             SSL_CTX_free(ssl_ctx_global_scope);
579         free(p->ssl_ctxs);
580     }
581 
582     if (NULL == p->cvlist) return;
583     /* (init i to 0 if global context; to 1 to skip empty global context) */
584     for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) {
585         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
586         for (; -1 != cpv->k_id; ++cpv) {
587             switch (cpv->k_id) {
588               case 0: /* ssl.pemfile */
589                 if (cpv->vtype == T_CONFIG_LOCAL) {
590                     plugin_cert *pc = cpv->v.v;
591                     EVP_PKEY_free(pc->ssl_pemfile_pkey);
592                     X509_free(pc->ssl_pemfile_x509);
593                     sk_X509_pop_free(pc->ssl_pemfile_chain, X509_free);
594                     buffer_free(pc->ssl_stapling);
595                     free(pc);
596                 }
597                 break;
598               case 2: /* ssl.ca-file */
599                 if (cpv->vtype == T_CONFIG_LOCAL) {
600                     plugin_cacerts *cacerts = cpv->v.v;
601                     sk_X509_NAME_pop_free(cacerts->names, X509_NAME_free);
602                     X509_STORE_free(cacerts->certs);
603                     free(cacerts);
604                 }
605                 break;
606               case 3: /* ssl.ca-dn-file */
607                 if (cpv->vtype == T_CONFIG_LOCAL)
608                     sk_X509_NAME_pop_free(cpv->v.v, X509_NAME_free);
609                 break;
610               default:
611                 break;
612             }
613         }
614     }
615 }
616 
617 
618 /* use memory from openssl secure heap for temporary buffers, returned storage
619  * (pemfile might contain a private key in addition to certificate chain)
620  * Interfaces similar to those constructed in include/openssl/pem.h for
621  * PEM_read_bio_X509(), except this is named PEM_read_bio_X509_secmem().
622  * Similar for PEM_read_bio_X509_AUX_secmem().
623  *
624  * Supporting routine PEM_ASN1_read_bio_secmem() modified from openssl
625  * crypto/pem/pem_oth.c:PEM_ASN1_read_bio():
626  *   uses PEM_bytes_read_bio_secmem() instead of PEM_bytes_read_bio()
627  *   uses OPENSSL_secure_clear_free() instead of OPENSSL_free()
628  *
629  * 'man PEM_bytes_read_bio_secmem()' and see NOTES section for more info
630  * PEM_bytes_read_bio_secmem() openssl 1.1.1 or later
631  * OPENSSL_secure_clear_free() openssl 1.1.0g or later
632  * As this comment is being written, only openssl 1.1.1 is actively maintained.
633  * Earlier vers of openssl no longer receive security patches from openssl.org.
634  */
635 static void *
636 PEM_ASN1_read_bio_secmem(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
637                          pem_password_cb *cb, void *u)
638 {
639     const unsigned char *p = NULL;
640     unsigned char *data = NULL;
641     long len = 0;
642     char *ret = NULL;
643 
644   #if OPENSSL_VERSION_NUMBER >= 0x10101000L \
645    && !defined(LIBRESSL_VERSION_NUMBER)
646     if (!PEM_bytes_read_bio_secmem(&data, &len, NULL, name, bp, cb, u))
647   #else
648     if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u))
649   #endif
650         return NULL;
651     p = data;
652     ret = d2i(x, &p, len);
653   #ifndef BORINGSSL_API_VERSION /* missing PEMerr() macro */
654     if (ret == NULL)
655         PEMerr(PEM_F_PEM_ASN1_READ_BIO, ERR_R_ASN1_LIB);
656   #endif
657   #if OPENSSL_VERSION_NUMBER >= 0x10101000L \
658    && !defined(LIBRESSL_VERSION_NUMBER)
659     OPENSSL_secure_clear_free(data, len);
660   #else
661     OPENSSL_cleanse(data, len);
662     OPENSSL_free(data);
663   #endif
664     return ret;
665 }
666 
667 
668 static X509 *
669 PEM_read_bio_X509_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
670 {
671     return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509,
672                                     PEM_STRING_X509,
673                                     bp, (void **)x, cb, u);
674 }
675 
676 
677 static X509 *
678 PEM_read_bio_X509_AUX_secmem(BIO *bp, X509 **x, pem_password_cb *cb, void *u)
679 {
680     return PEM_ASN1_read_bio_secmem((d2i_of_void *)d2i_X509_AUX,
681                                     PEM_STRING_X509_TRUSTED,
682                                     bp, (void **)x, cb, u);
683 }
684 
685 
686 static int
687 mod_openssl_load_X509_sk (const char *file, log_error_st *errh, STACK_OF(X509) **chain, BIO *in)
688 {
689     STACK_OF(X509) *chain_sk = NULL;
690     for (X509 *ca; (ca = PEM_read_bio_X509_secmem(in,NULL,NULL,NULL)); ) {
691         if (NULL == chain_sk) /*(allocate only if it will not be empty)*/
692             chain_sk = sk_X509_new_null();
693         if (!chain_sk || !sk_X509_push(chain_sk, ca)) {
694             log_error(errh, __FILE__, __LINE__,
695               "SSL: couldn't read X509 certificates from '%s'", file);
696             if (chain_sk) sk_X509_pop_free(chain_sk, X509_free);
697             X509_free(ca);
698             return 0;
699         }
700     }
701     *chain = chain_sk;
702     return 1;
703 }
704 
705 
706 static int
707 mod_openssl_load_X509_STORE (const char *file, log_error_st *errh, X509_STORE **chain, BIO *in)
708 {
709     X509_STORE *chain_store = NULL;
710     for (X509 *ca; (ca = PEM_read_bio_X509(in,NULL,NULL,NULL)); X509_free(ca)) {
711         if (NULL == chain_store) /*(allocate only if it will not be empty)*/
712             chain_store = X509_STORE_new();
713         if (!chain_store || !X509_STORE_add_cert(chain_store, ca)) {
714             log_error(errh, __FILE__, __LINE__,
715               "SSL: couldn't read X509 certificates from '%s'", file);
716             if (chain_store) X509_STORE_free(chain_store);
717             X509_free(ca);
718             return 0;
719         }
720     }
721     *chain = chain_store;
722     return 1;
723 }
724 
725 
726 static plugin_cacerts *
727 mod_openssl_load_cacerts (const buffer *ssl_ca_file, log_error_st *errh)
728 {
729     const char *file = ssl_ca_file->ptr;
730     BIO *in = BIO_new(BIO_s_file());
731     if (NULL == in) {
732         log_error(errh, __FILE__, __LINE__,
733           "SSL: BIO_new(BIO_s_file()) failed");
734         return NULL;
735     }
736 
737     if (BIO_read_filename(in, file) <= 0) {
738         log_error(errh, __FILE__, __LINE__,
739           "SSL: BIO_read_filename('%s') failed", file);
740         BIO_free(in);
741         return NULL;
742     }
743 
744     X509_STORE *chain_store = NULL;
745     if (!mod_openssl_load_X509_STORE(file, errh, &chain_store, in)) {
746         BIO_free(in);
747         return NULL;
748     }
749 
750     BIO_free(in);
751 
752     if (NULL == chain_store) {
753         log_error(errh, __FILE__, __LINE__,
754           "SSL: ssl.ca-file is empty %s", file);
755         return NULL;
756     }
757 
758     plugin_cacerts *cacerts = malloc(sizeof(plugin_cacerts));
759     force_assert(cacerts);
760 
761     /* (would be more efficient to walk the X509_STORE and build the list,
762      *  but this works for now and matches how ssl.ca-dn-file is handled) */
763     cacerts->names = SSL_load_client_CA_file(file);
764     if (NULL == cacerts->names) {
765         X509_STORE_free(chain_store);
766         free(cacerts);
767         return NULL;
768     }
769 
770     cacerts->certs = chain_store;
771     return cacerts;
772 }
773 
774 
775 static int
776 mod_openssl_load_cacrls (X509_STORE *store, const buffer *ssl_ca_crl_file, server *srv)
777 {
778   #if OPENSSL_VERSION_NUMBER >= 0x30000000L
779     if (1 != X509_STORE_load_file(store, ssl_ca_crl_file->ptr))
780   #else
781     if (1 != X509_STORE_load_locations(store, ssl_ca_crl_file->ptr, NULL))
782   #endif
783     {
784         log_error(srv->errh, __FILE__, __LINE__,
785           "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
786           ssl_ca_crl_file->ptr);
787         return 0;
788     }
789     X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
790     return 1;
791 }
792 
793 
794 #if OPENSSL_VERSION_NUMBER < 0x10002000 \
795  || defined(LIBRESSL_VERSION_NUMBER)
796 static int
797 mod_openssl_load_verify_locn (SSL_CTX *ssl_ctx, const buffer *b, server *srv)
798 {
799     const char *fn = b->ptr;
800     if (1 == SSL_CTX_load_verify_locations(ssl_ctx, fn, NULL))
801         return 1;
802 
803     log_error(srv->errh, __FILE__, __LINE__,
804       "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), fn);
805     return 0;
806 }
807 
808 
809 static int
810 mod_openssl_load_ca_files (SSL_CTX *ssl_ctx, plugin_data *p, server *srv)
811 {
812     /* load all ssl.ca-files specified in the config into each SSL_CTX */
813 
814     for (uint32_t i = 0, used = p->cafiles->used; i < used; ++i) {
815         const buffer *b = &((data_string *)p->cafiles->data[i])->value;
816         if (!mod_openssl_load_verify_locn(ssl_ctx, b, srv))
817             return 0;
818     }
819     return 1;
820 }
821 #endif
822 
823 
824 FREE_FUNC(mod_openssl_free)
825 {
826     plugin_data *p = p_d;
827     if (NULL == p->srv) return;
828     mod_openssl_free_config(p->srv, p);
829     mod_openssl_free_openssl();
830 }
831 
832 
833 static void
834 mod_openssl_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv)
835 {
836     switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */
837       case 0: /* ssl.pemfile */
838         if (cpv->vtype == T_CONFIG_LOCAL)
839             pconf->pc = cpv->v.v;
840         break;
841       case 1: /* ssl.privkey */
842         break;
843       case 2: /* ssl.ca-file */
844         if (cpv->vtype == T_CONFIG_LOCAL)
845             pconf->ssl_ca_file = cpv->v.v;
846         break;
847       case 3: /* ssl.ca-dn-file */
848         if (cpv->vtype == T_CONFIG_LOCAL)
849             pconf->ssl_ca_dn_file = cpv->v.v;
850         break;
851       case 4: /* ssl.ca-crl-file */
852         pconf->ssl_ca_crl_file = cpv->v.b;
853         break;
854       case 5: /* ssl.read-ahead */
855         pconf->ssl_read_ahead = (0 != cpv->v.u);
856         break;
857       case 6: /* ssl.disable-client-renegotiation */
858         pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u);
859         break;
860       case 7: /* ssl.verifyclient.activate */
861         pconf->ssl_verifyclient = (0 != cpv->v.u);
862         break;
863       case 8: /* ssl.verifyclient.enforce */
864         pconf->ssl_verifyclient_enforce = (0 != cpv->v.u);
865         break;
866       case 9: /* ssl.verifyclient.depth */
867         pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
868         break;
869       case 10:/* ssl.verifyclient.username */
870         pconf->ssl_verifyclient_username = cpv->v.b;
871         break;
872       case 11:/* ssl.verifyclient.exportcert */
873         pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u);
874         break;
875       case 12:/* ssl.acme-tls-1 */
876         pconf->ssl_acme_tls_1 = cpv->v.b;
877         break;
878       case 13:/* ssl.stapling-file */
879         break;
880       case 14:/* debug.log-ssl-noise */
881         pconf->ssl_log_noise = (0 != cpv->v.u);
882         break;
883       default:/* should not happen */
884         return;
885     }
886 }
887 
888 
889 static void
890 mod_openssl_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv)
891 {
892     do {
893         mod_openssl_merge_config_cpv(pconf, cpv);
894     } while ((++cpv)->k_id != -1);
895 }
896 
897 
898 static void
899 mod_openssl_patch_config (request_st * const r, plugin_config * const pconf)
900 {
901     plugin_data * const p = plugin_data_singleton;
902     memcpy(pconf, &p->defaults, sizeof(plugin_config));
903     for (int i = 1, used = p->nconfig; i < used; ++i) {
904         if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id))
905             mod_openssl_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]);
906     }
907 }
908 
909 
910 static int
911 safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
912 {
913     BIO *bio = BIO_new(BIO_s_mem());
914     if (bio) {
915         int len = X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE);
916         BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
917         BIO_free(bio);
918         return len; /*return value has similar semantics to that of snprintf()*/
919     }
920     else {
921         buf[0] = '\0';
922         return -1;
923     }
924 }
925 
926 
927 static void
928 ssl_info_callback (const SSL *ssl, int where, int ret)
929 {
930     UNUSED(ret);
931 
932     if (0 != (where & SSL_CB_HANDSHAKE_START)) {
933         handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
934         if (hctx->renegotiations >= 0) ++hctx->renegotiations;
935     }
936   #ifdef TLS1_3_VERSION
937     /* https://github.com/openssl/openssl/issues/5721
938      * "TLSv1.3 unexpected InfoCallback after handshake completed" */
939     if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
940         /* SSL_version() is valid after initial handshake completed */
941         if (SSL_version(ssl) >= TLS1_3_VERSION) {
942             /* https://wiki.openssl.org/index.php/TLS1.3
943              * "Renegotiation is not possible in a TLSv1.3 connection" */
944             handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
945             hctx->renegotiations = -1;
946         }
947     }
948   #endif
949 }
950 
951 /* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
952 static int
953 verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
954 {
955     char buf[256];
956     X509 *err_cert;
957     int err, depth;
958     SSL *ssl;
959     handler_ctx *hctx;
960 
961     err = X509_STORE_CTX_get_error(ctx);
962     depth = X509_STORE_CTX_get_error_depth(ctx);
963 
964     /*
965      * Retrieve the pointer to the SSL of the connection currently treated
966      * and the application specific data stored into the SSL object.
967      */
968     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
969     hctx = (handler_ctx *) SSL_get_app_data(ssl);
970 
971     /*
972      * Catch a too long certificate chain. The depth limit set using
973      * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
974      * that whenever the "depth>verify_depth" condition is met, we
975      * have violated the limit and want to log this error condition.
976      * We must do it here, because the CHAIN_TOO_LONG error would not
977      * be found explicitly; only errors introduced by cutting off the
978      * additional certificates would be logged.
979      */
980     if (depth > hctx->conf.ssl_verifyclient_depth) {
981         preverify_ok = 0;
982         err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
983         X509_STORE_CTX_set_error(ctx, err);
984     }
985 
986     if (preverify_ok && 0 == depth && NULL != hctx->conf.ssl_ca_dn_file) {
987         /* verify that client cert is issued by CA in ssl.ca-dn-file
988          * if both ssl.ca-dn-file and ssl.ca-file were configured */
989         STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file;
990         X509_NAME *issuer;
991       #if OPENSSL_VERSION_NUMBER >= 0x10002000L
992         err_cert = X509_STORE_CTX_get_current_cert(ctx);
993       #else
994         err_cert = ctx->current_cert;
995       #endif
996         if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
997         issuer = X509_get_issuer_name(err_cert);
998       #if 0 /*(?desirable/undesirable to have cert_names sorted?)*/
999         if (-1 != sk_X509_NAME_find(cert_names, issuer))
1000             return preverify_ok; /* match */
1001       #else
1002         for (int i = 0, len = sk_X509_NAME_num(cert_names); i < len; ++i) {
1003             if (0 == X509_NAME_cmp(sk_X509_NAME_value(cert_names, i), issuer))
1004                 return preverify_ok; /* match */
1005         }
1006       #endif
1007 
1008         preverify_ok = 0;
1009         err = X509_V_ERR_CERT_REJECTED;
1010         X509_STORE_CTX_set_error(ctx, err);
1011     }
1012 
1013     if (preverify_ok) {
1014         return preverify_ok;
1015     }
1016 
1017   #if OPENSSL_VERSION_NUMBER >= 0x10002000L
1018     err_cert = X509_STORE_CTX_get_current_cert(ctx);
1019   #else
1020     err_cert = ctx->current_cert;
1021   #endif
1022     if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
1023     safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf));
1024     log_error_st *errh = hctx->r->conf.errh;
1025     log_error(errh, __FILE__, __LINE__,
1026       "SSL: verify error:num=%d:%s:depth=%d:subject=%s",
1027       err, X509_verify_cert_error_string(err), depth, buf);
1028 
1029     /*
1030      * At this point, err contains the last verification error. We can use
1031      * it for something special
1032      */
1033     if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
1034                           err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
1035         safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf));
1036         log_error(errh, __FILE__, __LINE__, "SSL: issuer=%s", buf);
1037     }
1038 
1039     return !hctx->conf.ssl_verifyclient_enforce;
1040 }
1041 
1042 static int
1043 mod_openssl_cert_cb (SSL *ssl, void *arg)
1044 {
1045     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1046     plugin_cert *pc = hctx->conf.pc;
1047     UNUSED(arg);
1048 
1049     if (NULL == pc->ssl_pemfile_x509 || NULL == pc->ssl_pemfile_pkey) {
1050         /* x509/pkey available <=> pemfile was set <=> pemfile got patched:
1051          * so this should never happen, unless you nest $SERVER["socket"] */
1052         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1053           "SSL: no certificate/private key for TLS server name %s",
1054           hctx->r->uri.authority.ptr);
1055         return 0;
1056     }
1057 
1058     /* first set certificate!
1059      * setting private key checks whether certificate matches it */
1060     if (1 != SSL_use_certificate(ssl, pc->ssl_pemfile_x509)) {
1061         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1062           "SSL: failed to set certificate for TLS server name %s: %s",
1063           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1064         return 0;
1065     }
1066 
1067   #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
1068    && !defined(LIBRESSL_VERSION_NUMBER)
1069     /* libressl >= 0x3000000fL has SSL_set1_chain(), but not other APIs below)*/
1070     if (pc->ssl_pemfile_chain)
1071         SSL_set1_chain(ssl, pc->ssl_pemfile_chain);
1072    #ifndef BORINGSSL_API_VERSION /* BoringSSL limitation */
1073     else if (hctx->conf.ssl_ca_file) {
1074         /* preserve legacy behavior whereby openssl will reuse CAs trusted for
1075          * certificate verification (set by SSL_CTX_load_verify_locations() in
1076          * SSL_CTX) in order to build certificate chain for server certificate
1077          * sent to client */
1078         SSL_set1_chain_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
1079 
1080         if (1 != SSL_build_cert_chain(ssl,
1081                                         SSL_BUILD_CHAIN_FLAG_NO_ROOT
1082                                       | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR
1083                                       | SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)) {
1084             log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1085               "SSL: building cert chain for TLS server name %s: %s",
1086               hctx->r->uri.authority.ptr,
1087               ERR_error_string(ERR_get_error(), NULL));
1088             return 0;
1089         }
1090         else { /* copy chain for future reuse */
1091             STACK_OF(X509) *chain = NULL;
1092             SSL_get0_chain_certs(ssl, &chain);
1093             pc->ssl_pemfile_chain = X509_chain_up_ref(chain);
1094             SSL_set1_chain_cert_store(ssl, NULL);
1095         }
1096     }
1097    #endif
1098   #endif
1099 
1100     if (1 != SSL_use_PrivateKey(ssl, pc->ssl_pemfile_pkey)) {
1101         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1102           "SSL: failed to set private key for TLS server name %s: %s",
1103           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1104         return 0;
1105     }
1106 
1107   #ifndef OPENSSL_NO_OCSP
1108   #ifdef BORINGSSL_API_VERSION
1109     /* BoringSSL suggests API different than SSL_CTX_set_tlsext_status_cb() */
1110     buffer *ocsp_resp = pc->ssl_stapling;
1111     if (NULL != ocsp_resp
1112         && !SSL_set_ocsp_response(ssl, (uint8_t *)CONST_BUF_LEN(ocsp_resp))) {
1113         log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1114           "SSL: failed to set OCSP response for TLS server name %s: %s",
1115           hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL));
1116         return 0;
1117     }
1118   #endif
1119   #endif
1120 
1121     if (hctx->conf.ssl_verifyclient) {
1122         if (NULL == hctx->conf.ssl_ca_file) {
1123             log_error(hctx->r->conf.errh, __FILE__, __LINE__,
1124               "SSL: can't verify client without ssl.ca-file "
1125               "for TLS server name %s", hctx->r->uri.authority.ptr);
1126             return 0;
1127         }
1128       #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
1129        && !defined(LIBRESSL_VERSION_NUMBER)
1130         SSL_set1_verify_cert_store(ssl, hctx->conf.ssl_ca_file->certs);
1131       #endif
1132         /* WTH openssl?  SSL_set_client_CA_list() calls set0_CA_list(),
1133          * but there is no set1_CA_list() to simply up the reference count
1134          * (without needing to duplicate the list) */
1135         /* WolfSSL does not support setting per-session CA list;
1136          * limitation is to per-CTX CA list, and is not changed after SNI */
1137         STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file
1138           ? hctx->conf.ssl_ca_dn_file
1139           : hctx->conf.ssl_ca_file->names;
1140         SSL_set_client_CA_list(ssl, SSL_dup_CA_list(cert_names));
1141         int mode = SSL_VERIFY_PEER;
1142         if (hctx->conf.ssl_verifyclient_enforce)
1143             mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1144         SSL_set_verify(ssl, mode, verify_callback);
1145         SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
1146     }
1147     else {
1148         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1149     }
1150 
1151     return 1;
1152 }
1153 
1154 #ifndef OPENSSL_NO_TLSEXT
1155 static int
1156 mod_openssl_SNI (handler_ctx *hctx, const char *servername, size_t len)
1157 {
1158     request_st * const r = hctx->r;
1159     if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
1160         log_error(r->conf.errh, __FILE__, __LINE__,
1161                   "SSL: SNI name too long %.*s", (int)len, servername);
1162         return SSL_TLSEXT_ERR_ALERT_FATAL;
1163     }
1164 
1165     /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
1166     buffer_copy_string_len(&r->uri.authority, servername, len);
1167     buffer_to_lower(&r->uri.authority);
1168   #if 0
1169     /*(r->uri.authority used below for configuration before request read;
1170      * revisit for h2)*/
1171     if (0 != http_request_host_policy(&r->uri.authority,
1172                                       r->conf.http_parseopts, 443))
1173         return SSL_TLSEXT_ERR_ALERT_FATAL;
1174   #endif
1175 
1176     r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME)
1177                             |  (1 << COMP_HTTP_HOST);
1178     mod_openssl_patch_config(r, &hctx->conf);
1179     /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
1180     /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
1181     /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/
1182     /*buffer_clear(&r->uri.authority);*/
1183 
1184   #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
1185    && !defined(LIBRESSL_VERSION_NUMBER)
1186     return SSL_TLSEXT_ERR_OK;
1187   #else
1188     return (mod_openssl_cert_cb(hctx->ssl, NULL) == 1)
1189       ? SSL_TLSEXT_ERR_OK
1190       : SSL_TLSEXT_ERR_ALERT_FATAL;
1191   #endif
1192 }
1193 
1194 #ifdef SSL_CLIENT_HELLO_SUCCESS
1195 static int
1196 mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv)
1197 {
1198     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1199     buffer_copy_string(&hctx->r->uri.scheme, "https");
1200     UNUSED(srv);
1201 
1202     const unsigned char *name;
1203     size_t len, slen;
1204     if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) {
1205         return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */
1206     }
1207 
1208     /* expecting single element in the server_name extension; parse first one */
1209     if (len > 5
1210         && (size_t)((name[0] << 8) + name[1]) == len-2
1211         && name[2] == TLSEXT_TYPE_server_name
1212         && (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/
1213         int read_ahead = hctx->conf.ssl_read_ahead;
1214         int rc = mod_openssl_SNI(hctx, (const char *)name+5, slen);
1215         if (!read_ahead && hctx->conf.ssl_read_ahead)
1216             SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
1217         if (rc == SSL_TLSEXT_ERR_OK)
1218             return SSL_CLIENT_HELLO_SUCCESS;
1219     }
1220 
1221     *al = TLS1_AD_UNRECOGNIZED_NAME;
1222     return SSL_CLIENT_HELLO_ERROR;
1223 }
1224 #else
1225 static int
1226 network_ssl_servername_callback (SSL *ssl, int *al, void *srv)
1227 {
1228     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1229     buffer_copy_string(&hctx->r->uri.scheme, "https");
1230     UNUSED(al);
1231     UNUSED(srv);
1232 
1233     const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1234     if (NULL == servername)
1235         return SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */
1236     size_t len = strlen(servername);
1237     int read_ahead = hctx->conf.ssl_read_ahead;
1238     int rc = mod_openssl_SNI(hctx, servername, len);
1239     if (!read_ahead && hctx->conf.ssl_read_ahead)
1240         SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead);
1241     return rc;
1242 }
1243 #endif
1244 #endif
1245 
1246 
1247 static X509 *
1248 mod_openssl_load_pem_file (const char *file, log_error_st *errh, STACK_OF(X509) **chain)
1249 {
1250     *chain = NULL;
1251 
1252     off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
1253     char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1254     if (NULL == data) return NULL;
1255 
1256     BIO *in = BIO_new_mem_buf(data, (int)dlen);
1257     if (NULL == in) {
1258         log_error(errh, __FILE__, __LINE__,
1259           "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1260         if (dlen) safe_memclear(data, dlen);
1261         free(data);
1262         return NULL;
1263     }
1264 
1265     X509 *x = PEM_read_bio_X509_AUX_secmem(in, NULL, NULL, NULL);
1266     if (NULL == x) {
1267         log_error(errh, __FILE__, __LINE__,
1268           "SSL: couldn't read X509 certificate from '%s'", file);
1269     }
1270     else if (!mod_openssl_load_X509_sk(file, errh, chain, in)) {
1271         X509_free(x);
1272         x = NULL;
1273     }
1274 
1275     BIO_free(in);
1276     if (dlen) safe_memclear(data, dlen);
1277     free(data);
1278     return x;
1279 }
1280 
1281 
1282 static EVP_PKEY *
1283 mod_openssl_evp_pkey_load_pem_file (const char *file, log_error_st *errh)
1284 {
1285     off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/
1286     char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1287     if (NULL == data) return NULL;
1288     EVP_PKEY *x = NULL;
1289     BIO *in = BIO_new_mem_buf(data, (int)dlen);
1290     if (NULL != in) {
1291         x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
1292         BIO_free(in);
1293     }
1294     if (dlen) safe_memclear(data, dlen);
1295     free(data);
1296 
1297     if (NULL == in)
1298         log_error(errh, __FILE__, __LINE__,
1299           "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1300     else if (NULL == x)
1301         log_error(errh, __FILE__, __LINE__,
1302           "SSL: couldn't read private key from '%s'", file);
1303 
1304     return x;
1305 }
1306 
1307 
1308 #ifndef OPENSSL_NO_OCSP
1309 
1310 static buffer *
1311 mod_openssl_load_stapling_file (const char *file, log_error_st *errh, buffer *b)
1312 {
1313     /* load stapling .der into buffer *b only if successful
1314      *
1315      * Note: for some TLS libs, the OCSP stapling response is not copied when
1316      * assigned to a session (and is reasonable since not changed frequently)
1317      * - BoringSSL SSL_set_ocsp_response()
1318      * - WolfSSL SSL_set_tlsext_status_ocsp_resp() (differs from OpenSSL API)
1319      * Therefore, there is a potential race condition if the OCSP response is
1320      * assigned to the session during the handshake and the Server Hello is
1321      * partially sent, AND (unlikely, if possible at all), the TLS library is
1322      * in the middle of reading this OSCP response buffer.  If the OCSP response
1323      * is replaced due to an updated ssl.stapling-file (checked periodically),
1324      * AND the buffer is resized, this would be a problem.  Resizing the buffer
1325      * is unlikely since updated OSCP response for same certificate are
1326      * typically the same size with the signature and dates refreshed.
1327      */
1328 
1329     /* load raw .der file */
1330     off_t dlen = 1*1024*1024;/*(arbitrary limit: 1 MB file; expect < 1 KB)*/
1331     char *data = fdevent_load_file(file, &dlen, errh, malloc, free);
1332     if (NULL == data) return NULL;
1333 
1334   #if defined(BORINGSSL_API_VERSION)
1335 
1336     if (NULL == b)
1337         b = buffer_init();
1338     else if (b->ptr)
1339         free(b->ptr);
1340     b->ptr  = data;
1341     b->used = (uint32_t)dlen;
1342     b->size = (uint32_t)dlen+1;
1343     return b;
1344 
1345   #else
1346 
1347     BIO *in = BIO_new_mem_buf(data, (int)dlen);
1348     if (NULL == in) {
1349         log_error(errh, __FILE__, __LINE__,
1350           "SSL: BIO_new/BIO_read_filename('%s') failed", file);
1351         free(data);
1352         return NULL;
1353     }
1354 
1355     OCSP_RESPONSE *x = d2i_OCSP_RESPONSE_bio(in, NULL);
1356     BIO_free(in);
1357     free(data);
1358     if (NULL == x) {
1359         log_error(errh, __FILE__, __LINE__,
1360           "SSL: OCSP stapling file read error: %s %s",
1361           ERR_error_string(ERR_get_error(), NULL), file);
1362         return NULL;
1363     }
1364 
1365     unsigned char *rspder = NULL;
1366     int rspderlen = i2d_OCSP_RESPONSE(x, &rspder);
1367 
1368     if (rspderlen > 0) {
1369         if (NULL == b) b = buffer_init();
1370         buffer_copy_string_len(b, (char *)rspder, (uint32_t)rspderlen);
1371     }
1372 
1373     OPENSSL_free(rspder);
1374     OCSP_RESPONSE_free(x);
1375     return rspderlen ? b : NULL;
1376 
1377   #endif
1378 }
1379 
1380 
1381 #if !defined(BORINGSSL_API_VERSION)
1382 static time_t
1383 mod_openssl_asn1_time_to_posix (ASN1_TIME *asn1time)
1384 {
1385   #ifdef LIBRESSL_VERSION_NUMBER
1386     /* LibreSSL was forked from OpenSSL 1.0.1; does not have ASN1_TIME_diff */
1387 
1388     /*(Note: all certificate times are expected to use UTC)*/
1389     /*(Note: does not strictly validate string contains appropriate digits)*/
1390     /*(Note: incorrectly assumes GMT if 'Z' or offset not provided)*/
1391     /*(Note: incorrectly ignores if local timezone might be in DST)*/
1392 
1393     if (NULL == asn1time || NULL == asn1time->data) return (time_t)-1;
1394     const char *s = (const char *)asn1time->data;
1395     size_t len = strlen(s);
1396     struct tm x;
1397     x.tm_isdst = 0;
1398     x.tm_yday = 0;
1399     x.tm_wday = 0;
1400     switch (asn1time->type) {
1401       case V_ASN1_UTCTIME:         /* 2-digit year */
1402         if (len < 8) return (time_t)-1;
1403         len -= 8;
1404         x.tm_year = (s[0]-'0')*10 + (s[1]-'0');
1405         x.tm_year += (x.tm_year < 50 ? 2000 : 1900);
1406         s += 2;
1407         break;
1408       case V_ASN1_GENERALIZEDTIME: /* 4-digit year */
1409         if (len < 10) return (time_t)-1;
1410         len -= 10;
1411         x.tm_year = (s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+(s[3]-'0');
1412         s += 4;
1413         break;
1414       default:
1415         return (time_t)-1;
1416     }
1417     x.tm_mon  = (s[0]-'0')*10 + (s[1]-'0');
1418     x.tm_mday = (s[2]-'0')*10 + (s[3]-'0');
1419     x.tm_hour = (s[4]-'0')*10 + (s[5]-'0');
1420     x.tm_min  = 0;
1421     x.tm_sec  = 0;
1422     s += 6;
1423     if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') {
1424         len -= 2;
1425         x.tm_min = (s[0]-'0')*10 + (s[1]-'0');
1426         s += 2;
1427         if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') {
1428             len -= 2;
1429             x.tm_sec = (s[0]-'0')*10 + (s[1]-'0');
1430             s += 2;
1431             if (len && s[0] == '.') {
1432                 /*(ignore .fff fractional seconds;
1433                  * should be up to 3 digits but we ignore more)*/
1434                 do { ++s; --len; } while (*s >= '0' && *s <= '9');
1435             }
1436         }
1437     }
1438     int offset = 0;
1439     if ((*s == '-' || *s == '+') && len != 5) {
1440         offset = ((s[1]-'0')*10 + (s[2]-'0')) * 3600
1441                + ((s[3]-'0')*10 + (s[4]-'0')) * 60;
1442         if (*s == '-') offset = -offset;
1443     }
1444     else if (s[0] != '\0' && (s[0] != 'Z' || s[1] != '\0'))
1445         return (time_t)-1;
1446 
1447     if (x.tm_year == 9999 && x.tm_mon == 12 && x.tm_mday == 31
1448         && x.tm_hour == 23 && x.tm_min == 59 && x.tm_sec == 59 && s[0] == 'Z')
1449         return (time_t)-1; // 99991231235959Z RFC 5280
1450 
1451    #if 0
1452     #if defined(_WIN32) && !defined(__CYGWIN__)
1453     #define timegm(x) _mkgmtime(x)
1454     #endif
1455     /* timegm() might not be available, and mktime() is sensitive to TZ */
1456     x.tm_year-= 1900;
1457     x.tm_mon -= 1;
1458     time_t t = timegm(&d);
1459     return (t != (time_t)-1) ? t + offset : t;
1460    #else
1461     int y = x.tm_year;
1462     int m = x.tm_mon;
1463     int d = x.tm_mday;
1464     /* days_from_civil() http://howardhinnant.github.io/date_algorithms.html */
1465     y -= m <= 2;
1466     int era = y / 400;
1467     int yoe = y - era * 400;                                   // [0, 399]
1468     int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;  // [0, 365]
1469     int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;           // [0, 146096]
1470     int days_since_1970 = era * 146097 + doe - 719468;
1471     return 60*(60*(24L*days_since_1970+x.tm_hour)+x.tm_min)+x.tm_sec+offset;
1472    #endif
1473 
1474   #else
1475 
1476     /* Note: this does not check for integer overflow of time_t! */
1477     int day, sec;
1478     return ASN1_TIME_diff(&day, &sec, NULL, asn1time)
1479       ? log_epoch_secs + day*86400 + sec
1480       : (time_t)-1;
1481 
1482   #endif
1483 }
1484 #endif
1485 
1486 
1487 static time_t
1488 mod_openssl_ocsp_next_update (plugin_cert *pc)
1489 {
1490   #if defined(BORINGSSL_API_VERSION)
1491     UNUSED(pc);
1492     return (time_t)-1; /*(not implemented)*/
1493   #else
1494     buffer *der = pc->ssl_stapling;
1495     const unsigned char *p = (unsigned char *)der->ptr; /*(p gets modified)*/
1496     OCSP_RESPONSE *ocsp = d2i_OCSP_RESPONSE(NULL,&p,buffer_string_length(der));
1497     if (NULL == ocsp) return (time_t)-1;
1498     OCSP_BASICRESP *bs = OCSP_response_get1_basic(ocsp);
1499     if (NULL == bs) {
1500         OCSP_RESPONSE_free(ocsp);
1501         return (time_t)-1;
1502     }
1503 
1504     /* XXX: should save and evaluate cert status returned by these calls */
1505     ASN1_TIME *nextupd = NULL;
1506     OCSP_single_get0_status(OCSP_resp_get0(bs, 0), NULL, NULL, NULL, &nextupd);
1507     time_t t = nextupd ? mod_openssl_asn1_time_to_posix(nextupd) : (time_t)-1;
1508 
1509     /* Note: trust external process which creates ssl.stapling-file to verify
1510      *       (as well as to validate certificate status)
1511      * future: verify OCSP response here to double-check */
1512 
1513     OCSP_BASICRESP_free(bs);
1514     OCSP_RESPONSE_free(ocsp);
1515 
1516     return t;
1517   #endif
1518 }
1519 
1520 
1521 static int
1522 mod_openssl_reload_stapling_file (server *srv, plugin_cert *pc, const time_t cur_ts)
1523 {
1524     buffer *b = mod_openssl_load_stapling_file(pc->ssl_stapling_file->ptr,
1525                                                srv->errh, pc->ssl_stapling);
1526     if (!b) return 0;
1527 
1528     pc->ssl_stapling = b; /*(unchanged unless orig was NULL)*/
1529     pc->ssl_stapling_loadts = cur_ts;
1530     pc->ssl_stapling_nextts = mod_openssl_ocsp_next_update(pc);
1531     if (pc->ssl_stapling_nextts == (time_t)-1) {
1532         /* "Next Update" might not be provided by OCSP responder
1533          * Use 3600 sec (1 hour) in that case. */
1534         /* retry in 1 hour if unable to determine Next Update */
1535         pc->ssl_stapling_nextts = cur_ts + 3600;
1536         pc->ssl_stapling_loadts = 0;
1537     }
1538 
1539     return 1;
1540 }
1541 
1542 
1543 static int
1544 mod_openssl_refresh_stapling_file (server *srv, plugin_cert *pc, const time_t cur_ts)
1545 {
1546     if (pc->ssl_stapling && pc->ssl_stapling_nextts - 256 > cur_ts)
1547         return 1; /* skip check for refresh unless close to expire */
1548     struct stat st;
1549     if (0 != stat(pc->ssl_stapling_file->ptr, &st)
1550         || st.st_mtime <= pc->ssl_stapling_loadts) {
1551         if (pc->ssl_stapling_nextts < cur_ts) {
1552             /* discard expired OCSP stapling response */
1553             buffer_free(pc->ssl_stapling);
1554             pc->ssl_stapling = NULL;
1555             if (pc->must_staple) {
1556                 log_error(srv->errh, __FILE__, __LINE__,
1557                           "certificate marked OCSP Must-Staple, "
1558                           "but OCSP response expired from ssl.stapling-file %s",
1559                           pc->ssl_stapling_file->ptr);
1560             }
1561         }
1562         return 1;
1563     }
1564     return mod_openssl_reload_stapling_file(srv, pc, cur_ts);
1565 }
1566 
1567 
1568 static void
1569 mod_openssl_refresh_stapling_files (server *srv, const plugin_data *p, const time_t cur_ts)
1570 {
1571     /* future: might construct array of (plugin_cert *) at startup
1572      *         to avoid the need to search for them here */
1573     for (int i = 0, used = p->nconfig; i < used; ++i) {
1574         const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
1575         for (; cpv->k_id != -1; ++cpv) {
1576             if (cpv->k_id != 0) continue; /* k_id == 0 for ssl.pemfile */
1577             if (cpv->vtype != T_CONFIG_LOCAL) continue;
1578             plugin_cert *pc = cpv->v.v;
1579             if (!buffer_string_is_empty(pc->ssl_stapling_file))
1580                 mod_openssl_refresh_stapling_file(srv, pc, cur_ts);
1581         }
1582     }
1583 }
1584 
1585 
1586 static int
1587 mod_openssl_crt_must_staple (const X509 *crt)
1588 {
1589   #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1590    || defined(BORINGSSL_API_VERSION) \
1591    || defined(LIBRESSL_VERSION_NUMBER)
1592     /*(not currently supported in BoringSSL or LibreSSL)*/
1593     UNUSED(crt);
1594     return 0;
1595   #else
1596     /* openssl/x509v3.h:typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE; */
1597 
1598     TLS_FEATURE *tlsf = X509_get_ext_d2i(crt, NID_tlsfeature, NULL, NULL);
1599     if (NULL == tlsf) return 0;
1600 
1601     int rc = 0;
1602 
1603     for (int i = 0; i < sk_ASN1_INTEGER_num(tlsf); ++i) {
1604         ASN1_INTEGER *ai = sk_ASN1_INTEGER_value(tlsf, i);
1605         long tlsextid = ASN1_INTEGER_get(ai);
1606         if (tlsextid == 5) { /* 5 = OCSP Must-Staple */
1607             rc = 1;
1608             break;
1609         }
1610     }
1611 
1612     sk_ASN1_INTEGER_pop_free(tlsf, ASN1_INTEGER_free);
1613     return rc; /* 1 if OCSP Must-Staple found; 0 if not */
1614   #endif
1615 }
1616 
1617 #endif /* OPENSSL_NO_OCSP */
1618 
1619 
1620 static plugin_cert *
1621 network_openssl_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey, const buffer *ssl_stapling_file)
1622 {
1623     if (!mod_openssl_init_once_openssl(srv)) return NULL;
1624 
1625     STACK_OF(X509) *ssl_pemfile_chain = NULL;
1626     X509 *ssl_pemfile_x509 =
1627       mod_openssl_load_pem_file(pemfile->ptr, srv->errh, &ssl_pemfile_chain);
1628     if (NULL == ssl_pemfile_x509)
1629         return NULL;
1630 
1631     EVP_PKEY *ssl_pemfile_pkey =
1632       mod_openssl_evp_pkey_load_pem_file(privkey->ptr, srv->errh);
1633     if (NULL == ssl_pemfile_pkey) {
1634         X509_free(ssl_pemfile_x509);
1635         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1636         return NULL;
1637     }
1638 
1639     if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1640         log_error(srv->errh, __FILE__, __LINE__, "SSL:"
1641           "Private key does not match the certificate public key, "
1642           "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
1643           pemfile->ptr, privkey->ptr);
1644         EVP_PKEY_free(ssl_pemfile_pkey);
1645         X509_free(ssl_pemfile_x509);
1646         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1647         return NULL;
1648     }
1649 
1650     plugin_cert *pc = malloc(sizeof(plugin_cert));
1651     force_assert(pc);
1652     pc->ssl_pemfile_pkey = ssl_pemfile_pkey;
1653     pc->ssl_pemfile_x509 = ssl_pemfile_x509;
1654     pc->ssl_pemfile_chain= ssl_pemfile_chain;
1655     pc->ssl_pemfile = pemfile;
1656     pc->ssl_privkey = privkey;
1657     pc->ssl_stapling     = NULL;
1658     pc->ssl_stapling_file= ssl_stapling_file;
1659     pc->ssl_stapling_loadts = 0;
1660     pc->ssl_stapling_nextts = 0;
1661   #ifndef OPENSSL_NO_OCSP
1662     pc->must_staple = mod_openssl_crt_must_staple(ssl_pemfile_x509);
1663   #else
1664     pc->must_staple = 0;
1665   #endif
1666 
1667     if (!buffer_string_is_empty(pc->ssl_stapling_file)) {
1668       #ifndef OPENSSL_NO_OCSP
1669         if (!mod_openssl_reload_stapling_file(srv, pc, log_epoch_secs)) {
1670             /* continue without OCSP response if there is an error */
1671         }
1672       #else
1673         log_error(srv->errh, __FILE__, __LINE__, "SSL:"
1674           "OCSP stapling not supported; ignoring %s",
1675           pc->ssl_stapling_file->ptr);
1676       #endif
1677     }
1678     else if (pc->must_staple) {
1679         log_error(srv->errh, __FILE__, __LINE__,
1680                   "certificate %s marked OCSP Must-Staple, "
1681                   "but ssl.stapling-file not provided", pemfile->ptr);
1682     }
1683 
1684     return pc;
1685 }
1686 
1687 
1688 #ifndef OPENSSL_NO_TLSEXT
1689 
1690 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1691 
1692 static int
1693 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
1694 {
1695     buffer * const b = hctx->tmp_buf;
1696     const buffer * const name = &hctx->r->uri.authority;
1697     log_error_st * const errh = hctx->r->conf.errh;
1698     X509 *ssl_pemfile_x509 = NULL;
1699     STACK_OF(X509) *ssl_pemfile_chain = NULL;
1700     EVP_PKEY *ssl_pemfile_pkey = NULL;
1701     size_t len;
1702     int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
1703 
1704     /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
1705     if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
1706         return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
1707     buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
1708     buffer_append_slash(b);
1709 
1710     /* check if SNI set server name (required for acme-tls/1 protocol)
1711      * and perform simple path checks for no '/'
1712      * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
1713     if (buffer_string_is_empty(name))   return rc;
1714     if (NULL != strchr(name->ptr, '/')) return rc;
1715     if (name->ptr[0] == '.')            return rc;
1716   #if 0
1717     if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443))
1718         return rc;
1719   #endif
1720     buffer_append_string_buffer(b, name);
1721     len = buffer_string_length(b);
1722 
1723     do {
1724         buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
1725         ssl_pemfile_x509 =
1726           mod_openssl_load_pem_file(b->ptr, errh, &ssl_pemfile_chain);
1727         if (NULL == ssl_pemfile_x509) {
1728             log_error(errh, __FILE__, __LINE__,
1729               "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1730             break;
1731         }
1732 
1733         buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
1734         buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
1735         ssl_pemfile_pkey = mod_openssl_evp_pkey_load_pem_file(b->ptr, errh);
1736         if (NULL == ssl_pemfile_pkey) {
1737             log_error(errh, __FILE__, __LINE__,
1738               "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr);
1739             break;
1740         }
1741 
1742       #if 0 /* redundant with below? */
1743         if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
1744             log_error(errh, __FILE__, __LINE__,
1745                "SSL: Private key does not match acme-tls/1 "
1746                "certificate public key, reason: %s %s"
1747                ERR_error_string(ERR_get_error(), NULL), b->ptr);
1748             break;
1749         }
1750       #endif
1751 
1752         /* first set certificate!
1753          * setting private key checks whether certificate matches it */
1754         if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
1755             log_error(errh, __FILE__, __LINE__,
1756               "SSL: failed to set acme-tls/1 certificate for TLS server "
1757               "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1758             break;
1759         }
1760 
1761         if (ssl_pemfile_chain) {
1762             SSL_set0_chain(ssl, ssl_pemfile_chain);
1763             ssl_pemfile_chain = NULL;
1764         }
1765 
1766         if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
1767             log_error(errh, __FILE__, __LINE__,
1768               "SSL: failed to set acme-tls/1 private key for TLS server "
1769               "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL));
1770             break;
1771         }
1772 
1773         hctx->conf.ssl_verifyclient_enforce = 0;
1774         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
1775         rc = SSL_TLSEXT_ERR_OK;
1776     } while (0);
1777 
1778     if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
1779     if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
1780     if (ssl_pemfile_chain)
1781         sk_X509_pop_free(ssl_pemfile_chain, X509_free);
1782 
1783     return rc;
1784 }
1785 
1786 enum {
1787   MOD_OPENSSL_ALPN_HTTP11      = 1
1788  ,MOD_OPENSSL_ALPN_HTTP10      = 2
1789  ,MOD_OPENSSL_ALPN_H2          = 3
1790  ,MOD_OPENSSL_ALPN_ACME_TLS_1  = 4
1791 };
1792 
1793 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
1794 static int
1795 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
1796 {
1797     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
1798     unsigned short proto;
1799     UNUSED(arg);
1800 
1801     for (unsigned int i = 0, n; i < inlen; i += n) {
1802         n = in[i++];
1803         if (i+n > inlen || 0 == n) break;
1804         switch (n) {
1805           case 2:  /* "h2" */
1806             if (in[i] == 'h' && in[i+1] == '2') {
1807                 if (!hctx->r->conf.h2proto) continue;
1808                 proto = MOD_OPENSSL_ALPN_H2;
1809                 hctx->r->http_version = HTTP_VERSION_2;
1810                 break;
1811             }
1812             continue;
1813           case 8:  /* "http/1.1" "http/1.0" */
1814             if (0 == memcmp(in+i, "http/1.", 7)) {
1815                 if (in[i+7] == '1') {
1816                     proto = MOD_OPENSSL_ALPN_HTTP11;
1817                     break;
1818                 }
1819                 if (in[i+7] == '0') {
1820                     proto = MOD_OPENSSL_ALPN_HTTP10;
1821                     break;
1822                 }
1823             }
1824             continue;
1825           case 10: /* "acme-tls/1" */
1826             if (0 == memcmp(in+i, "acme-tls/1", 10)) {
1827                 int rc = mod_openssl_acme_tls_1(ssl, hctx);
1828                 if (rc == SSL_TLSEXT_ERR_OK) {
1829                     proto = MOD_OPENSSL_ALPN_ACME_TLS_1;
1830                     break;
1831                 }
1832                 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */
1833                 if (rc == SSL_TLSEXT_ERR_NOACK) continue;
1834                 return rc;
1835             }
1836             continue;
1837           default:
1838             continue;
1839         }
1840 
1841         hctx->alpn = proto;
1842         *out = in+i;
1843         *outlen = n;
1844         return SSL_TLSEXT_ERR_OK;
1845     }
1846 
1847   #if OPENSSL_VERSION_NUMBER < 0x10100000L
1848     return SSL_TLSEXT_ERR_NOACK;
1849   #else
1850     return SSL_TLSEXT_ERR_ALERT_FATAL;
1851   #endif
1852 }
1853 
1854 #endif /* TLSEXT_TYPE_application_layer_protocol_negotiation */
1855 
1856 #endif /* OPENSSL_NO_TLSEXT */
1857 
1858 
1859 #if defined(BORINGSSL_API_VERSION) \
1860  || defined(LIBRESSL_VERSION_NUMBER)
1861 static int
1862 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s);
1863 #endif
1864 
1865 
1866 static int
1867 network_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s)
1868 {
1869   #ifdef SSL_CONF_FLAG_CMDLINE
1870 
1871     int rc = 0;
1872     const data_string *ds;
1873     SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new();
1874     SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx);
1875     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE
1876                                | SSL_CONF_FLAG_SERVER
1877                                | SSL_CONF_FLAG_SHOW_ERRORS
1878                                | SSL_CONF_FLAG_CERTIFICATE);
1879 
1880     /* always disable null and export ciphers */
1881     ds = (const data_string *)
1882       array_get_element_klen(s->ssl_conf_cmd,
1883                              CONST_STR_LEN("CipherString"));
1884     if (NULL != ds) {
1885         buffer *cipher_string =
1886           array_get_buf_ptr(s->ssl_conf_cmd, CONST_STR_LEN("CipherString"));
1887         if (buffer_string_is_empty(cipher_string))
1888             buffer_append_string_len(cipher_string, CONST_STR_LEN("HIGH"));
1889         buffer_append_string_len(cipher_string,
1890                                  CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
1891     }
1892 
1893     for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
1894         ds = (data_string *)s->ssl_conf_cmd->data[i];
1895         ERR_clear_error();
1896         if (SSL_CONF_cmd(cctx, ds->key.ptr, ds->value.ptr) <= 0) {
1897             log_error(srv->errh, __FILE__, __LINE__,
1898               "SSL: SSL_CONF_cmd %s %s: %s", ds->key.ptr, ds->value.ptr,
1899               ERR_error_string(ERR_get_error(), NULL));
1900             rc = -1;
1901             break;
1902         }
1903     }
1904 
1905     if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) {
1906         log_error(srv->errh, __FILE__, __LINE__,
1907           "SSL: SSL_CONF_CTX_finish(): %s",
1908           ERR_error_string(ERR_get_error(), NULL));
1909         rc = -1;
1910     }
1911 
1912     SSL_CONF_CTX_free(cctx);
1913     return rc;
1914 
1915   #elif defined(BORINGSSL_API_VERSION) \
1916      || defined(LIBRESSL_VERSION_NUMBER)
1917 
1918     return mod_openssl_ssl_conf_cmd(srv, s);
1919 
1920   #else
1921 
1922     UNUSED(s);
1923     log_error(srv->errh, __FILE__, __LINE__,
1924       "SSL: ssl.openssl.ssl-conf-cmd not available; ignored");
1925     return 0;
1926 
1927   #endif
1928 }
1929 
1930 
1931 #ifndef OPENSSL_NO_DH
1932 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1933  || defined(LIBRESSL_VERSION_NUMBER)
1934 #define DH_set0_pqg(dh, dh_p, NULL, dh_g) \
1935         ((dh)->p = (dh_p), (dh)->g = (dh_g), (dh_p) != NULL && (dh_g) != NULL)
1936 #endif
1937 /* https://tools.ietf.org/html/rfc7919#appendix-A.1
1938  * A.1.  ffdhe2048
1939  *
1940  * https://ssl-config.mozilla.org/ffdhe2048.txt
1941  * C code generated with: openssl dhparam -C -in ffdhe2048.txt
1942  */
1943 static DH *get_dh2048(void)
1944 {
1945     static unsigned char dhp_2048[] = {
1946         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8,
1947         0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, 0xAF, 0xDC, 0x56, 0x20,
1948         0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D,
1949         0x36, 0x95, 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
1950         0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, 0x7D, 0x2F,
1951         0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02,
1952         0xAE, 0xC4, 0x61, 0x7A, 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD,
1953         0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
1954         0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57,
1955         0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, 0x98, 0x4F, 0x0C, 0x70,
1956         0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF,
1957         0xE8, 0x72, 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
1958         0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, 0xBC, 0x0A,
1959         0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B,
1960         0xB2, 0xC8, 0xE3, 0xFB, 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7,
1961         0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
1962         0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07,
1963         0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, 0x9E, 0x02, 0xFC, 0xE1,
1964         0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34,
1965         0x2F, 0x61, 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
1966         0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, 0xC3, 0xFE,
1967         0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC,
1968         0x2E, 0xC2, 0x20, 0x05, 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16,
1969         0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
1970         0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, 0xFF, 0xFF,
1971         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
1972     };
1973     static unsigned char dhg_2048[] = {
1974         0x02
1975     };
1976     DH *dh = DH_new();
1977     BIGNUM *p, *g;
1978 
1979     if (dh == NULL)
1980         return NULL;
1981     p = BN_bin2bn(dhp_2048, sizeof(dhp_2048), NULL);
1982     g = BN_bin2bn(dhg_2048, sizeof(dhg_2048), NULL);
1983     if (p == NULL || g == NULL || !DH_set0_pqg(dh, p, NULL, g)) {
1984         DH_free(dh);
1985         BN_free(p);
1986         BN_free(g);
1987         return NULL;
1988     }
1989     return dh;
1990 }
1991 #endif
1992 
1993 
1994 static int
1995 mod_openssl_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *ssl_ec_curve)
1996 {
1997   #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1998   #ifndef OPENSSL_NO_ECDH
1999     int nid = 0;
2000     /* Support for Elliptic-Curve Diffie-Hellman key exchange */
2001     if (!buffer_string_is_empty(ssl_ec_curve)) {
2002         /* OpenSSL only supports the "named curves"
2003          * from RFC 4492, section 5.1.1. */
2004         nid = OBJ_sn2nid((char *) ssl_ec_curve->ptr);
2005         if (nid == 0) {
2006             log_error(srv->errh, __FILE__, __LINE__,
2007               "SSL: Unknown curve name %s", ssl_ec_curve->ptr);
2008             return 0;
2009         }
2010     }
2011     else {
2012       #if OPENSSL_VERSION_NUMBER < 0x10002000
2013         /* Default curve */
2014         nid = OBJ_sn2nid("prime256v1");
2015       #elif OPENSSL_VERSION_NUMBER < 0x10100000L \
2016          || defined(LIBRESSL_VERSION_NUMBER)
2017         if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) {
2018             log_error(srv->errh, __FILE__, __LINE__,
2019               "SSL: SSL_CTX_set_ecdh_auto() failed");
2020         }
2021       #endif
2022     }
2023     if (nid) {
2024         EC_KEY *ecdh;
2025         ecdh = EC_KEY_new_by_curve_name(nid);
2026         if (ecdh == NULL) {
2027             log_error(srv->errh, __FILE__, __LINE__,
2028               "SSL: Unable to create curve %s", ssl_ec_curve->ptr);
2029             return 0;
2030         }
2031         SSL_CTX_set_tmp_ecdh(s->ssl_ctx, ecdh);
2032         SSL_CTX_set_options(s->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
2033         EC_KEY_free(ecdh);
2034     }
2035   #endif
2036   #endif
2037     UNUSED(srv);
2038     UNUSED(s);
2039     UNUSED(ssl_ec_curve);
2040 
2041     return 1;
2042 }
2043 
2044 
2045 static int
2046 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p)
2047 {
2048     /* load SSL certificates */
2049 
2050       #ifndef SSL_OP_NO_COMPRESSION
2051       #define SSL_OP_NO_COMPRESSION 0
2052       #endif
2053       #ifndef SSL_MODE_RELEASE_BUFFERS    /* OpenSSL >= 1.0.0 */
2054       #define SSL_MODE_RELEASE_BUFFERS 0
2055       #endif
2056         long ssloptions = SSL_OP_ALL
2057                         | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2058                         | SSL_OP_NO_COMPRESSION;
2059 
2060       #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2061         s->ssl_ctx = (!s->ssl_use_sslv2 && !s->ssl_use_sslv3)
2062           ? SSL_CTX_new(TLS_server_method())
2063           : SSL_CTX_new(SSLv23_server_method());
2064       #else
2065         s->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
2066       #endif
2067         if (NULL == s->ssl_ctx) {
2068             log_error(srv->errh, __FILE__, __LINE__,
2069               "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2070             return -1;
2071         }
2072 
2073       #ifdef SSL_OP_NO_RENEGOTIATION /* openssl 1.1.0 */
2074         if (s->ssl_disable_client_renegotiation)
2075             ssloptions |= SSL_OP_NO_RENEGOTIATION;
2076       #endif
2077 
2078         /* completely useless identifier;
2079          * required for client cert verification to work with sessions */
2080         if (0 == SSL_CTX_set_session_id_context(
2081                    s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){
2082             log_error(srv->errh, __FILE__, __LINE__,
2083               "SSL: failed to set session context: %s",
2084               ERR_error_string(ERR_get_error(), NULL));
2085             return -1;
2086         }
2087 
2088         const int disable_sess_cache =
2089           srv->srvconf.feature_flags
2090           && !config_plugin_value_tobool(
2091                array_get_element_klen(srv->srvconf.feature_flags,
2092                                       CONST_STR_LEN("ssl.session-cache")), 0);
2093         if (disable_sess_cache)
2094             /* disable session cache; session tickets are preferred */
2095             SSL_CTX_set_session_cache_mode(s->ssl_ctx,
2096                                              SSL_SESS_CACHE_OFF
2097                                            | SSL_SESS_CACHE_NO_AUTO_CLEAR
2098                                            | SSL_SESS_CACHE_NO_INTERNAL);
2099 
2100         if (s->ssl_empty_fragments) {
2101           #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
2102             ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2103           #else
2104             ssloptions &= ~0x00000800L; /* hardcode constant */
2105             log_error(srv->errh, __FILE__, __LINE__,
2106               "WARNING: SSL: 'insert empty fragments' not supported by the "
2107               "openssl version used to compile lighttpd with");
2108           #endif
2109         }
2110 
2111         SSL_CTX_set_options(s->ssl_ctx, ssloptions);
2112         SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback);
2113 
2114         if (!s->ssl_use_sslv2 && 0 != SSL_OP_NO_SSLv2) {
2115             /* disable SSLv2 */
2116             if ((SSL_OP_NO_SSLv2
2117                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2))
2118                 != SSL_OP_NO_SSLv2) {
2119                 log_error(srv->errh, __FILE__, __LINE__,
2120                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2121                 return -1;
2122             }
2123         }
2124 
2125         if (!s->ssl_use_sslv3 && 0 != SSL_OP_NO_SSLv3) {
2126             /* disable SSLv3 */
2127             if ((SSL_OP_NO_SSLv3
2128                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3))
2129                 != SSL_OP_NO_SSLv3) {
2130                 log_error(srv->errh, __FILE__, __LINE__,
2131                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2132                 return -1;
2133             }
2134         }
2135 
2136         if (!buffer_string_is_empty(s->ssl_cipher_list)) {
2137             /* Disable support for low encryption ciphers */
2138             if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){
2139                 log_error(srv->errh, __FILE__, __LINE__,
2140                   "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
2141                 return -1;
2142             }
2143 
2144             if (s->ssl_honor_cipher_order) {
2145                 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE);
2146             }
2147         }
2148 
2149       #ifdef SSL_OP_PRIORITIZE_CHACHA /*(openssl 1.1.1)*/
2150         if (s->ssl_honor_cipher_order)
2151             SSL_CTX_set_options(s->ssl_ctx, SSL_OP_PRIORITIZE_CHACHA);
2152       #endif
2153 
2154       #ifndef OPENSSL_NO_DH
2155       {
2156         DH *dh;
2157         /* Support for Diffie-Hellman key exchange */
2158         if (!buffer_string_is_empty(s->ssl_dh_file)) {
2159             /* DH parameters from file */
2160             BIO *bio;
2161             bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r");
2162             if (bio == NULL) {
2163                 log_error(srv->errh, __FILE__, __LINE__,
2164                   "SSL: Unable to open file %s", s->ssl_dh_file->ptr);
2165                 return -1;
2166             }
2167             dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2168             BIO_free(bio);
2169             if (dh == NULL) {
2170                 log_error(srv->errh, __FILE__, __LINE__,
2171                   "SSL: PEM_read_bio_DHparams failed %s", s->ssl_dh_file->ptr);
2172                 return -1;
2173             }
2174             SSL_CTX_set_tmp_dh(s->ssl_ctx,dh);
2175             DH_free(dh);
2176         }
2177         else {
2178             dh = get_dh2048();
2179             if (dh == NULL) {
2180                 log_error(srv->errh, __FILE__, __LINE__,
2181                   "SSL: get_dh2048() failed");
2182                 return -1;
2183             }
2184             SSL_CTX_set_tmp_dh(s->ssl_ctx,dh);
2185             DH_free(dh);
2186         }
2187         SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE);
2188       }
2189       #else
2190         if (!buffer_string_is_empty(s->ssl_dh_file)) {
2191             log_error(srv->errh, __FILE__, __LINE__,
2192               "SSL: openssl compiled without DH support, "
2193               "can't load parameters from %s", s->ssl_dh_file->ptr);
2194         }
2195       #endif
2196 
2197         if (!mod_openssl_ssl_conf_curves(srv, s, s->ssl_ec_curve))
2198             return -1;
2199 
2200       #ifdef TLSEXT_TYPE_session_ticket
2201        #if OPENSSL_VERSION_NUMBER < 0x30000000L
2202         SSL_CTX_set_tlsext_ticket_key_cb(s->ssl_ctx, ssl_tlsext_ticket_key_cb);
2203        #else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
2204         SSL_CTX_set_tlsext_ticket_key_evp_cb(s->ssl_ctx,
2205                                              ssl_tlsext_ticket_key_cb);
2206        #endif
2207       #endif
2208 
2209       #ifndef OPENSSL_NO_OCSP
2210       #ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */
2211         SSL_CTX_set_tlsext_status_cb(s->ssl_ctx, ssl_tlsext_status_cb);
2212       #endif
2213       #endif
2214 
2215       #if OPENSSL_VERSION_NUMBER >= 0x10002000 \
2216        && !defined(LIBRESSL_VERSION_NUMBER)
2217 
2218         SSL_CTX_set_cert_cb(s->ssl_ctx, mod_openssl_cert_cb, NULL);
2219         UNUSED(p);
2220 
2221        #if defined(BORINGSSL_API_VERSION) /* BoringSSL limitation */
2222         /* set cert store for auto-chaining
2223          * BoringSSL does not support SSL_set1_chain_cert_store() in cert_cb */
2224         if (s->ssl_ca_file && s->ssl_ca_file->certs) {
2225             if (!X509_STORE_up_ref(s->ssl_ca_file->certs))
2226                 return -1;
2227             SSL_CTX_set_cert_store(s->ssl_ctx, s->ssl_ca_file->certs);
2228         }
2229        #endif
2230 
2231       #else /* OPENSSL_VERSION_NUMBER < 0x10002000 */
2232 
2233         /* load all ssl.ca-files specified in the config into each SSL_CTX
2234          * XXX: This might be a bit excessive, but are all trusted CAs
2235          *      TODO: prefer to load on-demand in mod_openssl_cert_cb()
2236          *            for openssl >= 1.0.2 */
2237         if (!mod_openssl_load_ca_files(s->ssl_ctx, p, srv))
2238             return -1;
2239 
2240         if (s->ssl_verifyclient) {
2241             if (NULL == s->ssl_ca_file) {
2242                 log_error(srv->errh, __FILE__, __LINE__,
2243                   "SSL: You specified ssl.verifyclient.activate "
2244                   "but no ssl.ca-file");
2245                 return -1;
2246             }
2247             /* WTH openssl?  SSL_CTX_set_client_CA_list() calls set0_CA_list(),
2248              * but there is no set1_CA_list() to simply up the reference count
2249              * (without needing to duplicate the list) */
2250             /* WTH wolfssl?  wolfSSL_dup_CA_list() is a stub which returns NULL
2251              * and so DN names in cert request are not set here.
2252              * (A patch has been submitted to WolfSSL to correct this)*/
2253             STACK_OF(X509_NAME) * const cert_names = s->ssl_ca_dn_file
2254               ? s->ssl_ca_dn_file
2255               : s->ssl_ca_file->names;
2256             SSL_CTX_set_client_CA_list(s->ssl_ctx, SSL_dup_CA_list(cert_names));
2257             int mode = SSL_VERIFY_PEER;
2258             if (s->ssl_verifyclient_enforce) {
2259                 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2260             }
2261             SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback);
2262             SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1);
2263             if (!buffer_string_is_empty(s->ssl_ca_crl_file)) {
2264                 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx);
2265                 if (!mod_openssl_load_cacrls(store, s->ssl_ca_crl_file, srv))
2266                     return -1;
2267             }
2268         }
2269 
2270         if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx,
2271                                                     s->pc->ssl_pemfile->ptr)) {
2272             log_error(srv->errh, __FILE__, __LINE__,
2273               "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL),
2274               s->pc->ssl_pemfile->ptr);
2275             return -1;
2276         }
2277 
2278         if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->pc->ssl_pemfile_pkey)) {
2279             log_error(srv->errh, __FILE__, __LINE__,
2280               "SSL: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
2281               s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
2282             return -1;
2283         }
2284 
2285         if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) {
2286             log_error(srv->errh, __FILE__, __LINE__,
2287               "SSL: Private key does not match the certificate public key, "
2288               "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL),
2289               s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr);
2290             return -1;
2291         }
2292 
2293       #endif /* OPENSSL_VERSION_NUMBER < 0x10002000 */
2294 
2295        #if defined(BORINGSSL_API_VERSION)
2296        #define SSL_CTX_set_default_read_ahead(ctx,m) \
2297                SSL_CTX_set_read_ahead(ctx,m)
2298        #endif
2299         SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead);
2300         SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx)
2301                                    | SSL_MODE_ENABLE_PARTIAL_WRITE
2302                                    | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
2303                                    | SSL_MODE_RELEASE_BUFFERS);
2304 
2305       #ifndef OPENSSL_NO_TLSEXT
2306        #ifdef SSL_CLIENT_HELLO_SUCCESS
2307         SSL_CTX_set_client_hello_cb(s->ssl_ctx,mod_openssl_client_hello_cb,srv);
2308        #else
2309         if (!SSL_CTX_set_tlsext_servername_callback(
2310                s->ssl_ctx, network_ssl_servername_callback) ||
2311             !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) {
2312             log_error(srv->errh, __FILE__, __LINE__,
2313               "SSL: failed to initialize TLS servername callback, "
2314               "openssl library does not support TLS servername extension");
2315             return -1;
2316         }
2317        #endif
2318 
2319        #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2320         SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL);
2321        #endif
2322       #endif
2323 
2324       #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
2325        || defined(BORINGSSL_API_VERSION) \
2326        || defined(LIBRESSL_VERSION_NUMBER)
2327         if (!s->ssl_use_sslv3 && !s->ssl_use_sslv2
2328             && !SSL_CTX_set_min_proto_version(s->ssl_ctx, TLS1_2_VERSION))
2329             return -1;
2330       #endif
2331 
2332         if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) {
2333             if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1;
2334         }
2335 
2336         return 0;
2337 }
2338 
2339 
2340 static int
2341 mod_openssl_set_defaults_sockets(server *srv, plugin_data *p)
2342 {
2343     static const config_plugin_keys_t cpk[] = {
2344       { CONST_STR_LEN("ssl.engine"),
2345         T_CONFIG_BOOL,
2346         T_CONFIG_SCOPE_CONNECTION }
2347      ,{ CONST_STR_LEN("ssl.cipher-list"),
2348         T_CONFIG_STRING,
2349         T_CONFIG_SCOPE_CONNECTION }
2350      ,{ CONST_STR_LEN("ssl.honor-cipher-order"),
2351         T_CONFIG_BOOL,
2352         T_CONFIG_SCOPE_CONNECTION }
2353      ,{ CONST_STR_LEN("ssl.dh-file"),
2354         T_CONFIG_STRING,
2355         T_CONFIG_SCOPE_CONNECTION }
2356      ,{ CONST_STR_LEN("ssl.ec-curve"),
2357         T_CONFIG_STRING,
2358         T_CONFIG_SCOPE_CONNECTION }
2359      ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"),
2360         T_CONFIG_ARRAY_KVSTRING,
2361         T_CONFIG_SCOPE_CONNECTION }
2362      ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */
2363         T_CONFIG_STRING,
2364         T_CONFIG_SCOPE_CONNECTION }
2365      ,{ CONST_STR_LEN("ssl.empty-fragments"),
2366         T_CONFIG_BOOL,
2367         T_CONFIG_SCOPE_CONNECTION }
2368      ,{ CONST_STR_LEN("ssl.use-sslv2"),
2369         T_CONFIG_BOOL,
2370         T_CONFIG_SCOPE_CONNECTION }
2371      ,{ CONST_STR_LEN("ssl.use-sslv3"),
2372         T_CONFIG_BOOL,
2373         T_CONFIG_SCOPE_CONNECTION }
2374      ,{ CONST_STR_LEN("ssl.stek-file"),
2375         T_CONFIG_STRING,
2376         T_CONFIG_SCOPE_SERVER }
2377      ,{ NULL, 0,
2378         T_CONFIG_UNSET,
2379         T_CONFIG_SCOPE_UNSET }
2380     };
2381     static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 };
2382 
2383     p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx));
2384     force_assert(p->ssl_ctxs);
2385 
2386     int rc = HANDLER_GO_ON;
2387     plugin_data_base srvplug;
2388     memset(&srvplug, 0, sizeof(srvplug));
2389     plugin_data_base * const ps = &srvplug;
2390     if (!config_plugin_values_init(srv, ps, cpk, "mod_openssl"))
2391         return HANDLER_ERROR;
2392 
2393     plugin_config_socket defaults;
2394     memset(&defaults, 0, sizeof(defaults));
2395     defaults.ssl_honor_cipher_order = 1;
2396     defaults.ssl_cipher_list = &default_ssl_cipher_list;
2397 
2398     /* process and validate config directives for global and $SERVER["socket"]
2399      * (init i to 0 if global context; to 1 to skip empty global context) */
2400     for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) {
2401         config_cond_info cfginfo;
2402         config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id);
2403         int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET);
2404         int count_not_engine = 0;
2405 
2406         plugin_config_socket conf;
2407         memcpy(&conf, &defaults, sizeof(conf));
2408 
2409         /*(preserve prior behavior; not inherited)*/
2410         /*(forcing inheritance might break existing configs where SSL is enabled
2411          * by default in the global scope, but not $SERVER["socket"]=="*:80") */
2412         conf.ssl_enabled = 0;
2413 
2414         config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0];
2415         for (; -1 != cpv->k_id; ++cpv) {
2416             /* ignore ssl.pemfile (k_id=6); included to process global scope */
2417             if (!is_socket_scope && cpv->k_id != 6) {
2418                 log_error(srv->errh, __FILE__, __LINE__,
2419                   "%s is valid only in global scope or "
2420                   "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k);
2421                 continue;
2422             }
2423             ++count_not_engine;
2424             switch (cpv->k_id) {
2425               case 0: /* ssl.engine */
2426                 conf.ssl_enabled = (0 != cpv->v.u);
2427                 --count_not_engine;
2428                 break;
2429               case 1: /* ssl.cipher-list */
2430                 conf.ssl_cipher_list = cpv->v.b;
2431                 break;
2432               case 2: /* ssl.honor-cipher-order */
2433                 conf.ssl_honor_cipher_order = (0 != cpv->v.u);
2434                 break;
2435               case 3: /* ssl.dh-file */
2436                 conf.ssl_dh_file = cpv->v.b;
2437                 break;
2438               case 4: /* ssl.ec-curve */
2439                 conf.ssl_ec_curve = cpv->v.b;
2440                 break;
2441               case 5: /* ssl.openssl.ssl-conf-cmd */
2442                 *(const array **)&conf.ssl_conf_cmd = cpv->v.a;
2443                 break;
2444               case 6: /* ssl.pemfile */
2445                 /* ignore here; included to process global scope when
2446                  * ssl.pemfile is set, but ssl.engine is not "enable" */
2447                 break;
2448               case 7: /* ssl.empty-fragments */
2449                 conf.ssl_empty_fragments = (0 != cpv->v.u);
2450                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2451                   "ssl.empty-fragments is deprecated and will soon be "
2452                   "removed.  It is disabled by default.");
2453                 if (conf.ssl_empty_fragments)
2454                     log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2455                       "If needed, use: ssl.openssl.ssl-conf-cmd = "
2456                       "(\"Options\" => \"EmptyFragments\")");
2457                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2458                   "ssl.empty-fragments is a "
2459                   "counter-measure against a SSL 3.0/TLS 1.0 protocol "
2460                   "vulnerability affecting CBC ciphers, which cannot be handled"
2461                   " by some broken (Microsoft) SSL implementations.");
2462                 break;
2463               case 8: /* ssl.use-sslv2 */
2464                 conf.ssl_use_sslv2 = (0 != cpv->v.u);
2465                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2466                   "ssl.use-sslv2 is deprecated and will soon be removed.  "
2467                   "It is disabled by default.  "
2468                   "Many modern TLS libraries no longer support SSLv2.");
2469                 break;
2470               case 9: /* ssl.use-sslv3 */
2471                 conf.ssl_use_sslv3 = (0 != cpv->v.u);
2472                 log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2473                   "ssl.use-sslv3 is deprecated and will soon be removed.  "
2474                   "It is disabled by default.  "
2475                   "Many modern TLS libraries no longer support SSLv3.");
2476                 if (conf.ssl_use_sslv3)
2477                     log_error(srv->errh, __FILE__, __LINE__, "SSL: "
2478                       "If needed, use: ssl.openssl.ssl-conf-cmd = "
2479                       "(\"MinProtocol\" => \"SSLv3\")");
2480                 break;
2481               case 10:/* ssl.stek-file */
2482                 if (!buffer_is_empty(cpv->v.b))
2483                     p->ssl_stek_file = cpv->v.b->ptr;
2484                 break;
2485               default:/* should not happen */
2486                 break;
2487             }
2488         }
2489         if (HANDLER_GO_ON != rc) break;
2490         if (0 == i) memcpy(&defaults, &conf, sizeof(conf));
2491 
2492         if (0 != i && !conf.ssl_enabled) continue;
2493 
2494         /* fill plugin_config_socket with global context then $SERVER["socket"]
2495          * only for directives directly in current $SERVER["socket"] condition*/
2496 
2497         /*conf.pc                     = p->defaults.pc;*/
2498         conf.ssl_ca_file              = p->defaults.ssl_ca_file;
2499         conf.ssl_ca_dn_file           = p->defaults.ssl_ca_dn_file;
2500         conf.ssl_ca_crl_file          = p->defaults.ssl_ca_crl_file;
2501         conf.ssl_verifyclient         = p->defaults.ssl_verifyclient;
2502         conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce;
2503         conf.ssl_verifyclient_depth   = p->defaults.ssl_verifyclient_depth;
2504         conf.ssl_read_ahead           = p->defaults.ssl_read_ahead;
2505 
2506         int sidx = ps->cvlist[i].k_id;
2507         for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) {
2508             if (p->cvlist[j].k_id != sidx) continue;
2509             /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/
2510             cpv = p->cvlist + p->cvlist[j].v.u2[0];
2511             for (; -1 != cpv->k_id; ++cpv) {
2512                 ++count_not_engine;
2513                 switch (cpv->k_id) {
2514                   case 0: /* ssl.pemfile */
2515                     if (cpv->vtype == T_CONFIG_LOCAL)
2516                         conf.pc = cpv->v.v;
2517                     break;
2518                   case 2: /* ssl.ca-file */
2519                     if (cpv->vtype == T_CONFIG_LOCAL)
2520                         conf.ssl_ca_file = cpv->v.v;
2521                     break;
2522                   case 3: /* ssl.ca-dn-file */
2523                     if (cpv->vtype == T_CONFIG_LOCAL)
2524                         conf.ssl_ca_dn_file = cpv->v.v;
2525                     break;
2526                   case 4: /* ssl.ca-crl-file */
2527                     conf.ssl_ca_crl_file = cpv->v.b;
2528                     break;
2529                   case 5: /* ssl.read-ahead */
2530                     conf.ssl_read_ahead = (0 != cpv->v.u);
2531                     break;
2532                   case 6: /* ssl.disable-client-renegotiation */
2533                     conf.ssl_disable_client_renegotiation = (0 != cpv->v.u);
2534                     break;
2535                   case 7: /* ssl.verifyclient.activate */
2536                     conf.ssl_verifyclient = (0 != cpv->v.u);
2537                     break;
2538                   case 8: /* ssl.verifyclient.enforce */
2539                     conf.ssl_verifyclient_enforce = (0 != cpv->v.u);
2540                     break;
2541                   case 9: /* ssl.verifyclient.depth */
2542                     conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt;
2543                     break;
2544                   default:
2545                     break;
2546                 }
2547             }
2548             break;
2549         }
2550 
2551         if (NULL == conf.pc) {
2552             if (0 == i && !conf.ssl_enabled) continue;
2553             if (0 != i) {
2554                 /* inherit ssl settings from global scope
2555                  * (if only ssl.engine = "enable" and no other ssl.* settings)
2556                  * (This is for convenience when defining both IPv4 and IPv6
2557                  *  and desiring to inherit the ssl config from global context
2558                  *  without having to duplicate the directives)*/
2559                 if (count_not_engine
2560                     || (conf.ssl_enabled && NULL == p->ssl_ctxs[0].ssl_ctx)) {
2561                     log_error(srv->errh, __FILE__, __LINE__,
2562                       "ssl.pemfile has to be set in same $SERVER[\"socket\"] scope "
2563                       "as other ssl.* directives, unless only ssl.engine is set, "
2564                       "inheriting ssl.* from global scope");
2565                     rc = HANDLER_ERROR;
2566                     continue;
2567                 }
2568                 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
2569                 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/
2570                 continue;
2571             }
2572             /* PEM file is required */
2573             log_error(srv->errh, __FILE__, __LINE__,
2574               "ssl.pemfile has to be set when ssl.engine = \"enable\"");
2575             rc = HANDLER_ERROR;
2576             continue;
2577         }
2578 
2579         /* configure ssl_ctx for socket */
2580 
2581         /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/
2582         if (0 == network_init_ssl(srv, &conf, p)) {
2583             plugin_ssl_ctx * const s = p->ssl_ctxs + sidx;
2584             s->ssl_ctx = conf.ssl_ctx;
2585         }
2586         else {
2587             SSL_CTX_free(conf.ssl_ctx);
2588             rc = HANDLER_ERROR;
2589         }
2590     }
2591 
2592   #ifdef TLSEXT_TYPE_session_ticket
2593     if (rc == HANDLER_GO_ON && ssl_is_init)
2594         mod_openssl_session_ticket_key_check(p, log_epoch_secs);
2595   #endif
2596 
2597     free(srvplug.cvlist);
2598     return rc;
2599 }
2600 
2601 
2602 SETDEFAULTS_FUNC(mod_openssl_set_defaults)
2603 {
2604     static const config_plugin_keys_t cpk[] = {
2605       { CONST_STR_LEN("ssl.pemfile"),
2606         T_CONFIG_STRING,
2607         T_CONFIG_SCOPE_CONNECTION }
2608      ,{ CONST_STR_LEN("ssl.privkey"),
2609         T_CONFIG_STRING,
2610         T_CONFIG_SCOPE_CONNECTION }
2611      ,{ CONST_STR_LEN("ssl.ca-file"),
2612         T_CONFIG_STRING,
2613         T_CONFIG_SCOPE_CONNECTION }
2614      ,{ CONST_STR_LEN("ssl.ca-dn-file"),
2615         T_CONFIG_STRING,
2616         T_CONFIG_SCOPE_CONNECTION }
2617      ,{ CONST_STR_LEN("ssl.ca-crl-file"),
2618         T_CONFIG_STRING,
2619         T_CONFIG_SCOPE_CONNECTION }
2620      ,{ CONST_STR_LEN("ssl.read-ahead"),
2621         T_CONFIG_BOOL,
2622         T_CONFIG_SCOPE_CONNECTION }
2623      ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"),
2624         T_CONFIG_BOOL,
2625         T_CONFIG_SCOPE_CONNECTION }
2626      ,{ CONST_STR_LEN("ssl.verifyclient.activate"),
2627         T_CONFIG_BOOL,
2628         T_CONFIG_SCOPE_CONNECTION }
2629      ,{ CONST_STR_LEN("ssl.verifyclient.enforce"),
2630         T_CONFIG_BOOL,
2631         T_CONFIG_SCOPE_CONNECTION }
2632      ,{ CONST_STR_LEN("ssl.verifyclient.depth"),
2633         T_CONFIG_SHORT,
2634         T_CONFIG_SCOPE_CONNECTION }
2635      ,{ CONST_STR_LEN("ssl.verifyclient.username"),
2636         T_CONFIG_STRING,
2637         T_CONFIG_SCOPE_CONNECTION }
2638      ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"),
2639         T_CONFIG_BOOL,
2640         T_CONFIG_SCOPE_CONNECTION }
2641      ,{ CONST_STR_LEN("ssl.acme-tls-1"),
2642         T_CONFIG_STRING,
2643         T_CONFIG_SCOPE_CONNECTION }
2644      ,{ CONST_STR_LEN("ssl.stapling-file"),
2645         T_CONFIG_STRING,
2646         T_CONFIG_SCOPE_CONNECTION }
2647      ,{ CONST_STR_LEN("debug.log-ssl-noise"),
2648         T_CONFIG_BOOL,
2649         T_CONFIG_SCOPE_CONNECTION }
2650      ,{ NULL, 0,
2651         T_CONFIG_UNSET,
2652         T_CONFIG_SCOPE_UNSET }
2653     };
2654 
2655     plugin_data * const p = p_d;
2656     p->srv = srv;
2657     p->cafiles = array_init(0);
2658     if (!config_plugin_values_init(srv, p, cpk, "mod_openssl"))
2659         return HANDLER_ERROR;
2660 
2661     const buffer *default_ssl_ca_crl_file = NULL;
2662 
2663     /* process and validate config directives
2664      * (init i to 0 if global context; to 1 to skip empty global context) */
2665     for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) {
2666         config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0];
2667         config_plugin_value_t *pemfile = NULL;
2668         config_plugin_value_t *privkey = NULL;
2669         const buffer *ssl_stapling_file = NULL;
2670         const buffer *ssl_ca_file = NULL;
2671         const buffer *ssl_ca_dn_file = NULL;
2672         const buffer *ssl_ca_crl_file = NULL;
2673         X509_STORE *ca_store = NULL;
2674         for (; -1 != cpv->k_id; ++cpv) {
2675             switch (cpv->k_id) {
2676               case 0: /* ssl.pemfile */
2677                 if (!buffer_string_is_empty(cpv->v.b)) pemfile = cpv;
2678                 break;
2679               case 1: /* ssl.privkey */
2680                 if (!buffer_string_is_empty(cpv->v.b)) privkey = cpv;
2681                 break;
2682               case 2: /* ssl.ca-file */
2683                 if (buffer_string_is_empty(cpv->v.b)) break;
2684                 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
2685                 ssl_ca_file = cpv->v.b;
2686                 cpv->v.v = mod_openssl_load_cacerts(ssl_ca_file, srv->errh);
2687                 if (NULL != cpv->v.v) {
2688                     cpv->vtype = T_CONFIG_LOCAL;
2689                     ca_store = ((plugin_cacerts *)cpv->v.v)->certs;
2690                 }
2691                 else {
2692                     log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2693                       ERR_error_string(ERR_get_error(), NULL),
2694                       ssl_ca_file->ptr);
2695                     return HANDLER_ERROR;
2696                 }
2697                 break;
2698               case 3: /* ssl.ca-dn-file */
2699                 if (buffer_string_is_empty(cpv->v.b)) break;
2700                 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR;
2701                 ssl_ca_dn_file = cpv->v.b;
2702                 cpv->v.v = SSL_load_client_CA_file(ssl_ca_dn_file->ptr);
2703                 if (NULL != cpv->v.v) {
2704                     cpv->vtype = T_CONFIG_LOCAL;
2705                 }
2706                 else {
2707                     log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s",
2708                       ERR_error_string(ERR_get_error(), NULL),
2709                       ssl_ca_dn_file->ptr);
2710                     return HANDLER_ERROR;
2711                 }
2712                 break;
2713               case 4: /* ssl.ca-crl-file */
2714                 if (buffer_string_is_empty(cpv->v.b)) break;
2715                 ssl_ca_crl_file = cpv->v.b;
2716                 if (0 == i) default_ssl_ca_crl_file = cpv->v.b;
2717                 break;
2718               case 5: /* ssl.read-ahead */
2719               case 6: /* ssl.disable-client-renegotiation */
2720               case 7: /* ssl.verifyclient.activate */
2721               case 8: /* ssl.verifyclient.enforce */
2722                 break;
2723               case 9: /* ssl.verifyclient.depth */
2724                 if (cpv->v.shrt > 255) {
2725                     log_error(srv->errh, __FILE__, __LINE__,
2726                       "%s is absurdly large (%hu); limiting to 255",
2727                       cpk[cpv->k_id].k, cpv->v.shrt);
2728                     cpv->v.shrt = 255;
2729                 }
2730                 break;
2731               case 10:/* ssl.verifyclient.username */
2732               case 11:/* ssl.verifyclient.exportcert */
2733               case 12:/* ssl.acme-tls-1 */
2734                 break;
2735               case 13:/* ssl.stapling-file */
2736                 ssl_stapling_file = cpv->v.b;
2737                 break;
2738               case 14:/* debug.log-ssl-noise */
2739                 break;
2740               default:/* should not happen */
2741                 break;
2742             }
2743         }
2744 
2745       #if OPENSSL_VERSION_NUMBER < 0x10002000 /* p->cafiles for legacy only */ \
2746        || defined(LIBRESSL_VERSION_NUMBER)
2747         /* load all ssl.ca-files into a single chain */
2748         /*(certificate load order might matter)*/
2749         if (ssl_ca_dn_file)
2750             array_insert_value(p->cafiles, CONST_BUF_LEN(ssl_ca_dn_file));
2751         if (ssl_ca_file)
2752             array_insert_value(p->cafiles, CONST_BUF_LEN(ssl_ca_file));
2753         UNUSED(ca_store);
2754         UNUSED(ssl_ca_crl_file);
2755         UNUSED(default_ssl_ca_crl_file);
2756       #else
2757         if (NULL == ca_store && ssl_ca_crl_file && i != 0) {
2758             log_error(srv->errh, __FILE__, __LINE__,
2759               "ssl.ca-crl-file (%s) ignored unless issued with ssl.ca-file",
2760               ssl_ca_crl_file->ptr);
2761         }
2762         else if (ca_store && (ssl_ca_crl_file || default_ssl_ca_crl_file)) {
2763             /* prior behavior in lighttpd allowed ssl.ca-crl-file only in global
2764              * scope or $SERVER["socket"], so this inheritence from global scope
2765              * is reasonable.  This code does not implement inheritance of
2766              * ssl.ca-crl-file from $SERVER["socket"] into nested $HTTP["host"],
2767              * but the solution is to repeat ssl.ca-crl-file where ssl.ca-file
2768              * is issued (and to not unnecessarily repeat ssl.ca-file)
2769              * Alternative: write code to load ssl.ca-crl-file into (X509_CRL *)
2770              * using PEM_read_bio_X509_CRL() and in mod_openssl_cert_cb(),
2771              * create a new (X509_STORE *) which merges with CA (X509_STORE *)
2772              * using X509_STORE_add_cert() and X509_STORE_add_crl(), and keeps
2773              * the result in our (plugin_cert *) for reuse */
2774             if (NULL == ssl_ca_crl_file)
2775                 ssl_ca_crl_file = default_ssl_ca_crl_file;
2776             if (!mod_openssl_load_cacrls(ca_store, ssl_ca_crl_file, srv))
2777                 return HANDLER_ERROR;
2778         }
2779       #endif
2780 
2781         if (pemfile) {
2782           #ifdef OPENSSL_NO_TLSEXT
2783             config_cond_info cfginfo;
2784             uint32_t j = (uint32_t)p->cvlist[i].k_id;
2785             config_get_config_cond_info(&cfginfo, j);
2786             if (j > 0 && (COMP_SERVER_SOCKET != cfginfo.comp
2787                           || cfginfo.cond != CONFIG_COND_EQ)) {
2788                 if (COMP_HTTP_HOST == cfginfo.comp)
2789                     log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2790                       "can't use ssl.pemfile with $HTTP[\"host\"], "
2791                       "as openssl version does not support TLS extensions");
2792                 else
2793                     log_error(srv->errh, __FILE__, __LINE__, "SSL:"
2794                       "ssl.pemfile only works in SSL socket binding context "
2795                       "as openssl version does not support TLS extensions");
2796                 return HANDLER_ERROR;
2797             }
2798           #endif
2799             if (NULL == privkey) privkey = pemfile;
2800             pemfile->v.v =
2801               network_openssl_load_pemfile(srv, pemfile->v.b, privkey->v.b,
2802                                            ssl_stapling_file);
2803             if (pemfile->v.v)
2804                 pemfile->vtype = T_CONFIG_LOCAL;
2805             else
2806                 return HANDLER_ERROR;
2807         }
2808     }
2809 
2810     p->defaults.ssl_verifyclient = 0;
2811     p->defaults.ssl_verifyclient_enforce = 1;
2812     p->defaults.ssl_verifyclient_depth = 9;
2813     p->defaults.ssl_verifyclient_export_cert = 0;
2814     p->defaults.ssl_disable_client_renegotiation = 1;
2815     p->defaults.ssl_read_ahead = 0;
2816 
2817     /* initialize p->defaults from global config context */
2818     if (p->nconfig > 0 && p->cvlist->v.u2[1]) {
2819         const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0];
2820         if (-1 != cpv->k_id)
2821             mod_openssl_merge_config(&p->defaults, cpv);
2822     }
2823 
2824     return mod_openssl_set_defaults_sockets(srv, p);
2825 }
2826 
2827 
2828     /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
2829      *
2830      * it has to stay at the same location all the time to satisfy the needs
2831      * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE
2832      *
2833      * buffer is allocated once, is NOT realloced (note: not thread-safe)
2834      *
2835      * (Note: above restriction no longer true since SSL_CTX_set_mode() is
2836      *        called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
2837      * */
2838 
2839             /* copy small mem chunks into single large buffer before SSL_write()
2840              * to reduce number times write() called underneath SSL_write() and
2841              * potentially reduce number of packets generated if TCP_NODELAY */
2842 
2843 
2844 static int
2845 mod_openssl_close_notify(handler_ctx *hctx);
2846 
2847 
2848 static int
2849 connection_write_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
2850 {
2851     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
2852     SSL *ssl = hctx->ssl;
2853     log_error_st * const errh = hctx->errh;
2854 
2855     if (0 != hctx->close_notify) return mod_openssl_close_notify(hctx);
2856 
2857     chunkqueue_remove_finished_chunks(cq);
2858 
2859     while (max_bytes > 0 && !chunkqueue_is_empty(cq)) {
2860         char *data = local_send_buffer;
2861         uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes
2862           ? LOCAL_SEND_BUFSIZE
2863           : (uint32_t)max_bytes;
2864         int wr;
2865 
2866         if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1;
2867 
2868         /**
2869          * SSL_write man-page
2870          *
2871          * WARNING
2872          *        When an SSL_write() operation has to be repeated because of
2873          *        SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be
2874          *        repeated with the same arguments.
2875          */
2876 
2877         ERR_clear_error();
2878         wr = SSL_write(ssl, data, data_len);
2879 
2880         if (hctx->renegotiations > 1
2881             && hctx->conf.ssl_disable_client_renegotiation) {
2882             log_error(errh, __FILE__, __LINE__,
2883               "SSL: renegotiation initiated by client, killing connection");
2884             return -1;
2885         }
2886 
2887         if (wr <= 0) {
2888             int ssl_r;
2889             unsigned long err;
2890 
2891             switch ((ssl_r = SSL_get_error(ssl, wr))) {
2892             case SSL_ERROR_WANT_READ:
2893                 con->is_readable = -1;
2894                 return 0; /* try again later */
2895             case SSL_ERROR_WANT_WRITE:
2896                 con->is_writable = -1;
2897                 return 0; /* try again later */
2898             case SSL_ERROR_SYSCALL:
2899                 /* perhaps we have error waiting in our error-queue */
2900                 if (0 != (err = ERR_get_error())) {
2901                     do {
2902                         log_error(errh, __FILE__, __LINE__,
2903                           "SSL: %d %d %s",ssl_r,wr,ERR_error_string(err,NULL));
2904                     } while((err = ERR_get_error()));
2905                 } else if (wr == -1) {
2906                     /* no, but we have errno */
2907                     switch(errno) {
2908                     case EPIPE:
2909                     case ECONNRESET:
2910                         return -2;
2911                     default:
2912                         log_perror(errh, __FILE__, __LINE__,
2913                           "SSL: %d %d", ssl_r, wr);
2914                         break;
2915                     }
2916                 } else {
2917                     /* neither error-queue nor errno ? */
2918                     log_perror(errh, __FILE__, __LINE__,
2919                       "SSL (error): %d %d", ssl_r, wr);
2920                 }
2921                 break;
2922 
2923             case SSL_ERROR_ZERO_RETURN:
2924                 /* clean shutdown on the remote side */
2925 
2926                 if (wr == 0) return -2;
2927 
2928                 /* fall through */
2929             default:
2930                 while((err = ERR_get_error())) {
2931                     log_error(errh, __FILE__, __LINE__,
2932                       "SSL: %d %d %s", ssl_r, wr, ERR_error_string(err, NULL));
2933                 }
2934                 break;
2935             }
2936             return -1;
2937         }
2938 
2939         chunkqueue_mark_written(cq, wr);
2940         max_bytes -= wr;
2941 
2942         if ((size_t) wr < data_len) break; /* try again later */
2943     }
2944 
2945     return 0;
2946 }
2947 
2948 
2949 static int
2950 connection_read_cq_ssl (connection *con, chunkqueue *cq, off_t max_bytes)
2951 {
2952     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
2953     int len;
2954     char *mem = NULL;
2955     size_t mem_len = 0;
2956 
2957     UNUSED(max_bytes);
2958 
2959     if (0 != hctx->close_notify) return mod_openssl_close_notify(hctx);
2960 
2961     ERR_clear_error();
2962     do {
2963         len = SSL_pending(hctx->ssl);
2964         mem_len = len < 2048 ? 2048 : (size_t)len;
2965         chunk * const ckpt = cq->last;
2966         mem = chunkqueue_get_memory(cq, &mem_len);
2967 
2968         len = SSL_read(hctx->ssl, mem, mem_len);
2969         if (len > 0) {
2970             chunkqueue_use_memory(cq, ckpt, len);
2971             con->bytes_read += len;
2972         } else {
2973             chunkqueue_use_memory(cq, ckpt, 0);
2974         }
2975 
2976         if (hctx->renegotiations > 1
2977             && hctx->conf.ssl_disable_client_renegotiation) {
2978             log_error(hctx->errh, __FILE__, __LINE__,
2979               "SSL: renegotiation initiated by client, killing connection");
2980             return -1;
2981         }
2982 
2983       #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2984         if (hctx->alpn) {
2985             if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) {
2986                 chunkqueue_reset(cq);
2987                 /* initiate handshake in order to send ServerHello.
2988                  * Once TLS handshake is complete, return -1 to result in
2989                  * CON_STATE_ERROR so that socket connection is quickly closed*/
2990                 if (1 == SSL_do_handshake(hctx->ssl)) return -1;
2991                 len = -1;
2992                 break;
2993             }
2994             hctx->alpn = 0;
2995         }
2996       #endif
2997     } while (len > 0
2998              && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0));
2999 
3000     if (len < 0) {
3001         int oerrno = errno;
3002         int rc, ssl_err;
3003         switch ((rc = SSL_get_error(hctx->ssl, len))) {
3004         case SSL_ERROR_WANT_WRITE:
3005             con->is_writable = -1;
3006             /* fall through */
3007         case SSL_ERROR_WANT_READ:
3008             con->is_readable = 0;
3009 
3010             /* the manual says we have to call SSL_read with the same arguments
3011              * next time.  we ignore this restriction; no one has complained
3012              * about it in 1.5 yet, so it probably works anyway.
3013              */
3014 
3015             return 0;
3016         case SSL_ERROR_SYSCALL:
3017             /**
3018              * man SSL_get_error()
3019              *
3020              * SSL_ERROR_SYSCALL
3021              *   Some I/O error occurred.  The OpenSSL error queue may contain
3022              *   more information on the error.  If the error queue is empty
3023              *   (i.e. ERR_get_error() returns 0), ret can be used to find out
3024              *   more about the error: If ret == 0, an EOF was observed that
3025              *   violates the protocol.  If ret == -1, the underlying BIO
3026              *   reported an I/O error (for socket I/O on Unix systems, consult
3027              *   errno for details).
3028              *
3029              */
3030             while((ssl_err = ERR_get_error())) {
3031                 /* get all errors from the error-queue */
3032                 log_error(hctx->errh, __FILE__, __LINE__,
3033                   "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL));
3034             }
3035 
3036             switch(oerrno) {
3037             case ECONNRESET:
3038                 if (!hctx->conf.ssl_log_noise) break;
3039                 /* fall through */
3040             default:
3041                 /* (oerrno should be something like ECONNABORTED not 0
3042                  *  if client disconnected before anything was sent
3043                  *  (e.g. TCP connection probe), but it does not appear
3044                  *  that openssl provides such notification, not even
3045                  *  something like SSL_R_SSL_HANDSHAKE_FAILURE) */
3046                 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise)
3047                     break;
3048 
3049                 log_error(hctx->errh, __FILE__, __LINE__,
3050                   "SSL: %d %d %d %s", len, rc, oerrno, strerror(oerrno));
3051                 break;
3052             }
3053 
3054             break;
3055         case SSL_ERROR_ZERO_RETURN:
3056             /* clean shutdown on the remote side */
3057 
3058             if (rc == 0) {
3059                 /* FIXME: later */
3060             }
3061 
3062             /* fall through */
3063         default:
3064             while((ssl_err = ERR_get_error())) {
3065                 switch (ERR_GET_REASON(ssl_err)) {
3066                 case SSL_R_SSL_HANDSHAKE_FAILURE:
3067               #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
3068                 case SSL_R_UNEXPECTED_EOF_WHILE_READING:
3069               #endif
3070               #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA
3071                 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
3072               #endif
3073               #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN
3074                 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
3075               #endif
3076               #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
3077                 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
3078               #endif
3079                     if (!hctx->conf.ssl_log_noise) continue;
3080                     break;
3081                 default:
3082                     break;
3083                 }
3084                 /* get all errors from the error-queue */
3085                 log_error(hctx->errh, __FILE__, __LINE__,
3086                   "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL));
3087             }
3088             break;
3089         }
3090         return -1;
3091     } else if (len == 0) {
3092         con->is_readable = 0;
3093         /* the other end close the connection -> KEEP-ALIVE */
3094 
3095         return -2;
3096     } else {
3097         return 0;
3098     }
3099 }
3100 
3101 
3102 CONNECTION_FUNC(mod_openssl_handle_con_accept)
3103 {
3104     server_socket *srv_sock = con->srv_socket;
3105     if (!srv_sock->is_ssl) return HANDLER_GO_ON;
3106 
3107     plugin_data *p = p_d;
3108     handler_ctx * const hctx = handler_ctx_init();
3109     request_st * const r = &con->request;
3110     hctx->r = r;
3111     hctx->con = con;
3112     hctx->tmp_buf = con->srv->tmp_buf;
3113     hctx->errh = r->conf.errh;
3114     con->plugin_ctx[p->id] = hctx;
3115 
3116     plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx;
3117     hctx->ssl = SSL_new(s->ssl_ctx);
3118     if (NULL != hctx->ssl
3119         && SSL_set_app_data(hctx->ssl, hctx)
3120         && SSL_set_fd(hctx->ssl, con->fd)) {
3121         SSL_set_accept_state(hctx->ssl);
3122         con->network_read = connection_read_cq_ssl;
3123         con->network_write = connection_write_cq_ssl;
3124         con->proto_default_port = 443; /* "https" */
3125         mod_openssl_patch_config(r, &hctx->conf);
3126         return HANDLER_GO_ON;
3127     }
3128     else {
3129         log_error(r->conf.errh, __FILE__, __LINE__,
3130           "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
3131         return HANDLER_ERROR;
3132     }
3133 }
3134 
3135 
3136 static void
3137 mod_openssl_detach(handler_ctx *hctx)
3138 {
3139     /* step aside from further SSL processing
3140      * (used after handle_connection_shut_wr hook) */
3141     /* future: might restore prior network_read and network_write fn ptrs */
3142     hctx->con->is_ssl_sock = 0;
3143     /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
3144     if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
3145     hctx->close_notify = 1;
3146 }
3147 
3148 
3149 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)
3150 {
3151     plugin_data *p = p_d;
3152     handler_ctx *hctx = con->plugin_ctx[p->id];
3153     if (NULL == hctx) return HANDLER_GO_ON;
3154 
3155     hctx->close_notify = -2;
3156     if (SSL_is_init_finished(hctx->ssl)) {
3157         mod_openssl_close_notify(hctx);
3158     }
3159     else {
3160         mod_openssl_detach(hctx);
3161     }
3162 
3163     return HANDLER_GO_ON;
3164 }
3165 
3166 
3167 static int
3168 mod_openssl_close_notify(handler_ctx *hctx)
3169 {
3170         int ret, ssl_r;
3171         unsigned long err;
3172         log_error_st *errh;
3173 
3174         if (1 == hctx->close_notify) return -2;
3175 
3176         ERR_clear_error();
3177         switch ((ret = SSL_shutdown(hctx->ssl))) {
3178         case 1:
3179             mod_openssl_detach(hctx);
3180             return -2;
3181         case 0:
3182             /* Drain SSL read buffers in case pending records need processing.
3183              * Limit to reading next record to avoid denial of service when CPU
3184              * processing TLS is slower than arrival speed of TLS data packets.
3185              * (unless hctx->conf.ssl_read_ahead is set)
3186              *
3187              * references:
3188              *
3189              * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection"
3190              * https://github.com/openssl/openssl/issues/6262
3191              *
3192              * The peer is still allowed to send data after receiving the
3193              * "close notify" event. If the peer did send data it need to be
3194              * processed by calling SSL_read() before calling SSL_shutdown() a
3195              * second time. SSL_read() will indicate the end of the peer data by
3196              * returning <= 0 and SSL_get_error() returning
3197              * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read()
3198              * between SSL_shutdown() calls.
3199              *
3200              * Additional discussion in "Auto retry in shutdown"
3201              * https://github.com/openssl/openssl/pull/6340
3202              */
3203             ssl_r = SSL_pending(hctx->ssl);
3204             if (ssl_r) {
3205                 do {
3206                     char buf[4096];
3207                     ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf));
3208                 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret)));
3209             }
3210 
3211             ERR_clear_error();
3212             switch ((ret = SSL_shutdown(hctx->ssl))) {
3213             case 1:
3214                 mod_openssl_detach(hctx);
3215                 return -2;
3216             case 0:
3217                 hctx->close_notify = -1;
3218                 return 0;
3219             default:
3220                 break;
3221             }
3222 
3223             /* fall through */
3224         default:
3225 
3226             if (!SSL_is_init_finished(hctx->ssl)) {
3227                 mod_openssl_detach(hctx);
3228                 return -2;
3229             }
3230 
3231             switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) {
3232             case SSL_ERROR_ZERO_RETURN:
3233             case SSL_ERROR_WANT_WRITE:
3234             case SSL_ERROR_WANT_READ:
3235                 hctx->close_notify = -1;
3236                 return 0; /* try again later */
3237             case SSL_ERROR_SYSCALL:
3238                 /* perhaps we have error waiting in our error-queue */
3239                 errh = hctx->r->conf.errh;
3240                 if (0 != (err = ERR_get_error())) {
3241                     do {
3242                         log_error(errh, __FILE__, __LINE__,
3243                           "SSL: %d %d %s",ssl_r,ret,ERR_error_string(err,NULL));
3244                     } while((err = ERR_get_error()));
3245                 } else if (errno != 0) {
3246                     /*ssl bug (see lighttpd ticket #2213): sometimes errno==0*/
3247                     switch(errno) {
3248                     case EPIPE:
3249                     case ECONNRESET:
3250                         break;
3251                     default:
3252                         log_perror(errh, __FILE__, __LINE__,
3253                           "SSL (error): %d %d", ssl_r, ret);
3254                         break;
3255                     }
3256                 }
3257 
3258                 break;
3259             default:
3260                 errh = hctx->r->conf.errh;
3261                 while((err = ERR_get_error())) {
3262                     log_error(errh, __FILE__, __LINE__,
3263                       "SSL: %d %d %s", ssl_r, ret, ERR_error_string(err, NULL));
3264                 }
3265 
3266                 break;
3267             }
3268         }
3269         ERR_clear_error();
3270         hctx->close_notify = -1;
3271         return ret;
3272 }
3273 
3274 
3275 CONNECTION_FUNC(mod_openssl_handle_con_close)
3276 {
3277     plugin_data *p = p_d;
3278     handler_ctx *hctx = con->plugin_ctx[p->id];
3279     if (NULL != hctx) {
3280         con->plugin_ctx[p->id] = NULL;
3281         handler_ctx_free(hctx);
3282     }
3283 
3284     return HANDLER_GO_ON;
3285 }
3286 
3287 
3288 static void
3289 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx)
3290 {
3291     buffer * const tb = r->tmp_buf;
3292     X509 *xs;
3293     X509_NAME *xn;
3294     int i, nentries;
3295 
3296     long vr = SSL_get_verify_result(hctx->ssl);
3297     if (vr != X509_V_OK) {
3298         char errstr[256];
3299         ERR_error_string_n(vr, errstr, sizeof(errstr));
3300         buffer_copy_string_len(tb, CONST_STR_LEN("FAILED:"));
3301         buffer_append_string(tb, errstr);
3302         http_header_env_set(r,
3303                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
3304                             CONST_BUF_LEN(tb));
3305         return;
3306     } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) {
3307         http_header_env_set(r,
3308                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
3309                             CONST_STR_LEN("NONE"));
3310         return;
3311     } else {
3312         http_header_env_set(r,
3313                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
3314                             CONST_STR_LEN("SUCCESS"));
3315     }
3316 
3317     xn = X509_get_subject_name(xs);
3318     {
3319         char buf[256];
3320         int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf));
3321         if (len > 0) {
3322             if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1;
3323             http_header_env_set(r,
3324                                 CONST_STR_LEN("SSL_CLIENT_S_DN"),
3325                                 buf, (size_t)len);
3326         }
3327     }
3328     buffer_copy_string_len(tb, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
3329     for (i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) {
3330         int xobjnid;
3331         const char * xobjsn;
3332         X509_NAME_ENTRY *xe;
3333 
3334         if (!(xe = X509_NAME_get_entry(xn, i))) {
3335             continue;
3336         }
3337         xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe));
3338         xobjsn = OBJ_nid2sn(xobjnid);
3339         if (xobjsn) {
3340             buffer_string_set_length(tb, sizeof("SSL_CLIENT_S_DN_")-1);
3341             buffer_append_string(tb, xobjsn);
3342             http_header_env_set(r,
3343                                 CONST_BUF_LEN(tb),
3344                                 (const char*)X509_NAME_ENTRY_get_data(xe)->data,
3345                                 X509_NAME_ENTRY_get_data(xe)->length);
3346         }
3347     }
3348 
3349     {
3350         ASN1_INTEGER *xsn = X509_get_serialNumber(xs);
3351         BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL);
3352         char *serialHex = BN_bn2hex(serialBN);
3353         http_header_env_set(r,
3354                             CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
3355                             serialHex, strlen(serialHex));
3356         OPENSSL_free(serialHex);
3357         BN_free(serialBN);
3358     }
3359 
3360     if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
3361         /* pick one of the exported values as "REMOTE_USER", for example
3362          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
3363          * or
3364          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
3365          */
3366         const buffer *varname = hctx->conf.ssl_verifyclient_username;
3367         const buffer *vb = http_header_env_get(r, CONST_BUF_LEN(varname));
3368         if (vb) { /* same as http_auth.c:http_auth_setenv() */
3369             http_header_env_set(r,
3370                                 CONST_STR_LEN("REMOTE_USER"),
3371                                 CONST_BUF_LEN(vb));
3372             http_header_env_set(r,
3373                                 CONST_STR_LEN("AUTH_TYPE"),
3374                                 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
3375         }
3376     }
3377 
3378     if (hctx->conf.ssl_verifyclient_export_cert) {
3379         BIO *bio;
3380         if (NULL != (bio = BIO_new(BIO_s_mem()))) {
3381             PEM_write_bio_X509(bio, xs);
3382             const int n = BIO_pending(bio);
3383 
3384             buffer_string_prepare_copy(tb, n);
3385             BIO_read(bio, tb->ptr, n);
3386             BIO_free(bio);
3387             buffer_commit(tb, n);
3388             http_header_env_set(r,
3389                                 CONST_STR_LEN("SSL_CLIENT_CERT"),
3390                                 CONST_BUF_LEN(tb));
3391         }
3392     }
3393     X509_free(xs);
3394 }
3395 
3396 
3397 static void
3398 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx)
3399 {
3400     const char *s;
3401     const SSL_CIPHER *cipher;
3402 
3403     s = SSL_get_version(hctx->ssl);
3404     http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s));
3405 
3406     if ((cipher = SSL_get_current_cipher(hctx->ssl))) {
3407         int usekeysize, algkeysize = 0;
3408         char buf[LI_ITOSTRING_LENGTH];
3409         s = SSL_CIPHER_get_name(cipher);
3410         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s));
3411         usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize);
3412         if (0 == algkeysize) algkeysize = usekeysize;
3413         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
3414                             buf, li_itostrn(buf, sizeof(buf), usekeysize));
3415         http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
3416                             buf, li_itostrn(buf, sizeof(buf), algkeysize));
3417     }
3418 }
3419 
3420 
3421 REQUEST_FUNC(mod_openssl_handle_request_env)
3422 {
3423     plugin_data *p = p_d;
3424     /* simple flag for request_env_patched */
3425     if (r->plugin_ctx[p->id]) return HANDLER_GO_ON;
3426     handler_ctx *hctx = r->con->plugin_ctx[p->id];
3427     if (NULL == hctx) return HANDLER_GO_ON;
3428     r->plugin_ctx[p->id] = (void *)(uintptr_t)1u;
3429 
3430     http_cgi_ssl_env(r, hctx);
3431     if (hctx->conf.ssl_verifyclient) {
3432         https_add_ssl_client_entries(r, hctx);
3433     }
3434 
3435     return HANDLER_GO_ON;
3436 }
3437 
3438 
3439 REQUEST_FUNC(mod_openssl_handle_uri_raw)
3440 {
3441     /* mod_openssl must be loaded prior to mod_auth
3442      * if mod_openssl is configured to set REMOTE_USER based on client cert */
3443     /* mod_openssl must be loaded after mod_extforward
3444      * if mod_openssl config is based on lighttpd.conf remote IP conditional
3445      * using remote IP address set by mod_extforward, *unless* PROXY protocol
3446      * is enabled with extforward.hap-PROXY = "enable", in which case the
3447      * reverse is true: mod_extforward must be loaded after mod_openssl */
3448     plugin_data *p = p_d;
3449     handler_ctx *hctx = r->con->plugin_ctx[p->id];
3450     if (NULL == hctx) return HANDLER_GO_ON;
3451 
3452     mod_openssl_patch_config(r, &hctx->conf);
3453     if (hctx->conf.ssl_verifyclient) {
3454         mod_openssl_handle_request_env(r, p);
3455     }
3456 
3457     return HANDLER_GO_ON;
3458 }
3459 
3460 
3461 REQUEST_FUNC(mod_openssl_handle_request_reset)
3462 {
3463     plugin_data *p = p_d;
3464     r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */
3465     return HANDLER_GO_ON;
3466 }
3467 
3468 
3469 TRIGGER_FUNC(mod_openssl_handle_trigger) {
3470     const plugin_data * const p = p_d;
3471     const time_t cur_ts = log_epoch_secs;
3472     if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/
3473     UNUSED(srv);
3474     UNUSED(p);
3475 
3476   #ifdef TLSEXT_TYPE_session_ticket
3477     mod_openssl_session_ticket_key_check(p, cur_ts);
3478   #endif
3479 
3480   #ifndef OPENSSL_NO_OCSP
3481     mod_openssl_refresh_stapling_files(srv, p, cur_ts);
3482   #endif
3483 
3484     return HANDLER_GO_ON;
3485 }
3486 
3487 
3488 int mod_openssl_plugin_init (plugin *p);
3489 int mod_openssl_plugin_init (plugin *p)
3490 {
3491     p->version      = LIGHTTPD_VERSION_ID;
3492     p->name         = "openssl";
3493     p->init         = mod_openssl_init;
3494     p->cleanup      = mod_openssl_free;
3495     p->priv_defaults= mod_openssl_set_defaults;
3496 
3497     p->handle_connection_accept  = mod_openssl_handle_con_accept;
3498     p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr;
3499     p->handle_connection_close   = mod_openssl_handle_con_close;
3500     p->handle_uri_raw            = mod_openssl_handle_uri_raw;
3501     p->handle_request_env        = mod_openssl_handle_request_env;
3502     p->handle_request_reset      = mod_openssl_handle_request_reset;
3503     p->handle_trigger            = mod_openssl_handle_trigger;
3504 
3505     return 0;
3506 }
3507 
3508 
3509 #if defined(BORINGSSL_API_VERSION) \
3510  || defined(LIBRESSL_VERSION_NUMBER)
3511 
3512 static int
3513 mod_openssl_ssl_conf_proto_val (server *srv, plugin_config_socket *s, const buffer *b, int max)
3514 {
3515     if (NULL == b) /* default: min TLSv1.2, max TLSv1.3 */
3516       #ifdef TLS1_3_VERSION
3517         return max ? TLS1_3_VERSION : TLS1_2_VERSION;
3518       #else
3519         return TLS1_2_VERSION;
3520       #endif
3521     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("None"))) /*"disable" limit*/
3522         return max
3523           ?
3524            #ifdef TLS1_3_VERSION
3525             TLS1_3_VERSION
3526            #else
3527             TLS1_2_VERSION
3528            #endif
3529           : (s->ssl_use_sslv3 ? SSL3_VERSION : TLS1_VERSION);
3530     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("SSLv3")))
3531         return SSL3_VERSION;
3532     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.0")))
3533         return TLS1_VERSION;
3534     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.1")))
3535         return TLS1_1_VERSION;
3536     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.2")))
3537         return TLS1_2_VERSION;
3538   #ifdef TLS1_3_VERSION
3539     else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3")))
3540         return TLS1_3_VERSION;
3541   #endif
3542     else {
3543         if (buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1"))
3544             || buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1.2")))
3545             log_error(srv->errh, __FILE__, __LINE__,
3546                       "SSL: ssl.openssl.ssl-conf-cmd %s %s ignored",
3547                       max ? "MaxProtocol" : "MinProtocol", b->ptr);
3548         else
3549             log_error(srv->errh, __FILE__, __LINE__,
3550                       "SSL: ssl.openssl.ssl-conf-cmd %s %s invalid; ignored",
3551                       max ? "MaxProtocol" : "MinProtocol", b->ptr);
3552     }
3553   #ifdef TLS1_3_VERSION
3554     return max ? TLS1_3_VERSION : TLS1_2_VERSION;
3555   #else
3556     return TLS1_2_VERSION;
3557   #endif
3558 }
3559 
3560 
3561 static int
3562 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s)
3563 {
3564     /* reference:
3565      * https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html */
3566     int rc = 0;
3567     buffer *cipherstring = NULL;
3568     /*buffer *ciphersuites = NULL;*/
3569     buffer *minb = NULL;
3570     buffer *maxb = NULL;
3571     buffer *curves = NULL;
3572 
3573     for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
3574         data_string *ds = (data_string *)s->ssl_conf_cmd->data[i];
3575         if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString")))
3576             cipherstring = &ds->value;
3577       #if 0
3578         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites")))
3579             ciphersuites = &ds->value;
3580       #endif
3581         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves"))
3582               || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups")))
3583             curves = &ds->value;
3584         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol")))
3585             maxb = &ds->value;
3586         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol")))
3587             minb = &ds->value;
3588         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) {
3589             /* openssl config for Protocol=... is complex and deprecated */
3590             log_error(srv->errh, __FILE__, __LINE__,
3591                       "SSL: ssl.openssl.ssl-conf-cmd %s ignored; "
3592                       "use MinProtocol=... and MaxProtocol=... instead",
3593                       ds->key.ptr);
3594         }
3595         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) {
3596             for (char *v = ds->value.ptr, *e; *v; v = e) {
3597                 while (*v == ' ' || *v == '\t' || *v == ',') ++v;
3598                 int flag = 1;
3599                 if (*v == '-') {
3600                     flag = 0;
3601                     ++v;
3602                 }
3603                 for (e = v; light_isalpha(*e); ++e) ;
3604                 switch ((int)(e-v)) {
3605                   case 11:
3606                     if (buffer_eq_icase_ssn(v, "Compression", 11)) {
3607                         if (flag)
3608                             SSL_CTX_clear_options(s->ssl_ctx,
3609                                                   SSL_OP_NO_COMPRESSION);
3610                         else
3611                             SSL_CTX_set_options(s->ssl_ctx,
3612                                                 SSL_OP_NO_COMPRESSION);
3613                         continue;
3614                     }
3615                     break;
3616                   case 13:
3617                     if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) {
3618                         if (flag)
3619                             SSL_CTX_clear_options(s->ssl_ctx,
3620                                                   SSL_OP_NO_TICKET);
3621                         else
3622                             SSL_CTX_set_options(s->ssl_ctx,
3623                                                 SSL_OP_NO_TICKET);
3624                         continue;
3625                     }
3626                     break;
3627                   case 16:
3628                     if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) {
3629                         if (flag)
3630                             SSL_CTX_set_options(s->ssl_ctx,
3631                                                SSL_OP_CIPHER_SERVER_PREFERENCE);
3632                         else
3633                             SSL_CTX_clear_options(s->ssl_ctx,
3634                                                SSL_OP_CIPHER_SERVER_PREFERENCE);
3635                         s->ssl_honor_cipher_order = flag;
3636                         continue;
3637                     }
3638                     break;
3639                   default:
3640                     break;
3641                 }
3642                 /* warn if not explicitly handled or ignored above */
3643                 if (!flag) --v;
3644                 log_error(srv->errh, __FILE__, __LINE__,
3645                           "SSL: ssl.openssl.ssl-conf-cmd Options %.*s "
3646                           "ignored", (int)(e-v), v);
3647             }
3648         }
3649       #if 0
3650         else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) {
3651         }
3652       #endif
3653         else {
3654             /* warn if not explicitly handled or ignored above */
3655             log_error(srv->errh, __FILE__, __LINE__,
3656                       "SSL: ssl.openssl.ssl-conf-cmd %s ignored",
3657                       ds->key.ptr);
3658         }
3659 
3660     }
3661 
3662     if (minb) {
3663         int n = mod_openssl_ssl_conf_proto_val(srv, s, minb, 0);
3664         if (!SSL_CTX_set_min_proto_version(s->ssl_ctx, n))
3665             rc = -1;
3666     }
3667 
3668     if (maxb) {
3669         int x = mod_openssl_ssl_conf_proto_val(srv, s, maxb, 1);
3670         if (!SSL_CTX_set_max_proto_version(s->ssl_ctx, x))
3671             rc = -1;
3672     }
3673 
3674     if (!buffer_string_is_empty(cipherstring)) {
3675         /* Disable support for low encryption ciphers */
3676         buffer_append_string_len(cipherstring,
3677                                  CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
3678         if (SSL_CTX_set_cipher_list(s->ssl_ctx, s->ssl_cipher_list->ptr) != 1) {
3679             log_error(srv->errh, __FILE__, __LINE__,
3680               "SSL: %s", ERR_error_string(ERR_get_error(), NULL));
3681             rc = -1;
3682         }
3683 
3684         if (s->ssl_honor_cipher_order)
3685             SSL_CTX_set_options(s->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
3686     }
3687 
3688     if (curves) {
3689         if (!mod_openssl_ssl_conf_curves(srv, s, curves))
3690             rc = -1;
3691     }
3692 
3693     return rc;
3694 }
3695 
3696 #endif /* BORINGSSL_API_VERSION || LIBRESSL_VERSION_NUMBER */
3697