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