[mod_auth] require digest uri= match original URI
[lighttpd.git] / src / mod_openssl.c
blobf9a4fe827b010a0a8b23c809c463ba851bde0dde
1 #include "first.h"
3 #include <errno.h>
4 #include <string.h>
5 #include <unistd.h>
7 #ifndef USE_OPENSSL_KERBEROS
8 #ifndef OPENSSL_NO_KRB5
9 #define OPENSSL_NO_KRB5
10 #endif
11 #endif
13 #include "sys-crypto.h"
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
26 #if ! defined OPENSSL_NO_TLSEXT && ! defined SSL_CTRL_SET_TLSEXT_HOSTNAME
27 #define OPENSSL_NO_TLSEXT
28 #endif
30 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
31 #ifndef OPENSSL_NO_ECDH
32 #include <openssl/ecdh.h>
33 #endif
34 #endif
36 #include "base.h"
37 #include "http_header.h"
38 #include "log.h"
39 #include "plugin.h"
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;
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;
54 unsigned short ssl_disable_client_renegotiation;
55 unsigned short ssl_read_ahead;
56 unsigned short ssl_log_noise;
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;
76 typedef struct {
77 PLUGIN_DATA;
78 plugin_config **config_storage;
79 } plugin_data;
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;
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;
100 static handler_ctx *
101 handler_ctx_init (void)
103 handler_ctx *hctx = calloc(1, sizeof(*hctx));
104 force_assert(hctx);
105 return hctx;
109 static void
110 handler_ctx_free (handler_ctx *hctx)
112 if (hctx->ssl) SSL_free(hctx->ssl);
113 free(hctx);
117 INIT_FUNC(mod_openssl_init)
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;
127 FREE_FUNC(mod_openssl_free)
129 plugin_data *p = p_d;
130 if (!p) return HANDLER_GO_ON;
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);
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);
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;
161 free(s);
163 free(p->config_storage);
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
182 free(local_send_buffer);
185 free(p);
187 return HANDLER_GO_ON;
191 static int
192 safer_X509_NAME_oneline(X509_NAME *name, char *buf, size_t sz)
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()*/
201 else {
202 buf[0] = '\0';
203 return -1;
208 static void
209 ssl_info_callback (const SSL *ssl, int where, int ret)
211 UNUSED(ret);
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;
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;
229 #endif
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)
236 char buf[256];
237 X509 *err_cert;
238 int err, depth;
239 SSL *ssl;
240 handler_ctx *hctx;
241 server *srv;
243 err = X509_STORE_CTX_get_error(ctx);
244 depth = X509_STORE_CTX_get_error_depth(ctx);
247 * Retrieve the pointer to the SSL of the connection currently treated
248 * and the application specific data stored into the SSL object.
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;
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.
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);
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 */
291 #endif
293 preverify_ok = 0;
294 err = X509_V_ERR_CERT_REJECTED;
295 X509_STORE_CTX_set_error(ctx, err);
298 if (preverify_ok) {
299 return preverify_ok;
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);
315 * At this point, err contains the last verification error. We can use
316 * it for something special
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);
324 return !hctx->conf.ssl_verifyclient_enforce;
327 #ifndef OPENSSL_NO_TLSEXT
328 static int mod_openssl_patch_connection (server *srv, connection *con, handler_ctx *hctx);
330 static int
331 mod_openssl_SNI (SSL *ssl, server *srv, handler_ctx *hctx, const char *servername, size_t len)
333 if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/
334 log_error(srv->errh, __FILE__, __LINE__,
335 "SSL: SNI name too long %.*s", (int)len, servername);
336 return SSL_TLSEXT_ERR_ALERT_FATAL;
339 /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */
340 connection * const con = hctx->con;
341 buffer_copy_string_len(con->uri.authority, servername, len);
342 buffer_to_lower(con->uri.authority);
343 #if 0
344 /*(con->uri.authority used below for configuration before request read;
345 * revisit for h2)*/
346 if (0 != http_request_host_policy(con, con->uri.authority, con->uri.scheme))
347 return SSL_TLSEXT_ERR_ALERT_FATAL;
348 #endif
350 con->conditional_is_valid[COMP_HTTP_SCHEME] = 1;
351 con->conditional_is_valid[COMP_HTTP_HOST] = 1;
352 mod_openssl_patch_connection(srv, con, hctx);
353 /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */
354 /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/
355 /*config_cond_cache_reset_item(con, COMP_HTTP_HOST);*/
356 /*buffer_clear(con->uri.authority);*/
358 if (NULL == hctx->conf.ssl_pemfile_x509
359 || NULL == hctx->conf.ssl_pemfile_pkey) {
360 /* x509/pkey available <=> pemfile was set <=> pemfile got patched:
361 * so this should never happen, unless you nest $SERVER["socket"] */
362 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
363 "no certificate/private key for TLS server name",
364 con->uri.authority);
365 return SSL_TLSEXT_ERR_ALERT_FATAL;
368 /* first set certificate!
369 * setting private key checks whether certificate matches it */
370 if (1 != SSL_use_certificate(ssl, hctx->conf.ssl_pemfile_x509)) {
371 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
372 "failed to set certificate for TLS server name",
373 con->uri.authority,
374 ERR_error_string(ERR_get_error(), NULL));
375 return SSL_TLSEXT_ERR_ALERT_FATAL;
378 if (1 != SSL_use_PrivateKey(ssl, hctx->conf.ssl_pemfile_pkey)) {
379 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
380 "failed to set private key for TLS server name",
381 con->uri.authority,
382 ERR_error_string(ERR_get_error(), NULL));
383 return SSL_TLSEXT_ERR_ALERT_FATAL;
386 if (hctx->conf.ssl_verifyclient) {
387 int mode;
388 if (NULL == hctx->conf.ssl_ca_file_cert_names) {
389 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
390 "can't verify client without ssl.ca-file "
391 "or ssl.ca-dn-file for TLS server name",
392 con->uri.authority,
393 ERR_error_string(ERR_get_error(), NULL));
394 return SSL_TLSEXT_ERR_ALERT_FATAL;
397 SSL_set_client_CA_list(
398 ssl, SSL_dup_CA_list(hctx->conf.ssl_ca_file_cert_names));
399 /* forcing verification here is really not that useful
400 * -- a client could just connect without SNI */
401 mode = SSL_VERIFY_PEER;
402 if (hctx->conf.ssl_verifyclient_enforce) {
403 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
405 SSL_set_verify(ssl, mode, verify_callback);
406 SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1);
407 } else {
408 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
411 return SSL_TLSEXT_ERR_OK;
414 #ifdef SSL_CLIENT_HELLO_SUCCESS
415 static int
416 mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv)
418 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
419 buffer_copy_string(hctx->con->uri.scheme, "https");
421 const unsigned char *name;
422 size_t len, slen;
423 if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) {
424 return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */
427 /* expecting single element in the server_name extension; parse first one */
428 if (len > 5
429 && (size_t)((name[0] << 8) + name[1]) == len-2
430 && name[2] == TLSEXT_TYPE_server_name
431 && (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/
432 int rc = mod_openssl_SNI(ssl, srv, hctx, (const char *)name+5, slen);
433 if (rc == SSL_TLSEXT_ERR_OK)
434 return SSL_CLIENT_HELLO_SUCCESS;
437 *al = TLS1_AD_UNRECOGNIZED_NAME;
438 return SSL_CLIENT_HELLO_ERROR;
440 #else
441 static int
442 network_ssl_servername_callback (SSL *ssl, int *al, server *srv)
444 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
445 buffer_copy_string(hctx->con->uri.scheme, "https");
446 UNUSED(al);
448 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
449 return (NULL != servername)
450 ? mod_openssl_SNI(ssl, srv, hctx, servername, strlen(servername))
451 : SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */
453 #endif
454 #endif
457 static X509 *
458 x509_load_pem_file (server *srv, const char *file)
460 BIO *in;
461 X509 *x = NULL;
463 in = BIO_new(BIO_s_file());
464 if (NULL == in) {
465 log_error_write(srv, __FILE__, __LINE__, "S",
466 "SSL: BIO_new(BIO_s_file()) failed");
467 goto error;
470 if (BIO_read_filename(in,file) <= 0) {
471 log_error_write(srv, __FILE__, __LINE__, "SSS",
472 "SSL: BIO_read_filename('", file,"') failed");
473 goto error;
476 x = PEM_read_bio_X509(in, NULL, NULL, NULL);
477 if (NULL == x) {
478 log_error_write(srv, __FILE__, __LINE__, "SSS",
479 "SSL: couldn't read X509 certificate from '", file,"'");
480 goto error;
483 BIO_free(in);
484 return x;
486 error:
487 if (NULL != in) BIO_free(in);
488 return NULL;
492 static EVP_PKEY *
493 evp_pkey_load_pem_file (server *srv, const char *file)
495 BIO *in;
496 EVP_PKEY *x = NULL;
498 in = BIO_new(BIO_s_file());
499 if (NULL == in) {
500 log_error_write(srv, __FILE__, __LINE__, "s",
501 "SSL: BIO_new(BIO_s_file()) failed");
502 goto error;
505 if (BIO_read_filename(in,file) <= 0) {
506 log_error_write(srv, __FILE__, __LINE__, "SSS",
507 "SSL: BIO_read_filename('", file,"') failed");
508 goto error;
511 x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
512 if (NULL == x) {
513 log_error_write(srv, __FILE__, __LINE__, "SSS",
514 "SSL: couldn't read private key from '", file,"'");
515 goto error;
518 BIO_free(in);
519 return x;
521 error:
522 if (NULL != in) BIO_free(in);
523 return NULL;
527 static int
528 network_openssl_load_pemfile (server *srv, plugin_config *s, size_t ndx)
530 #ifdef OPENSSL_NO_TLSEXT
531 data_config *dc = (data_config *)srv->config_context->data[ndx];
532 if ((ndx > 0 && (COMP_SERVER_SOCKET != dc->comp
533 || dc->cond != CONFIG_COND_EQ)) || !s->ssl_enabled) {
534 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
535 "ssl.pemfile only works in SSL socket binding context "
536 "as openssl version does not support TLS extensions");
537 return -1;
539 #else
540 UNUSED(ndx);
541 #endif
543 s->ssl_pemfile_x509 = x509_load_pem_file(srv, s->ssl_pemfile->ptr);
544 if (NULL == s->ssl_pemfile_x509) return -1;
545 s->ssl_pemfile_pkey = !buffer_string_is_empty(s->ssl_privkey)
546 ? evp_pkey_load_pem_file(srv, s->ssl_privkey->ptr)
547 : evp_pkey_load_pem_file(srv, s->ssl_pemfile->ptr);
548 if (NULL == s->ssl_pemfile_pkey) return -1;
550 if (!X509_check_private_key(s->ssl_pemfile_x509, s->ssl_pemfile_pkey)) {
551 log_error_write(srv, __FILE__, __LINE__, "sssbb", "SSL:",
552 "Private key does not match the certificate public key,"
553 " reason:", ERR_error_string(ERR_get_error(), NULL),
554 s->ssl_pemfile, s->ssl_privkey);
555 return -1;
558 return 0;
562 #ifndef OPENSSL_NO_TLSEXT
564 #if OPENSSL_VERSION_NUMBER >= 0x10002000
566 static int
567 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx)
569 server *srv = hctx->srv;
570 buffer *b = srv->tmp_buf;
571 buffer *name = hctx->con->uri.authority;
572 X509 *ssl_pemfile_x509 = NULL;
573 EVP_PKEY *ssl_pemfile_pkey = NULL;
574 size_t len;
575 int rc = SSL_TLSEXT_ERR_ALERT_FATAL;
577 /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/
578 if (buffer_string_is_empty(hctx->conf.ssl_acme_tls_1))
579 return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/
580 buffer_copy_buffer(b, hctx->conf.ssl_acme_tls_1);
581 buffer_append_slash(b);
583 /* check if SNI set server name (required for acme-tls/1 protocol)
584 * and perform simple path checks for no '/'
585 * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */
586 if (buffer_string_is_empty(name)) return rc;
587 if (NULL != strchr(name->ptr, '/')) return rc;
588 if (name->ptr[0] == '.') return rc;
589 #if 0
590 if (0 != http_request_host_policy(hctx->con, name, hctx->con->uri.scheme))
591 return rc;
592 #endif
593 buffer_append_string_buffer(b, name);
594 len = buffer_string_length(b);
596 do {
597 buffer_append_string_len(b, CONST_STR_LEN(".crt.pem"));
598 ssl_pemfile_x509 = x509_load_pem_file(srv, b->ptr);
599 if (NULL == ssl_pemfile_x509) {
600 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
601 "Failed to load acme-tls/1 pemfile:", b);
602 break;
605 buffer_string_set_length(b, len); /*(remove ".crt.pem")*/
606 buffer_append_string_len(b, CONST_STR_LEN(".key.pem"));
607 ssl_pemfile_pkey = evp_pkey_load_pem_file(srv, b->ptr);
608 if (NULL == ssl_pemfile_pkey) {
609 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
610 "Failed to load acme-tls/1 pemfile:", b);
611 break;
614 #if 0 /* redundant with below? */
615 if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) {
616 log_error_write(srv, __FILE__, __LINE__, "sssb", "SSL:",
617 "Private key does not match acme-tls/1 certificate public key,"
618 " reason:" ERR_error_string(ERR_get_error(), NULL), b);
619 break;
621 #endif
623 /* first set certificate!
624 * setting private key checks whether certificate matches it */
625 if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) {
626 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
627 "failed to set acme-tls/1 certificate for TLS server name",
628 name, ERR_error_string(ERR_get_error(), NULL));
629 break;
632 if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) {
633 log_error_write(srv, __FILE__, __LINE__, "ssb:s", "SSL:",
634 "failed to set acme-tls/1 private key for TLS server name",
635 name, ERR_error_string(ERR_get_error(), NULL));
636 break;
639 rc = SSL_TLSEXT_ERR_OK;
640 } while (0);
642 if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey);
643 if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509);
645 return rc;
648 enum {
649 MOD_OPENSSL_ALPN_HTTP11 = 1
650 ,MOD_OPENSSL_ALPN_HTTP10 = 2
651 ,MOD_OPENSSL_ALPN_H2 = 3
652 ,MOD_OPENSSL_ALPN_ACME_TLS_1 = 4
655 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
656 static int
657 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
659 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl);
660 unsigned short proto;
661 UNUSED(arg);
663 for (unsigned int i = 0, n; i < inlen; i += n) {
664 n = in[i++];
665 if (i+n > inlen) break;
666 switch (n) {
667 #if 0
668 case 2: /* "h2" */
669 if (in[i] == 'h' && in[i+1] == '2') {
670 proto = MOD_OPENSSL_ALPN_H2;
671 break;
673 continue;
674 #endif
675 case 8: /* "http/1.1" "http/1.0" */
676 if (0 == memcmp(in+i, "http/1.", 7)) {
677 if (in[i+7] == '1') {
678 proto = MOD_OPENSSL_ALPN_HTTP11;
679 break;
681 if (in[i+7] == '0') {
682 proto = MOD_OPENSSL_ALPN_HTTP10;
683 break;
686 continue;
687 case 10: /* "acme-tls/1" */
688 if (0 == memcmp(in+i, "acme-tls/1", 10)) {
689 int rc = mod_openssl_acme_tls_1(ssl, hctx);
690 if (rc == SSL_TLSEXT_ERR_OK) {
691 proto = MOD_OPENSSL_ALPN_ACME_TLS_1;
692 break;
694 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */
695 if (rc == SSL_TLSEXT_ERR_NOACK) continue;
696 return rc;
698 continue;
699 default:
700 continue;
703 hctx->alpn = proto;
704 *out = in+i;
705 *outlen = n;
706 return SSL_TLSEXT_ERR_OK;
709 #if OPENSSL_VERSION_NUMBER < 0x10100000L
710 return SSL_TLSEXT_ERR_NOACK;
711 #else
712 return SSL_TLSEXT_ERR_ALERT_FATAL;
713 #endif
716 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000 */
718 #endif /* OPENSSL_NO_TLSEXT */
721 static int
722 network_openssl_ssl_conf_cmd (server *srv, plugin_config *s)
724 #ifdef SSL_CONF_FLAG_CMDLINE
726 int rc = 0;
727 data_string *ds;
728 SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new();
729 SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx);
730 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE
731 | SSL_CONF_FLAG_SERVER
732 | SSL_CONF_FLAG_SHOW_ERRORS
733 | SSL_CONF_FLAG_CERTIFICATE);
735 /* always disable null and export ciphers */
736 ds = (data_string *)
737 array_get_element_klen(s->ssl_conf_cmd,
738 CONST_STR_LEN("CipherString"));
739 if (NULL != ds) {
740 buffer_append_string_len(ds->value,
741 CONST_STR_LEN(":!aNULL:!eNULL:!EXP"));
744 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) {
745 ds = (data_string *)s->ssl_conf_cmd->data[i];
746 ERR_clear_error();
747 if (SSL_CONF_cmd(cctx, ds->key->ptr, ds->value->ptr) <= 0) {
748 log_error_write(srv, __FILE__, __LINE__, "ssbbss", "SSL:",
749 "SSL_CONF_cmd", ds->key, ds->value, ":",
750 ERR_error_string(ERR_get_error(), NULL));
751 rc = -1;
752 break;
756 if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) {
757 log_error_write(srv, __FILE__, __LINE__, "sss", "SSL:",
758 "SSL_CONF_CTX_finish():",
759 ERR_error_string(ERR_get_error(), NULL));
760 rc = -1;
763 SSL_CONF_CTX_free(cctx);
764 return rc;
766 #else
768 UNUSED(s);
769 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
770 "ssl.openssl.ssl-conf-cmd not available; ignored");
771 return 0;
773 #endif
777 static int
778 network_init_ssl (server *srv, void *p_d)
780 plugin_data *p = p_d;
782 #ifndef OPENSSL_NO_DH
783 /* 1024-bit MODP Group with 160-bit prime order subgroup (RFC5114)
784 * -----BEGIN DH PARAMETERS-----
785 * MIIBDAKBgQCxC4+WoIDgHd6S3l6uXVTsUsmfvPsGo8aaap3KUtI7YWBz4oZ1oj0Y
786 * mDjvHi7mUsAT7LSuqQYRIySXXDzUm4O/rMvdfZDEvXCYSI6cIZpzck7/1vrlZEc4
787 * +qMaT/VbzMChUa9fDci0vUW/N982XBpl5oz9p21NpwjfH7K8LkpDcQKBgQCk0cvV
788 * w/00EmdlpELvuZkF+BBN0lisUH/WQGz/FCZtMSZv6h5cQVZLd35pD1UE8hMWAhe0
789 * sBuIal6RVH+eJ0n01/vX07mpLuGQnQ0iY/gKdqaiTAh6CR9THb8KAWm2oorWYqTR
790 * jnOvoy13nVkY0IvIhY9Nzvl8KiSFXm7rIrOy5QICAKA=
791 * -----END DH PARAMETERS-----
794 static const unsigned char dh1024_p[]={
795 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E,
796 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6,
797 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86,
798 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0,
799 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C,
800 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70,
801 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA,
802 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0,
803 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF,
804 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08,
805 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71,
808 static const unsigned char dh1024_g[]={
809 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42,
810 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F,
811 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E,
812 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13,
813 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F,
814 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1,
815 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08,
816 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A,
817 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59,
818 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24,
819 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5,
821 #endif
823 /* load SSL certificates */
824 for (size_t i = 0; i < srv->config_context->used; ++i) {
825 plugin_config *s = p->config_storage[i];
826 #ifndef SSL_OP_NO_COMPRESSION
827 #define SSL_OP_NO_COMPRESSION 0
828 #endif
829 #ifndef SSL_MODE_RELEASE_BUFFERS /* OpenSSL >= 1.0.0 */
830 #define SSL_MODE_RELEASE_BUFFERS 0
831 #endif
832 long ssloptions = SSL_OP_ALL
833 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
834 | SSL_OP_NO_COMPRESSION;
836 if (s->ssl_enabled) {
837 if (buffer_string_is_empty(s->ssl_pemfile)) {
838 /* inherit ssl settings from global scope
839 * (if only ssl.engine = "enable" and no other ssl.* settings)*/
840 if (0 != i && p->config_storage[0]->ssl_enabled) {
841 s->ssl_ctx = p->config_storage[0]->ssl_ctx;
842 continue;
844 /* PEM file is require */
845 log_error_write(srv, __FILE__, __LINE__, "s",
846 "ssl.pemfile has to be set "
847 "when ssl.engine = \"enable\"");
848 return -1;
852 if (buffer_string_is_empty(s->ssl_pemfile)
853 && buffer_string_is_empty(s->ssl_ca_dn_file)
854 && buffer_string_is_empty(s->ssl_ca_file)) continue;
856 if (ssl_is_init == 0) {
857 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
858 && !defined(LIBRESSL_VERSION_NUMBER)
859 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
860 |OPENSSL_INIT_LOAD_CRYPTO_STRINGS,NULL);
861 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
862 |OPENSSL_INIT_ADD_ALL_DIGESTS
863 |OPENSSL_INIT_LOAD_CONFIG, NULL);
864 #else
865 SSL_load_error_strings();
866 SSL_library_init();
867 OpenSSL_add_all_algorithms();
868 #endif
869 ssl_is_init = 1;
871 if (0 == RAND_status()) {
872 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
873 "not enough entropy in the pool");
874 return -1;
877 local_send_buffer = malloc(LOCAL_SEND_BUFSIZE);
878 force_assert(NULL != local_send_buffer);
881 if (!buffer_string_is_empty(s->ssl_pemfile)) {
882 #ifdef OPENSSL_NO_TLSEXT
883 data_config *dc = (data_config *)srv->config_context->data[i];
884 if (COMP_HTTP_HOST == dc->comp) {
885 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
886 "can't use ssl.pemfile with $HTTP[\"host\"], "
887 "openssl version does not support TLS "
888 "extensions");
889 return -1;
891 #endif
892 if (network_openssl_load_pemfile(srv, s, i)) return -1;
896 if (!buffer_string_is_empty(s->ssl_ca_dn_file)) {
897 s->ssl_ca_file_cert_names =
898 SSL_load_client_CA_file(s->ssl_ca_dn_file->ptr);
899 if (NULL == s->ssl_ca_file_cert_names) {
900 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
901 ERR_error_string(ERR_get_error(), NULL),
902 s->ssl_ca_dn_file);
906 if (NULL == s->ssl_ca_file_cert_names
907 && !buffer_string_is_empty(s->ssl_ca_file)) {
908 s->ssl_ca_file_cert_names =
909 SSL_load_client_CA_file(s->ssl_ca_file->ptr);
910 if (NULL == s->ssl_ca_file_cert_names) {
911 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
912 ERR_error_string(ERR_get_error(), NULL),
913 s->ssl_ca_file);
917 if (buffer_string_is_empty(s->ssl_pemfile) || !s->ssl_enabled) continue;
919 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
920 s->ssl_ctx = (!s->ssl_use_sslv2 && !s->ssl_use_sslv3)
921 ? SSL_CTX_new(TLS_server_method())
922 : SSL_CTX_new(SSLv23_server_method());
923 #else
924 s->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
925 #endif
926 if (NULL == s->ssl_ctx) {
927 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
928 ERR_error_string(ERR_get_error(), NULL));
929 return -1;
932 /* completely useless identifier;
933 * required for client cert verification to work with sessions */
934 if (0 == SSL_CTX_set_session_id_context(
935 s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){
936 log_error_write(srv, __FILE__, __LINE__, "ss:s", "SSL:",
937 "failed to set session context",
938 ERR_error_string(ERR_get_error(), NULL));
939 return -1;
942 if (s->ssl_empty_fragments) {
943 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
944 ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
945 #else
946 ssloptions &= ~0x00000800L; /* hardcode constant */
947 log_error_write(srv, __FILE__, __LINE__, "ss", "WARNING: SSL:",
948 "'insert empty fragments' not supported by the "
949 "openssl version used to compile lighttpd with");
950 #endif
953 SSL_CTX_set_options(s->ssl_ctx, ssloptions);
954 SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback);
956 #ifndef HAVE_WOLFSSL_SSL_H /*(wolfSSL does not support SSLv2)*/
957 if (!s->ssl_use_sslv2 && 0 != SSL_OP_NO_SSLv2) {
958 /* disable SSLv2 */
959 if ((SSL_OP_NO_SSLv2
960 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2))
961 != SSL_OP_NO_SSLv2) {
962 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
963 ERR_error_string(ERR_get_error(), NULL));
964 return -1;
967 #endif
969 if (!s->ssl_use_sslv3 && 0 != SSL_OP_NO_SSLv3) {
970 /* disable SSLv3 */
971 if ((SSL_OP_NO_SSLv3
972 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3))
973 != SSL_OP_NO_SSLv3) {
974 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
975 ERR_error_string(ERR_get_error(), NULL));
976 return -1;
980 if (!buffer_string_is_empty(s->ssl_cipher_list)) {
981 /* Disable support for low encryption ciphers */
982 if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){
983 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
984 ERR_error_string(ERR_get_error(), NULL));
985 return -1;
988 if (s->ssl_honor_cipher_order) {
989 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE);
993 #ifndef OPENSSL_NO_DH
995 DH *dh;
996 /* Support for Diffie-Hellman key exchange */
997 if (!buffer_string_is_empty(s->ssl_dh_file)) {
998 /* DH parameters from file */
999 BIO *bio;
1000 bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r");
1001 if (bio == NULL) {
1002 log_error_write(srv, __FILE__, __LINE__, "ss",
1003 "SSL: Unable to open file",
1004 s->ssl_dh_file->ptr);
1005 return -1;
1007 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1008 BIO_free(bio);
1009 if (dh == NULL) {
1010 log_error_write(srv, __FILE__, __LINE__, "ss",
1011 "SSL: PEM_read_bio_DHparams failed",
1012 s->ssl_dh_file->ptr);
1013 return -1;
1015 } else {
1016 BIGNUM *dh_p, *dh_g;
1017 /* Default DH parameters from RFC5114 */
1018 dh = DH_new();
1019 if (dh == NULL) {
1020 log_error_write(srv, __FILE__, __LINE__, "s",
1021 "SSL: DH_new () failed");
1022 return -1;
1024 dh_p = BN_bin2bn(dh1024_p,sizeof(dh1024_p), NULL);
1025 dh_g = BN_bin2bn(dh1024_g,sizeof(dh1024_g), NULL);
1026 if ((dh_p == NULL) || (dh_g == NULL)) {
1027 DH_free(dh);
1028 log_error_write(srv, __FILE__, __LINE__, "s",
1029 "SSL: BN_bin2bn () failed");
1030 return -1;
1032 #if OPENSSL_VERSION_NUMBER < 0x10100000L \
1033 || defined(LIBRESSL_VERSION_NUMBER)
1034 dh->p = dh_p;
1035 dh->g = dh_g;
1036 dh->length = 160;
1037 #else
1038 DH_set0_pqg(dh, dh_p, NULL, dh_g);
1039 DH_set_length(dh, 160);
1040 #endif
1042 SSL_CTX_set_tmp_dh(s->ssl_ctx,dh);
1043 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE);
1044 DH_free(dh);
1046 #else
1047 if (!buffer_string_is_empty(s->ssl_dh_file)) {
1048 log_error_write(srv, __FILE__, __LINE__, "ss",
1049 "SSL: openssl compiled without DH support, "
1050 "can't load parameters from", s->ssl_dh_file->ptr);
1052 #endif
1054 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1055 #ifndef OPENSSL_NO_ECDH
1057 int nid = 0;
1058 /* Support for Elliptic-Curve Diffie-Hellman key exchange */
1059 if (!buffer_string_is_empty(s->ssl_ec_curve)) {
1060 /* OpenSSL only supports the "named curves"
1061 * from RFC 4492, section 5.1.1. */
1062 nid = OBJ_sn2nid((char *) s->ssl_ec_curve->ptr);
1063 if (nid == 0) {
1064 log_error_write(srv, __FILE__, __LINE__, "ss",
1065 "SSL: Unknown curve name",
1066 s->ssl_ec_curve->ptr);
1067 return -1;
1069 } else {
1070 #if OPENSSL_VERSION_NUMBER < 0x10002000
1071 /* Default curve */
1072 nid = OBJ_sn2nid("prime256v1");
1073 #elif OPENSSL_VERSION_NUMBER < 0x10100000L \
1074 || defined(LIBRESSL_VERSION_NUMBER)
1075 if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) {
1076 log_error_write(srv, __FILE__, __LINE__, "s",
1077 "SSL: SSL_CTX_set_ecdh_auto() failed");
1079 #endif
1081 if (nid) {
1082 EC_KEY *ecdh;
1083 ecdh = EC_KEY_new_by_curve_name(nid);
1084 if (ecdh == NULL) {
1085 log_error_write(srv, __FILE__, __LINE__, "ss",
1086 "SSL: Unable to create curve",
1087 s->ssl_ec_curve->ptr);
1088 return -1;
1090 SSL_CTX_set_tmp_ecdh(s->ssl_ctx,ecdh);
1091 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_ECDH_USE);
1092 EC_KEY_free(ecdh);
1095 #endif
1096 #endif
1098 /* load all ssl.ca-files specified in the config into each SSL_CTX
1099 * to be prepared for SNI */
1100 for (size_t j = 0; j < srv->config_context->used; ++j) {
1101 plugin_config *s1 = p->config_storage[j];
1103 if (!buffer_string_is_empty(s1->ssl_ca_dn_file)) {
1104 if (1 != SSL_CTX_load_verify_locations(
1105 s->ssl_ctx, s1->ssl_ca_dn_file->ptr, NULL)) {
1106 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1107 ERR_error_string(ERR_get_error(), NULL),
1108 s1->ssl_ca_dn_file);
1109 return -1;
1112 if (!buffer_string_is_empty(s1->ssl_ca_file)) {
1113 if (1 != SSL_CTX_load_verify_locations(
1114 s->ssl_ctx, s1->ssl_ca_file->ptr, NULL)) {
1115 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1116 ERR_error_string(ERR_get_error(), NULL),
1117 s1->ssl_ca_file);
1118 return -1;
1123 if (s->ssl_verifyclient) {
1124 int mode;
1125 if (NULL == s->ssl_ca_file_cert_names) {
1126 log_error_write(srv, __FILE__, __LINE__, "s",
1127 "SSL: You specified ssl.verifyclient.activate "
1128 "but no ssl.ca-file or ssl.ca-dn-file");
1129 return -1;
1131 SSL_CTX_set_client_CA_list(
1132 s->ssl_ctx, SSL_dup_CA_list(s->ssl_ca_file_cert_names));
1133 mode = SSL_VERIFY_PEER;
1134 if (s->ssl_verifyclient_enforce) {
1135 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1137 SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback);
1138 SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1);
1139 if (!buffer_string_is_empty(s->ssl_ca_crl_file)) {
1140 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx);
1141 if (1 != X509_STORE_load_locations(store, s->ssl_ca_crl_file->ptr, NULL)) {
1142 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1143 ERR_error_string(ERR_get_error(), NULL), s->ssl_ca_crl_file);
1144 return -1;
1146 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1150 if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx,
1151 s->ssl_pemfile->ptr)) {
1152 log_error_write(srv, __FILE__, __LINE__, "ssb", "SSL:",
1153 ERR_error_string(ERR_get_error(), NULL),
1154 s->ssl_pemfile);
1155 return -1;
1158 if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->ssl_pemfile_pkey)) {
1159 log_error_write(srv, __FILE__, __LINE__, "ssbb", "SSL:",
1160 ERR_error_string(ERR_get_error(), NULL),
1161 s->ssl_pemfile, s->ssl_privkey);
1162 return -1;
1165 if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) {
1166 log_error_write(srv, __FILE__, __LINE__, "sssbb", "SSL:",
1167 "Private key does not match the certificate public "
1168 "key, reason:",
1169 ERR_error_string(ERR_get_error(), NULL),
1170 s->ssl_pemfile, s->ssl_privkey);
1171 return -1;
1173 SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead);
1174 SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx)
1175 | SSL_MODE_ENABLE_PARTIAL_WRITE
1176 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
1177 | SSL_MODE_RELEASE_BUFFERS);
1179 #ifndef OPENSSL_NO_TLSEXT
1180 #ifdef SSL_CLIENT_HELLO_SUCCESS
1181 SSL_CTX_set_client_hello_cb(s->ssl_ctx,mod_openssl_client_hello_cb,srv);
1182 #else
1183 if (!SSL_CTX_set_tlsext_servername_callback(
1184 s->ssl_ctx, network_ssl_servername_callback) ||
1185 !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) {
1186 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1187 "failed to initialize TLS servername callback, "
1188 "openssl library does not support TLS servername "
1189 "extension");
1190 return -1;
1192 #endif
1194 #if OPENSSL_VERSION_NUMBER >= 0x10002000
1195 SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL);
1196 #endif
1197 #endif
1199 if (s->ssl_conf_cmd->used) {
1200 if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1;
1204 return 0;
1208 SETDEFAULTS_FUNC(mod_openssl_set_defaults)
1210 plugin_data *p = p_d;
1211 config_values_t cv[] = {
1212 { "debug.log-ssl-noise", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1213 { "ssl.engine", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1214 { "ssl.pemfile", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1215 { "ssl.ca-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1216 { "ssl.dh-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1217 { "ssl.ec-curve", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1218 { "ssl.cipher-list", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
1219 { "ssl.honor-cipher-order", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1220 { "ssl.empty-fragments", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1221 { "ssl.disable-client-renegotiation", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1222 { "ssl.read-ahead", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1223 { "ssl.verifyclient.activate", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1224 { "ssl.verifyclient.enforce", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1225 { "ssl.verifyclient.depth", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1226 { "ssl.verifyclient.username", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1227 { "ssl.verifyclient.exportcert", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1228 { "ssl.use-sslv2", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 16 */
1229 { "ssl.use-sslv3", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 17 */
1230 { "ssl.ca-crl-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 18 */
1231 { "ssl.ca-dn-file", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 19 */
1232 { "ssl.openssl.ssl-conf-cmd", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 20 */
1233 { "ssl.acme-tls-1", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 21 */
1234 { "ssl.privkey", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 22 */
1235 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1238 if (!p) return HANDLER_ERROR;
1240 p->config_storage = calloc(srv->config_context->used, sizeof(plugin_config *));
1242 for (size_t i = 0; i < srv->config_context->used; i++) {
1243 data_config const* config = (data_config const*)srv->config_context->data[i];
1244 plugin_config *s = calloc(1, sizeof(plugin_config));
1246 s->ssl_enabled = 0;
1247 s->ssl_pemfile = buffer_init();
1248 s->ssl_privkey = buffer_init();
1249 s->ssl_ca_file = buffer_init();
1250 s->ssl_ca_crl_file = buffer_init();
1251 s->ssl_ca_dn_file = buffer_init();
1252 s->ssl_cipher_list = buffer_init();
1253 s->ssl_dh_file = buffer_init();
1254 s->ssl_ec_curve = buffer_init();
1255 s->ssl_honor_cipher_order = 1;
1256 s->ssl_empty_fragments = 0;
1257 s->ssl_use_sslv2 = 0;
1258 s->ssl_use_sslv3 = 0;
1259 s->ssl_verifyclient = 0;
1260 s->ssl_verifyclient_enforce = 1;
1261 s->ssl_verifyclient_username = buffer_init();
1262 s->ssl_verifyclient_depth = 9;
1263 s->ssl_verifyclient_export_cert = 0;
1264 s->ssl_disable_client_renegotiation = 1;
1265 s->ssl_read_ahead = (0 == i)
1267 : p->config_storage[0]->ssl_read_ahead;
1268 if (0 == i)
1269 buffer_copy_string_len(s->ssl_cipher_list, CONST_STR_LEN("HIGH"));
1270 if (0 != i) {
1271 buffer *b;
1272 b = p->config_storage[0]->ssl_ca_crl_file;
1273 if (!buffer_string_is_empty(b))
1274 buffer_copy_buffer(s->ssl_ca_crl_file, b);
1275 b = p->config_storage[0]->ssl_ca_dn_file;
1276 if (!buffer_string_is_empty(b))
1277 buffer_copy_buffer(s->ssl_ca_dn_file, b);
1278 b = p->config_storage[0]->ssl_cipher_list;
1279 if (!buffer_string_is_empty(b))
1280 buffer_copy_buffer(s->ssl_cipher_list, b);
1282 s->ssl_conf_cmd = (0 == i)
1283 ? array_init()
1284 : array_init_array(p->config_storage[0]->ssl_conf_cmd);
1285 s->ssl_acme_tls_1 = buffer_init();
1287 cv[0].destination = &(s->ssl_log_noise);
1288 cv[1].destination = &(s->ssl_enabled);
1289 cv[2].destination = s->ssl_pemfile;
1290 cv[3].destination = s->ssl_ca_file;
1291 cv[4].destination = s->ssl_dh_file;
1292 cv[5].destination = s->ssl_ec_curve;
1293 cv[6].destination = s->ssl_cipher_list;
1294 cv[7].destination = &(s->ssl_honor_cipher_order);
1295 cv[8].destination = &(s->ssl_empty_fragments);
1296 cv[9].destination = &(s->ssl_disable_client_renegotiation);
1297 cv[10].destination = &(s->ssl_read_ahead);
1298 cv[11].destination = &(s->ssl_verifyclient);
1299 cv[12].destination = &(s->ssl_verifyclient_enforce);
1300 cv[13].destination = &(s->ssl_verifyclient_depth);
1301 cv[14].destination = s->ssl_verifyclient_username;
1302 cv[15].destination = &(s->ssl_verifyclient_export_cert);
1303 cv[16].destination = &(s->ssl_use_sslv2);
1304 cv[17].destination = &(s->ssl_use_sslv3);
1305 cv[18].destination = s->ssl_ca_crl_file;
1306 cv[19].destination = s->ssl_ca_dn_file;
1307 cv[20].destination = s->ssl_conf_cmd;
1308 cv[21].destination = s->ssl_acme_tls_1;
1309 cv[22].destination = s->ssl_privkey;
1311 p->config_storage[i] = s;
1313 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1314 return HANDLER_ERROR;
1317 if (0 != i && s->ssl_enabled && buffer_string_is_empty(s->ssl_pemfile)){
1318 /* inherit ssl settings from global scope (in network_init_ssl())
1319 * (if only ssl.engine = "enable" and no other ssl.* settings)*/
1320 for (size_t j = 0; j < config->value->used; ++j) {
1321 buffer *k = config->value->data[j]->key;
1322 if (0 == strncmp(k->ptr, "ssl.", sizeof("ssl.")-1)
1323 && !buffer_is_equal_string(k, CONST_STR_LEN("ssl.engine"))){
1324 log_error_write(srv, __FILE__, __LINE__, "sb",
1325 "ssl.pemfile has to be set in same scope "
1326 "as other ssl.* directives, unless only "
1327 "ssl.engine is set, inheriting ssl.* from "
1328 "global scope", k);
1329 return HANDLER_ERROR;
1334 if (0 != i && s->ssl_enabled && config->comp != COMP_SERVER_SOCKET) {
1335 log_error_write(srv, __FILE__, __LINE__, "s",
1336 "ssl.engine is valid only in global scope "
1337 "or $SERVER[\"socket\"] condition");
1340 if (!array_is_kvstring(s->ssl_conf_cmd)) {
1341 log_error_write(srv, __FILE__, __LINE__, "s",
1342 "ssl.openssl.ssl-conf-cmd must be array "
1343 "of \"key\" => \"value\" strings");
1347 if (0 != network_init_ssl(srv, p)) return HANDLER_ERROR;
1349 return HANDLER_GO_ON;
1353 #define PATCH(x) \
1354 hctx->conf.x = s->x;
1355 static int
1356 mod_openssl_patch_connection (server *srv, connection *con, handler_ctx *hctx)
1358 plugin_config *s = plugin_data_singleton->config_storage[0];
1360 /*PATCH(ssl_enabled);*//*(not patched)*/
1361 /*PATCH(ssl_pemfile);*//*(not patched)*/
1362 /*PATCH(ssl_privkey);*//*(not patched)*/
1363 PATCH(ssl_pemfile_x509);
1364 PATCH(ssl_pemfile_pkey);
1365 PATCH(ssl_ca_file);
1366 /*PATCH(ssl_ca_crl_file);*//*(not patched)*/
1367 PATCH(ssl_ca_dn_file);
1368 PATCH(ssl_ca_file_cert_names);
1369 /*PATCH(ssl_cipher_list);*//*(not patched)*/
1370 /*PATCH(ssl_dh_file);*//*(not patched)*/
1371 /*PATCH(ssl_ec_curve);*//*(not patched)*/
1372 /*PATCH(ssl_honor_cipher_order);*//*(not patched)*/
1373 /*PATCH(ssl_empty_fragments);*//*(not patched)*/
1374 /*PATCH(ssl_use_sslv2);*//*(not patched)*/
1375 /*PATCH(ssl_use_sslv3);*//*(not patched)*/
1376 /*PATCH(ssl_conf_cmd);*//*(not patched)*/
1378 PATCH(ssl_verifyclient);
1379 PATCH(ssl_verifyclient_enforce);
1380 PATCH(ssl_verifyclient_depth);
1381 PATCH(ssl_verifyclient_username);
1382 PATCH(ssl_verifyclient_export_cert);
1383 PATCH(ssl_disable_client_renegotiation);
1384 PATCH(ssl_read_ahead);
1385 PATCH(ssl_acme_tls_1);
1387 PATCH(ssl_log_noise);
1389 /* skip the first, the global context */
1390 for (size_t i = 1; i < srv->config_context->used; ++i) {
1391 data_config *dc = (data_config *)srv->config_context->data[i];
1392 s = plugin_data_singleton->config_storage[i];
1394 /* condition didn't match */
1395 if (!config_check_cond(srv, con, dc)) continue;
1397 /* merge config */
1398 for (size_t j = 0; j < dc->value->used; ++j) {
1399 data_unset *du = dc->value->data[j];
1401 if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.pemfile"))) {
1402 /*PATCH(ssl_pemfile);*//*(not patched)*/
1403 /*PATCH(ssl_privkey);*//*(not patched)*/
1404 PATCH(ssl_pemfile_x509);
1405 PATCH(ssl_pemfile_pkey);
1406 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-file"))) {
1407 PATCH(ssl_ca_file);
1408 PATCH(ssl_ca_file_cert_names);
1409 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-dn-file"))) {
1410 PATCH(ssl_ca_dn_file);
1411 PATCH(ssl_ca_file_cert_names);
1412 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.activate"))) {
1413 PATCH(ssl_verifyclient);
1414 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.enforce"))) {
1415 PATCH(ssl_verifyclient_enforce);
1416 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.depth"))) {
1417 PATCH(ssl_verifyclient_depth);
1418 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.username"))) {
1419 PATCH(ssl_verifyclient_username);
1420 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.verifyclient.exportcert"))) {
1421 PATCH(ssl_verifyclient_export_cert);
1422 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.disable-client-renegotiation"))) {
1423 PATCH(ssl_disable_client_renegotiation);
1424 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.read-ahead"))) {
1425 PATCH(ssl_read_ahead);
1426 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.acme-tls-1"))) {
1427 PATCH(ssl_acme_tls_1);
1428 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("debug.log-ssl-noise"))) {
1429 PATCH(ssl_log_noise);
1430 #if 0 /*(not patched)*/
1431 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ca-crl-file"))) {
1432 PATCH(ssl_ca_crl_file);
1433 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.honor-cipher-order"))) {
1434 PATCH(ssl_honor_cipher_order);
1435 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.empty-fragments"))) {
1436 PATCH(ssl_empty_fragments);
1437 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.use-sslv2"))) {
1438 PATCH(ssl_use_sslv2);
1439 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.use-sslv3"))) {
1440 PATCH(ssl_use_sslv3);
1441 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.cipher-list"))) {
1442 PATCH(ssl_cipher_list);
1443 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.dh-file"))) {
1444 PATCH(ssl_dh_file);
1445 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.ec-curve"))) {
1446 PATCH(ssl_ec_curve);
1447 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.engine"))) {
1448 PATCH(ssl_enabled);
1449 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"))) {
1450 PATCH(ssl_conf_cmd);
1451 #endif
1456 return 0;
1458 #undef PATCH
1461 static int
1462 load_next_chunk (server *srv, chunkqueue *cq, off_t max_bytes,
1463 const char **data, size_t *data_len)
1465 chunk *c = cq->first;
1467 /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE)
1469 * it has to stay at the same location all the time to satisfy the needs
1470 * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE
1472 * buffer is allocated once, is NOT realloced (note: not thread-safe)
1474 * (Note: above restriction no longer true since SSL_CTX_set_mode() is
1475 * called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1476 * */
1478 force_assert(NULL != c);
1480 switch (c->type) {
1481 case MEM_CHUNK:
1482 *data = NULL;
1483 *data_len = 0;
1484 do {
1485 size_t have;
1487 force_assert(c->offset >= 0
1488 && c->offset <= (off_t)buffer_string_length(c->mem));
1490 have = buffer_string_length(c->mem) - c->offset;
1492 /* copy small mem chunks into single large buffer before SSL_write()
1493 * to reduce number times write() called underneath SSL_write() and
1494 * potentially reduce number of packets generated if TCP_NODELAY */
1495 if (*data_len) {
1496 size_t space = LOCAL_SEND_BUFSIZE - *data_len;
1497 if (have > space)
1498 have = space;
1499 if (have > (size_t)max_bytes - *data_len)
1500 have = (size_t)max_bytes - *data_len;
1501 if (*data != local_send_buffer) {
1502 memcpy(local_send_buffer, *data, *data_len);
1503 *data = local_send_buffer;
1505 memcpy(local_send_buffer+*data_len,c->mem->ptr+c->offset,have);
1506 *data_len += have;
1507 continue;
1510 if ((off_t) have > max_bytes) have = max_bytes;
1512 *data = c->mem->ptr + c->offset;
1513 *data_len = have;
1514 } while ((c = c->next) && c->type == MEM_CHUNK
1515 && *data_len < LOCAL_SEND_BUFSIZE
1516 && (off_t) *data_len < max_bytes);
1517 return 0;
1519 case FILE_CHUNK:
1520 if (0 != chunkqueue_open_file_chunk(srv, cq)) return -1;
1523 off_t offset, toSend;
1525 force_assert(c->offset >= 0 && c->offset <= c->file.length);
1526 offset = c->file.start + c->offset;
1527 toSend = c->file.length - c->offset;
1529 if (toSend > LOCAL_SEND_BUFSIZE) toSend = LOCAL_SEND_BUFSIZE;
1530 if (toSend > max_bytes) toSend = max_bytes;
1532 if (-1 == lseek(c->file.fd, offset, SEEK_SET)) {
1533 log_error_write(srv, __FILE__, __LINE__, "ss",
1534 "lseek: ", strerror(errno));
1535 return -1;
1537 if (-1 == (toSend = read(c->file.fd, local_send_buffer, toSend))) {
1538 log_error_write(srv, __FILE__, __LINE__, "ss",
1539 "read: ", strerror(errno));
1540 return -1;
1543 *data = local_send_buffer;
1544 *data_len = toSend;
1546 return 0;
1549 return -1;
1553 static int
1554 mod_openssl_close_notify(server *srv, handler_ctx *hctx);
1557 static int
1558 connection_write_cq_ssl (server *srv, connection *con,
1559 chunkqueue *cq, off_t max_bytes)
1561 handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1562 SSL *ssl = hctx->ssl;
1564 if (0 != hctx->close_notify) return mod_openssl_close_notify(srv, hctx);
1566 chunkqueue_remove_finished_chunks(cq);
1568 while (max_bytes > 0 && NULL != cq->first) {
1569 const char *data;
1570 size_t data_len;
1571 int r;
1573 if (0 != load_next_chunk(srv,cq,max_bytes,&data,&data_len)) return -1;
1576 * SSL_write man-page
1578 * WARNING
1579 * When an SSL_write() operation has to be repeated because of
1580 * SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be
1581 * repeated with the same arguments.
1584 ERR_clear_error();
1585 r = SSL_write(ssl, data, data_len);
1587 if (hctx->renegotiations > 1
1588 && hctx->conf.ssl_disable_client_renegotiation) {
1589 log_error_write(srv, __FILE__, __LINE__, "s",
1590 "SSL: renegotiation initiated by client, killing connection");
1591 return -1;
1594 if (r <= 0) {
1595 int ssl_r;
1596 unsigned long err;
1598 switch ((ssl_r = SSL_get_error(ssl, r))) {
1599 case SSL_ERROR_WANT_READ:
1600 con->is_readable = -1;
1601 return 0; /* try again later */
1602 case SSL_ERROR_WANT_WRITE:
1603 con->is_writable = -1;
1604 return 0; /* try again later */
1605 case SSL_ERROR_SYSCALL:
1606 /* perhaps we have error waiting in our error-queue */
1607 if (0 != (err = ERR_get_error())) {
1608 do {
1609 log_error_write(srv, __FILE__, __LINE__, "sdds",
1610 "SSL:", ssl_r, r,
1611 ERR_error_string(err, NULL));
1612 } while((err = ERR_get_error()));
1613 } else if (r == -1) {
1614 /* no, but we have errno */
1615 switch(errno) {
1616 case EPIPE:
1617 case ECONNRESET:
1618 return -2;
1619 default:
1620 log_error_write(srv, __FILE__, __LINE__, "sddds",
1621 "SSL:", ssl_r, r, errno,
1622 strerror(errno));
1623 break;
1625 } else {
1626 /* neither error-queue nor errno ? */
1627 log_error_write(srv, __FILE__, __LINE__, "sddds",
1628 "SSL (error):", ssl_r, r, errno,
1629 strerror(errno));
1631 break;
1633 case SSL_ERROR_ZERO_RETURN:
1634 /* clean shutdown on the remote side */
1636 if (r == 0) return -2;
1638 /* fall through */
1639 default:
1640 while((err = ERR_get_error())) {
1641 log_error_write(srv, __FILE__, __LINE__, "sdds",
1642 "SSL:", ssl_r, r,
1643 ERR_error_string(err, NULL));
1645 break;
1647 return -1;
1650 chunkqueue_mark_written(cq, r);
1651 max_bytes -= r;
1653 if ((size_t) r < data_len) break; /* try again later */
1656 return 0;
1660 static int
1661 connection_read_cq_ssl (server *srv, connection *con,
1662 chunkqueue *cq, off_t max_bytes)
1664 handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id];
1665 int r, ssl_err, len;
1666 char *mem = NULL;
1667 size_t mem_len = 0;
1669 /*(code transform assumption; minimize diff)*/
1670 force_assert(cq == con->read_queue);
1671 UNUSED(max_bytes);
1673 if (0 != hctx->close_notify) return mod_openssl_close_notify(srv, hctx);
1675 ERR_clear_error();
1676 do {
1677 len = SSL_pending(hctx->ssl);
1678 mem_len = len < 2048 ? 2048 : (size_t)len;
1679 mem = chunkqueue_get_memory(con->read_queue, &mem_len);
1680 #if 0
1681 /* overwrite everything with 0 */
1682 memset(mem, 0, mem_len);
1683 #endif
1685 len = SSL_read(hctx->ssl, mem, mem_len);
1686 if (len > 0) {
1687 chunkqueue_use_memory(con->read_queue, len);
1688 con->bytes_read += len;
1689 } else {
1690 chunkqueue_use_memory(con->read_queue, 0);
1693 if (hctx->renegotiations > 1
1694 && hctx->conf.ssl_disable_client_renegotiation) {
1695 log_error_write(srv, __FILE__, __LINE__, "s",
1696 "SSL: renegotiation initiated by client, killing connection");
1697 return -1;
1700 #if OPENSSL_VERSION_NUMBER >= 0x10002000
1701 if (hctx->alpn) {
1702 if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) {
1703 chunkqueue_reset(con->read_queue);
1704 /* initiate handshake in order to send ServerHello.
1705 * Once TLS handshake is complete, return -1 to result in
1706 * CON_STATE_ERROR so that socket connection is quickly closed*/
1707 if (1 == SSL_do_handshake(hctx->ssl)) return -1;
1708 len = -1;
1709 break;
1711 hctx->alpn = 0;
1713 #endif
1714 } while (len > 0
1715 && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0));
1717 if (len < 0) {
1718 int oerrno = errno;
1719 switch ((r = SSL_get_error(hctx->ssl, len))) {
1720 case SSL_ERROR_WANT_WRITE:
1721 con->is_writable = -1;
1722 /* fall through */
1723 case SSL_ERROR_WANT_READ:
1724 con->is_readable = 0;
1726 /* the manual says we have to call SSL_read with the same arguments
1727 * next time. we ignore this restriction; no one has complained
1728 * about it in 1.5 yet, so it probably works anyway.
1731 return 0;
1732 case SSL_ERROR_SYSCALL:
1734 * man SSL_get_error()
1736 * SSL_ERROR_SYSCALL
1737 * Some I/O error occurred. The OpenSSL error queue may contain
1738 * more information on the error. If the error queue is empty
1739 * (i.e. ERR_get_error() returns 0), ret can be used to find out
1740 * more about the error: If ret == 0, an EOF was observed that
1741 * violates the protocol. If ret == -1, the underlying BIO
1742 * reported an I/O error (for socket I/O on Unix systems, consult
1743 * errno for details).
1746 while((ssl_err = ERR_get_error())) {
1747 /* get all errors from the error-queue */
1748 log_error_write(srv, __FILE__, __LINE__, "sds", "SSL:",
1749 r, ERR_error_string(ssl_err, NULL));
1752 switch(oerrno) {
1753 default:
1754 /* (oerrno should be something like ECONNABORTED not 0
1755 * if client disconnected before anything was sent
1756 * (e.g. TCP connection probe), but it does not appear
1757 * that openssl provides such notification, not even
1758 * something like SSL_R_SSL_HANDSHAKE_FAILURE) */
1759 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise)
1760 break;
1762 log_error_write(srv, __FILE__, __LINE__, "sddds", "SSL:",
1763 len, r, oerrno,
1764 strerror(oerrno));
1765 break;
1768 break;
1769 case SSL_ERROR_ZERO_RETURN:
1770 /* clean shutdown on the remote side */
1772 if (r == 0) {
1773 /* FIXME: later */
1776 /* fall through */
1777 default:
1778 while((ssl_err = ERR_get_error())) {
1779 switch (ERR_GET_REASON(ssl_err)) {
1780 case SSL_R_SSL_HANDSHAKE_FAILURE:
1781 #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA
1782 case SSL_R_TLSV1_ALERT_UNKNOWN_CA:
1783 #endif
1784 #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN
1785 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN:
1786 #endif
1787 #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
1788 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE:
1789 #endif
1790 if (!hctx->conf.ssl_log_noise) continue;
1791 break;
1792 default:
1793 break;
1795 /* get all errors from the error-queue */
1796 log_error_write(srv, __FILE__, __LINE__, "sds", "SSL:",
1797 r, ERR_error_string(ssl_err, NULL));
1799 break;
1801 return -1;
1802 } else if (len == 0) {
1803 con->is_readable = 0;
1804 /* the other end close the connection -> KEEP-ALIVE */
1806 return -2;
1807 } else {
1808 return 0;
1813 CONNECTION_FUNC(mod_openssl_handle_con_accept)
1815 plugin_data *p = p_d;
1816 handler_ctx *hctx;
1817 server_socket *srv_sock = con->srv_socket;
1818 if (!srv_sock->is_ssl) return HANDLER_GO_ON;
1820 hctx = handler_ctx_init();
1821 hctx->con = con;
1822 hctx->srv = srv;
1823 con->plugin_ctx[p->id] = hctx;
1824 mod_openssl_patch_connection(srv, con, hctx);
1826 /* connect fd to SSL */
1827 hctx->ssl = SSL_new(p->config_storage[srv_sock->sidx]->ssl_ctx);
1828 if (NULL == hctx->ssl) {
1829 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1830 ERR_error_string(ERR_get_error(), NULL));
1831 return HANDLER_ERROR;
1834 buffer_copy_string_len(con->proto, CONST_STR_LEN("https"));
1835 con->network_read = connection_read_cq_ssl;
1836 con->network_write = connection_write_cq_ssl;
1837 SSL_set_app_data(hctx->ssl, hctx);
1838 SSL_set_accept_state(hctx->ssl);
1840 if (1 != (SSL_set_fd(hctx->ssl, con->fd))) {
1841 log_error_write(srv, __FILE__, __LINE__, "ss", "SSL:",
1842 ERR_error_string(ERR_get_error(), NULL));
1843 return HANDLER_ERROR;
1846 return HANDLER_GO_ON;
1850 static void
1851 mod_openssl_detach(handler_ctx *hctx)
1853 /* step aside from futher SSL processing
1854 * (used after handle_connection_shut_wr hook) */
1855 /* future: might restore prior network_read and network_write fn ptrs */
1856 hctx->con->is_ssl_sock = 0;
1857 /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */
1858 if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR);
1859 hctx->close_notify = 1;
1863 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr)
1865 plugin_data *p = p_d;
1866 handler_ctx *hctx = con->plugin_ctx[p->id];
1867 if (NULL == hctx) return HANDLER_GO_ON;
1869 hctx->close_notify = -2;
1870 if (SSL_is_init_finished(hctx->ssl)) {
1871 mod_openssl_close_notify(srv, hctx);
1873 else {
1874 mod_openssl_detach(hctx);
1877 return HANDLER_GO_ON;
1881 static int
1882 mod_openssl_close_notify(server *srv, handler_ctx *hctx)
1884 int ret, ssl_r;
1885 unsigned long err;
1887 if (1 == hctx->close_notify) return -2;
1889 ERR_clear_error();
1890 switch ((ret = SSL_shutdown(hctx->ssl))) {
1891 case 1:
1892 mod_openssl_detach(hctx);
1893 return -2;
1894 case 0:
1895 /* Drain SSL read buffers in case pending records need processing.
1896 * Limit to reading next record to avoid denial of service when CPU
1897 * processing TLS is slower than arrival speed of TLS data packets.
1898 * (unless hctx->conf.ssl_read_ahead is set)
1900 * references:
1902 * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection"
1903 * https://github.com/openssl/openssl/issues/6262
1905 * The peer is still allowed to send data after receiving the
1906 * "close notify" event. If the peer did send data it need to be
1907 * processed by calling SSL_read() before calling SSL_shutdown() a
1908 * second time. SSL_read() will indicate the end of the peer data by
1909 * returning <= 0 and SSL_get_error() returning
1910 * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read()
1911 * between SSL_shutdown() calls.
1913 * Additional discussion in "Auto retry in shutdown"
1914 * https://github.com/openssl/openssl/pull/6340
1916 ssl_r = SSL_pending(hctx->ssl);
1917 if (ssl_r) {
1918 do {
1919 char buf[4096];
1920 ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf));
1921 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret)));
1924 ERR_clear_error();
1925 switch ((ret = SSL_shutdown(hctx->ssl))) {
1926 case 1:
1927 mod_openssl_detach(hctx);
1928 return -2;
1929 case 0:
1930 hctx->close_notify = -1;
1931 return 0;
1932 default:
1933 break;
1936 /* fall through */
1937 default:
1939 if (!SSL_is_init_finished(hctx->ssl)) {
1940 mod_openssl_detach(hctx);
1941 return -2;
1944 switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) {
1945 case SSL_ERROR_ZERO_RETURN:
1946 case SSL_ERROR_WANT_WRITE:
1947 case SSL_ERROR_WANT_READ:
1948 hctx->close_notify = -1;
1949 return 0; /* try again later */
1950 case SSL_ERROR_SYSCALL:
1951 /* perhaps we have error waiting in our error-queue */
1952 if (0 != (err = ERR_get_error())) {
1953 do {
1954 log_error_write(srv, __FILE__, __LINE__, "sdds",
1955 "SSL:", ssl_r, ret,
1956 ERR_error_string(err, NULL));
1957 } while((err = ERR_get_error()));
1958 } else if (errno != 0) {
1959 /*ssl bug (see lighttpd ticket #2213): sometimes errno==0*/
1960 switch(errno) {
1961 case EPIPE:
1962 case ECONNRESET:
1963 break;
1964 default:
1965 log_error_write(srv, __FILE__, __LINE__, "sddds",
1966 "SSL (error):", ssl_r, ret, errno,
1967 strerror(errno));
1968 break;
1972 break;
1973 default:
1974 while((err = ERR_get_error())) {
1975 log_error_write(srv, __FILE__, __LINE__, "sdds",
1976 "SSL:", ssl_r, ret,
1977 ERR_error_string(err, NULL));
1980 break;
1983 ERR_clear_error();
1984 hctx->close_notify = -1;
1985 return ret;
1989 CONNECTION_FUNC(mod_openssl_handle_con_close)
1991 plugin_data *p = p_d;
1992 handler_ctx *hctx = con->plugin_ctx[p->id];
1993 if (NULL != hctx) {
1994 handler_ctx_free(hctx);
1995 con->plugin_ctx[p->id] = NULL;
1998 UNUSED(srv);
1999 return HANDLER_GO_ON;
2003 static void
2004 https_add_ssl_client_entries (server *srv, connection *con, handler_ctx *hctx)
2006 X509 *xs;
2007 X509_NAME *xn;
2008 int i, nentries;
2010 long vr = SSL_get_verify_result(hctx->ssl);
2011 if (vr != X509_V_OK) {
2012 char errstr[256];
2013 ERR_error_string_n(vr, errstr, sizeof(errstr));
2014 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("FAILED:"));
2015 buffer_append_string(srv->tmp_buf, errstr);
2016 http_header_env_set(con,
2017 CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2018 CONST_BUF_LEN(srv->tmp_buf));
2019 return;
2020 } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) {
2021 http_header_env_set(con,
2022 CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2023 CONST_STR_LEN("NONE"));
2024 return;
2025 } else {
2026 http_header_env_set(con,
2027 CONST_STR_LEN("SSL_CLIENT_VERIFY"),
2028 CONST_STR_LEN("SUCCESS"));
2031 xn = X509_get_subject_name(xs);
2033 char buf[256];
2034 int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf));
2035 if (len > 0) {
2036 if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1;
2037 http_header_env_set(con,
2038 CONST_STR_LEN("SSL_CLIENT_S_DN"),
2039 buf, (size_t)len);
2042 buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("SSL_CLIENT_S_DN_"));
2043 for (i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) {
2044 int xobjnid;
2045 const char * xobjsn;
2046 X509_NAME_ENTRY *xe;
2048 if (!(xe = X509_NAME_get_entry(xn, i))) {
2049 continue;
2051 xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe));
2052 xobjsn = OBJ_nid2sn(xobjnid);
2053 if (xobjsn) {
2054 buffer_string_set_length(srv->tmp_buf,sizeof("SSL_CLIENT_S_DN_")-1);
2055 buffer_append_string(srv->tmp_buf, xobjsn);
2056 http_header_env_set(con,
2057 CONST_BUF_LEN(srv->tmp_buf),
2058 (const char*)X509_NAME_ENTRY_get_data(xe)->data,
2059 X509_NAME_ENTRY_get_data(xe)->length);
2064 ASN1_INTEGER *xsn = X509_get_serialNumber(xs);
2065 BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL);
2066 char *serialHex = BN_bn2hex(serialBN);
2067 http_header_env_set(con,
2068 CONST_STR_LEN("SSL_CLIENT_M_SERIAL"),
2069 serialHex, strlen(serialHex));
2070 OPENSSL_free(serialHex);
2071 BN_free(serialBN);
2074 if (!buffer_string_is_empty(hctx->conf.ssl_verifyclient_username)) {
2075 /* pick one of the exported values as "REMOTE_USER", for example
2076 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID"
2077 * or
2078 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress"
2080 buffer *varname = hctx->conf.ssl_verifyclient_username;
2081 buffer *vb = http_header_env_get(con, CONST_BUF_LEN(varname));
2082 if (vb) { /* same as http_auth.c:http_auth_setenv() */
2083 http_header_env_set(con,
2084 CONST_STR_LEN("REMOTE_USER"),
2085 CONST_BUF_LEN(vb));
2086 http_header_env_set(con,
2087 CONST_STR_LEN("AUTH_TYPE"),
2088 CONST_STR_LEN("SSL_CLIENT_VERIFY"));
2092 if (hctx->conf.ssl_verifyclient_export_cert) {
2093 BIO *bio;
2094 if (NULL != (bio = BIO_new(BIO_s_mem()))) {
2095 buffer *cert = srv->tmp_buf;
2096 int n;
2098 PEM_write_bio_X509(bio, xs);
2099 n = BIO_pending(bio);
2101 buffer_string_prepare_copy(cert, n);
2102 BIO_read(bio, cert->ptr, n);
2103 BIO_free(bio);
2104 buffer_commit(cert, n);
2105 http_header_env_set(con,
2106 CONST_STR_LEN("SSL_CLIENT_CERT"),
2107 CONST_BUF_LEN(cert));
2110 X509_free(xs);
2114 static void
2115 http_cgi_ssl_env (server *srv, connection *con, handler_ctx *hctx)
2117 const char *s;
2118 const SSL_CIPHER *cipher;
2119 UNUSED(srv);
2121 s = SSL_get_version(hctx->ssl);
2122 http_header_env_set(con,
2123 CONST_STR_LEN("SSL_PROTOCOL"),
2124 s, strlen(s));
2126 if ((cipher = SSL_get_current_cipher(hctx->ssl))) {
2127 int usekeysize, algkeysize;
2128 char buf[LI_ITOSTRING_LENGTH];
2129 s = SSL_CIPHER_get_name(cipher);
2130 http_header_env_set(con,
2131 CONST_STR_LEN("SSL_CIPHER"),
2132 s, strlen(s));
2133 usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize);
2134 li_itostrn(buf, sizeof(buf), usekeysize);
2135 http_header_env_set(con,
2136 CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"),
2137 buf, strlen(buf));
2138 li_itostrn(buf, sizeof(buf), algkeysize);
2139 http_header_env_set(con,
2140 CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"),
2141 buf, strlen(buf));
2146 CONNECTION_FUNC(mod_openssl_handle_request_env)
2148 plugin_data *p = p_d;
2149 handler_ctx *hctx = con->plugin_ctx[p->id];
2150 if (NULL == hctx) return HANDLER_GO_ON;
2151 if (hctx->request_env_patched) return HANDLER_GO_ON;
2152 hctx->request_env_patched = 1;
2154 http_cgi_ssl_env(srv, con, hctx);
2155 if (hctx->conf.ssl_verifyclient) {
2156 https_add_ssl_client_entries(srv, con, hctx);
2159 return HANDLER_GO_ON;
2163 CONNECTION_FUNC(mod_openssl_handle_uri_raw)
2165 /* mod_openssl must be loaded prior to mod_auth
2166 * if mod_openssl is configured to set REMOTE_USER based on client cert */
2167 /* mod_openssl must be loaded after mod_extforward
2168 * if mod_openssl config is based on lighttpd.conf remote IP conditional
2169 * using remote IP address set by mod_extforward, *unless* PROXY protocol
2170 * is enabled with extforward.hap-PROXY = "enable", in which case the
2171 * reverse is true: mod_extforward must be loaded after mod_openssl */
2172 plugin_data *p = p_d;
2173 handler_ctx *hctx = con->plugin_ctx[p->id];
2174 if (NULL == hctx) return HANDLER_GO_ON;
2176 mod_openssl_patch_connection(srv, con, hctx);
2177 if (hctx->conf.ssl_verifyclient) {
2178 mod_openssl_handle_request_env(srv, con, p);
2181 return HANDLER_GO_ON;
2185 CONNECTION_FUNC(mod_openssl_handle_request_reset)
2187 plugin_data *p = p_d;
2188 handler_ctx *hctx = con->plugin_ctx[p->id];
2189 if (NULL == hctx) return HANDLER_GO_ON;
2191 hctx->request_env_patched = 0;
2193 UNUSED(srv);
2194 return HANDLER_GO_ON;
2198 int mod_openssl_plugin_init (plugin *p);
2199 int mod_openssl_plugin_init (plugin *p)
2201 p->version = LIGHTTPD_VERSION_ID;
2202 p->name = buffer_init_string("openssl");
2203 p->init = mod_openssl_init;
2204 p->cleanup = mod_openssl_free;
2205 p->priv_defaults= mod_openssl_set_defaults;
2207 p->handle_connection_accept = mod_openssl_handle_con_accept;
2208 p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr;
2209 p->handle_connection_close = mod_openssl_handle_con_close;
2210 p->handle_uri_raw = mod_openssl_handle_uri_raw;
2211 p->handle_request_env = mod_openssl_handle_request_env;
2212 p->connection_reset = mod_openssl_handle_request_reset;
2214 p->data = NULL;
2216 return 0;