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