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