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