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