xref: /lighttpd1.4/src/mod_openssl.c (revision 49e9f0ac)
1 #include "first.h"
2 
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
6 
7 #ifndef USE_OPENSSL_KERBEROS
8 #ifndef OPENSSL_NO_KRB5
9 #define OPENSSL_NO_KRB5
10 #endif
11 #endif
12 
13 #include "sys-crypto.h"
14 
15 #include <openssl/ssl.h>
16 #include <openssl/bio.h>
17 #include <openssl/bn.h>
18 #include <openssl/err.h>
19 #include <openssl/objects.h>
20 #include <openssl/pem.h>
21 #include <openssl/rand.h>
22 #ifndef OPENSSL_NO_DH
23 #include <openssl/dh.h>
24 #endif
25 
26 #if ! defined OPENSSL_NO_TLSEXT && ! defined SSL_CTRL_SET_TLSEXT_HOSTNAME
27 #define OPENSSL_NO_TLSEXT
28 #endif
29 
30 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
31 #ifndef OPENSSL_NO_ECDH
32 #include <openssl/ecdh.h>
33 #endif
34 #endif
35 
36 #include "base.h"
37 #include "http_header.h"
38 #include "log.h"
39 #include "plugin.h"
40 
41 typedef struct {
42     SSL_CTX *ssl_ctx; /* not patched */
43     /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */
44     EVP_PKEY *ssl_pemfile_pkey;
45     X509 *ssl_pemfile_x509;
46     STACK_OF(X509_NAME) *ssl_ca_file_cert_names;
47 
48     unsigned short ssl_verifyclient;
49     unsigned short ssl_verifyclient_enforce;
50     unsigned short ssl_verifyclient_depth;
51     unsigned short ssl_verifyclient_export_cert;
52     buffer *ssl_verifyclient_username;
53 
54     unsigned short ssl_disable_client_renegotiation;
55     unsigned short ssl_read_ahead;
56     unsigned short ssl_log_noise;
57 
58     /*(used only during startup; not patched)*/
59     unsigned short ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */
60     unsigned short ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */
61     unsigned short ssl_empty_fragments; /* whether to not set SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS */
62     unsigned short ssl_use_sslv2;
63     unsigned short ssl_use_sslv3;
64     buffer *ssl_pemfile;
65     buffer *ssl_privkey;
66     buffer *ssl_ca_file;
67     buffer *ssl_ca_crl_file;
68     buffer *ssl_ca_dn_file;
69     buffer *ssl_cipher_list;
70     buffer *ssl_dh_file;
71     buffer *ssl_ec_curve;
72     array *ssl_conf_cmd;
73     buffer *ssl_acme_tls_1;
74 } plugin_config;
75 
76 typedef struct {
77     PLUGIN_DATA;
78     plugin_config **config_storage;
79 } plugin_data;
80 
81 static int ssl_is_init;
82 /* need assigned p->id for deep access of module handler_ctx for connection
83  *   i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */
84 static plugin_data *plugin_data_singleton;
85 #define LOCAL_SEND_BUFSIZE (16 * 1024)
86 static char *local_send_buffer;
87 
88 typedef struct {
89     SSL *ssl;
90     connection *con;
91     short renegotiations; /* count of SSL_CB_HANDSHAKE_START */
92     short close_notify;
93     unsigned short request_env_patched;
94     unsigned short alpn;
95     plugin_config conf;
96     server *srv;
97 } handler_ctx;
98 
99 
100 static handler_ctx *
101 handler_ctx_init (void)
102 {
103     handler_ctx *hctx = calloc(1, sizeof(*hctx));
104     force_assert(hctx);
105     return hctx;
106 }
107 
108 
109 static void
110 handler_ctx_free (handler_ctx *hctx)
111 {
112     if (hctx->ssl) SSL_free(hctx->ssl);
113     free(hctx);
114 }
115 
116 
117 INIT_FUNC(mod_openssl_init)
118 {
119     plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data));
120   #ifdef DEBUG_WOLFSSL
121     wolfSSL_Debugging_ON();
122   #endif
123     return plugin_data_singleton;
124 }
125 
126 
127 FREE_FUNC(mod_openssl_free)
128 {
129     plugin_data *p = p_d;
130     if (!p) return HANDLER_GO_ON;
131 
132     if (p->config_storage) {
133         for (size_t i = 0; i < srv->config_context->used; ++i) {
134             plugin_config *s = p->config_storage[i];
135             int copy;
136             if (NULL == s) continue;
137             copy = s->ssl_enabled && buffer_string_is_empty(s->ssl_pemfile);
138             buffer_free(s->ssl_pemfile);
139             buffer_free(s->ssl_privkey);
140             buffer_free(s->ssl_ca_file);
141             buffer_free(s->ssl_ca_crl_file);
142             buffer_free(s->ssl_ca_dn_file);
143             buffer_free(s->ssl_cipher_list);
144             buffer_free(s->ssl_dh_file);
145             buffer_free(s->ssl_ec_curve);
146             buffer_free(s->ssl_verifyclient_username);
147             array_free(s->ssl_conf_cmd);
148             buffer_free(s->ssl_acme_tls_1);
149 
150             if (copy) continue;
151             SSL_CTX_free(s->ssl_ctx);
152             EVP_PKEY_free(s->ssl_pemfile_pkey);
153             X509_free(s->ssl_pemfile_x509);
154             if (NULL != s->ssl_ca_file_cert_names)
155                 sk_X509_NAME_pop_free(s->ssl_ca_file_cert_names,X509_NAME_free);
156         }
157         for (size_t i = 0; i < srv->config_context->used; ++i) {
158             plugin_config *s = p->config_storage[i];
159             if (NULL == s) continue;
160 
161             free(s);
162         }
163         free(p->config_storage);
164     }
165 
166     if (ssl_is_init) {
167       #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
168        && !defined(LIBRESSL_VERSION_NUMBER)
169         /*(OpenSSL libraries handle thread init and deinit)
170          * https://github.com/openssl/openssl/pull/1048 */
171       #else
172         CRYPTO_cleanup_all_ex_data();
173         ERR_free_strings();
174        #if OPENSSL_VERSION_NUMBER >= 0x10000000L
175         ERR_remove_thread_state(NULL);
176        #else
177         ERR_remove_state(0);
178        #endif
179         EVP_cleanup();
180       #endif
181 
182         free(local_send_buffer);
183     }
184 
185     free(p);
186 
187     return HANDLER_GO_ON;
188 }
189 
190 
191 static int
192 safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
193 {
194     BIO *bio = BIO_new(BIO_s_mem());
195     if (bio) {
196         int len = X509_NAME_print_ex(bio, name, 0, XN_FLAG_ONELINE);
197         BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/
198         BIO_free(bio);
199         return len; /*return value has similar semantics to that of snprintf()*/
200     }
201     else {
202         buf[0] = '\0';
203         return -1;
204     }
205 }
206 
207 
208 static void
209 ssl_info_callback (const SSL *ssl, int where, int ret)
210 {
211     UNUSED(ret);
212 
213     if (0 != (where & SSL_CB_HANDSHAKE_START)) {
214         handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
215         if (hctx->renegotiations >= 0) ++hctx->renegotiations;
216     }
217   #ifdef TLS1_3_VERSION
218     /* https://github.com/openssl/openssl/issues/5721
219      * "TLSv1.3 unexpected InfoCallback after handshake completed" */
220     if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
221         /* SSL_version() is valid after initial handshake completed */
222         if (SSL_version(ssl) >= TLS1_3_VERSION) {
223             /* https://wiki.openssl.org/index.php/TLS1.3
224              * "Renegotiation is not possible in a TLSv1.3 connection" */
225             handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
226             hctx->renegotiations = -1;
227         }
228     }
229   #endif
230 }
231 
232 /* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */
233 static int
234 verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
235 {
236     char buf[256];
237     X509 *err_cert;
238     int err, depth;
239     SSL *ssl;
240     handler_ctx *hctx;
241     server *srv;
242 
243     err = X509_STORE_CTX_get_error(ctx);
244     depth = X509_STORE_CTX_get_error_depth(ctx);
245 
246     /*
247      * Retrieve the pointer to the SSL of the connection currently treated
248      * and the application specific data stored into the SSL object.
249      */
250     ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
251     hctx = (handler_ctx *) SSL_get_app_data(ssl);
252     srv = hctx->srv;
253 
254     /*
255      * Catch a too long certificate chain. The depth limit set using
256      * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
257      * that whenever the "depth>verify_depth" condition is met, we
258      * have violated the limit and want to log this error condition.
259      * We must do it here, because the CHAIN_TOO_LONG error would not
260      * be found explicitly; only errors introduced by cutting off the
261      * additional certificates would be logged.
262      */
263     if (depth > hctx->conf.ssl_verifyclient_depth) {
264         preverify_ok = 0;
265         err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
266         X509_STORE_CTX_set_error(ctx, err);
267     }
268 
269     if (preverify_ok && 0 == depth
270         && !buffer_string_is_empty(hctx->conf.ssl_ca_dn_file)
271         && !buffer_string_is_empty(hctx->conf.ssl_ca_file)) {
272         /* verify that client cert is issued by CA in ssl.ca-dn-file
273          * if both ssl.ca-dn-file and ssl.ca-file were configured */
274         STACK_OF(X509_NAME) * const names = hctx->conf.ssl_ca_file_cert_names;
275         X509_NAME *issuer;
276       #if OPENSSL_VERSION_NUMBER >= 0x10002000L
277         err_cert = X509_STORE_CTX_get_current_cert(ctx);
278       #else
279         err_cert = ctx->current_cert;
280       #endif
281         if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
282         issuer = X509_get_issuer_name(err_cert);
283       #if 0 /*(?desirable/undesirable to have ssl_ca_file_cert_names sorted?)*/
284         if (-1 != sk_X509_NAME_find(names, issuer))
285             return preverify_ok; /* match */
286       #else
287         for (int i = 0, len = sk_X509_NAME_num(names); i < len; ++i) {
288             if (0 == X509_NAME_cmp(sk_X509_NAME_value(names, i), issuer))
289                 return preverify_ok; /* match */
290         }
291       #endif
292 
293         preverify_ok = 0;
294         err = X509_V_ERR_CERT_REJECTED;
295         X509_STORE_CTX_set_error(ctx, err);
296     }
297 
298     if (preverify_ok) {
299         return preverify_ok;
300     }
301 
302   #if OPENSSL_VERSION_NUMBER >= 0x10002000L
303     err_cert = X509_STORE_CTX_get_current_cert(ctx);
304   #else
305     err_cert = ctx->current_cert;
306   #endif
307     if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce;
308     safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf));
309     log_error_write(srv, __FILE__, __LINE__, "SDSSSDSS",
310                         "SSL: verify error:num=", err, ":",
311                         X509_verify_cert_error_string(err), ":depth=", depth,
312                         ":subject=", buf);
313 
314     /*
315      * At this point, err contains the last verification error. We can use
316      * it for something special
317      */
318     if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY ||
319                           err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
320         safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf));
321         log_error_write(srv, __FILE__, __LINE__, "SS", "SSL: issuer=", buf);
322     }
323 
324     return !hctx->conf.ssl_verifyclient_enforce;
325 }
326 
327 #ifndef OPENSSL_NO_TLSEXT
328 static int mod_openssl_patch_connection (server *srv, connection *con, handler_ctx *hctx);
329 
330 static int
331 network_ssl_servername_callback (SSL *ssl, int *al, server *srv)
332 {
333     const char *servername;
334     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
335     connection *con = hctx->con;
336     size_t len;
337     UNUSED(al);
338 
339     buffer_copy_string(con->uri.scheme, "https");
340 
341     servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
342     if (NULL == servername) {
343 #if 0
344         /* this "error" just means the client didn't support it */
345         log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
346                 "failed to get TLS server name");
347 #endif
348         return SSL_TLSEXT_ERR_NOACK;
349     }
350     len = strlen(servername);
351     if (len >= 1024) { /*(expecting < 256)*/
352         log_error_write(srv, __FILE__, __LINE__, "sss", "SSL:",
353                         "SNI name too long", servername);
354         return SSL_TLSEXT_ERR_ALERT_FATAL;
355     }
356     /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
357     buffer_copy_string_len(con->uri.authority, servername, len);
358     buffer_to_lower(con->uri.authority);
359   #if 0
360     /*(con->uri.authority used below for configuration before request read;
361      * revisit for h2)*/
362     if (0 != http_request_host_policy(con, con->uri.authority, con->uri.scheme))
363         return SSL_TLSEXT_ERR_ALERT_FATAL;
364   #endif
365 
366     con->conditional_is_valid[COMP_HTTP_SCHEME] = 1;
367     con->conditional_is_valid[COMP_HTTP_HOST] = 1;
368     mod_openssl_patch_connection(srv, con, hctx);
369     /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
370     /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
371     /*config_cond_cache_reset_item(con, COMP_HTTP_HOST);*/
372     /*buffer_clear(con->uri.authority);*/
373 
374     if (NULL == hctx->conf.ssl_pemfile_x509
375         || NULL == hctx->conf.ssl_pemfile_pkey) {
376         /* x509/pkey available <=> pemfile was set <=> pemfile got patched:
377          * so this should never happen, unless you nest $SERVER["socket"] */
378         log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
379                         "no certificate/private key for TLS server name",
380                         con->uri.authority);
381         return SSL_TLSEXT_ERR_ALERT_FATAL;
382     }
383 
384     /* first set certificate!
385      * setting private key checks whether certificate matches it */
386     if (1 != SSL_use_certificate(ssl, hctx->conf.ssl_pemfile_x509)) {
387         log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
388                         "failed to set certificate for TLS server name",
389                         con->uri.authority,
390                         ERR_error_string(ERR_get_error(), NULL));
391         return SSL_TLSEXT_ERR_ALERT_FATAL;
392     }
393 
394     if (1 != SSL_use_PrivateKey(ssl, hctx->conf.ssl_pemfile_pkey)) {
395         log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
396                         "failed to set private key for TLS server name",
397                         con->uri.authority,
398                         ERR_error_string(ERR_get_error(), NULL));
399         return SSL_TLSEXT_ERR_ALERT_FATAL;
400     }
401 
402     if (hctx->conf.ssl_verifyclient) {
403         int mode;
404         if (NULL == hctx->conf.ssl_ca_file_cert_names) {
405             log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
406                             "can't verify client without ssl.ca-file "
407                             "or ssl.ca-dn-file for TLS server name",
408                             con->uri.authority,
409                             ERR_error_string(ERR_get_error(), NULL));
410             return SSL_TLSEXT_ERR_ALERT_FATAL;
411         }
412 
413         SSL_set_client_CA_list(
414           ssl, SSL_dup_CA_list(hctx->conf.ssl_ca_file_cert_names));
415         /* forcing verification here is really not that useful
416          * -- a client could just connect without SNI */
417         mode = SSL_VERIFY_PEER;
418         if (hctx->conf.ssl_verifyclient_enforce) {
419             mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
420         }
421         SSL_set_verify(ssl, mode, verify_callback);
422         SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
423     } else {
424         SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
425     }
426 
427     return SSL_TLSEXT_ERR_OK;
428 }
429 #endif
430 
431 
432 static X509 *
433 x509_load_pem_file (server *srv, const char *file)
434 {
435     BIO *in;
436     X509 *x = NULL;
437 
438     in = BIO_new(BIO_s_file());
439     if (NULL == in) {
440         log_error_write(srv, __FILE__, __LINE__, "S",
441                         "SSL: BIO_new(BIO_s_file()) failed");
442         goto error;
443     }
444 
445     if (BIO_read_filename(in,file) <= 0) {
446         log_error_write(srv, __FILE__, __LINE__, "SSS",
447                         "SSL: BIO_read_filename('", file,"') failed");
448         goto error;
449     }
450 
451     x = PEM_read_bio_X509(in, NULL, NULL, NULL);
452     if (NULL == x) {
453         log_error_write(srv, __FILE__, __LINE__, "SSS",
454                         "SSL: couldn't read X509 certificate from '", file,"'");
455         goto error;
456     }
457 
458     BIO_free(in);
459     return x;
460 
461 error:
462     if (NULL != in) BIO_free(in);
463     return NULL;
464 }
465 
466 
467 static EVP_PKEY *
468 evp_pkey_load_pem_file (server *srv, const char *file)
469 {
470     BIO *in;
471     EVP_PKEY *x = NULL;
472 
473     in = BIO_new(BIO_s_file());
474     if (NULL == in) {
475         log_error_write(srv, __FILE__, __LINE__, "s",
476                         "SSL: BIO_new(BIO_s_file()) failed");
477         goto error;
478     }
479 
480     if (BIO_read_filename(in,file) <= 0) {
481         log_error_write(srv, __FILE__, __LINE__, "SSS",
482                         "SSL: BIO_read_filename('", file,"') failed");
483         goto error;
484     }
485 
486     x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
487     if (NULL == x) {
488         log_error_write(srv, __FILE__, __LINE__, "SSS",
489                         "SSL: couldn't read private key from '", file,"'");
490         goto error;
491     }
492 
493     BIO_free(in);
494     return x;
495 
496 error:
497     if (NULL != in) BIO_free(in);
498     return NULL;
499 }
500 
501 
502 static int
503 network_openssl_load_pemfile (server *srv, plugin_config *s, size_t ndx)
504 {
505   #ifdef OPENSSL_NO_TLSEXT
506     data_config *dc = (data_config *)srv->config_context->data[ndx];
507     if ((ndx > 0 && (COMP_SERVER_SOCKET != dc->comp
508                      || dc->cond != CONFIG_COND_EQ)) || !s->ssl_enabled) {
509         log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
510                         "ssl.pemfile only works in SSL socket binding context "
511                         "as openssl version does not support TLS extensions");
512         return -1;
513     }
514   #else
515     UNUSED(ndx);
516   #endif
517 
518     s->ssl_pemfile_x509 = x509_load_pem_file(srv, s->ssl_pemfile->ptr);
519     if (NULL == s->ssl_pemfile_x509) return -1;
520     s->ssl_pemfile_pkey = !buffer_string_is_empty(s->ssl_privkey)
521       ? evp_pkey_load_pem_file(srv, s->ssl_privkey->ptr)
522       : evp_pkey_load_pem_file(srv, s->ssl_pemfile->ptr);
523     if (NULL == s->ssl_pemfile_pkey) return -1;
524 
525     if (!X509_check_private_key(s->ssl_pemfile_x509, s->ssl_pemfile_pkey)) {
526         log_error_write(srv, __FILE__, __LINE__, "sssbb", "SSL:",
527                         "Private key does not match the certificate public key,"
528                         " reason:", ERR_error_string(ERR_get_error(), NULL),
529                         s->ssl_pemfile, s->ssl_privkey);
530         return -1;
531     }
532 
533     return 0;
534 }
535 
536 
537 #ifndef OPENSSL_NO_TLSEXT
538 
539 #if OPENSSL_VERSION_NUMBER >= 0x10002000
540 
541 static int
542 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
543 {
544     server *srv = hctx->srv;
545     buffer *b = srv->tmp_buf;
546     buffer *name = hctx->con->uri.authority;
547     X509 *ssl_pemfile_x509 = NULL;
548     EVP_PKEY *ssl_pemfile_pkey = NULL;
549     size_t len;
550     int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
551 
552     /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
553     if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
554         return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
555     buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
556     buffer_append_slash(b);
557 
558     /* check if SNI set server name (required for acme-tls/1 protocol)
559      * and perform simple path checks for no '/'
560      * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
561     if (buffer_string_is_empty(name))   return rc;
562     if (NULL != strchr(name->ptr, '/')) return rc;
563     if (name->ptr[0] == '.')            return rc;
564   #if 0
565     if (0 != http_request_host_policy(hctx->con, name, hctx->con->uri.scheme))
566         return rc;
567   #endif
568     buffer_append_string_buffer(b, name);
569     len = buffer_string_length(b);
570 
571     do {
572         buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
573         ssl_pemfile_x509 = x509_load_pem_file(srv, b->ptr);
574         if (NULL == ssl_pemfile_x509) {
575             log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
576                             "Failed to load acme-tls/1 pemfile:", b);
577             break;
578         }
579 
580         buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
581         buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
582         ssl_pemfile_pkey = evp_pkey_load_pem_file(srv, b->ptr);
583         if (NULL == ssl_pemfile_pkey) {
584             log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
585                             "Failed to load acme-tls/1 pemfile:", b);
586             break;
587         }
588 
589       #if 0 /* redundant with below? */
590         if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
591             log_error_write(srv, __FILE__, __LINE__, "sssb", "SSL:",
592                "Private key does not match acme-tls/1 certificate public key,"
593                " reason:" ERR_error_string(ERR_get_error(), NULL), b);
594             break;
595         }
596       #endif
597 
598         /* first set certificate!
599          * setting private key checks whether certificate matches it */
600         if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
601             log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
602               "failed to set acme-tls/1 certificate for TLS server name",
603               name, ERR_error_string(ERR_get_error(), NULL));
604             break;
605         }
606 
607         if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
608             log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
609               "failed to set acme-tls/1 private key for TLS server name",
610               name, ERR_error_string(ERR_get_error(), NULL));
611             break;
612         }
613 
614         rc = SSL_TLSEXT_ERR_OK;
615     } while (0);
616 
617     if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
618     if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
619 
620     return rc;
621 }
622 
623 enum {
624   MOD_OPENSSL_ALPN_HTTP11      = 1
625  ,MOD_OPENSSL_ALPN_HTTP10      = 2
626  ,MOD_OPENSSL_ALPN_H2          = 3
627  ,MOD_OPENSSL_ALPN_ACME_TLS_1  = 4
628 };
629 
630 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
631 static int
632 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
633 {
634     handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
635     unsigned short proto;
636     UNUSED(arg);
637 
638     for (unsigned int i = 0, n; i < inlen; i += n) {
639         n = in[i++];
640         if (i+n > inlen) break;
641         switch (n) {
642          #if 0
643           case 2:  /* "h2" */
644             if (in[i] == 'h' && in[i+1] == '2') {
645                 proto = MOD_OPENSSL_ALPN_H2;
646                 break;
647             }
648             continue;
649          #endif
650           case 8:  /* "http/1.1" "http/1.0" */
651             if (0 == memcmp(in+i, "http/1.", 7)) {
652                 if (in[i+7] == '1') {
653                     proto = MOD_OPENSSL_ALPN_HTTP11;
654                     break;
655                 }
656                 if (in[i+7] == '0') {
657                     proto = MOD_OPENSSL_ALPN_HTTP10;
658                     break;
659                 }
660             }
661             continue;
662           case 10: /* "acme-tls/1" */
663             if (0 == memcmp(in+i, "acme-tls/1", 10)) {
664                 int rc = mod_openssl_acme_tls_1(ssl, hctx);
665                 if (rc == SSL_TLSEXT_ERR_OK) {
666                     proto = MOD_OPENSSL_ALPN_ACME_TLS_1;
667                     break;
668                 }
669                 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */
670                 if (rc == SSL_TLSEXT_ERR_NOACK) continue;
671                 return rc;
672             }
673             continue;
674           default:
675             continue;
676         }
677 
678         hctx->alpn = proto;
679         *out = in+i;
680         *outlen = n;
681         return SSL_TLSEXT_ERR_OK;
682     }
683 
684   #if OPENSSL_VERSION_NUMBER < 0x10100000L
685     return SSL_TLSEXT_ERR_NOACK;
686   #else
687     return SSL_TLSEXT_ERR_ALERT_FATAL;
688   #endif
689 }
690 
691 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000 */
692 
693 #endif /* OPENSSL_NO_TLSEXT */
694 
695 
696 static int
697 network_openssl_ssl_conf_cmd (server *srv, plugin_config *s)
698 {
699   #ifdef SSL_CONF_FLAG_CMDLINE
700 
701     int rc = 0;
702     data_string *ds;
703     SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new();
704     SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx);
705     SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE
706                                | SSL_CONF_FLAG_SERVER
707                                | SSL_CONF_FLAG_SHOW_ERRORS
708                                | SSL_CONF_FLAG_CERTIFICATE);
709 
710     /* always disable null and export ciphers */
711     ds = (data_string *)
712       array_get_element_klen(s->ssl_conf_cmd,
713                              CONST_STR_LEN("CipherString"));
714     if (NULL != ds) {
715         buffer_append_string_len(ds->value,
716                                  CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
717     }
718 
719     for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
720         ds = (data_string *)s->ssl_conf_cmd->data[i];
721         ERR_clear_error();
722         if (SSL_CONF_cmd(cctx, ds->key->ptr, ds->value->ptr) <= 0) {
723             log_error_write(srv, __FILE__, __LINE__, "ssbbss", "SSL:",
724                             "SSL_CONF_cmd", ds->key, ds->value, ":",
725                             ERR_error_string(ERR_get_error(), NULL));
726             rc = -1;
727             break;
728         }
729     }
730 
731     if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) {
732         log_error_write(srv, __FILE__, __LINE__, "sss", "SSL:",
733                         "SSL_CONF_CTX_finish():",
734                         ERR_error_string(ERR_get_error(), NULL));
735         rc = -1;
736     }
737 
738     SSL_CONF_CTX_free(cctx);
739     return rc;
740 
741   #else
742 
743     UNUSED(s);
744     log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
745                     "ssl.openssl.ssl-conf-cmd not available; ignored");
746     return 0;
747 
748   #endif
749 }
750 
751 
752 static int
753 network_init_ssl (server *srv, void *p_d)
754 {
755     plugin_data *p = p_d;
756 
757   #ifndef OPENSSL_NO_DH
758    /* 1024-bit MODP Group with 160-bit prime order subgroup (RFC5114)
759     * -----BEGIN DH PARAMETERS-----
760     * MIIBDAKBgQCxC4+WoIDgHd6S3l6uXVTsUsmfvPsGo8aaap3KUtI7YWBz4oZ1oj0Y
761     * mDjvHi7mUsAT7LSuqQYRIySXXDzUm4O/rMvdfZDEvXCYSI6cIZpzck7/1vrlZEc4
762     * +qMaT/VbzMChUa9fDci0vUW/N982XBpl5oz9p21NpwjfH7K8LkpDcQKBgQCk0cvV
763     * w/00EmdlpELvuZkF+BBN0lisUH/WQGz/FCZtMSZv6h5cQVZLd35pD1UE8hMWAhe0
764     * sBuIal6RVH+eJ0n01/vX07mpLuGQnQ0iY/gKdqaiTAh6CR9THb8KAWm2oorWYqTR
765     * jnOvoy13nVkY0IvIhY9Nzvl8KiSFXm7rIrOy5QICAKA=
766     * -----END DH PARAMETERS-----
767     */
768 
769     static const unsigned char dh1024_p[]={
770         0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E,
771         0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6,
772         0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86,
773         0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0,
774         0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C,
775         0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70,
776         0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA,
777         0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0,
778         0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF,
779         0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08,
780         0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71,
781     };
782 
783     static const unsigned char dh1024_g[]={
784         0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42,
785         0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F,
786         0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E,
787         0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13,
788         0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F,
789         0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1,
790         0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08,
791         0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A,
792         0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59,
793         0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24,
794         0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5,
795     };
796   #endif
797 
798     /* load SSL certificates */
799     for (size_t i = 0; i < srv->config_context->used; ++i) {
800         plugin_config *s = p->config_storage[i];
801       #ifndef SSL_OP_NO_COMPRESSION
802       #define SSL_OP_NO_COMPRESSION 0
803       #endif
804       #ifndef SSL_MODE_RELEASE_BUFFERS    /* OpenSSL >= 1.0.0 */
805       #define SSL_MODE_RELEASE_BUFFERS 0
806       #endif
807         long ssloptions = SSL_OP_ALL
808                         | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
809                         | SSL_OP_NO_COMPRESSION;
810 
811         if (s->ssl_enabled) {
812             if (buffer_string_is_empty(s->ssl_pemfile)) {
813                 /* inherit ssl settings from global scope
814                  * (if only ssl.engine = "enable" and no other ssl.* settings)*/
815                 if (0 != i && p->config_storage[0]->ssl_enabled) {
816                     s->ssl_ctx = p->config_storage[0]->ssl_ctx;
817                     continue;
818                 }
819                 /* PEM file is require */
820                 log_error_write(srv, __FILE__, __LINE__, "s",
821                                 "ssl.pemfile has to be set "
822                                 "when ssl.engine = \"enable\"");
823                 return -1;
824             }
825         }
826 
827         if (buffer_string_is_empty(s->ssl_pemfile)
828             && buffer_string_is_empty(s->ssl_ca_dn_file)
829             && buffer_string_is_empty(s->ssl_ca_file)) continue;
830 
831         if (ssl_is_init == 0) {
832           #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
833            && !defined(LIBRESSL_VERSION_NUMBER)
834             OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
835                             |OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
836             OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
837                                |OPENSSL_INIT_ADD_ALL_DIGESTS
838                                |OPENSSL_INIT_LOAD_CONFIG, NULL);
839           #else
840             SSL_load_error_strings();
841             SSL_library_init();
842             OpenSSL_add_all_algorithms();
843           #endif
844             ssl_is_init = 1;
845 
846             if (0 == RAND_status()) {
847                 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
848                                 "not enough entropy in the pool");
849                 return -1;
850             }
851 
852             local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
853             force_assert(NULL != local_send_buffer);
854         }
855 
856         if (!buffer_string_is_empty(s->ssl_pemfile)) {
857           #ifdef OPENSSL_NO_TLSEXT
858             data_config *dc = (data_config *)srv->config_context->data[i];
859             if (COMP_HTTP_HOST == dc->comp) {
860                 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
861                                 "can't use ssl.pemfile with $HTTP[\"host\"], "
862                                 "openssl version does not support TLS "
863                                 "extensions");
864                 return -1;
865             }
866           #endif
867             if (network_openssl_load_pemfile(srv, s, i)) return -1;
868         }
869 
870 
871         if (!buffer_string_is_empty(s->ssl_ca_dn_file)) {
872             s->ssl_ca_file_cert_names =
873               SSL_load_client_CA_file(s->ssl_ca_dn_file->ptr);
874             if (NULL == s->ssl_ca_file_cert_names) {
875                 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
876                                 ERR_error_string(ERR_get_error(), NULL),
877                                 s->ssl_ca_dn_file);
878             }
879         }
880 
881         if (NULL == s->ssl_ca_file_cert_names
882             && !buffer_string_is_empty(s->ssl_ca_file)) {
883             s->ssl_ca_file_cert_names =
884               SSL_load_client_CA_file(s->ssl_ca_file->ptr);
885             if (NULL == s->ssl_ca_file_cert_names) {
886                 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
887                                 ERR_error_string(ERR_get_error(), NULL),
888                                 s->ssl_ca_file);
889             }
890         }
891 
892         if (buffer_string_is_empty(s->ssl_pemfile) || !s->ssl_enabled) continue;
893 
894       #if OPENSSL_VERSION_NUMBER >= 0x10100000L
895         s->ssl_ctx = (!s->ssl_use_sslv2 && !s->ssl_use_sslv3)
896           ? SSL_CTX_new(TLS_server_method())
897           : SSL_CTX_new(SSLv23_server_method());
898       #else
899         s->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
900       #endif
901         if (NULL == s->ssl_ctx) {
902             log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
903                             ERR_error_string(ERR_get_error(), NULL));
904             return -1;
905         }
906 
907         /* completely useless identifier;
908          * required for client cert verification to work with sessions */
909         if (0 == SSL_CTX_set_session_id_context(
910                    s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){
911             log_error_write(srv, __FILE__, __LINE__, "ss:s", "SSL:",
912                             "failed to set session context",
913                             ERR_error_string(ERR_get_error(), NULL));
914             return -1;
915         }
916 
917         if (s->ssl_empty_fragments) {
918           #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
919             ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
920           #else
921             ssloptions &= ~0x00000800L; /* hardcode constant */
922             log_error_write(srv, __FILE__, __LINE__, "ss", "WARNING: SSL:",
923                             "'insert empty fragments' not supported by the "
924                             "openssl version used to compile lighttpd with");
925           #endif
926         }
927 
928         SSL_CTX_set_options(s->ssl_ctx, ssloptions);
929         SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback);
930 
931       #ifndef HAVE_WOLFSSL_SSL_H /*(wolfSSL does not support SSLv2)*/
932         if (!s->ssl_use_sslv2 && 0 != SSL_OP_NO_SSLv2) {
933             /* disable SSLv2 */
934             if ((SSL_OP_NO_SSLv2
935                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2))
936                 != SSL_OP_NO_SSLv2) {
937                 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
938                                 ERR_error_string(ERR_get_error(), NULL));
939                 return -1;
940             }
941         }
942       #endif
943 
944         if (!s->ssl_use_sslv3 && 0 != SSL_OP_NO_SSLv3) {
945             /* disable SSLv3 */
946             if ((SSL_OP_NO_SSLv3
947                  & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3))
948                 != SSL_OP_NO_SSLv3) {
949                 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
950                                 ERR_error_string(ERR_get_error(), NULL));
951                 return -1;
952             }
953         }
954 
955         if (!buffer_string_is_empty(s->ssl_cipher_list)) {
956             /* Disable support for low encryption ciphers */
957             if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){
958                 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
959                                 ERR_error_string(ERR_get_error(), NULL));
960                 return -1;
961             }
962 
963             if (s->ssl_honor_cipher_order) {
964                 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE);
965             }
966         }
967 
968       #ifndef OPENSSL_NO_DH
969       {
970         DH *dh;
971         /* Support for Diffie-Hellman key exchange */
972         if (!buffer_string_is_empty(s->ssl_dh_file)) {
973             /* DH parameters from file */
974             BIO *bio;
975             bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r");
976             if (bio == NULL) {
977                 log_error_write(srv, __FILE__, __LINE__, "ss",
978                                 "SSL: Unable to open file",
979                                 s->ssl_dh_file->ptr);
980                 return -1;
981             }
982             dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
983             BIO_free(bio);
984             if (dh == NULL) {
985                 log_error_write(srv, __FILE__, __LINE__, "ss",
986                                 "SSL: PEM_read_bio_DHparams failed",
987                                 s->ssl_dh_file->ptr);
988                 return -1;
989             }
990         } else {
991             BIGNUM *dh_p, *dh_g;
992             /* Default DH parameters from RFC5114 */
993             dh = DH_new();
994             if (dh == NULL) {
995                 log_error_write(srv, __FILE__, __LINE__, "s",
996                                 "SSL: DH_new () failed");
997                 return -1;
998             }
999             dh_p = BN_bin2bn(dh1024_p,sizeof(dh1024_p), NULL);
1000             dh_g = BN_bin2bn(dh1024_g,sizeof(dh1024_g), NULL);
1001             if ((dh_p == NULL) || (dh_g == NULL)) {
1002                 DH_free(dh);
1003                 log_error_write(srv, __FILE__, __LINE__, "s",
1004                                 "SSL: BN_bin2bn () failed");
1005                 return -1;
1006             }
1007           #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1008            || defined(LIBRESSL_VERSION_NUMBER)
1009             dh->p = dh_p;
1010             dh->g = dh_g;
1011             dh->length = 160;
1012           #else
1013             DH_set0_pqg(dh, dh_p, NULL, dh_g);
1014             DH_set_length(dh, 160);
1015           #endif
1016         }
1017         SSL_CTX_set_tmp_dh(s->ssl_ctx,dh);
1018         SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE);
1019         DH_free(dh);
1020       }
1021       #else
1022         if (!buffer_string_is_empty(s->ssl_dh_file)) {
1023             log_error_write(srv, __FILE__, __LINE__, "ss",
1024                             "SSL: openssl compiled without DH support, "
1025                             "can't load parameters from", s->ssl_dh_file->ptr);
1026         }
1027       #endif
1028 
1029       #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1030       #ifndef OPENSSL_NO_ECDH
1031       {
1032         int nid = 0;
1033         /* Support for Elliptic-Curve Diffie-Hellman key exchange */
1034         if (!buffer_string_is_empty(s->ssl_ec_curve)) {
1035             /* OpenSSL only supports the "named curves"
1036              * from RFC 4492, section 5.1.1. */
1037             nid = OBJ_sn2nid((char *) s->ssl_ec_curve->ptr);
1038             if (nid == 0) {
1039                 log_error_write(srv, __FILE__, __LINE__, "ss",
1040                                 "SSL: Unknown curve name",
1041                                 s->ssl_ec_curve->ptr);
1042                 return -1;
1043             }
1044         } else {
1045           #if OPENSSL_VERSION_NUMBER < 0x10002000
1046             /* Default curve */
1047             nid = OBJ_sn2nid("prime256v1");
1048           #elif OPENSSL_VERSION_NUMBER < 0x10100000L \
1049              || defined(LIBRESSL_VERSION_NUMBER)
1050             if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) {
1051                 log_error_write(srv, __FILE__, __LINE__, "s",
1052                                 "SSL: SSL_CTX_set_ecdh_auto() failed");
1053             }
1054           #endif
1055         }
1056         if (nid) {
1057             EC_KEY *ecdh;
1058             ecdh = EC_KEY_new_by_curve_name(nid);
1059             if (ecdh == NULL) {
1060                 log_error_write(srv, __FILE__, __LINE__, "ss",
1061                                 "SSL: Unable to create curve",
1062                                 s->ssl_ec_curve->ptr);
1063                 return -1;
1064             }
1065             SSL_CTX_set_tmp_ecdh(s->ssl_ctx,ecdh);
1066             SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_ECDH_USE);
1067             EC_KEY_free(ecdh);
1068         }
1069       }
1070       #endif
1071       #endif
1072 
1073         /* load all ssl.ca-files specified in the config into each SSL_CTX
1074          * to be prepared for SNI */
1075         for (size_t j = 0; j < srv->config_context->used; ++j) {
1076             plugin_config *s1 = p->config_storage[j];
1077 
1078             if (!buffer_string_is_empty(s1->ssl_ca_dn_file)) {
1079                 if (1 != SSL_CTX_load_verify_locations(
1080                            s->ssl_ctx, s1->ssl_ca_dn_file->ptr, NULL)) {
1081                     log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1082                                     ERR_error_string(ERR_get_error(), NULL),
1083                                     s1->ssl_ca_dn_file);
1084                     return -1;
1085                 }
1086             }
1087             if (!buffer_string_is_empty(s1->ssl_ca_file)) {
1088                 if (1 != SSL_CTX_load_verify_locations(
1089                            s->ssl_ctx, s1->ssl_ca_file->ptr, NULL)) {
1090                     log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1091                                     ERR_error_string(ERR_get_error(), NULL),
1092                                     s1->ssl_ca_file);
1093                     return -1;
1094                 }
1095             }
1096         }
1097 
1098         if (s->ssl_verifyclient) {
1099             int mode;
1100             if (NULL == s->ssl_ca_file_cert_names) {
1101                 log_error_write(srv, __FILE__, __LINE__, "s",
1102                                 "SSL: You specified ssl.verifyclient.activate "
1103                                 "but no ssl.ca-file or ssl.ca-dn-file");
1104                 return -1;
1105             }
1106             SSL_CTX_set_client_CA_list(
1107               s->ssl_ctx, SSL_dup_CA_list(s->ssl_ca_file_cert_names));
1108             mode = SSL_VERIFY_PEER;
1109             if (s->ssl_verifyclient_enforce) {
1110                 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1111             }
1112             SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback);
1113             SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1);
1114             if (!buffer_string_is_empty(s->ssl_ca_crl_file)) {
1115                 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx);
1116                 if (1 != X509_STORE_load_locations(store, s->ssl_ca_crl_file->ptr, NULL)) {
1117                     log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1118                     ERR_error_string(ERR_get_error(), NULL), s->ssl_ca_crl_file);
1119                     return -1;
1120                 }
1121                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1122             }
1123         }
1124 
1125         if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx,
1126                                                     s->ssl_pemfile->ptr)) {
1127             log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1128                             ERR_error_string(ERR_get_error(), NULL),
1129                             s->ssl_pemfile);
1130             return -1;
1131         }
1132 
1133         if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->ssl_pemfile_pkey)) {
1134             log_error_write(srv, __FILE__, __LINE__, "ssbb", "SSL:",
1135                             ERR_error_string(ERR_get_error(), NULL),
1136                             s->ssl_pemfile, s->ssl_privkey);
1137             return -1;
1138         }
1139 
1140         if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) {
1141             log_error_write(srv, __FILE__, __LINE__, "sssbb", "SSL:",
1142                             "Private key does not match the certificate public "
1143                             "key, reason:",
1144                             ERR_error_string(ERR_get_error(), NULL),
1145                             s->ssl_pemfile, s->ssl_privkey);
1146             return -1;
1147         }
1148         SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead);
1149         SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx)
1150                                    | SSL_MODE_ENABLE_PARTIAL_WRITE
1151                                    | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
1152                                    | SSL_MODE_RELEASE_BUFFERS);
1153 
1154       #ifndef OPENSSL_NO_TLSEXT
1155         if (!SSL_CTX_set_tlsext_servername_callback(
1156                s->ssl_ctx, network_ssl_servername_callback) ||
1157             !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) {
1158             log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1159                             "failed to initialize TLS servername callback, "
1160                             "openssl library does not support TLS servername "
1161                             "extension");
1162             return -1;
1163         }
1164 
1165        #if OPENSSL_VERSION_NUMBER >= 0x10002000
1166         SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL);
1167        #endif
1168       #endif
1169 
1170         if (s->ssl_conf_cmd->used) {
1171             if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1;
1172         }
1173     }
1174 
1175     return 0;
1176 }
1177 
1178 
1179 SETDEFAULTS_FUNC(mod_openssl_set_defaults)
1180 {
1181     plugin_data *p = p_d;
1182     config_values_t cv[] = {
1183         { "debug.log-ssl-noise",               NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1184         { "ssl.engine",                        NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1185         { "ssl.pemfile",                       NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1186         { "ssl.ca-file",                       NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1187         { "ssl.dh-file",                       NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1188         { "ssl.ec-curve",                      NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1189         { "ssl.cipher-list",                   NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 6 */
1190         { "ssl.honor-cipher-order",            NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1191         { "ssl.empty-fragments",               NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1192         { "ssl.disable-client-renegotiation",  NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1193         { "ssl.read-ahead",                    NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1194         { "ssl.verifyclient.activate",         NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1195         { "ssl.verifyclient.enforce",          NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1196         { "ssl.verifyclient.depth",            NULL, T_CONFIG_SHORT,   T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1197         { "ssl.verifyclient.username",         NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1198         { "ssl.verifyclient.exportcert",       NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1199         { "ssl.use-sslv2",                     NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 16 */
1200         { "ssl.use-sslv3",                     NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 17 */
1201         { "ssl.ca-crl-file",                   NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 18 */
1202         { "ssl.ca-dn-file",                    NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 19 */
1203         { "ssl.openssl.ssl-conf-cmd",          NULL, T_CONFIG_ARRAY,   T_CONFIG_SCOPE_CONNECTION }, /* 20 */
1204         { "ssl.acme-tls-1",                    NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 21 */
1205         { "ssl.privkey",                       NULL, T_CONFIG_STRING,  T_CONFIG_SCOPE_CONNECTION }, /* 22 */
1206         { NULL,                         NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1207     };
1208 
1209     if (!p) return HANDLER_ERROR;
1210 
1211     p->config_storage = calloc(srv->config_context->used, sizeof(plugin_config *));
1212 
1213     for (size_t i = 0; i < srv->config_context->used; i++) {
1214         data_config const* config = (data_config const*)srv->config_context->data[i];
1215         plugin_config *s = calloc(1, sizeof(plugin_config));
1216 
1217         s->ssl_enabled   = 0;
1218         s->ssl_pemfile   = buffer_init();
1219         s->ssl_privkey   = buffer_init();
1220         s->ssl_ca_file   = buffer_init();
1221         s->ssl_ca_crl_file = buffer_init();
1222         s->ssl_ca_dn_file = buffer_init();
1223         s->ssl_cipher_list = buffer_init();
1224         s->ssl_dh_file   = buffer_init();
1225         s->ssl_ec_curve  = buffer_init();
1226         s->ssl_honor_cipher_order = 1;
1227         s->ssl_empty_fragments = 0;
1228         s->ssl_use_sslv2 = 0;
1229         s->ssl_use_sslv3 = 0;
1230         s->ssl_verifyclient = 0;
1231         s->ssl_verifyclient_enforce = 1;
1232         s->ssl_verifyclient_username = buffer_init();
1233         s->ssl_verifyclient_depth = 9;
1234         s->ssl_verifyclient_export_cert = 0;
1235         s->ssl_disable_client_renegotiation = 1;
1236         s->ssl_read_ahead = (0 == i)
1237           ? 0
1238           : p->config_storage[0]->ssl_read_ahead;
1239         if (0 == i)
1240             buffer_copy_string_len(s->ssl_cipher_list, CONST_STR_LEN("HIGH"));
1241         if (0 != i) {
1242             buffer *b;
1243             b = p->config_storage[0]->ssl_ca_crl_file;
1244             if (!buffer_string_is_empty(b))
1245                 buffer_copy_buffer(s->ssl_ca_crl_file, b);
1246             b = p->config_storage[0]->ssl_ca_dn_file;
1247             if (!buffer_string_is_empty(b))
1248                 buffer_copy_buffer(s->ssl_ca_dn_file, b);
1249             b = p->config_storage[0]->ssl_cipher_list;
1250             if (!buffer_string_is_empty(b))
1251                 buffer_copy_buffer(s->ssl_cipher_list, b);
1252         }
1253         s->ssl_conf_cmd = (0 == i)
1254           ? array_init()
1255           : array_init_array(p->config_storage[0]->ssl_conf_cmd);
1256         s->ssl_acme_tls_1 = buffer_init();
1257 
1258         cv[0].destination = &(s->ssl_log_noise);
1259         cv[1].destination = &(s->ssl_enabled);
1260         cv[2].destination = s->ssl_pemfile;
1261         cv[3].destination = s->ssl_ca_file;
1262         cv[4].destination = s->ssl_dh_file;
1263         cv[5].destination = s->ssl_ec_curve;
1264         cv[6].destination = s->ssl_cipher_list;
1265         cv[7].destination = &(s->ssl_honor_cipher_order);
1266         cv[8].destination = &(s->ssl_empty_fragments);
1267         cv[9].destination = &(s->ssl_disable_client_renegotiation);
1268         cv[10].destination = &(s->ssl_read_ahead);
1269         cv[11].destination = &(s->ssl_verifyclient);
1270         cv[12].destination = &(s->ssl_verifyclient_enforce);
1271         cv[13].destination = &(s->ssl_verifyclient_depth);
1272         cv[14].destination = s->ssl_verifyclient_username;
1273         cv[15].destination = &(s->ssl_verifyclient_export_cert);
1274         cv[16].destination = &(s->ssl_use_sslv2);
1275         cv[17].destination = &(s->ssl_use_sslv3);
1276         cv[18].destination = s->ssl_ca_crl_file;
1277         cv[19].destination = s->ssl_ca_dn_file;
1278         cv[20].destination = s->ssl_conf_cmd;
1279         cv[21].destination = s->ssl_acme_tls_1;
1280         cv[22].destination = s->ssl_privkey;
1281 
1282         p->config_storage[i] = s;
1283 
1284         if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1285             return HANDLER_ERROR;
1286         }
1287 
1288         if (0 != i && s->ssl_enabled && buffer_string_is_empty(s->ssl_pemfile)){
1289             /* inherit ssl settings from global scope (in network_init_ssl())
1290              * (if only ssl.engine = "enable" and no other ssl.* settings)*/
1291             for (size_t j = 0; j < config->value->used; ++j) {
1292                 buffer *k = config->value->data[j]->key;
1293                 if (0 == strncmp(k->ptr, "ssl.", sizeof("ssl.")-1)
1294                     && !buffer_is_equal_string(k, CONST_STR_LEN("ssl.engine"))){
1295                     log_error_write(srv, __FILE__, __LINE__, "sb",
1296                                     "ssl.pemfile has to be set in same scope "
1297                                     "as other ssl.* directives, unless only "
1298                                     "ssl.engine is set, inheriting ssl.* from "
1299                                     "global scope", k);
1300                     return HANDLER_ERROR;
1301                 }
1302             }
1303         }
1304 
1305         if (0 != i && s->ssl_enabled && config->comp != COMP_SERVER_SOCKET) {
1306             log_error_write(srv, __FILE__, __LINE__, "s",
1307                             "ssl.engine is valid only in global scope "
1308                             "or $SERVER[\"socket\"] condition");
1309         }
1310 
1311         if (!array_is_kvstring(s->ssl_conf_cmd)) {
1312             log_error_write(srv, __FILE__, __LINE__, "s",
1313                             "ssl.openssl.ssl-conf-cmd must be array "
1314                             "of \"key\" => \"value\" strings");
1315         }
1316     }
1317 
1318     if (0 != network_init_ssl(srv, p)) return HANDLER_ERROR;
1319 
1320     return HANDLER_GO_ON;
1321 }
1322 
1323 
1324 #define PATCH(x) \
1325     hctx->conf.x = s->x;
1326 static int
1327 mod_openssl_patch_connection (server *srv, connection *con, handler_ctx *hctx)
1328 {
1329     plugin_config *s = plugin_data_singleton->config_storage[0];
1330 
1331     /*PATCH(ssl_enabled);*//*(not patched)*/
1332     /*PATCH(ssl_pemfile);*//*(not patched)*/
1333     /*PATCH(ssl_privkey);*//*(not patched)*/
1334     PATCH(ssl_pemfile_x509);
1335     PATCH(ssl_pemfile_pkey);
1336     PATCH(ssl_ca_file);
1337     /*PATCH(ssl_ca_crl_file);*//*(not patched)*/
1338     PATCH(ssl_ca_dn_file);
1339     PATCH(ssl_ca_file_cert_names);
1340     /*PATCH(ssl_cipher_list);*//*(not patched)*/
1341     /*PATCH(ssl_dh_file);*//*(not patched)*/
1342     /*PATCH(ssl_ec_curve);*//*(not patched)*/
1343     /*PATCH(ssl_honor_cipher_order);*//*(not patched)*/
1344     /*PATCH(ssl_empty_fragments);*//*(not patched)*/
1345     /*PATCH(ssl_use_sslv2);*//*(not patched)*/
1346     /*PATCH(ssl_use_sslv3);*//*(not patched)*/
1347     /*PATCH(ssl_conf_cmd);*//*(not patched)*/
1348 
1349     PATCH(ssl_verifyclient);
1350     PATCH(ssl_verifyclient_enforce);
1351     PATCH(ssl_verifyclient_depth);
1352     PATCH(ssl_verifyclient_username);
1353     PATCH(ssl_verifyclient_export_cert);
1354     PATCH(ssl_disable_client_renegotiation);
1355     PATCH(ssl_read_ahead);
1356     PATCH(ssl_acme_tls_1);
1357 
1358     PATCH(ssl_log_noise);
1359 
1360     /* skip the first, the global context */
1361     for (size_t i = 1; i < srv->config_context->used; ++i) {
1362         data_config *dc = (data_config *)srv->config_context->data[i];
1363         s = plugin_data_singleton->config_storage[i];
1364 
1365         /* condition didn't match */
1366         if (!config_check_cond(srv, con, dc)) continue;
1367 
1368         /* merge config */
1369         for (size_t j = 0; j < dc->value->used; ++j) {
1370             data_unset *du = dc->value->data[j];
1371 
1372             if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.pemfile"))) {
1373                 /*PATCH(ssl_pemfile);*//*(not patched)*/
1374                 /*PATCH(ssl_privkey);*//*(not patched)*/
1375                 PATCH(ssl_pemfile_x509);
1376                 PATCH(ssl_pemfile_pkey);
1377             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-file"))) {
1378                 PATCH(ssl_ca_file);
1379                 PATCH(ssl_ca_file_cert_names);
1380             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-dn-file"))) {
1381                 PATCH(ssl_ca_dn_file);
1382                 PATCH(ssl_ca_file_cert_names);
1383             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.activate"))) {
1384                 PATCH(ssl_verifyclient);
1385             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.enforce"))) {
1386                 PATCH(ssl_verifyclient_enforce);
1387             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.depth"))) {
1388                 PATCH(ssl_verifyclient_depth);
1389             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.username"))) {
1390                 PATCH(ssl_verifyclient_username);
1391             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.exportcert"))) {
1392                 PATCH(ssl_verifyclient_export_cert);
1393             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.disable-client-renegotiation"))) {
1394                 PATCH(ssl_disable_client_renegotiation);
1395             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.read-ahead"))) {
1396                 PATCH(ssl_read_ahead);
1397             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.acme-tls-1"))) {
1398                 PATCH(ssl_acme_tls_1);
1399             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-ssl-noise"))) {
1400                 PATCH(ssl_log_noise);
1401           #if 0 /*(not patched)*/
1402             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-crl-file"))) {
1403                 PATCH(ssl_ca_crl_file);
1404             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.honor-cipher-order"))) {
1405                 PATCH(ssl_honor_cipher_order);
1406             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.empty-fragments"))) {
1407                 PATCH(ssl_empty_fragments);
1408             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.use-sslv2"))) {
1409                 PATCH(ssl_use_sslv2);
1410             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.use-sslv3"))) {
1411                 PATCH(ssl_use_sslv3);
1412             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.cipher-list"))) {
1413                 PATCH(ssl_cipher_list);
1414             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.dh-file"))) {
1415                 PATCH(ssl_dh_file);
1416             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ec-curve"))) {
1417                 PATCH(ssl_ec_curve);
1418             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.engine"))) {
1419                 PATCH(ssl_enabled);
1420             } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"))) {
1421                 PATCH(ssl_conf_cmd);
1422           #endif
1423             }
1424         }
1425     }
1426 
1427     return 0;
1428 }
1429 #undef PATCH
1430 
1431 
1432 static int
1433 load_next_chunk (server *srv, chunkqueue *cq, off_t max_bytes,
1434                  const char **data, size_t *data_len)
1435 {
1436     chunk *c = cq->first;
1437 
1438     /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
1439      *
1440      * it has to stay at the same location all the time to satisfy the needs
1441      * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE
1442      *
1443      * buffer is allocated once, is NOT realloced (note: not thread-safe)
1444      *
1445      * (Note: above restriction no longer true since SSL_CTX_set_mode() is
1446      *        called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1447      * */
1448 
1449     force_assert(NULL != c);
1450 
1451     switch (c->type) {
1452     case MEM_CHUNK:
1453         *data = NULL;
1454         *data_len = 0;
1455         do {
1456             size_t have;
1457 
1458             force_assert(c->offset >= 0
1459                          && c->offset <= (off_t)buffer_string_length(c->mem));
1460 
1461             have = buffer_string_length(c->mem) - c->offset;
1462 
1463             /* copy small mem chunks into single large buffer before SSL_write()
1464              * to reduce number times write() called underneath SSL_write() and
1465              * potentially reduce number of packets generated if TCP_NODELAY */
1466             if (*data_len) {
1467                 size_t space = LOCAL_SEND_BUFSIZE - *data_len;
1468                 if (have > space)
1469                     have = space;
1470                 if (have > (size_t)max_bytes - *data_len)
1471                     have = (size_t)max_bytes - *data_len;
1472                 if (*data != local_send_buffer) {
1473                     memcpy(local_send_buffer, *data, *data_len);
1474                     *data = local_send_buffer;
1475                 }
1476                 memcpy(local_send_buffer+*data_len,c->mem->ptr+c->offset,have);
1477                 *data_len += have;
1478                 continue;
1479             }
1480 
1481             if ((off_t) have > max_bytes) have = max_bytes;
1482 
1483             *data = c->mem->ptr + c->offset;
1484             *data_len = have;
1485         } while ((c = c->next) && c->type == MEM_CHUNK
1486                  && *data_len < LOCAL_SEND_BUFSIZE
1487                  && (off_t) *data_len < max_bytes);
1488         return 0;
1489 
1490     case FILE_CHUNK:
1491         if (0 != chunkqueue_open_file_chunk(srv, cq)) return -1;
1492 
1493         {
1494             off_t offset, toSend;
1495 
1496             force_assert(c->offset >= 0 && c->offset <= c->file.length);
1497             offset = c->file.start + c->offset;
1498             toSend = c->file.length - c->offset;
1499 
1500             if (toSend > LOCAL_SEND_BUFSIZE) toSend = LOCAL_SEND_BUFSIZE;
1501             if (toSend > max_bytes) toSend = max_bytes;
1502 
1503             if (-1 == lseek(c->file.fd, offset, SEEK_SET)) {
1504                 log_error_write(srv, __FILE__, __LINE__, "ss",
1505                                 "lseek: ", strerror(errno));
1506                 return -1;
1507             }
1508             if (-1 == (toSend = read(c->file.fd, local_send_buffer, toSend))) {
1509                 log_error_write(srv, __FILE__, __LINE__, "ss",
1510                                 "read: ", strerror(errno));
1511                 return -1;
1512             }
1513 
1514             *data = local_send_buffer;
1515             *data_len = toSend;
1516         }
1517         return 0;
1518     }
1519 
1520     return -1;
1521 }
1522 
1523 
1524 static int
1525 mod_openssl_close_notify(server *srv, handler_ctx *hctx);
1526 
1527 
1528 static int
1529 connection_write_cq_ssl (server *srv, connection *con,
1530                          chunkqueue *cq, off_t max_bytes)
1531 {
1532     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1533     SSL *ssl = hctx->ssl;
1534 
1535     if (0 != hctx->close_notify) return mod_openssl_close_notify(srv, hctx);
1536 
1537     chunkqueue_remove_finished_chunks(cq);
1538 
1539     while (max_bytes > 0 && NULL != cq->first) {
1540         const char *data;
1541         size_t data_len;
1542         int r;
1543 
1544         if (0 != load_next_chunk(srv,cq,max_bytes,&data,&data_len)) return -1;
1545 
1546         /**
1547          * SSL_write man-page
1548          *
1549          * WARNING
1550          *        When an SSL_write() operation has to be repeated because of
1551          *        SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be
1552          *        repeated with the same arguments.
1553          */
1554 
1555         ERR_clear_error();
1556         r = SSL_write(ssl, data, data_len);
1557 
1558         if (hctx->renegotiations > 1
1559             && hctx->conf.ssl_disable_client_renegotiation) {
1560             log_error_write(srv, __FILE__, __LINE__, "s",
1561               "SSL: renegotiation initiated by client, killing connection");
1562             return -1;
1563         }
1564 
1565         if (r <= 0) {
1566             int ssl_r;
1567             unsigned long err;
1568 
1569             switch ((ssl_r = SSL_get_error(ssl, r))) {
1570             case SSL_ERROR_WANT_READ:
1571                 con->is_readable = -1;
1572                 return 0; /* try again later */
1573             case SSL_ERROR_WANT_WRITE:
1574                 con->is_writable = -1;
1575                 return 0; /* try again later */
1576             case SSL_ERROR_SYSCALL:
1577                 /* perhaps we have error waiting in our error-queue */
1578                 if (0 != (err = ERR_get_error())) {
1579                     do {
1580                         log_error_write(srv, __FILE__, __LINE__, "sdds",
1581                                         "SSL:", ssl_r, r,
1582                                         ERR_error_string(err, NULL));
1583                     } while((err = ERR_get_error()));
1584                 } else if (r == -1) {
1585                     /* no, but we have errno */
1586                     switch(errno) {
1587                     case EPIPE:
1588                     case ECONNRESET:
1589                         return -2;
1590                     default:
1591                         log_error_write(srv, __FILE__, __LINE__, "sddds",
1592                                         "SSL:", ssl_r, r, errno,
1593                                         strerror(errno));
1594                         break;
1595                     }
1596                 } else {
1597                     /* neither error-queue nor errno ? */
1598                     log_error_write(srv, __FILE__, __LINE__, "sddds",
1599                                     "SSL (error):", ssl_r, r, errno,
1600                                     strerror(errno));
1601                 }
1602                 break;
1603 
1604             case SSL_ERROR_ZERO_RETURN:
1605                 /* clean shutdown on the remote side */
1606 
1607                 if (r == 0) return -2;
1608 
1609                 /* fall through */
1610             default:
1611                 while((err = ERR_get_error())) {
1612                     log_error_write(srv, __FILE__, __LINE__, "sdds",
1613                                     "SSL:", ssl_r, r,
1614                                     ERR_error_string(err, NULL));
1615                 }
1616                 break;
1617             }
1618             return -1;
1619         }
1620 
1621         chunkqueue_mark_written(cq, r);
1622         max_bytes -= r;
1623 
1624         if ((size_t) r < data_len) break; /* try again later */
1625     }
1626 
1627     return 0;
1628 }
1629 
1630 
1631 static int
1632 connection_read_cq_ssl (server *srv, connection *con,
1633                         chunkqueue *cq, off_t max_bytes)
1634 {
1635     handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1636     int r, ssl_err, len;
1637     char *mem = NULL;
1638     size_t mem_len = 0;
1639 
1640     /*(code transform assumption; minimize diff)*/
1641     force_assert(cq == con->read_queue);
1642     UNUSED(max_bytes);
1643 
1644     if (0 != hctx->close_notify) return mod_openssl_close_notify(srv, hctx);
1645 
1646     ERR_clear_error();
1647     do {
1648         len = SSL_pending(hctx->ssl);
1649         mem_len = len < 2048 ? 2048 : (size_t)len;
1650         mem = chunkqueue_get_memory(con->read_queue, &mem_len);
1651 #if 0
1652         /* overwrite everything with 0 */
1653         memset(mem, 0, mem_len);
1654 #endif
1655 
1656         len = SSL_read(hctx->ssl, mem, mem_len);
1657         if (len > 0) {
1658             chunkqueue_use_memory(con->read_queue, len);
1659             con->bytes_read += len;
1660         } else {
1661             chunkqueue_use_memory(con->read_queue, 0);
1662         }
1663 
1664         if (hctx->renegotiations > 1
1665             && hctx->conf.ssl_disable_client_renegotiation) {
1666             log_error_write(srv, __FILE__, __LINE__, "s",
1667               "SSL: renegotiation initiated by client, killing connection");
1668             return -1;
1669         }
1670 
1671       #if OPENSSL_VERSION_NUMBER >= 0x10002000
1672         if (hctx->alpn) {
1673             if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) {
1674                 chunkqueue_reset(con->read_queue);
1675                 /* initiate handshake in order to send ServerHello.
1676                  * Once TLS handshake is complete, return -1 to result in
1677                  * CON_STATE_ERROR so that socket connection is quickly closed*/
1678                 if (1 == SSL_do_handshake(hctx->ssl)) return -1;
1679                 len = -1;
1680                 break;
1681             }
1682             hctx->alpn = 0;
1683         }
1684       #endif
1685     } while (len > 0
1686              && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0));
1687 
1688     if (len < 0) {
1689         int oerrno = errno;
1690         switch ((r = SSL_get_error(hctx->ssl, len))) {
1691         case SSL_ERROR_WANT_WRITE:
1692             con->is_writable = -1;
1693             /* fall through */
1694         case SSL_ERROR_WANT_READ:
1695             con->is_readable = 0;
1696 
1697             /* the manual says we have to call SSL_read with the same arguments
1698              * next time.  we ignore this restriction; no one has complained
1699              * about it in 1.5 yet, so it probably works anyway.
1700              */
1701 
1702             return 0;
1703         case SSL_ERROR_SYSCALL:
1704             /**
1705              * man SSL_get_error()
1706              *
1707              * SSL_ERROR_SYSCALL
1708              *   Some I/O error occurred.  The OpenSSL error queue may contain
1709              *   more information on the error.  If the error queue is empty
1710              *   (i.e. ERR_get_error() returns 0), ret can be used to find out
1711              *   more about the error: If ret == 0, an EOF was observed that
1712              *   violates the protocol.  If ret == -1, the underlying BIO
1713              *   reported an I/O error (for socket I/O on Unix systems, consult
1714              *   errno for details).
1715              *
1716              */
1717             while((ssl_err = ERR_get_error())) {
1718                 /* get all errors from the error-queue */
1719                 log_error_write(srv, __FILE__, __LINE__, "sds", "SSL:",
1720                         r, ERR_error_string(ssl_err, NULL));
1721             }
1722 
1723             switch(oerrno) {
1724             default:
1725                 /* (oerrno should be something like ECONNABORTED not 0
1726                  *  if client disconnected before anything was sent
1727                  *  (e.g. TCP connection probe), but it does not appear
1728                  *  that openssl provides such notification, not even
1729                  *  something like SSL_R_SSL_HANDSHAKE_FAILURE) */
1730                 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise)
1731                     break;
1732 
1733                 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL:",
1734                         len, r, oerrno,
1735                         strerror(oerrno));
1736                 break;
1737             }
1738 
1739             break;
1740         case SSL_ERROR_ZERO_RETURN:
1741             /* clean shutdown on the remote side */
1742 
1743             if (r == 0) {
1744                 /* FIXME: later */
1745             }
1746 
1747             /* fall through */
1748         default:
1749             while((ssl_err = ERR_get_error())) {
1750                 switch (ERR_GET_REASON(ssl_err)) {
1751                 case SSL_R_SSL_HANDSHAKE_FAILURE:
1752                   #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA
1753                 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
1754                   #endif
1755                   #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN
1756                 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
1757                   #endif
1758                   #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
1759                 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
1760                   #endif
1761                     if (!hctx->conf.ssl_log_noise) continue;
1762                     break;
1763                 default:
1764                     break;
1765                 }
1766                 /* get all errors from the error-queue */
1767                 log_error_write(srv, __FILE__, __LINE__, "sds", "SSL:",
1768                                 r, ERR_error_string(ssl_err, NULL));
1769             }
1770             break;
1771         }
1772         return -1;
1773     } else if (len == 0) {
1774         con->is_readable = 0;
1775         /* the other end close the connection -> KEEP-ALIVE */
1776 
1777         return -2;
1778     } else {
1779         return 0;
1780     }
1781 }
1782 
1783 
1784 CONNECTION_FUNC(mod_openssl_handle_con_accept)
1785 {
1786     plugin_data *p = p_d;
1787     handler_ctx *hctx;
1788     server_socket *srv_sock = con->srv_socket;
1789     if (!srv_sock->is_ssl) return HANDLER_GO_ON;
1790 
1791     hctx = handler_ctx_init();
1792     hctx->con = con;
1793     hctx->srv = srv;
1794     con->plugin_ctx[p->id] = hctx;
1795     mod_openssl_patch_connection(srv, con, hctx);
1796 
1797     /* connect fd to SSL */
1798     hctx->ssl = SSL_new(p->config_storage[srv_sock->sidx]->ssl_ctx);
1799     if (NULL == hctx->ssl) {
1800         log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1801                         ERR_error_string(ERR_get_error(), NULL));
1802         return HANDLER_ERROR;
1803     }
1804 
1805     buffer_copy_string_len(con->proto, CONST_STR_LEN("https"));
1806     con->network_read = connection_read_cq_ssl;
1807     con->network_write = connection_write_cq_ssl;
1808     SSL_set_app_data(hctx->ssl, hctx);
1809     SSL_set_accept_state(hctx->ssl);
1810 
1811     if (1 != (SSL_set_fd(hctx->ssl, con->fd))) {
1812         log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1813                         ERR_error_string(ERR_get_error(), NULL));
1814         return HANDLER_ERROR;
1815     }
1816 
1817     return HANDLER_GO_ON;
1818 }
1819 
1820 
1821 static void
1822 mod_openssl_detach(handler_ctx *hctx)
1823 {
1824     /* step aside from futher SSL processing
1825      * (used after handle_connection_shut_wr hook) */
1826     /* future: might restore prior network_read and network_write fn ptrs */
1827     hctx->con->is_ssl_sock = 0;
1828     /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
1829     if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
1830     hctx->close_notify = 1;
1831 }
1832 
1833 
1834 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)
1835 {
1836     plugin_data *p = p_d;
1837     handler_ctx *hctx = con->plugin_ctx[p->id];
1838     if (NULL == hctx) return HANDLER_GO_ON;
1839 
1840     hctx->close_notify = -2;
1841     if (SSL_is_init_finished(hctx->ssl)) {
1842         mod_openssl_close_notify(srv, hctx);
1843     }
1844     else {
1845         mod_openssl_detach(hctx);
1846     }
1847 
1848     return HANDLER_GO_ON;
1849 }
1850 
1851 
1852 static int
1853 mod_openssl_close_notify(server *srv, handler_ctx *hctx)
1854 {
1855         int ret, ssl_r;
1856         unsigned long err;
1857 
1858         if (1 == hctx->close_notify) return -2;
1859 
1860         ERR_clear_error();
1861         switch ((ret = SSL_shutdown(hctx->ssl))) {
1862         case 1:
1863             mod_openssl_detach(hctx);
1864             return -2;
1865         case 0:
1866             /* Drain SSL read buffers in case pending records need processing.
1867              * Limit to reading next record to avoid denial of service when CPU
1868              * processing TLS is slower than arrival speed of TLS data packets.
1869              * (unless hctx->conf.ssl_read_ahead is set)
1870              *
1871              * references:
1872              *
1873              * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection"
1874              * https://github.com/openssl/openssl/issues/6262
1875              *
1876              * The peer is still allowed to send data after receiving the
1877              * "close notify" event. If the peer did send data it need to be
1878              * processed by calling SSL_read() before calling SSL_shutdown() a
1879              * second time. SSL_read() will indicate the end of the peer data by
1880              * returning <= 0 and SSL_get_error() returning
1881              * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read()
1882              * between SSL_shutdown() calls.
1883              *
1884              * Additional discussion in "Auto retry in shutdown"
1885              * https://github.com/openssl/openssl/pull/6340
1886              */
1887             ssl_r = SSL_pending(hctx->ssl);
1888             if (ssl_r) {
1889                 do {
1890                     char buf[4096];
1891                     ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf));
1892                 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret)));
1893             }
1894 
1895             ERR_clear_error();
1896             switch ((ret = SSL_shutdown(hctx->ssl))) {
1897             case 1:
1898                 mod_openssl_detach(hctx);
1899                 return -2;
1900             case 0:
1901                 hctx->close_notify = -1;
1902                 return 0;
1903             default:
1904                 break;
1905             }
1906 
1907             /* fall through */
1908         default:
1909 
1910             if (!SSL_is_init_finished(hctx->ssl)) {
1911                 mod_openssl_detach(hctx);
1912                 return -2;
1913             }
1914 
1915             switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) {
1916             case SSL_ERROR_ZERO_RETURN:
1917             case SSL_ERROR_WANT_WRITE:
1918             case SSL_ERROR_WANT_READ:
1919                 hctx->close_notify = -1;
1920                 return 0; /* try again later */
1921             case SSL_ERROR_SYSCALL:
1922                 /* perhaps we have error waiting in our error-queue */
1923                 if (0 != (err = ERR_get_error())) {
1924                     do {
1925                         log_error_write(srv, __FILE__, __LINE__, "sdds",
1926                                         "SSL:", ssl_r, ret,
1927                                         ERR_error_string(err, NULL));
1928                     } while((err = ERR_get_error()));
1929                 } else if (errno != 0) {
1930                     /*ssl bug (see lighttpd ticket #2213): sometimes errno==0*/
1931                     switch(errno) {
1932                     case EPIPE:
1933                     case ECONNRESET:
1934                         break;
1935                     default:
1936                         log_error_write(srv, __FILE__, __LINE__, "sddds",
1937                                         "SSL (error):", ssl_r, ret, errno,
1938                                         strerror(errno));
1939                         break;
1940                     }
1941                 }
1942 
1943                 break;
1944             default:
1945                 while((err = ERR_get_error())) {
1946                     log_error_write(srv, __FILE__, __LINE__, "sdds",
1947                                     "SSL:", ssl_r, ret,
1948                                     ERR_error_string(err, NULL));
1949                 }
1950 
1951                 break;
1952             }
1953         }
1954         ERR_clear_error();
1955         hctx->close_notify = -1;
1956         return ret;
1957 }
1958 
1959 
1960 CONNECTION_FUNC(mod_openssl_handle_con_close)
1961 {
1962     plugin_data *p = p_d;
1963     handler_ctx *hctx = con->plugin_ctx[p->id];
1964     if (NULL != hctx) {
1965         handler_ctx_free(hctx);
1966         con->plugin_ctx[p->id] = NULL;
1967     }
1968 
1969     UNUSED(srv);
1970     return HANDLER_GO_ON;
1971 }
1972 
1973 
1974 static void
1975 https_add_ssl_client_entries (server *srv, connection *con, handler_ctx *hctx)
1976 {
1977     X509 *xs;
1978     X509_NAME *xn;
1979     int i, nentries;
1980 
1981     long vr = SSL_get_verify_result(hctx->ssl);
1982     if (vr != X509_V_OK) {
1983         char errstr[256];
1984         ERR_error_string_n(vr, errstr, sizeof(errstr));
1985         buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("FAILED:"));
1986         buffer_append_string(srv->tmp_buf, errstr);
1987         http_header_env_set(con,
1988                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
1989                             CONST_BUF_LEN(srv->tmp_buf));
1990         return;
1991     } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) {
1992         http_header_env_set(con,
1993                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
1994                             CONST_STR_LEN("NONE"));
1995         return;
1996     } else {
1997         http_header_env_set(con,
1998                             CONST_STR_LEN("SSL_CLIENT_VERIFY"),
1999                             CONST_STR_LEN("SUCCESS"));
2000     }
2001 
2002     xn = X509_get_subject_name(xs);
2003     {
2004         char buf[256];
2005         int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf));
2006         if (len > 0) {
2007             if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1;
2008             http_header_env_set(con,
2009                                 CONST_STR_LEN("SSL_CLIENT_S_DN"),
2010                                 buf, (size_t)len);
2011         }
2012     }
2013     buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
2014     for (i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) {
2015         int xobjnid;
2016         const char * xobjsn;
2017         X509_NAME_ENTRY *xe;
2018 
2019         if (!(xe = X509_NAME_get_entry(xn, i))) {
2020             continue;
2021         }
2022         xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe));
2023         xobjsn = OBJ_nid2sn(xobjnid);
2024         if (xobjsn) {
2025             buffer_string_set_length(srv->tmp_buf,sizeof("SSL_CLIENT_S_DN_")-1);
2026             buffer_append_string(srv->tmp_buf, xobjsn);
2027             http_header_env_set(con,
2028                                 CONST_BUF_LEN(srv->tmp_buf),
2029                                 (const char*)X509_NAME_ENTRY_get_data(xe)->data,
2030                                 X509_NAME_ENTRY_get_data(xe)->length);
2031         }
2032     }
2033 
2034     {
2035         ASN1_INTEGER *xsn = X509_get_serialNumber(xs);
2036         BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL);
2037         char *serialHex = BN_bn2hex(serialBN);
2038         http_header_env_set(con,
2039                             CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
2040                             serialHex, strlen(serialHex));
2041         OPENSSL_free(serialHex);
2042         BN_free(serialBN);
2043     }
2044 
2045     if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
2046         /* pick one of the exported values as "REMOTE_USER", for example
2047          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
2048          * or
2049          *   ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
2050          */
2051         buffer *varname = hctx->conf.ssl_verifyclient_username;
2052         buffer *vb = http_header_env_get(con, CONST_BUF_LEN(varname));
2053         if (vb) { /* same as http_auth.c:http_auth_setenv() */
2054             http_header_env_set(con,
2055                                 CONST_STR_LEN("REMOTE_USER"),
2056                                 CONST_BUF_LEN(vb));
2057             http_header_env_set(con,
2058                                 CONST_STR_LEN("AUTH_TYPE"),
2059                                 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
2060         }
2061     }
2062 
2063     if (hctx->conf.ssl_verifyclient_export_cert) {
2064         BIO *bio;
2065         if (NULL != (bio = BIO_new(BIO_s_mem()))) {
2066             buffer *cert = srv->tmp_buf;
2067             int n;
2068 
2069             PEM_write_bio_X509(bio, xs);
2070             n = BIO_pending(bio);
2071 
2072             buffer_string_prepare_copy(cert, n);
2073             BIO_read(bio, cert->ptr, n);
2074             BIO_free(bio);
2075             buffer_commit(cert, n);
2076             http_header_env_set(con,
2077                                 CONST_STR_LEN("SSL_CLIENT_CERT"),
2078                                 CONST_BUF_LEN(cert));
2079         }
2080     }
2081     X509_free(xs);
2082 }
2083 
2084 
2085 static void
2086 http_cgi_ssl_env (server *srv, connection *con, handler_ctx *hctx)
2087 {
2088     const char *s;
2089     const SSL_CIPHER *cipher;
2090     UNUSED(srv);
2091 
2092     s = SSL_get_version(hctx->ssl);
2093     http_header_env_set(con,
2094                         CONST_STR_LEN("SSL_PROTOCOL"),
2095                         s, strlen(s));
2096 
2097     if ((cipher = SSL_get_current_cipher(hctx->ssl))) {
2098         int usekeysize, algkeysize;
2099         char buf[LI_ITOSTRING_LENGTH];
2100         s = SSL_CIPHER_get_name(cipher);
2101         http_header_env_set(con,
2102                             CONST_STR_LEN("SSL_CIPHER"),
2103                             s, strlen(s));
2104         usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize);
2105         li_itostrn(buf, sizeof(buf), usekeysize);
2106         http_header_env_set(con,
2107                             CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
2108                             buf, strlen(buf));
2109         li_itostrn(buf, sizeof(buf), algkeysize);
2110         http_header_env_set(con,
2111                             CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
2112                             buf, strlen(buf));
2113     }
2114 }
2115 
2116 
2117 CONNECTION_FUNC(mod_openssl_handle_request_env)
2118 {
2119     plugin_data *p = p_d;
2120     handler_ctx *hctx = con->plugin_ctx[p->id];
2121     if (NULL == hctx) return HANDLER_GO_ON;
2122     if (hctx->request_env_patched) return HANDLER_GO_ON;
2123     hctx->request_env_patched = 1;
2124 
2125     http_cgi_ssl_env(srv, con, hctx);
2126     if (hctx->conf.ssl_verifyclient) {
2127         https_add_ssl_client_entries(srv, con, hctx);
2128     }
2129 
2130     return HANDLER_GO_ON;
2131 }
2132 
2133 
2134 CONNECTION_FUNC(mod_openssl_handle_uri_raw)
2135 {
2136     /* mod_openssl must be loaded prior to mod_auth
2137      * if mod_openssl is configured to set REMOTE_USER based on client cert */
2138     /* mod_openssl must be loaded after mod_extforward
2139      * if mod_openssl config is based on lighttpd.conf remote IP conditional
2140      * using remote IP address set by mod_extforward, *unless* PROXY protocol
2141      * is enabled with extforward.hap-PROXY = "enable", in which case the
2142      * reverse is true: mod_extforward must be loaded after mod_openssl */
2143     plugin_data *p = p_d;
2144     handler_ctx *hctx = con->plugin_ctx[p->id];
2145     if (NULL == hctx) return HANDLER_GO_ON;
2146 
2147     mod_openssl_patch_connection(srv, con, hctx);
2148     if (hctx->conf.ssl_verifyclient) {
2149         mod_openssl_handle_request_env(srv, con, p);
2150     }
2151 
2152     return HANDLER_GO_ON;
2153 }
2154 
2155 
2156 CONNECTION_FUNC(mod_openssl_handle_request_reset)
2157 {
2158     plugin_data *p = p_d;
2159     handler_ctx *hctx = con->plugin_ctx[p->id];
2160     if (NULL == hctx) return HANDLER_GO_ON;
2161 
2162     hctx->request_env_patched = 0;
2163 
2164     UNUSED(srv);
2165     return HANDLER_GO_ON;
2166 }
2167 
2168 
2169 int mod_openssl_plugin_init (plugin *p);
2170 int mod_openssl_plugin_init (plugin *p)
2171 {
2172     p->version      = LIGHTTPD_VERSION_ID;
2173     p->name         = buffer_init_string("openssl");
2174     p->init         = mod_openssl_init;
2175     p->cleanup      = mod_openssl_free;
2176     p->priv_defaults= mod_openssl_set_defaults;
2177 
2178     p->handle_connection_accept  = mod_openssl_handle_con_accept;
2179     p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr;
2180     p->handle_connection_close   = mod_openssl_handle_con_close;
2181     p->handle_uri_raw            = mod_openssl_handle_uri_raw;
2182     p->handle_request_env        = mod_openssl_handle_request_env;
2183     p->connection_reset          = mod_openssl_handle_request_reset;
2184 
2185     p->data         = NULL;
2186 
2187     return 0;
2188 }
2189