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