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