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