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 HAVE_KRB5 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, 936 XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB); 937 BIO_gets(bio, buf, (int)sz); /*(may be truncated if len >= sz)*/ 938 BIO_free(bio); 939 return len; /*return value has similar semantics to that of snprintf()*/ 940 } 941 else { 942 buf[0] = '\0'; 943 return -1; 944 } 945 } 946 947 948 static void 949 ssl_info_callback (const SSL *ssl, int where, int ret) 950 { 951 UNUSED(ret); 952 953 if (0 != (where & SSL_CB_HANDSHAKE_START)) { 954 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 955 if (hctx->renegotiations >= 0) ++hctx->renegotiations; 956 } 957 #ifdef TLS1_3_VERSION 958 /* https://github.com/openssl/openssl/issues/5721 959 * "TLSv1.3 unexpected InfoCallback after handshake completed" */ 960 if (0 != (where & SSL_CB_HANDSHAKE_DONE)) { 961 /* SSL_version() is valid after initial handshake completed */ 962 if (SSL_version(ssl) >= TLS1_3_VERSION) { 963 /* https://wiki.openssl.org/index.php/TLS1.3 964 * "Renegotiation is not possible in a TLSv1.3 connection" */ 965 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 966 hctx->renegotiations = -1; 967 } 968 } 969 #endif 970 } 971 972 /* https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_verify(3)#EXAMPLES */ 973 static int 974 verify_callback(int preverify_ok, X509_STORE_CTX *ctx) 975 { 976 char buf[256]; 977 X509 *err_cert; 978 int err, depth; 979 SSL *ssl; 980 handler_ctx *hctx; 981 982 err = X509_STORE_CTX_get_error(ctx); 983 depth = X509_STORE_CTX_get_error_depth(ctx); 984 985 /* 986 * Retrieve the pointer to the SSL of the connection currently treated 987 * and the application specific data stored into the SSL object. 988 */ 989 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); 990 hctx = (handler_ctx *) SSL_get_app_data(ssl); 991 992 /* 993 * Catch a too long certificate chain. The depth limit set using 994 * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so 995 * that whenever the "depth>verify_depth" condition is met, we 996 * have violated the limit and want to log this error condition. 997 * We must do it here, because the CHAIN_TOO_LONG error would not 998 * be found explicitly; only errors introduced by cutting off the 999 * additional certificates would be logged. 1000 */ 1001 if (depth > hctx->conf.ssl_verifyclient_depth) { 1002 preverify_ok = 0; 1003 err = X509_V_ERR_CERT_CHAIN_TOO_LONG; 1004 X509_STORE_CTX_set_error(ctx, err); 1005 } 1006 1007 if (preverify_ok && 0 == depth && NULL != hctx->conf.ssl_ca_dn_file) { 1008 /* verify that client cert is issued by CA in ssl.ca-dn-file 1009 * if both ssl.ca-dn-file and ssl.ca-file were configured */ 1010 STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file; 1011 X509_NAME *issuer; 1012 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 1013 err_cert = X509_STORE_CTX_get_current_cert(ctx); 1014 #else 1015 err_cert = ctx->current_cert; 1016 #endif 1017 if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce; 1018 issuer = X509_get_issuer_name(err_cert); 1019 #if 0 /*(?desirable/undesirable to have cert_names sorted?)*/ 1020 if (-1 != sk_X509_NAME_find(cert_names, issuer)) 1021 return preverify_ok; /* match */ 1022 #else 1023 for (int i = 0, len = sk_X509_NAME_num(cert_names); i < len; ++i) { 1024 if (0 == X509_NAME_cmp(sk_X509_NAME_value(cert_names, i), issuer)) 1025 return preverify_ok; /* match */ 1026 } 1027 #endif 1028 1029 preverify_ok = 0; 1030 err = X509_V_ERR_CERT_REJECTED; 1031 X509_STORE_CTX_set_error(ctx, err); 1032 } 1033 1034 if (preverify_ok) { 1035 return preverify_ok; 1036 } 1037 1038 #if OPENSSL_VERSION_NUMBER >= 0x10002000L 1039 err_cert = X509_STORE_CTX_get_current_cert(ctx); 1040 #else 1041 err_cert = ctx->current_cert; 1042 #endif 1043 if (NULL == err_cert) return !hctx->conf.ssl_verifyclient_enforce; 1044 safer_X509_NAME_oneline(X509_get_subject_name(err_cert),buf,sizeof(buf)); 1045 log_error_st *errh = hctx->r->conf.errh; 1046 log_error(errh, __FILE__, __LINE__, 1047 "SSL: verify error:num=%d:%s:depth=%d:subject=%s", 1048 err, X509_verify_cert_error_string(err), depth, buf); 1049 1050 /* 1051 * At this point, err contains the last verification error. We can use 1052 * it for something special 1053 */ 1054 if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY || 1055 err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) { 1056 safer_X509_NAME_oneline(X509_get_issuer_name(err_cert),buf,sizeof(buf)); 1057 log_error(errh, __FILE__, __LINE__, "SSL: issuer=%s", buf); 1058 } 1059 1060 return !hctx->conf.ssl_verifyclient_enforce; 1061 } 1062 1063 enum { 1064 MOD_OPENSSL_ALPN_HTTP11 = 1 1065 ,MOD_OPENSSL_ALPN_HTTP10 = 2 1066 ,MOD_OPENSSL_ALPN_H2 = 3 1067 ,MOD_OPENSSL_ALPN_ACME_TLS_1 = 4 1068 }; 1069 1070 static int 1071 mod_openssl_cert_cb (SSL *ssl, void *arg) 1072 { 1073 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 1074 plugin_cert *pc = hctx->conf.pc; 1075 UNUSED(arg); 1076 if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) return 1; 1077 1078 if (!pc || NULL == pc->ssl_pemfile_x509 || NULL == pc->ssl_pemfile_pkey) { 1079 /* x509/pkey available <=> pemfile was set <=> pemfile got patched: 1080 * so this should never happen, unless you nest $SERVER["socket"] */ 1081 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1082 "SSL: no certificate/private key for TLS server name \"%s\". " 1083 "$SERVER[\"socket\"] should not be nested in other conditions.", 1084 hctx->r->uri.authority.ptr); 1085 return 0; 1086 } 1087 1088 /* first set certificate! 1089 * setting private key checks whether certificate matches it */ 1090 if (1 != SSL_use_certificate(ssl, pc->ssl_pemfile_x509)) { 1091 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1092 "SSL: failed to set certificate for TLS server name %s: %s", 1093 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL)); 1094 return 0; 1095 } 1096 1097 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \ 1098 && (!defined(LIBRESSL_VERSION_NUMBER) \ 1099 || LIBRESSL_VERSION_NUMBER >= 0x3000000fL) 1100 if (pc->ssl_pemfile_chain) 1101 SSL_set1_chain(ssl, pc->ssl_pemfile_chain); 1102 #if !defined(BORINGSSL_API_VERSION) \ 1103 && !defined(LIBRESSL_VERSION_NUMBER) 1104 /* (missing SSL_set1_chain_cert_store() and SSL_build_cert_chain()) */ 1105 else if (hctx->conf.ssl_ca_file && !pc->self_issued) { 1106 /* preserve legacy behavior whereby openssl will reuse CAs trusted for 1107 * certificate verification (set by SSL_CTX_load_verify_locations() in 1108 * SSL_CTX) in order to build certificate chain for server certificate 1109 * sent to client */ 1110 SSL_set1_chain_cert_store(ssl, hctx->conf.ssl_ca_file->certs); 1111 1112 if (1 != SSL_build_cert_chain(ssl, 1113 SSL_BUILD_CHAIN_FLAG_NO_ROOT 1114 | SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 1115 | SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)) { 1116 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1117 "SSL: building cert chain for TLS server name %s: %s", 1118 hctx->r->uri.authority.ptr, 1119 ERR_error_string(ERR_get_error(), NULL)); 1120 return 0; 1121 } 1122 else { /* copy chain for future reuse */ 1123 STACK_OF(X509) *chain = NULL; 1124 SSL_get0_chain_certs(ssl, &chain); 1125 pc->ssl_pemfile_chain = X509_chain_up_ref(chain); 1126 SSL_set1_chain_cert_store(ssl, NULL); 1127 } 1128 } 1129 #endif 1130 #endif 1131 1132 if (1 != SSL_use_PrivateKey(ssl, pc->ssl_pemfile_pkey)) { 1133 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1134 "SSL: failed to set private key for TLS server name %s: %s", 1135 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL)); 1136 return 0; 1137 } 1138 1139 #ifndef OPENSSL_NO_OCSP 1140 #ifdef BORINGSSL_API_VERSION 1141 /* BoringSSL suggests API different than SSL_CTX_set_tlsext_status_cb() */ 1142 buffer *ocsp_resp = pc->ssl_stapling; 1143 if (NULL != ocsp_resp 1144 && !SSL_set_ocsp_response(ssl, (uint8_t *)BUF_PTR_LEN(ocsp_resp))) { 1145 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1146 "SSL: failed to set OCSP response for TLS server name %s: %s", 1147 hctx->r->uri.authority.ptr, ERR_error_string(ERR_get_error(), NULL)); 1148 return 0; 1149 } 1150 #endif 1151 #endif 1152 1153 if (hctx->conf.ssl_verifyclient) { 1154 if (NULL == hctx->conf.ssl_ca_file) { 1155 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 1156 "SSL: can't verify client without ssl.verifyclient.ca-file " 1157 "for TLS server name %s", hctx->r->uri.authority.ptr); 1158 return 0; 1159 } 1160 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \ 1161 && !defined(LIBRESSL_VERSION_NUMBER) 1162 SSL_set1_verify_cert_store(ssl, hctx->conf.ssl_ca_file->certs); 1163 #endif 1164 /* WTH openssl? SSL_set_client_CA_list() calls set0_CA_list(), 1165 * but there is no set1_CA_list() to simply up the reference count 1166 * (without needing to duplicate the list) */ 1167 /* WolfSSL does not support setting per-session CA list; 1168 * limitation is to per-CTX CA list, and is not changed after SNI */ 1169 STACK_OF(X509_NAME) * const cert_names = hctx->conf.ssl_ca_dn_file 1170 ? hctx->conf.ssl_ca_dn_file 1171 : hctx->conf.ssl_ca_file->names; 1172 SSL_set_client_CA_list(ssl, SSL_dup_CA_list(cert_names)); 1173 int mode = SSL_VERIFY_PEER; 1174 if (hctx->conf.ssl_verifyclient_enforce) 1175 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; 1176 SSL_set_verify(ssl, mode, verify_callback); 1177 SSL_set_verify_depth(ssl, hctx->conf.ssl_verifyclient_depth + 1); 1178 } 1179 else { 1180 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL); 1181 } 1182 1183 return 1; 1184 } 1185 1186 #ifndef OPENSSL_NO_TLSEXT 1187 static int 1188 mod_openssl_SNI (handler_ctx *hctx, const char *servername, size_t len) 1189 { 1190 request_st * const r = hctx->r; 1191 if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/ 1192 log_error(r->conf.errh, __FILE__, __LINE__, 1193 "SSL: SNI name too long %.*s", (int)len, servername); 1194 return SSL_TLSEXT_ERR_ALERT_FATAL; 1195 } 1196 1197 /* use SNI to patch mod_openssl config and then reset COMP_HTTP_HOST */ 1198 buffer_copy_string_len_lc(&r->uri.authority, servername, len); 1199 #if 0 1200 /*(r->uri.authority used below for configuration before request read; 1201 * revisit for h2)*/ 1202 if (0 != http_request_host_policy(&r->uri.authority, 1203 r->conf.http_parseopts, 443)) 1204 return SSL_TLSEXT_ERR_ALERT_FATAL; 1205 #endif 1206 1207 r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME) 1208 | (1 << COMP_HTTP_HOST); 1209 mod_openssl_patch_config(r, &hctx->conf); 1210 /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */ 1211 /*(done in response.c:config_cond_cache_reset() after request hdrs read)*/ 1212 /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/ 1213 /*buffer_clear(&r->uri.authority);*/ 1214 1215 #if OPENSSL_VERSION_NUMBER >= 0x10002000L \ 1216 && !defined(LIBRESSL_VERSION_NUMBER) 1217 return SSL_TLSEXT_ERR_OK; 1218 #else 1219 return (mod_openssl_cert_cb(hctx->ssl, NULL) == 1) 1220 ? SSL_TLSEXT_ERR_OK 1221 : SSL_TLSEXT_ERR_ALERT_FATAL; 1222 #endif 1223 } 1224 1225 #ifdef SSL_CLIENT_HELLO_SUCCESS 1226 static int 1227 mod_openssl_client_hello_cb (SSL *ssl, int *al, void *srv) 1228 { 1229 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 1230 buffer_copy_string_len(&hctx->r->uri.scheme, CONST_STR_LEN("https")); 1231 UNUSED(srv); 1232 1233 const unsigned char *name; 1234 size_t len, slen; 1235 if (!SSL_client_hello_get0_ext(ssl, TLSEXT_TYPE_server_name, &name, &len)) { 1236 return SSL_CLIENT_HELLO_SUCCESS; /* client did not provide SNI */ 1237 } 1238 1239 /* expecting single element in the server_name extension; parse first one */ 1240 if (len > 5 1241 && (size_t)((name[0] << 8) + name[1]) == len-2 1242 && name[2] == TLSEXT_TYPE_server_name 1243 && (slen = (name[3] << 8) + name[4]) <= len-5) { /*(first)*/ 1244 int read_ahead = hctx->conf.ssl_read_ahead; 1245 int rc = mod_openssl_SNI(hctx, (const char *)name+5, slen); 1246 if (!read_ahead && hctx->conf.ssl_read_ahead) 1247 SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead); 1248 if (rc == SSL_TLSEXT_ERR_OK) 1249 return SSL_CLIENT_HELLO_SUCCESS; 1250 } 1251 1252 *al = TLS1_AD_UNRECOGNIZED_NAME; 1253 return SSL_CLIENT_HELLO_ERROR; 1254 } 1255 #else 1256 static int 1257 network_ssl_servername_callback (SSL *ssl, int *al, void *srv) 1258 { 1259 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 1260 buffer_copy_string_len(&hctx->r->uri.scheme, CONST_STR_LEN("https")); 1261 UNUSED(al); 1262 UNUSED(srv); 1263 1264 const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); 1265 if (NULL == servername) 1266 return SSL_TLSEXT_ERR_NOACK; /* client did not provide SNI */ 1267 size_t len = strlen(servername); 1268 int read_ahead = hctx->conf.ssl_read_ahead; 1269 int rc = mod_openssl_SNI(hctx, servername, len); 1270 if (!read_ahead && hctx->conf.ssl_read_ahead) 1271 SSL_set_read_ahead(ssl, hctx->conf.ssl_read_ahead); 1272 return rc; 1273 } 1274 #endif 1275 #endif 1276 1277 1278 #if defined(BORINGSSL_API_VERSION) \ 1279 || defined(LIBRESSL_VERSION_NUMBER) 1280 static unix_time64_t 1281 mod_openssl_asn1_time_to_posix (const ASN1_TIME *asn1time); 1282 #endif 1283 1284 static int 1285 mod_openssl_cert_is_active (const X509 *crt) 1286 { 1287 const ASN1_TIME *notBefore = X509_get0_notBefore(crt); 1288 const ASN1_TIME *notAfter = X509_get0_notAfter(crt); 1289 #if OPENSSL_VERSION_NUMBER < 0x10101000L \ 1290 || defined(BORINGSSL_API_VERSION) \ 1291 || defined(LIBRESSL_VERSION_NUMBER) 1292 const unix_time64_t before = mod_openssl_asn1_time_to_posix(notBefore); 1293 const unix_time64_t after = mod_openssl_asn1_time_to_posix(notAfter); 1294 const unix_time64_t now = log_epoch_secs; 1295 return (before <= now && now <= after); 1296 #else /*(-2 is an error from ASN1_TIME_cmp_time_t(); test cmp for -1, 0, 1)*/ 1297 const unix_time64_t now = log_epoch_secs; 1298 const int before_cmp = ASN1_TIME_cmp_time_t(notBefore, (time_t)now); 1299 const int after_cmp = ASN1_TIME_cmp_time_t(notAfter, (time_t)now); 1300 return ((before_cmp == -1 || before_cmp == 0) && 0 <= after_cmp); 1301 #endif 1302 } 1303 1304 1305 static X509 * 1306 mod_openssl_load_pem_file (const char *file, log_error_st *errh, STACK_OF(X509) **chain) 1307 { 1308 *chain = NULL; 1309 1310 off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/ 1311 char *data = fdevent_load_file(file, &dlen, errh, malloc, free); 1312 if (NULL == data) return NULL; 1313 1314 BIO *in = BIO_new_mem_buf(data, (int)dlen); 1315 if (NULL == in) { 1316 log_error(errh, __FILE__, __LINE__, 1317 "SSL: BIO_new/BIO_read_filename('%s') failed", file); 1318 if (dlen) ck_memzero(data, dlen); 1319 free(data); 1320 return NULL; 1321 } 1322 1323 X509 *x = PEM_read_bio_X509_AUX_secmem(in, NULL, NULL, NULL); 1324 if (NULL == x) { 1325 log_error(errh, __FILE__, __LINE__, 1326 "SSL: couldn't read X509 certificate from '%s'", file); 1327 } 1328 else if (!mod_openssl_load_X509_sk(file, errh, chain, in)) { 1329 X509_free(x); 1330 x = NULL; 1331 } 1332 else if (!mod_openssl_cert_is_active(x)) { 1333 log_error(errh, __FILE__, __LINE__, 1334 "SSL: inactive/expired X509 certificate '%s'", file); 1335 } 1336 1337 BIO_free(in); 1338 if (dlen) ck_memzero(data, dlen); 1339 free(data); 1340 return x; 1341 } 1342 1343 1344 static EVP_PKEY * 1345 mod_openssl_evp_pkey_load_pem_file (const char *file, log_error_st *errh) 1346 { 1347 off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/ 1348 char *data = fdevent_load_file(file, &dlen, errh, malloc, free); 1349 if (NULL == data) return NULL; 1350 EVP_PKEY *x = NULL; 1351 BIO *in = BIO_new_mem_buf(data, (int)dlen); 1352 if (NULL != in) { 1353 x = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL); 1354 BIO_free(in); 1355 } 1356 if (dlen) ck_memzero(data, dlen); 1357 free(data); 1358 1359 if (NULL == in) 1360 log_error(errh, __FILE__, __LINE__, 1361 "SSL: BIO_new/BIO_read_filename('%s') failed", file); 1362 else if (NULL == x) 1363 log_error(errh, __FILE__, __LINE__, 1364 "SSL: couldn't read private key from '%s'", file); 1365 1366 return x; 1367 } 1368 1369 1370 #ifndef OPENSSL_NO_OCSP 1371 1372 static buffer * 1373 mod_openssl_load_stapling_file (const char *file, log_error_st *errh, buffer *b) 1374 { 1375 /* load stapling .der into buffer *b only if successful 1376 * 1377 * Note: for some TLS libs, the OCSP stapling response is not copied when 1378 * assigned to a session (and is reasonable since not changed frequently) 1379 * - BoringSSL SSL_set_ocsp_response() 1380 * - WolfSSL SSL_set_tlsext_status_ocsp_resp() (differs from OpenSSL API) 1381 * Therefore, there is a potential race condition if the OCSP response is 1382 * assigned to the session during the handshake and the Server Hello is 1383 * partially sent, AND (unlikely, if possible at all), the TLS library is 1384 * in the middle of reading this OSCP response buffer. If the OCSP response 1385 * is replaced due to an updated ssl.stapling-file (checked periodically), 1386 * AND the buffer is resized, this would be a problem. Resizing the buffer 1387 * is unlikely since updated OSCP response for same certificate are 1388 * typically the same size with the signature and dates refreshed. 1389 */ 1390 1391 /* load raw .der file */ 1392 off_t dlen = 1*1024*1024;/*(arbitrary limit: 1 MB file; expect < 1 KB)*/ 1393 char *data = fdevent_load_file(file, &dlen, errh, malloc, free); 1394 if (NULL == data) return NULL; 1395 1396 #if defined(BORINGSSL_API_VERSION) 1397 1398 if (NULL == b) 1399 b = buffer_init(); 1400 else if (b->ptr) 1401 free(b->ptr); 1402 b->ptr = data; 1403 b->used = (uint32_t)dlen; 1404 b->size = (uint32_t)dlen+1; 1405 return b; 1406 1407 #else 1408 1409 BIO *in = BIO_new_mem_buf(data, (int)dlen); 1410 if (NULL == in) { 1411 log_error(errh, __FILE__, __LINE__, 1412 "SSL: BIO_new/BIO_read_filename('%s') failed", file); 1413 free(data); 1414 return NULL; 1415 } 1416 1417 OCSP_RESPONSE *x = d2i_OCSP_RESPONSE_bio(in, NULL); 1418 BIO_free(in); 1419 free(data); 1420 if (NULL == x) { 1421 log_error(errh, __FILE__, __LINE__, 1422 "SSL: OCSP stapling file read error: %s %s", 1423 ERR_error_string(ERR_get_error(), NULL), file); 1424 return NULL; 1425 } 1426 1427 unsigned char *rspder = NULL; 1428 int rspderlen = i2d_OCSP_RESPONSE(x, &rspder); 1429 1430 if (rspderlen > 0) { 1431 if (NULL == b) b = buffer_init(); 1432 buffer_copy_string_len(b, (char *)rspder, (uint32_t)rspderlen); 1433 } 1434 1435 OPENSSL_free(rspder); 1436 OCSP_RESPONSE_free(x); 1437 return rspderlen ? b : NULL; 1438 1439 #endif 1440 } 1441 1442 1443 static unix_time64_t 1444 mod_openssl_asn1_time_to_posix (const ASN1_TIME *asn1time) 1445 { 1446 #if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3050000fL 1447 /* LibreSSL was forked from OpenSSL 1.0.1; does not have ASN1_TIME_diff */ 1448 1449 /*(Note: all certificate times are expected to use UTC)*/ 1450 /*(Note: does not strictly validate string contains appropriate digits)*/ 1451 /*(Note: incorrectly assumes GMT if 'Z' or offset not provided)*/ 1452 /*(Note: incorrectly ignores if local timezone might be in DST)*/ 1453 1454 if (NULL == asn1time || NULL == asn1time->data) return -1; 1455 const char *s = (const char *)asn1time->data; 1456 size_t len = strlen(s); 1457 struct tm x; 1458 x.tm_isdst = 0; 1459 x.tm_yday = 0; 1460 x.tm_wday = 0; 1461 switch (asn1time->type) { 1462 case V_ASN1_UTCTIME: /* 2-digit year */ 1463 if (len < 8) return -1; 1464 len -= 8; 1465 x.tm_year = (s[0]-'0')*10 + (s[1]-'0'); 1466 x.tm_year += (x.tm_year < 50 ? 2000 : 1900); 1467 s += 2; 1468 break; 1469 case V_ASN1_GENERALIZEDTIME: /* 4-digit year */ 1470 if (len < 10) return -1; 1471 len -= 10; 1472 x.tm_year = (s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+(s[3]-'0'); 1473 s += 4; 1474 break; 1475 default: 1476 return -1; 1477 } 1478 x.tm_mon = (s[0]-'0')*10 + (s[1]-'0'); 1479 x.tm_mday = (s[2]-'0')*10 + (s[3]-'0'); 1480 x.tm_hour = (s[4]-'0')*10 + (s[5]-'0'); 1481 x.tm_min = 0; 1482 x.tm_sec = 0; 1483 s += 6; 1484 if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') { 1485 len -= 2; 1486 x.tm_min = (s[0]-'0')*10 + (s[1]-'0'); 1487 s += 2; 1488 if (len >= 2 && s[0] != '+' && s[0] != '-' && s[0] != 'Z') { 1489 len -= 2; 1490 x.tm_sec = (s[0]-'0')*10 + (s[1]-'0'); 1491 s += 2; 1492 if (len && s[0] == '.') { 1493 /*(ignore .fff fractional seconds; 1494 * should be up to 3 digits but we ignore more)*/ 1495 do { ++s; --len; } while (*s >= '0' && *s <= '9'); 1496 } 1497 } 1498 } 1499 int offset = 0; 1500 if ((*s == '-' || *s == '+') && len != 5) { 1501 offset = ((s[1]-'0')*10 + (s[2]-'0')) * 3600 1502 + ((s[3]-'0')*10 + (s[4]-'0')) * 60; 1503 if (*s == '-') offset = -offset; 1504 } 1505 else if (s[0] != '\0' && (s[0] != 'Z' || s[1] != '\0')) 1506 return -1; 1507 1508 if (x.tm_year == 9999 && x.tm_mon == 12 && x.tm_mday == 31 1509 && x.tm_hour == 23 && x.tm_min == 59 && x.tm_sec == 59 && s[0] == 'Z') 1510 return -1; // 99991231235959Z RFC 5280 1511 1512 x.tm_year-= 1900; 1513 x.tm_mon -= 1; 1514 time_t t = timegm(&x); 1515 return (t != -1) ? TIME64_CAST(t) + offset : t; 1516 1517 #else 1518 1519 /* Note: this does not check for integer overflow of time_t! */ 1520 int day, sec; 1521 return ASN1_TIME_diff(&day, &sec, NULL, asn1time) 1522 ? log_epoch_secs + day*86400 + sec 1523 : -1; 1524 1525 #endif 1526 } 1527 1528 1529 static unix_time64_t 1530 mod_openssl_ocsp_next_update (plugin_cert *pc) 1531 { 1532 #if defined(BORINGSSL_API_VERSION) 1533 UNUSED(pc); 1534 return -1; /*(not implemented)*/ 1535 #else 1536 buffer *der = pc->ssl_stapling; 1537 const unsigned char *p = (unsigned char *)der->ptr; /*(p gets modified)*/ 1538 OCSP_RESPONSE *ocsp = d2i_OCSP_RESPONSE(NULL, &p, buffer_clen(der)); 1539 if (NULL == ocsp) return -1; 1540 OCSP_BASICRESP *bs = OCSP_response_get1_basic(ocsp); 1541 if (NULL == bs) { 1542 OCSP_RESPONSE_free(ocsp); 1543 return -1; 1544 } 1545 1546 /* XXX: should save and evaluate cert status returned by these calls */ 1547 ASN1_TIME *nextupd = NULL; 1548 OCSP_single_get0_status(OCSP_resp_get0(bs, 0), NULL, NULL, NULL, &nextupd); 1549 unix_time64_t t = nextupd ? mod_openssl_asn1_time_to_posix(nextupd) : -1; 1550 1551 /* Note: trust external process which creates ssl.stapling-file to verify 1552 * (as well as to validate certificate status) 1553 * future: verify OCSP response here to double-check */ 1554 1555 OCSP_BASICRESP_free(bs); 1556 OCSP_RESPONSE_free(ocsp); 1557 1558 return t; 1559 #endif 1560 } 1561 1562 1563 __attribute_cold__ 1564 static void 1565 mod_openssl_expire_stapling_file (server *srv, plugin_cert *pc) 1566 { 1567 if (NULL == pc->ssl_stapling) /*(previously discarded or never loaded)*/ 1568 return; 1569 1570 /* discard expired OCSP stapling response */ 1571 buffer_free(pc->ssl_stapling); 1572 pc->ssl_stapling = NULL; 1573 if (pc->must_staple) 1574 log_error(srv->errh, __FILE__, __LINE__, 1575 "certificate marked OCSP Must-Staple, " 1576 "but OCSP response expired from ssl.stapling-file %s", 1577 pc->ssl_stapling_file->ptr); 1578 } 1579 1580 1581 static int 1582 mod_openssl_reload_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts) 1583 { 1584 buffer *b = mod_openssl_load_stapling_file(pc->ssl_stapling_file->ptr, 1585 srv->errh, pc->ssl_stapling); 1586 if (!b) return 0; 1587 1588 pc->ssl_stapling = b; /*(unchanged unless orig was NULL)*/ 1589 pc->ssl_stapling_loadts = cur_ts; 1590 pc->ssl_stapling_nextts = mod_openssl_ocsp_next_update(pc); 1591 if (pc->ssl_stapling_nextts == -1) { 1592 /* "Next Update" might not be provided by OCSP responder 1593 * Use 3600 sec (1 hour) in that case. */ 1594 /* retry in 1 hour if unable to determine Next Update */ 1595 pc->ssl_stapling_nextts = cur_ts + 3600; 1596 pc->ssl_stapling_loadts = 0; 1597 } 1598 else if (pc->ssl_stapling_nextts < cur_ts) { 1599 mod_openssl_expire_stapling_file(srv, pc); 1600 return 0; 1601 } 1602 1603 return 1; 1604 } 1605 1606 1607 static int 1608 mod_openssl_refresh_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts) 1609 { 1610 if (pc->ssl_stapling && pc->ssl_stapling_nextts > cur_ts + 256) 1611 return 1; /* skip check for refresh unless close to expire */ 1612 struct stat st; 1613 if (0 != stat(pc->ssl_stapling_file->ptr, &st) 1614 || TIME64_CAST(st.st_mtime) <= pc->ssl_stapling_loadts) { 1615 if (pc->ssl_stapling && pc->ssl_stapling_nextts < cur_ts) 1616 mod_openssl_expire_stapling_file(srv, pc); 1617 return 1; 1618 } 1619 return mod_openssl_reload_stapling_file(srv, pc, cur_ts); 1620 } 1621 1622 1623 static void 1624 mod_openssl_refresh_stapling_files (server *srv, const plugin_data *p, const unix_time64_t cur_ts) 1625 { 1626 /* future: might construct array of (plugin_cert *) at startup 1627 * to avoid the need to search for them here */ 1628 /* (init i to 0 if global context; to 1 to skip empty global context) */ 1629 if (NULL == p->cvlist) return; 1630 for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) { 1631 const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 1632 for (; cpv->k_id != -1; ++cpv) { 1633 if (cpv->k_id != 0) continue; /* k_id == 0 for ssl.pemfile */ 1634 if (cpv->vtype != T_CONFIG_LOCAL) continue; 1635 plugin_cert *pc = cpv->v.v; 1636 if (pc->ssl_stapling_file) 1637 mod_openssl_refresh_stapling_file(srv, pc, cur_ts); 1638 } 1639 } 1640 } 1641 1642 1643 static int 1644 mod_openssl_crt_must_staple (const X509 *crt) 1645 { 1646 #if OPENSSL_VERSION_NUMBER < 0x10100000L \ 1647 || defined(BORINGSSL_API_VERSION) \ 1648 || defined(LIBRESSL_VERSION_NUMBER) 1649 /*(not currently supported in BoringSSL or LibreSSL)*/ 1650 UNUSED(crt); 1651 return 0; 1652 #else 1653 /* openssl/x509v3.h:typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE; */ 1654 1655 TLS_FEATURE *tlsf = X509_get_ext_d2i(crt, NID_tlsfeature, NULL, NULL); 1656 if (NULL == tlsf) return 0; 1657 1658 int rc = 0; 1659 1660 for (int i = 0; i < sk_ASN1_INTEGER_num(tlsf); ++i) { 1661 ASN1_INTEGER *ai = sk_ASN1_INTEGER_value(tlsf, i); 1662 long tlsextid = ASN1_INTEGER_get(ai); 1663 if (tlsextid == 5) { /* 5 = OCSP Must-Staple */ 1664 rc = 1; 1665 break; 1666 } 1667 } 1668 1669 sk_ASN1_INTEGER_pop_free(tlsf, ASN1_INTEGER_free); 1670 return rc; /* 1 if OCSP Must-Staple found; 0 if not */ 1671 #endif 1672 } 1673 1674 #endif /* OPENSSL_NO_OCSP */ 1675 1676 1677 static plugin_cert * 1678 network_openssl_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey, const buffer *ssl_stapling_file) 1679 { 1680 if (!mod_openssl_init_once_openssl(srv)) return NULL; 1681 1682 STACK_OF(X509) *ssl_pemfile_chain = NULL; 1683 X509 *ssl_pemfile_x509 = 1684 mod_openssl_load_pem_file(pemfile->ptr, srv->errh, &ssl_pemfile_chain); 1685 if (NULL == ssl_pemfile_x509) 1686 return NULL; 1687 1688 EVP_PKEY *ssl_pemfile_pkey = 1689 mod_openssl_evp_pkey_load_pem_file(privkey->ptr, srv->errh); 1690 if (NULL == ssl_pemfile_pkey) { 1691 X509_free(ssl_pemfile_x509); 1692 sk_X509_pop_free(ssl_pemfile_chain, X509_free); 1693 return NULL; 1694 } 1695 1696 if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) { 1697 log_error(srv->errh, __FILE__, __LINE__, "SSL:" 1698 "Private key does not match the certificate public key, " 1699 "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL), 1700 pemfile->ptr, privkey->ptr); 1701 EVP_PKEY_free(ssl_pemfile_pkey); 1702 X509_free(ssl_pemfile_x509); 1703 sk_X509_pop_free(ssl_pemfile_chain, X509_free); 1704 return NULL; 1705 } 1706 1707 plugin_cert *pc = malloc(sizeof(plugin_cert)); 1708 force_assert(pc); 1709 pc->ssl_pemfile_pkey = ssl_pemfile_pkey; 1710 pc->ssl_pemfile_x509 = ssl_pemfile_x509; 1711 pc->ssl_pemfile_chain= ssl_pemfile_chain; 1712 pc->ssl_pemfile = pemfile; 1713 pc->ssl_privkey = privkey; 1714 pc->ssl_stapling = NULL; 1715 pc->ssl_stapling_file= ssl_stapling_file; 1716 pc->ssl_stapling_loadts = 0; 1717 pc->ssl_stapling_nextts = 0; 1718 #ifndef OPENSSL_NO_OCSP 1719 pc->must_staple = mod_openssl_crt_must_staple(ssl_pemfile_x509); 1720 #else 1721 pc->must_staple = 0; 1722 #endif 1723 pc->self_issued = 1724 (0 == X509_NAME_cmp(X509_get_subject_name(ssl_pemfile_x509), 1725 X509_get_issuer_name(ssl_pemfile_x509))); 1726 1727 if (pc->ssl_stapling_file) { 1728 #ifndef OPENSSL_NO_OCSP 1729 if (!mod_openssl_reload_stapling_file(srv, pc, log_epoch_secs)) { 1730 /* continue without OCSP response if there is an error */ 1731 } 1732 #else 1733 log_error(srv->errh, __FILE__, __LINE__, "SSL:" 1734 "OCSP stapling not supported; ignoring %s", 1735 pc->ssl_stapling_file->ptr); 1736 #endif 1737 } 1738 else if (pc->must_staple) { 1739 log_error(srv->errh, __FILE__, __LINE__, 1740 "certificate %s marked OCSP Must-Staple, " 1741 "but ssl.stapling-file not provided", pemfile->ptr); 1742 } 1743 1744 #if 0 1745 const ASN1_TIME *notAfter = X509_get0_notAfter(ssl_pemfile_x509); 1746 pc->notAfter = mod_openssl_asn1_time_to_posix(notAfter); 1747 #endif 1748 1749 return pc; 1750 } 1751 1752 1753 #ifndef OPENSSL_NO_TLSEXT 1754 1755 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation 1756 1757 static int 1758 mod_openssl_acme_tls_1 (SSL *ssl, handler_ctx *hctx) 1759 { 1760 buffer * const b = hctx->tmp_buf; 1761 const buffer * const name = &hctx->r->uri.authority; 1762 log_error_st * const errh = hctx->r->conf.errh; 1763 X509 *ssl_pemfile_x509 = NULL; 1764 STACK_OF(X509) *ssl_pemfile_chain = NULL; 1765 EVP_PKEY *ssl_pemfile_pkey = NULL; 1766 size_t len; 1767 int rc = SSL_TLSEXT_ERR_ALERT_FATAL; 1768 1769 /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/ 1770 if (!hctx->conf.ssl_acme_tls_1) 1771 return SSL_TLSEXT_ERR_NOACK; /*(reuse value here for not-configured)*/ 1772 1773 /* check if SNI set server name (required for acme-tls/1 protocol) 1774 * and perform simple path checks for no '/' 1775 * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */ 1776 if (buffer_is_blank(name)) return rc; 1777 if (NULL != strchr(name->ptr, '/')) return rc; 1778 if (name->ptr[0] == '.') return rc; 1779 #if 0 1780 if (0 != http_request_host_policy(name,hctx->r->conf.http_parseopts,443)) 1781 return rc; 1782 #endif 1783 buffer_copy_path_len2(b, BUF_PTR_LEN(hctx->conf.ssl_acme_tls_1), 1784 BUF_PTR_LEN(name)); 1785 len = buffer_clen(b); 1786 1787 do { 1788 buffer_append_string_len(b, CONST_STR_LEN(".crt.pem")); 1789 ssl_pemfile_x509 = 1790 mod_openssl_load_pem_file(b->ptr, errh, &ssl_pemfile_chain); 1791 if (NULL == ssl_pemfile_x509) { 1792 log_error(errh, __FILE__, __LINE__, 1793 "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr); 1794 break; 1795 } 1796 1797 buffer_truncate(b, len); /*(remove ".crt.pem")*/ 1798 buffer_append_string_len(b, CONST_STR_LEN(".key.pem")); 1799 ssl_pemfile_pkey = mod_openssl_evp_pkey_load_pem_file(b->ptr, errh); 1800 if (NULL == ssl_pemfile_pkey) { 1801 log_error(errh, __FILE__, __LINE__, 1802 "SSL: Failed to load acme-tls/1 pemfile: %s", b->ptr); 1803 break; 1804 } 1805 1806 #if 0 /* redundant with below? */ 1807 if (!X509_check_private_key(ssl_pemfile_x509, ssl_pemfile_pkey)) { 1808 log_error(errh, __FILE__, __LINE__, 1809 "SSL: Private key does not match acme-tls/1 " 1810 "certificate public key, reason: %s %s" 1811 ERR_error_string(ERR_get_error(), NULL), b->ptr); 1812 break; 1813 } 1814 #endif 1815 1816 /* first set certificate! 1817 * setting private key checks whether certificate matches it */ 1818 if (1 != SSL_use_certificate(ssl, ssl_pemfile_x509)) { 1819 log_error(errh, __FILE__, __LINE__, 1820 "SSL: failed to set acme-tls/1 certificate for TLS server " 1821 "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL)); 1822 break; 1823 } 1824 1825 if (ssl_pemfile_chain) { 1826 SSL_set0_chain(ssl, ssl_pemfile_chain); 1827 ssl_pemfile_chain = NULL; 1828 } 1829 1830 if (1 != SSL_use_PrivateKey(ssl, ssl_pemfile_pkey)) { 1831 log_error(errh, __FILE__, __LINE__, 1832 "SSL: failed to set acme-tls/1 private key for TLS server " 1833 "name %s: %s", name->ptr, ERR_error_string(ERR_get_error(),NULL)); 1834 break; 1835 } 1836 1837 hctx->conf.ssl_verifyclient_enforce = 0; 1838 SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL); 1839 rc = SSL_TLSEXT_ERR_OK; 1840 } while (0); 1841 1842 if (ssl_pemfile_pkey) EVP_PKEY_free(ssl_pemfile_pkey); 1843 if (ssl_pemfile_x509) X509_free(ssl_pemfile_x509); 1844 if (ssl_pemfile_chain) 1845 sk_X509_pop_free(ssl_pemfile_chain, X509_free); 1846 1847 return rc; 1848 } 1849 1850 static int 1851 mod_openssl_alpn_h2_policy (handler_ctx * const hctx) 1852 { 1853 /*(currently called after handshake has completed)*/ 1854 #if 0 /* SNI omitted by client when connecting to IP instead of to name */ 1855 if (buffer_is_blank(&hctx->r->uri.authority)) { 1856 log_error(hctx->errh, __FILE__, __LINE__, 1857 "SSL: error ALPN h2 without SNI"); 1858 return -1; 1859 } 1860 #endif 1861 if (SSL_version(hctx->ssl) < TLS1_2_VERSION) { 1862 log_error(hctx->errh, __FILE__, __LINE__, 1863 "SSL: error ALPN h2 requires TLSv1.2 or later"); 1864 return -1; 1865 } 1866 1867 return 0; 1868 } 1869 1870 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */ 1871 static int 1872 mod_openssl_alpn_select_cb (SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) 1873 { 1874 handler_ctx *hctx = (handler_ctx *) SSL_get_app_data(ssl); 1875 unsigned short proto; 1876 UNUSED(arg); 1877 1878 for (unsigned int i = 0, n; i < inlen; i += n) { 1879 n = in[i++]; 1880 if (i+n > inlen || 0 == n) break; 1881 switch (n) { 1882 case 2: /* "h2" */ 1883 if (in[i] == 'h' && in[i+1] == '2') { 1884 if (!hctx->r->conf.h2proto) continue; 1885 proto = MOD_OPENSSL_ALPN_H2; 1886 if (hctx->r->handler_module == NULL)/*(e.g. not mod_sockproxy)*/ 1887 hctx->r->http_version = HTTP_VERSION_2; 1888 break; 1889 } 1890 continue; 1891 case 8: /* "http/1.1" "http/1.0" */ 1892 if (0 == memcmp(in+i, "http/1.", 7)) { 1893 if (in[i+7] == '1') { 1894 proto = MOD_OPENSSL_ALPN_HTTP11; 1895 break; 1896 } 1897 if (in[i+7] == '0') { 1898 proto = MOD_OPENSSL_ALPN_HTTP10; 1899 break; 1900 } 1901 } 1902 continue; 1903 case 10: /* "acme-tls/1" */ 1904 if (0 == memcmp(in+i, "acme-tls/1", 10)) { 1905 int rc = mod_openssl_acme_tls_1(ssl, hctx); 1906 if (rc == SSL_TLSEXT_ERR_OK) { 1907 proto = MOD_OPENSSL_ALPN_ACME_TLS_1; 1908 break; 1909 } 1910 /* (use SSL_TLSEXT_ERR_NOACK for not-configured) */ 1911 if (rc == SSL_TLSEXT_ERR_NOACK) continue; 1912 return rc; 1913 } 1914 continue; 1915 default: 1916 continue; 1917 } 1918 1919 hctx->alpn = proto; 1920 *out = in+i; 1921 *outlen = n; 1922 return SSL_TLSEXT_ERR_OK; 1923 } 1924 1925 #if OPENSSL_VERSION_NUMBER < 0x10100000L 1926 return SSL_TLSEXT_ERR_NOACK; 1927 #else 1928 return hctx->r->handler_module /*(e.g. mod_sockproxy)*/ 1929 ? SSL_TLSEXT_ERR_NOACK 1930 : SSL_TLSEXT_ERR_ALERT_FATAL; 1931 #endif 1932 } 1933 1934 #endif /* TLSEXT_TYPE_application_layer_protocol_negotiation */ 1935 1936 #endif /* OPENSSL_NO_TLSEXT */ 1937 1938 1939 #if defined(BORINGSSL_API_VERSION) \ 1940 || defined(LIBRESSL_VERSION_NUMBER) 1941 static int 1942 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s); 1943 #endif 1944 1945 1946 static int 1947 network_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s) 1948 { 1949 #ifdef SSL_CONF_FLAG_CMDLINE 1950 1951 int rc = 0; 1952 const data_string *ds; 1953 SSL_CONF_CTX * const cctx = SSL_CONF_CTX_new(); 1954 SSL_CONF_CTX_set_ssl_ctx(cctx, s->ssl_ctx); 1955 SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE 1956 | SSL_CONF_FLAG_SERVER 1957 | SSL_CONF_FLAG_SHOW_ERRORS 1958 | SSL_CONF_FLAG_CERTIFICATE); 1959 1960 /* always disable null and export ciphers */ 1961 ds = (const data_string *) 1962 array_get_element_klen(s->ssl_conf_cmd, 1963 CONST_STR_LEN("CipherString")); 1964 if (NULL != ds) { 1965 buffer *cipher_string = 1966 array_get_buf_ptr(s->ssl_conf_cmd, CONST_STR_LEN("CipherString")); 1967 if (buffer_is_blank(cipher_string)) 1968 buffer_append_string_len(cipher_string, CONST_STR_LEN("HIGH")); 1969 buffer_append_string_len(cipher_string, 1970 CONST_STR_LEN(":!aNULL:!eNULL:!EXP")); 1971 } 1972 1973 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) { 1974 ds = (data_string *)s->ssl_conf_cmd->data[i]; 1975 /* ("SecurityLevel" is lighttpd extension to SSL_CONF_cmd() syntax) 1976 * SSL_CTX_set_security_level() is specific to OpenSSL >= 1.1.0 */ 1977 if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("SecurityLevel"))) { 1978 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 1979 int level = atoi(ds->value.ptr); 1980 if (level >= 0) SSL_CTX_set_security_level(s->ssl_ctx, level); 1981 #endif 1982 continue; 1983 } 1984 ERR_clear_error(); 1985 if (SSL_CONF_cmd(cctx, ds->key.ptr, ds->value.ptr) <= 0) { 1986 log_error(srv->errh, __FILE__, __LINE__, 1987 "SSL: SSL_CONF_cmd %s %s: %s", ds->key.ptr, ds->value.ptr, 1988 ERR_error_string(ERR_get_error(), NULL)); 1989 rc = -1; 1990 break; 1991 } 1992 } 1993 1994 if (0 == rc && 1 != SSL_CONF_CTX_finish(cctx)) { 1995 log_error(srv->errh, __FILE__, __LINE__, 1996 "SSL: SSL_CONF_CTX_finish(): %s", 1997 ERR_error_string(ERR_get_error(), NULL)); 1998 rc = -1; 1999 } 2000 2001 SSL_CONF_CTX_free(cctx); 2002 return rc; 2003 2004 #elif defined(BORINGSSL_API_VERSION) \ 2005 || defined(LIBRESSL_VERSION_NUMBER) 2006 2007 return mod_openssl_ssl_conf_cmd(srv, s); 2008 2009 #else 2010 2011 UNUSED(s); 2012 log_error(srv->errh, __FILE__, __LINE__, 2013 "SSL: ssl.openssl.ssl-conf-cmd not available; ignored"); 2014 return 0; 2015 2016 #endif 2017 } 2018 2019 2020 #if OPENSSL_VERSION_NUMBER < 0x30000000L 2021 #ifndef OPENSSL_NO_DH 2022 #if OPENSSL_VERSION_NUMBER < 0x10100000L \ 2023 || (defined(LIBRESSL_VERSION_NUMBER) \ 2024 && LIBRESSL_VERSION_NUMBER < 0x2070000fL) 2025 #define DH_set0_pqg(dh, dh_p, NULL, dh_g) \ 2026 ((dh)->p = (dh_p), (dh)->g = (dh_g), (dh_p) != NULL && (dh_g) != NULL) 2027 #endif 2028 /* https://tools.ietf.org/html/rfc7919#appendix-A.1 2029 * A.1. ffdhe2048 2030 * 2031 * https://ssl-config.mozilla.org/ffdhe2048.txt 2032 * C code generated with: openssl dhparam -C -in ffdhe2048.txt 2033 */ 2034 static DH *get_dh2048(void) 2035 { 2036 static unsigned char dhp_2048[] = { 2037 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 2038 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, 0xAF, 0xDC, 0x56, 0x20, 2039 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 2040 0x36, 0x95, 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 2041 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, 0x7D, 0x2F, 2042 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 2043 0xAE, 0xC4, 0x61, 0x7A, 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 2044 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, 2045 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 2046 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, 0x98, 0x4F, 0x0C, 0x70, 2047 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 2048 0xE8, 0x72, 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 2049 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, 0xBC, 0x0A, 2050 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 2051 0xB2, 0xC8, 0xE3, 0xFB, 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 2052 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, 2053 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 2054 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, 0x9E, 0x02, 0xFC, 0xE1, 2055 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 2056 0x2F, 0x61, 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 2057 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, 0xC3, 0xFE, 2058 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 2059 0x2E, 0xC2, 0x20, 0x05, 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 2060 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, 2061 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, 0xFF, 0xFF, 2062 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF 2063 }; 2064 static unsigned char dhg_2048[] = { 2065 0x02 2066 }; 2067 DH *dh = DH_new(); 2068 BIGNUM *p, *g; 2069 2070 if (dh == NULL) 2071 return NULL; 2072 p = BN_bin2bn(dhp_2048, sizeof(dhp_2048), NULL); 2073 g = BN_bin2bn(dhg_2048, sizeof(dhg_2048), NULL); 2074 if (p == NULL || g == NULL || !DH_set0_pqg(dh, p, NULL, g)) { 2075 DH_free(dh); 2076 BN_free(p); 2077 BN_free(g); 2078 return NULL; 2079 } 2080 return dh; 2081 } 2082 #endif 2083 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */ 2084 2085 2086 static int 2087 mod_openssl_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *ssl_ec_curve) 2088 { 2089 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL 2090 #ifndef OPENSSL_NO_ECDH 2091 /* Support for Elliptic-Curve Diffie-Hellman key exchange */ 2092 /* OpenSSL only supports the "named curves" from RFC 4492, section 5.1.1. */ 2093 const char *curve = ssl_ec_curve ? ssl_ec_curve->ptr : "prime256v1"; 2094 int nid = 0; 2095 if (ssl_ec_curve) { 2096 /* OpenSSL only supports the "named curves" 2097 * from RFC 4492, section 5.1.1. */ 2098 nid = OBJ_sn2nid((char *) curve); 2099 if (nid == 0) { 2100 log_error(srv->errh, __FILE__, __LINE__, 2101 "SSL: Unknown curve name %s", curve); 2102 return 0; 2103 } 2104 } 2105 else { 2106 #if OPENSSL_VERSION_NUMBER < 0x10002000 2107 /* Default curve */ 2108 nid = OBJ_sn2nid("prime256v1"); 2109 #elif OPENSSL_VERSION_NUMBER < 0x10100000L \ 2110 || defined(LIBRESSL_VERSION_NUMBER) 2111 if (!SSL_CTX_set_ecdh_auto(s->ssl_ctx, 1)) { 2112 log_error(srv->errh, __FILE__, __LINE__, 2113 "SSL: SSL_CTX_set_ecdh_auto() failed"); 2114 } 2115 #endif 2116 } 2117 if (nid) { 2118 #if OPENSSL_VERSION_NUMBER < 0x30000000L 2119 EC_KEY *ecdh; 2120 ecdh = EC_KEY_new_by_curve_name(nid); 2121 if (ecdh == NULL) { 2122 log_error(srv->errh, __FILE__, __LINE__, 2123 "SSL: Unable to create curve %s", curve); 2124 return 0; 2125 } 2126 SSL_CTX_set_tmp_ecdh(s->ssl_ctx, ecdh); 2127 EC_KEY_free(ecdh); 2128 #else 2129 /* SSL_CTX_set1_groups() available in openssl 1.1.1, but might 2130 * not be present in alt TLS libs (libressl or boringssl) */ 2131 if (1 != SSL_CTX_set1_groups(s->ssl_ctx, &nid, 1)) { 2132 log_error(srv->errh, __FILE__, __LINE__, 2133 "SSL: Unable to config curve %s", curve); 2134 return 0; 2135 } 2136 #endif 2137 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_SINGLE_ECDH_USE); 2138 } 2139 #endif 2140 #endif 2141 UNUSED(srv); 2142 UNUSED(s); 2143 UNUSED(ssl_ec_curve); 2144 2145 return 1; 2146 } 2147 2148 2149 static int 2150 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p) 2151 { 2152 /* load SSL certificates */ 2153 2154 #ifndef SSL_OP_NO_COMPRESSION 2155 #define SSL_OP_NO_COMPRESSION 0 2156 #endif 2157 #ifndef SSL_MODE_RELEASE_BUFFERS /* OpenSSL >= 1.0.0 */ 2158 #define SSL_MODE_RELEASE_BUFFERS 0 2159 #endif 2160 long ssloptions = SSL_OP_ALL 2161 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 2162 | SSL_OP_NO_COMPRESSION; 2163 2164 #if OPENSSL_VERSION_NUMBER >= 0x10100000L 2165 s->ssl_ctx = (!s->ssl_use_sslv2 && !s->ssl_use_sslv3) 2166 ? SSL_CTX_new(TLS_server_method()) 2167 : SSL_CTX_new(SSLv23_server_method()); 2168 #else 2169 s->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); 2170 #endif 2171 if (NULL == s->ssl_ctx) { 2172 log_error(srv->errh, __FILE__, __LINE__, 2173 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 2174 return -1; 2175 } 2176 2177 #ifdef SSL_OP_NO_RENEGOTIATION /* openssl 1.1.0 */ 2178 if (s->ssl_disable_client_renegotiation) 2179 ssloptions |= SSL_OP_NO_RENEGOTIATION; 2180 #endif 2181 2182 /* completely useless identifier; 2183 * required for client cert verification to work with sessions */ 2184 if (0 == SSL_CTX_set_session_id_context( 2185 s->ssl_ctx,(const unsigned char*)CONST_STR_LEN("lighttpd"))){ 2186 log_error(srv->errh, __FILE__, __LINE__, 2187 "SSL: failed to set session context: %s", 2188 ERR_error_string(ERR_get_error(), NULL)); 2189 return -1; 2190 } 2191 2192 const int disable_sess_cache = 2193 !config_feature_bool(srv, "ssl.session-cache", 0); 2194 if (disable_sess_cache) 2195 /* disable session cache; session tickets are preferred */ 2196 SSL_CTX_set_session_cache_mode(s->ssl_ctx, 2197 SSL_SESS_CACHE_OFF 2198 | SSL_SESS_CACHE_NO_AUTO_CLEAR 2199 | SSL_SESS_CACHE_NO_INTERNAL); 2200 2201 if (s->ssl_empty_fragments) { 2202 #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS 2203 ssloptions &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; 2204 #else 2205 ssloptions &= ~0x00000800L; /* hardcode constant */ 2206 log_error(srv->errh, __FILE__, __LINE__, 2207 "WARNING: SSL: 'insert empty fragments' not supported by the " 2208 "openssl version used to compile lighttpd with"); 2209 #endif 2210 } 2211 2212 SSL_CTX_set_options(s->ssl_ctx, ssloptions); 2213 SSL_CTX_set_info_callback(s->ssl_ctx, ssl_info_callback); 2214 2215 if (!s->ssl_use_sslv2 && 0 != SSL_OP_NO_SSLv2) { 2216 /* disable SSLv2 */ 2217 if ((SSL_OP_NO_SSLv2 2218 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv2)) 2219 != SSL_OP_NO_SSLv2) { 2220 log_error(srv->errh, __FILE__, __LINE__, 2221 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 2222 return -1; 2223 } 2224 } 2225 2226 if (!s->ssl_use_sslv3 && 0 != SSL_OP_NO_SSLv3) { 2227 /* disable SSLv3 */ 2228 if ((SSL_OP_NO_SSLv3 2229 & SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_SSLv3)) 2230 != SSL_OP_NO_SSLv3) { 2231 log_error(srv->errh, __FILE__, __LINE__, 2232 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 2233 return -1; 2234 } 2235 } 2236 2237 if (s->ssl_cipher_list) { 2238 /* Disable support for low encryption ciphers */ 2239 if (SSL_CTX_set_cipher_list(s->ssl_ctx,s->ssl_cipher_list->ptr)!=1){ 2240 log_error(srv->errh, __FILE__, __LINE__, 2241 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 2242 return -1; 2243 } 2244 2245 if (s->ssl_honor_cipher_order) { 2246 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_CIPHER_SERVER_PREFERENCE); 2247 } 2248 } 2249 2250 #ifdef SSL_OP_PRIORITIZE_CHACHA /*(openssl 1.1.1)*/ 2251 if (s->ssl_honor_cipher_order) 2252 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_PRIORITIZE_CHACHA); 2253 #endif 2254 2255 #ifndef OPENSSL_NO_DH 2256 { 2257 #if OPENSSL_VERSION_NUMBER < 0x30000000L 2258 DH *dh; 2259 /* Support for Diffie-Hellman key exchange */ 2260 if (s->ssl_dh_file) { 2261 /* DH parameters from file */ 2262 BIO *bio; 2263 bio = BIO_new_file((char *) s->ssl_dh_file->ptr, "r"); 2264 if (bio == NULL) { 2265 log_error(srv->errh, __FILE__, __LINE__, 2266 "SSL: Unable to open file %s", s->ssl_dh_file->ptr); 2267 return -1; 2268 } 2269 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); 2270 BIO_free(bio); 2271 if (dh == NULL) { 2272 log_error(srv->errh, __FILE__, __LINE__, 2273 "SSL: PEM_read_bio_DHparams failed %s", s->ssl_dh_file->ptr); 2274 return -1; 2275 } 2276 SSL_CTX_set_tmp_dh(s->ssl_ctx,dh); 2277 DH_free(dh); 2278 } 2279 else { 2280 dh = get_dh2048(); 2281 if (dh == NULL) { 2282 log_error(srv->errh, __FILE__, __LINE__, 2283 "SSL: get_dh2048() failed"); 2284 return -1; 2285 } 2286 SSL_CTX_set_tmp_dh(s->ssl_ctx,dh); 2287 DH_free(dh); 2288 } 2289 #else 2290 /* OSSL_STORE_open() available in openssl 1.1.1, but might 2291 * not be present in alt TLS libs (libressl or boringssl) */ 2292 EVP_PKEY *dhpkey = NULL; 2293 if (s->ssl_dh_file) { 2294 OSSL_STORE_CTX *ctx = NULL; 2295 ctx = OSSL_STORE_open(s->ssl_dh_file->ptr, NULL, NULL, NULL, NULL); 2296 if (NULL != ctx) { 2297 if (OSSL_STORE_expect(ctx, OSSL_STORE_INFO_PARAMS)) { 2298 while (!OSSL_STORE_eof(ctx)) { 2299 OSSL_STORE_INFO *info = OSSL_STORE_load(ctx); 2300 if (info) { 2301 dhpkey = OSSL_STORE_INFO_get1_PARAMS(info); 2302 OSSL_STORE_INFO_free(info); 2303 } 2304 break; 2305 } 2306 } 2307 OSSL_STORE_close(ctx); 2308 } 2309 if (!dhpkey || !EVP_PKEY_is_a(dhpkey, "DH") 2310 || !SSL_CTX_set0_tmp_dh_pkey(s->ssl_ctx, dhpkey)) { 2311 log_error(srv->errh, __FILE__, __LINE__, 2312 "Unable to load DH params from %s", s->ssl_dh_file->ptr); 2313 EVP_PKEY_free(dhpkey); 2314 dhpkey = NULL; 2315 } /*(else dhpkey ownership transferred upon success)*/ 2316 } 2317 if (NULL == dhpkey) 2318 SSL_CTX_set_dh_auto(s->ssl_ctx, 1); 2319 #endif 2320 SSL_CTX_set_options(s->ssl_ctx,SSL_OP_SINGLE_DH_USE); 2321 } 2322 #else 2323 if (s->ssl_dh_file) { 2324 log_error(srv->errh, __FILE__, __LINE__, 2325 "SSL: openssl compiled without DH support, " 2326 "can't load parameters from %s", s->ssl_dh_file->ptr); 2327 } 2328 #endif 2329 2330 if (!mod_openssl_ssl_conf_curves(srv, s, s->ssl_ec_curve)) 2331 return -1; 2332 2333 #ifdef TLSEXT_TYPE_session_ticket 2334 #if OPENSSL_VERSION_NUMBER < 0x30000000L 2335 SSL_CTX_set_tlsext_ticket_key_cb(s->ssl_ctx, ssl_tlsext_ticket_key_cb); 2336 #else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */ 2337 SSL_CTX_set_tlsext_ticket_key_evp_cb(s->ssl_ctx, 2338 ssl_tlsext_ticket_key_cb); 2339 #endif 2340 #endif 2341 2342 #ifndef OPENSSL_NO_OCSP 2343 #ifndef BORINGSSL_API_VERSION /* BoringSSL suggests using different API */ 2344 SSL_CTX_set_tlsext_status_cb(s->ssl_ctx, ssl_tlsext_status_cb); 2345 #endif 2346 #endif 2347 2348 #if OPENSSL_VERSION_NUMBER >= 0x10002000 \ 2349 && !defined(LIBRESSL_VERSION_NUMBER) 2350 2351 SSL_CTX_set_cert_cb(s->ssl_ctx, mod_openssl_cert_cb, NULL); 2352 UNUSED(p); 2353 2354 #if defined(BORINGSSL_API_VERSION) /* BoringSSL limitation */ 2355 /* set cert store for auto-chaining 2356 * BoringSSL does not support SSL_set1_chain_cert_store() in cert_cb */ 2357 if (s->ssl_ca_file && s->ssl_ca_file->certs) { 2358 if (!X509_STORE_up_ref(s->ssl_ca_file->certs)) 2359 return -1; 2360 SSL_CTX_set_cert_store(s->ssl_ctx, s->ssl_ca_file->certs); 2361 } 2362 #endif 2363 2364 #else /* OPENSSL_VERSION_NUMBER < 0x10002000 */ 2365 2366 /* load all ssl.ca-files specified in the config into each SSL_CTX 2367 * XXX: This might be a bit excessive, but are all trusted CAs 2368 * TODO: prefer to load on-demand in mod_openssl_cert_cb() 2369 * for openssl >= 1.0.2 */ 2370 if (!mod_openssl_load_ca_files(s->ssl_ctx, p, srv)) 2371 return -1; 2372 2373 if (s->ssl_verifyclient) { 2374 if (NULL == s->ssl_ca_file) { 2375 log_error(srv->errh, __FILE__, __LINE__, 2376 "SSL: You specified ssl.verifyclient.activate " 2377 "but no ssl.verifyclient.ca-file"); 2378 return -1; 2379 } 2380 /* WTH openssl? SSL_CTX_set_client_CA_list() calls set0_CA_list(), 2381 * but there is no set1_CA_list() to simply up the reference count 2382 * (without needing to duplicate the list) */ 2383 /* WTH wolfssl? wolfSSL_dup_CA_list() is a stub which returns NULL 2384 * and so DN names in cert request are not set here. 2385 * (A patch has been submitted to WolfSSL to correct this)*/ 2386 STACK_OF(X509_NAME) * const cert_names = s->ssl_ca_dn_file 2387 ? s->ssl_ca_dn_file 2388 : s->ssl_ca_file->names; 2389 SSL_CTX_set_client_CA_list(s->ssl_ctx, SSL_dup_CA_list(cert_names)); 2390 int mode = SSL_VERIFY_PEER; 2391 if (s->ssl_verifyclient_enforce) { 2392 mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; 2393 } 2394 SSL_CTX_set_verify(s->ssl_ctx, mode, verify_callback); 2395 SSL_CTX_set_verify_depth(s->ssl_ctx, s->ssl_verifyclient_depth + 1); 2396 if (s->ssl_ca_crl_file && !buffer_is_blank(s->ssl_ca_crl_file)) { 2397 X509_STORE *store = SSL_CTX_get_cert_store(s->ssl_ctx); 2398 if (!mod_openssl_load_cacrls(store, s->ssl_ca_crl_file, srv)) 2399 return -1; 2400 } 2401 } 2402 2403 if (1 != SSL_CTX_use_certificate_chain_file(s->ssl_ctx, 2404 s->pc->ssl_pemfile->ptr)) { 2405 log_error(srv->errh, __FILE__, __LINE__, 2406 "SSL: %s %s", ERR_error_string(ERR_get_error(), NULL), 2407 s->pc->ssl_pemfile->ptr); 2408 return -1; 2409 } 2410 2411 if (1 != SSL_CTX_use_PrivateKey(s->ssl_ctx, s->pc->ssl_pemfile_pkey)) { 2412 log_error(srv->errh, __FILE__, __LINE__, 2413 "SSL: %s %s %s", ERR_error_string(ERR_get_error(), NULL), 2414 s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr); 2415 return -1; 2416 } 2417 2418 if (SSL_CTX_check_private_key(s->ssl_ctx) != 1) { 2419 log_error(srv->errh, __FILE__, __LINE__, 2420 "SSL: Private key does not match the certificate public key, " 2421 "reason: %s %s %s", ERR_error_string(ERR_get_error(), NULL), 2422 s->pc->ssl_pemfile->ptr, s->pc->ssl_privkey->ptr); 2423 return -1; 2424 } 2425 2426 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000 */ 2427 2428 #if defined(BORINGSSL_API_VERSION) 2429 #define SSL_CTX_set_default_read_ahead(ctx,m) \ 2430 SSL_CTX_set_read_ahead(ctx,m) 2431 #endif 2432 SSL_CTX_set_default_read_ahead(s->ssl_ctx, s->ssl_read_ahead); 2433 SSL_CTX_set_mode(s->ssl_ctx, SSL_CTX_get_mode(s->ssl_ctx) 2434 | SSL_MODE_ENABLE_PARTIAL_WRITE 2435 | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 2436 | SSL_MODE_RELEASE_BUFFERS); 2437 2438 #ifndef OPENSSL_NO_TLSEXT 2439 #ifdef SSL_CLIENT_HELLO_SUCCESS 2440 SSL_CTX_set_client_hello_cb(s->ssl_ctx,mod_openssl_client_hello_cb,srv); 2441 #else 2442 if (!SSL_CTX_set_tlsext_servername_callback( 2443 s->ssl_ctx, network_ssl_servername_callback) || 2444 !SSL_CTX_set_tlsext_servername_arg(s->ssl_ctx, srv)) { 2445 log_error(srv->errh, __FILE__, __LINE__, 2446 "SSL: failed to initialize TLS servername callback, " 2447 "openssl library does not support TLS servername extension"); 2448 return -1; 2449 } 2450 #endif 2451 2452 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation 2453 SSL_CTX_set_alpn_select_cb(s->ssl_ctx,mod_openssl_alpn_select_cb,NULL); 2454 #endif 2455 #endif 2456 2457 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \ 2458 || defined(BORINGSSL_API_VERSION) \ 2459 || defined(LIBRESSL_VERSION_NUMBER) 2460 if (!s->ssl_use_sslv3 && !s->ssl_use_sslv2 2461 && !SSL_CTX_set_min_proto_version(s->ssl_ctx, TLS1_2_VERSION)) 2462 return -1; 2463 #endif 2464 2465 if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) { 2466 if (0 != network_openssl_ssl_conf_cmd(srv, s)) return -1; 2467 /* (force compression disabled, the default, if HTTP/2 enabled) */ 2468 if (srv->srvconf.h2proto) 2469 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_NO_COMPRESSION); 2470 } 2471 2472 return 0; 2473 } 2474 2475 2476 static int 2477 mod_openssl_set_defaults_sockets(server *srv, plugin_data *p) 2478 { 2479 static const config_plugin_keys_t cpk[] = { 2480 { CONST_STR_LEN("ssl.engine"), 2481 T_CONFIG_BOOL, 2482 T_CONFIG_SCOPE_SOCKET } 2483 ,{ CONST_STR_LEN("ssl.cipher-list"), 2484 T_CONFIG_STRING, 2485 T_CONFIG_SCOPE_SOCKET } 2486 ,{ CONST_STR_LEN("ssl.honor-cipher-order"), 2487 T_CONFIG_BOOL, 2488 T_CONFIG_SCOPE_SOCKET } 2489 ,{ CONST_STR_LEN("ssl.dh-file"), 2490 T_CONFIG_STRING, 2491 T_CONFIG_SCOPE_SOCKET } 2492 ,{ CONST_STR_LEN("ssl.ec-curve"), 2493 T_CONFIG_STRING, 2494 T_CONFIG_SCOPE_SOCKET } 2495 ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"), 2496 T_CONFIG_ARRAY_KVSTRING, 2497 T_CONFIG_SCOPE_SOCKET } 2498 ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */ 2499 T_CONFIG_STRING, 2500 T_CONFIG_SCOPE_CONNECTION } 2501 ,{ CONST_STR_LEN("ssl.empty-fragments"), 2502 T_CONFIG_BOOL, 2503 T_CONFIG_SCOPE_SOCKET } 2504 ,{ CONST_STR_LEN("ssl.use-sslv2"), 2505 T_CONFIG_BOOL, 2506 T_CONFIG_SCOPE_SOCKET } 2507 ,{ CONST_STR_LEN("ssl.use-sslv3"), 2508 T_CONFIG_BOOL, 2509 T_CONFIG_SCOPE_SOCKET } 2510 ,{ CONST_STR_LEN("ssl.stek-file"), 2511 T_CONFIG_STRING, 2512 T_CONFIG_SCOPE_SERVER } 2513 ,{ NULL, 0, 2514 T_CONFIG_UNSET, 2515 T_CONFIG_SCOPE_UNSET } 2516 }; 2517 static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 }; 2518 2519 p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx)); 2520 force_assert(p->ssl_ctxs); 2521 2522 int rc = HANDLER_GO_ON; 2523 plugin_data_base srvplug; 2524 memset(&srvplug, 0, sizeof(srvplug)); 2525 plugin_data_base * const ps = &srvplug; 2526 if (!config_plugin_values_init(srv, ps, cpk, "mod_openssl")) 2527 return HANDLER_ERROR; 2528 2529 plugin_config_socket defaults; 2530 memset(&defaults, 0, sizeof(defaults)); 2531 defaults.ssl_honor_cipher_order = 1; 2532 defaults.ssl_cipher_list = &default_ssl_cipher_list; 2533 2534 /* process and validate config directives for global and $SERVER["socket"] 2535 * (init i to 0 if global context; to 1 to skip empty global context) */ 2536 for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) { 2537 config_cond_info cfginfo; 2538 config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id); 2539 int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET); 2540 int count_not_engine = 0; 2541 2542 plugin_config_socket conf; 2543 memcpy(&conf, &defaults, sizeof(conf)); 2544 2545 /*(preserve prior behavior; not inherited)*/ 2546 /*(forcing inheritance might break existing configs where SSL is enabled 2547 * by default in the global scope, but not $SERVER["socket"]=="*:80") */ 2548 conf.ssl_enabled = 0; 2549 2550 config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0]; 2551 for (; -1 != cpv->k_id; ++cpv) { 2552 /* ignore ssl.pemfile (k_id=6); included to process global scope */ 2553 if (!is_socket_scope && cpv->k_id != 6) { 2554 log_error(srv->errh, __FILE__, __LINE__, 2555 "%s is valid only in global scope or " 2556 "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k); 2557 continue; 2558 } 2559 ++count_not_engine; 2560 switch (cpv->k_id) { 2561 case 0: /* ssl.engine */ 2562 conf.ssl_enabled = (0 != cpv->v.u); 2563 --count_not_engine; 2564 break; 2565 case 1: /* ssl.cipher-list */ 2566 if (!buffer_is_blank(cpv->v.b)) 2567 conf.ssl_cipher_list = cpv->v.b; 2568 break; 2569 case 2: /* ssl.honor-cipher-order */ 2570 conf.ssl_honor_cipher_order = (0 != cpv->v.u); 2571 break; 2572 case 3: /* ssl.dh-file */ 2573 if (!buffer_is_blank(cpv->v.b)) 2574 conf.ssl_dh_file = cpv->v.b; 2575 break; 2576 case 4: /* ssl.ec-curve */ 2577 if (!buffer_is_blank(cpv->v.b)) 2578 conf.ssl_ec_curve = cpv->v.b; 2579 break; 2580 case 5: /* ssl.openssl.ssl-conf-cmd */ 2581 *(const array **)&conf.ssl_conf_cmd = cpv->v.a; 2582 break; 2583 case 6: /* ssl.pemfile */ 2584 /* ignore here; included to process global scope when 2585 * ssl.pemfile is set, but ssl.engine is not "enable" */ 2586 break; 2587 case 7: /* ssl.empty-fragments */ 2588 conf.ssl_empty_fragments = (0 != cpv->v.u); 2589 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2590 "ssl.empty-fragments is deprecated and will soon be " 2591 "removed. It is disabled by default."); 2592 if (conf.ssl_empty_fragments) 2593 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2594 "If needed, use: ssl.openssl.ssl-conf-cmd = " 2595 "(\"Options\" => \"EmptyFragments\")"); 2596 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2597 "ssl.empty-fragments is a " 2598 "counter-measure against a SSL 3.0/TLS 1.0 protocol " 2599 "vulnerability affecting CBC ciphers, which cannot be handled" 2600 " by some broken (Microsoft) SSL implementations."); 2601 break; 2602 case 8: /* ssl.use-sslv2 */ 2603 conf.ssl_use_sslv2 = (0 != cpv->v.u); 2604 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2605 "ssl.use-sslv2 is deprecated and will soon be removed. " 2606 "It is disabled by default. " 2607 "Many modern TLS libraries no longer support SSLv2."); 2608 break; 2609 case 9: /* ssl.use-sslv3 */ 2610 conf.ssl_use_sslv3 = (0 != cpv->v.u); 2611 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2612 "ssl.use-sslv3 is deprecated and will soon be removed. " 2613 "It is disabled by default. " 2614 "Many modern TLS libraries no longer support SSLv3."); 2615 if (conf.ssl_use_sslv3) 2616 log_error(srv->errh, __FILE__, __LINE__, "SSL: " 2617 "If needed, use: ssl.openssl.ssl-conf-cmd = " 2618 "(\"MinProtocol\" => \"SSLv3\")"); 2619 break; 2620 case 10:/* ssl.stek-file */ 2621 if (!buffer_is_blank(cpv->v.b)) 2622 p->ssl_stek_file = cpv->v.b->ptr; 2623 break; 2624 default:/* should not happen */ 2625 break; 2626 } 2627 } 2628 if (HANDLER_GO_ON != rc) break; 2629 if (0 == i) memcpy(&defaults, &conf, sizeof(conf)); 2630 2631 if (0 != i && !conf.ssl_enabled) continue; 2632 2633 /* fill plugin_config_socket with global context then $SERVER["socket"] 2634 * only for directives directly in current $SERVER["socket"] condition*/ 2635 2636 /*conf.pc = p->defaults.pc;*/ 2637 conf.ssl_ca_file = p->defaults.ssl_ca_file; 2638 conf.ssl_ca_dn_file = p->defaults.ssl_ca_dn_file; 2639 conf.ssl_ca_crl_file = p->defaults.ssl_ca_crl_file; 2640 conf.ssl_verifyclient = p->defaults.ssl_verifyclient; 2641 conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce; 2642 conf.ssl_verifyclient_depth = p->defaults.ssl_verifyclient_depth; 2643 conf.ssl_read_ahead = p->defaults.ssl_read_ahead; 2644 conf.ssl_disable_client_renegotiation 2645 = p->defaults.ssl_disable_client_renegotiation; 2646 2647 int sidx = ps->cvlist[i].k_id; 2648 for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) { 2649 if (p->cvlist[j].k_id != sidx) continue; 2650 /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/ 2651 cpv = p->cvlist + p->cvlist[j].v.u2[0]; 2652 for (; -1 != cpv->k_id; ++cpv) { 2653 ++count_not_engine; 2654 switch (cpv->k_id) { 2655 case 0: /* ssl.pemfile */ 2656 if (cpv->vtype == T_CONFIG_LOCAL) 2657 conf.pc = cpv->v.v; 2658 break; 2659 case 2: /* ssl.ca-file */ 2660 if (cpv->vtype == T_CONFIG_LOCAL) 2661 conf.ssl_ca_file = cpv->v.v; 2662 break; 2663 case 3: /* ssl.ca-dn-file */ 2664 if (cpv->vtype == T_CONFIG_LOCAL) 2665 conf.ssl_ca_dn_file = cpv->v.v; 2666 break; 2667 case 4: /* ssl.ca-crl-file */ 2668 conf.ssl_ca_crl_file = cpv->v.b; 2669 break; 2670 case 5: /* ssl.read-ahead */ 2671 conf.ssl_read_ahead = (0 != cpv->v.u); 2672 break; 2673 case 6: /* ssl.disable-client-renegotiation */ 2674 conf.ssl_disable_client_renegotiation = (0 != cpv->v.u); 2675 break; 2676 case 7: /* ssl.verifyclient.activate */ 2677 conf.ssl_verifyclient = (0 != cpv->v.u); 2678 break; 2679 case 8: /* ssl.verifyclient.enforce */ 2680 conf.ssl_verifyclient_enforce = (0 != cpv->v.u); 2681 break; 2682 case 9: /* ssl.verifyclient.depth */ 2683 conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt; 2684 break; 2685 #if 0 /*(cpk->k_id remapped in mod_openssl_set_defaults())*/ 2686 case 15:/* ssl.verifyclient.ca-file */ 2687 case 16:/* ssl.verifyclient.ca-dn-file */ 2688 case 17:/* ssl.verifyclient.ca-crl-file */ 2689 #endif 2690 default: 2691 break; 2692 } 2693 } 2694 break; 2695 } 2696 2697 if (NULL == conf.pc) { 2698 if (0 == i && !conf.ssl_enabled) continue; 2699 if (0 != i) { 2700 /* inherit ssl settings from global scope 2701 * (if only ssl.engine = "enable" and no other ssl.* settings) 2702 * (This is for convenience when defining both IPv4 and IPv6 2703 * and desiring to inherit the ssl config from global context 2704 * without having to duplicate the directives)*/ 2705 if (count_not_engine 2706 || (conf.ssl_enabled && NULL == p->ssl_ctxs[0].ssl_ctx)) { 2707 log_error(srv->errh, __FILE__, __LINE__, 2708 "ssl.pemfile has to be set in same $SERVER[\"socket\"] scope " 2709 "as other ssl.* directives, unless only ssl.engine is set, " 2710 "inheriting ssl.* from global scope"); 2711 rc = HANDLER_ERROR; 2712 continue; 2713 } 2714 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx; 2715 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/ 2716 continue; 2717 } 2718 /* PEM file is required */ 2719 log_error(srv->errh, __FILE__, __LINE__, 2720 "ssl.pemfile has to be set when ssl.engine = \"enable\""); 2721 rc = HANDLER_ERROR; 2722 continue; 2723 } 2724 2725 /* configure ssl_ctx for socket */ 2726 2727 /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/ 2728 if (0 == network_init_ssl(srv, &conf, p)) { 2729 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx; 2730 s->ssl_ctx = conf.ssl_ctx; 2731 } 2732 else { 2733 SSL_CTX_free(conf.ssl_ctx); 2734 rc = HANDLER_ERROR; 2735 } 2736 } 2737 2738 #ifdef TLSEXT_TYPE_session_ticket 2739 if (rc == HANDLER_GO_ON && ssl_is_init) 2740 mod_openssl_session_ticket_key_check(p, log_epoch_secs); 2741 #endif 2742 2743 free(srvplug.cvlist); 2744 return rc; 2745 } 2746 2747 2748 SETDEFAULTS_FUNC(mod_openssl_set_defaults) 2749 { 2750 static const config_plugin_keys_t cpk[] = { 2751 { CONST_STR_LEN("ssl.pemfile"), 2752 T_CONFIG_STRING, 2753 T_CONFIG_SCOPE_CONNECTION } 2754 ,{ CONST_STR_LEN("ssl.privkey"), 2755 T_CONFIG_STRING, 2756 T_CONFIG_SCOPE_CONNECTION } 2757 ,{ CONST_STR_LEN("ssl.ca-file"), 2758 T_CONFIG_STRING, 2759 T_CONFIG_SCOPE_CONNECTION } 2760 ,{ CONST_STR_LEN("ssl.ca-dn-file"), 2761 T_CONFIG_STRING, 2762 T_CONFIG_SCOPE_CONNECTION } 2763 ,{ CONST_STR_LEN("ssl.ca-crl-file"), 2764 T_CONFIG_STRING, 2765 T_CONFIG_SCOPE_CONNECTION } 2766 ,{ CONST_STR_LEN("ssl.read-ahead"), 2767 T_CONFIG_BOOL, 2768 T_CONFIG_SCOPE_CONNECTION } 2769 ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"), 2770 T_CONFIG_BOOL, 2771 T_CONFIG_SCOPE_CONNECTION } 2772 ,{ CONST_STR_LEN("ssl.verifyclient.activate"), 2773 T_CONFIG_BOOL, 2774 T_CONFIG_SCOPE_CONNECTION } 2775 ,{ CONST_STR_LEN("ssl.verifyclient.enforce"), 2776 T_CONFIG_BOOL, 2777 T_CONFIG_SCOPE_CONNECTION } 2778 ,{ CONST_STR_LEN("ssl.verifyclient.depth"), 2779 T_CONFIG_SHORT, 2780 T_CONFIG_SCOPE_CONNECTION } 2781 ,{ CONST_STR_LEN("ssl.verifyclient.username"), 2782 T_CONFIG_STRING, 2783 T_CONFIG_SCOPE_CONNECTION } 2784 ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"), 2785 T_CONFIG_BOOL, 2786 T_CONFIG_SCOPE_CONNECTION } 2787 ,{ CONST_STR_LEN("ssl.acme-tls-1"), 2788 T_CONFIG_STRING, 2789 T_CONFIG_SCOPE_CONNECTION } 2790 ,{ CONST_STR_LEN("ssl.stapling-file"), 2791 T_CONFIG_STRING, 2792 T_CONFIG_SCOPE_CONNECTION } 2793 ,{ CONST_STR_LEN("debug.log-ssl-noise"), 2794 T_CONFIG_BOOL, 2795 T_CONFIG_SCOPE_CONNECTION } 2796 ,{ CONST_STR_LEN("ssl.verifyclient.ca-file"), 2797 T_CONFIG_STRING, 2798 T_CONFIG_SCOPE_CONNECTION } 2799 ,{ CONST_STR_LEN("ssl.verifyclient.ca-dn-file"), 2800 T_CONFIG_STRING, 2801 T_CONFIG_SCOPE_CONNECTION } 2802 ,{ CONST_STR_LEN("ssl.verifyclient.ca-crl-file"), 2803 T_CONFIG_STRING, 2804 T_CONFIG_SCOPE_CONNECTION } 2805 ,{ NULL, 0, 2806 T_CONFIG_UNSET, 2807 T_CONFIG_SCOPE_UNSET } 2808 }; 2809 2810 plugin_data * const p = p_d; 2811 p->srv = srv; 2812 p->cafiles = array_init(0); 2813 if (!config_plugin_values_init(srv, p, cpk, "mod_openssl")) 2814 return HANDLER_ERROR; 2815 2816 const buffer *default_ssl_ca_crl_file = NULL; 2817 2818 /* process and validate config directives 2819 * (init i to 0 if global context; to 1 to skip empty global context) */ 2820 for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) { 2821 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 2822 config_plugin_value_t *pemfile = NULL; 2823 config_plugin_value_t *privkey = NULL; 2824 const buffer *ssl_stapling_file = NULL; 2825 const buffer *ssl_ca_file = NULL; 2826 const buffer *ssl_ca_dn_file = NULL; 2827 const buffer *ssl_ca_crl_file = NULL; 2828 X509_STORE *ca_store = NULL; 2829 for (; -1 != cpv->k_id; ++cpv) { 2830 switch (cpv->k_id) { 2831 case 0: /* ssl.pemfile */ 2832 if (!buffer_is_blank(cpv->v.b)) pemfile = cpv; 2833 break; 2834 case 1: /* ssl.privkey */ 2835 if (!buffer_is_blank(cpv->v.b)) privkey = cpv; 2836 break; 2837 case 15:/* ssl.verifyclient.ca-file */ 2838 cpv->k_id = 2; 2839 __attribute_fallthrough__ 2840 case 2: /* ssl.ca-file */ 2841 if (buffer_is_blank(cpv->v.b)) break; 2842 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR; 2843 ssl_ca_file = cpv->v.b; 2844 cpv->v.v = mod_openssl_load_cacerts(ssl_ca_file, srv->errh); 2845 if (NULL != cpv->v.v) { 2846 cpv->vtype = T_CONFIG_LOCAL; 2847 ca_store = ((plugin_cacerts *)cpv->v.v)->certs; 2848 } 2849 else { 2850 log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s", 2851 ERR_error_string(ERR_get_error(), NULL), 2852 ssl_ca_file->ptr); 2853 return HANDLER_ERROR; 2854 } 2855 break; 2856 case 16:/* ssl.verifyclient.ca-dn-file */ 2857 cpv->k_id = 3; 2858 __attribute_fallthrough__ 2859 case 3: /* ssl.ca-dn-file */ 2860 if (buffer_is_blank(cpv->v.b)) break; 2861 if (!mod_openssl_init_once_openssl(srv)) return HANDLER_ERROR; 2862 ssl_ca_dn_file = cpv->v.b; 2863 cpv->v.v = SSL_load_client_CA_file(ssl_ca_dn_file->ptr); 2864 if (NULL != cpv->v.v) { 2865 cpv->vtype = T_CONFIG_LOCAL; 2866 } 2867 else { 2868 log_error(srv->errh, __FILE__, __LINE__, "SSL: %s %s", 2869 ERR_error_string(ERR_get_error(), NULL), 2870 ssl_ca_dn_file->ptr); 2871 return HANDLER_ERROR; 2872 } 2873 break; 2874 case 17:/* ssl.verifyclient.ca-crl-file */ 2875 cpv->k_id = 4; 2876 __attribute_fallthrough__ 2877 case 4: /* ssl.ca-crl-file */ 2878 if (buffer_is_blank(cpv->v.b)) break; 2879 ssl_ca_crl_file = cpv->v.b; 2880 if (0 == i) default_ssl_ca_crl_file = cpv->v.b; 2881 break; 2882 case 5: /* ssl.read-ahead */ 2883 break; 2884 case 6: /* ssl.disable-client-renegotiation */ 2885 /* (force disabled, the default, if HTTP/2 enabled in server) */ 2886 if (srv->srvconf.h2proto) 2887 cpv->v.u = 1; /* disable client renegotiation */ 2888 break; 2889 case 7: /* ssl.verifyclient.activate */ 2890 case 8: /* ssl.verifyclient.enforce */ 2891 break; 2892 case 9: /* ssl.verifyclient.depth */ 2893 if (cpv->v.shrt > 255) { 2894 log_error(srv->errh, __FILE__, __LINE__, 2895 "%s is absurdly large (%hu); limiting to 255", 2896 cpk[cpv->k_id].k, cpv->v.shrt); 2897 cpv->v.shrt = 255; 2898 } 2899 break; 2900 case 10:/* ssl.verifyclient.username */ 2901 if (buffer_is_blank(cpv->v.b)) 2902 cpv->v.b = NULL; 2903 break; 2904 case 11:/* ssl.verifyclient.exportcert */ 2905 break; 2906 case 12:/* ssl.acme-tls-1 */ 2907 if (buffer_is_blank(cpv->v.b)) 2908 cpv->v.b = NULL; 2909 break; 2910 case 13:/* ssl.stapling-file */ 2911 if (!buffer_is_blank(cpv->v.b)) 2912 ssl_stapling_file = cpv->v.b; 2913 break; 2914 case 14:/* debug.log-ssl-noise */ 2915 #if 0 /*(handled further above)*/ 2916 case 15:/* ssl.verifyclient.ca-file */ 2917 case 16:/* ssl.verifyclient.ca-dn-file */ 2918 case 17:/* ssl.verifyclient.ca-crl-file */ 2919 #endif 2920 break; 2921 default:/* should not happen */ 2922 break; 2923 } 2924 } 2925 2926 #if OPENSSL_VERSION_NUMBER < 0x10002000 /* p->cafiles for legacy only */ \ 2927 || defined(LIBRESSL_VERSION_NUMBER) 2928 /* load all ssl.ca-files into a single chain */ 2929 /*(certificate load order might matter)*/ 2930 if (ssl_ca_dn_file) 2931 array_insert_value(p->cafiles, BUF_PTR_LEN(ssl_ca_dn_file)); 2932 if (ssl_ca_file) 2933 array_insert_value(p->cafiles, BUF_PTR_LEN(ssl_ca_file)); 2934 UNUSED(ca_store); 2935 UNUSED(ssl_ca_crl_file); 2936 UNUSED(default_ssl_ca_crl_file); 2937 #else 2938 if (NULL == ca_store && ssl_ca_crl_file && i != 0) { 2939 log_error(srv->errh, __FILE__, __LINE__, 2940 "ssl.verifyclient.ca-crl-file (%s) ignored unless issued with " 2941 "ssl.verifyclient.ca-file", ssl_ca_crl_file->ptr); 2942 } 2943 else if (ca_store && (ssl_ca_crl_file || default_ssl_ca_crl_file)) { 2944 /* prior behavior in lighttpd allowed ssl.ca-crl-file only in global 2945 * scope or $SERVER["socket"], so this inheritence from global scope 2946 * is reasonable. This code does not implement inheritance of 2947 * ssl.ca-crl-file from $SERVER["socket"] into nested $HTTP["host"], 2948 * but the solution is to repeat ssl.ca-crl-file where ssl.ca-file 2949 * is issued (and to not unnecessarily repeat ssl.ca-file) 2950 * Alternative: write code to load ssl.ca-crl-file into (X509_CRL *) 2951 * using PEM_read_bio_X509_CRL() and in mod_openssl_cert_cb(), 2952 * create a new (X509_STORE *) which merges with CA (X509_STORE *) 2953 * using X509_STORE_add_cert() and X509_STORE_add_crl(), and keeps 2954 * the result in our (plugin_cert *) for reuse */ 2955 if (NULL == ssl_ca_crl_file) 2956 ssl_ca_crl_file = default_ssl_ca_crl_file; 2957 if (!mod_openssl_load_cacrls(ca_store, ssl_ca_crl_file, srv)) 2958 return HANDLER_ERROR; 2959 } 2960 #endif 2961 2962 if (pemfile) { 2963 #ifdef OPENSSL_NO_TLSEXT 2964 config_cond_info cfginfo; 2965 uint32_t j = (uint32_t)p->cvlist[i].k_id; 2966 config_get_config_cond_info(&cfginfo, j); 2967 if (j > 0 && (COMP_SERVER_SOCKET != cfginfo.comp 2968 || cfginfo.cond != CONFIG_COND_EQ)) { 2969 if (COMP_HTTP_HOST == cfginfo.comp) 2970 log_error(srv->errh, __FILE__, __LINE__, "SSL:" 2971 "can't use ssl.pemfile with $HTTP[\"host\"], " 2972 "as openssl version does not support TLS extensions"); 2973 else 2974 log_error(srv->errh, __FILE__, __LINE__, "SSL:" 2975 "ssl.pemfile only works in SSL socket binding context " 2976 "as openssl version does not support TLS extensions"); 2977 return HANDLER_ERROR; 2978 } 2979 #endif 2980 if (NULL == privkey) privkey = pemfile; 2981 pemfile->v.v = 2982 network_openssl_load_pemfile(srv, pemfile->v.b, privkey->v.b, 2983 ssl_stapling_file); 2984 if (pemfile->v.v) 2985 pemfile->vtype = T_CONFIG_LOCAL; 2986 else 2987 return HANDLER_ERROR; 2988 } 2989 } 2990 2991 p->defaults.ssl_verifyclient = 0; 2992 p->defaults.ssl_verifyclient_enforce = 1; 2993 p->defaults.ssl_verifyclient_depth = 9; 2994 p->defaults.ssl_verifyclient_export_cert = 0; 2995 p->defaults.ssl_disable_client_renegotiation = 1; 2996 p->defaults.ssl_read_ahead = 0; 2997 2998 /* initialize p->defaults from global config context */ 2999 if (p->nconfig > 0 && p->cvlist->v.u2[1]) { 3000 const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0]; 3001 if (-1 != cpv->k_id) 3002 mod_openssl_merge_config(&p->defaults, cpv); 3003 } 3004 3005 #if OPENSSL_VERSION_NUMBER < 0x10101000L \ 3006 && !defined(LIBRESSL_VERSION_NUMBER) 3007 log_error(srv->errh, __FILE__, __LINE__, "SSL:" 3008 "openssl library version is outdated and has reached end-of-life. " 3009 "As of 1 Jan 2020, only openssl 1.1.1 and later continue to receive " 3010 "security patches from openssl.org"); 3011 #endif 3012 3013 return mod_openssl_set_defaults_sockets(srv, p); 3014 } 3015 3016 3017 /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE) 3018 * 3019 * it has to stay at the same location all the time to satisfy the needs 3020 * of SSL_write to pass the SAME parameter in case of a _WANT_WRITE 3021 * 3022 * buffer is allocated once, is NOT realloced (note: not thread-safe) 3023 * 3024 * (Note: above restriction no longer true since SSL_CTX_set_mode() is 3025 * called with SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) 3026 * */ 3027 3028 /* copy small mem chunks into single large buffer before SSL_write() 3029 * to reduce number times write() called underneath SSL_write() and 3030 * potentially reduce number of packets generated if TCP_NODELAY */ 3031 3032 3033 static int 3034 mod_openssl_close_notify(handler_ctx *hctx); 3035 3036 3037 static int 3038 connection_write_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes) 3039 { 3040 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id]; 3041 SSL * const ssl = hctx->ssl; 3042 log_error_st * const errh = hctx->errh; 3043 3044 if (__builtin_expect( (0 != hctx->close_notify), 0)) 3045 return mod_openssl_close_notify(hctx); 3046 3047 while (max_bytes > 0 && !chunkqueue_is_empty(cq)) { 3048 char *data = local_send_buffer; 3049 uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes 3050 ? LOCAL_SEND_BUFSIZE 3051 : (uint32_t)max_bytes; 3052 int wr; 3053 3054 if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1; 3055 if (__builtin_expect( (0 == data_len), 0)) { 3056 chunkqueue_remove_finished_chunks(cq); 3057 continue; 3058 } 3059 3060 /** 3061 * SSL_write man-page 3062 * 3063 * WARNING 3064 * When an SSL_write() operation has to be repeated because of 3065 * SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it must be 3066 * repeated with the same arguments. 3067 */ 3068 3069 ERR_clear_error(); 3070 wr = SSL_write(ssl, data, data_len); 3071 3072 if (__builtin_expect( (hctx->renegotiations > 1), 0) 3073 && hctx->conf.ssl_disable_client_renegotiation) { 3074 log_error(errh, __FILE__, __LINE__, 3075 "SSL: renegotiation initiated by client, killing connection"); 3076 return -1; 3077 } 3078 3079 if (wr <= 0) { 3080 int ssl_r; 3081 unsigned long err; 3082 3083 switch ((ssl_r = SSL_get_error(ssl, wr))) { 3084 case SSL_ERROR_WANT_READ: 3085 con->is_readable = -1; 3086 return 0; /* try again later */ 3087 case SSL_ERROR_WANT_WRITE: 3088 con->is_writable = -1; 3089 return 0; /* try again later */ 3090 case SSL_ERROR_SYSCALL: 3091 /* perhaps we have error waiting in our error-queue */ 3092 if (0 != (err = ERR_get_error())) { 3093 do { 3094 log_error(errh, __FILE__, __LINE__, 3095 "SSL: %d %d %s",ssl_r,wr,ERR_error_string(err,NULL)); 3096 } while((err = ERR_get_error())); 3097 } else if (wr == -1) { 3098 /* no, but we have errno */ 3099 switch(errno) { 3100 case EPIPE: 3101 case ECONNRESET: 3102 return -2; 3103 default: 3104 log_perror(errh, __FILE__, __LINE__, 3105 "SSL: %d %d", ssl_r, wr); 3106 break; 3107 } 3108 } else { 3109 /* neither error-queue nor errno ? */ 3110 log_perror(errh, __FILE__, __LINE__, 3111 "SSL (error): %d %d", ssl_r, wr); 3112 } 3113 break; 3114 3115 case SSL_ERROR_ZERO_RETURN: 3116 /* clean shutdown on the remote side */ 3117 3118 if (wr == 0) return -2; 3119 3120 __attribute_fallthrough__ 3121 default: 3122 while((err = ERR_get_error())) { 3123 log_error(errh, __FILE__, __LINE__, 3124 "SSL: %d %d %s", ssl_r, wr, ERR_error_string(err, NULL)); 3125 } 3126 break; 3127 } 3128 return -1; 3129 } 3130 3131 chunkqueue_mark_written(cq, wr); 3132 max_bytes -= wr; 3133 3134 if ((size_t) wr < data_len) break; /* try again later */ 3135 } 3136 3137 return 0; 3138 } 3139 3140 3141 static int 3142 connection_read_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes) 3143 { 3144 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id]; 3145 int len; 3146 char *mem = NULL; 3147 size_t mem_len = 0; 3148 3149 UNUSED(max_bytes); 3150 3151 if (__builtin_expect( (0 != hctx->close_notify), 0)) 3152 return mod_openssl_close_notify(hctx); 3153 3154 ERR_clear_error(); 3155 do { 3156 len = SSL_pending(hctx->ssl); 3157 mem_len = len < 2048 ? 2048 : (size_t)len; 3158 chunk * const ckpt = cq->last; 3159 mem = chunkqueue_get_memory(cq, &mem_len); 3160 3161 len = SSL_read(hctx->ssl, mem, mem_len); 3162 chunkqueue_use_memory(cq, ckpt, len > 0 ? len : 0); 3163 3164 if (hctx->renegotiations > 1 3165 && hctx->conf.ssl_disable_client_renegotiation) { 3166 log_error(hctx->errh, __FILE__, __LINE__, 3167 "SSL: renegotiation initiated by client, killing connection (%s)", 3168 con->dst_addr_buf.ptr); 3169 return -1; 3170 } 3171 3172 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation 3173 if (hctx->alpn) { 3174 if (hctx->alpn == MOD_OPENSSL_ALPN_H2) { 3175 if (0 != mod_openssl_alpn_h2_policy(hctx)) 3176 return -1; 3177 } 3178 else if (hctx->alpn == MOD_OPENSSL_ALPN_ACME_TLS_1) { 3179 chunkqueue_reset(cq); 3180 /* initiate handshake in order to send ServerHello. 3181 * Once TLS handshake is complete, return -1 to result in 3182 * CON_STATE_ERROR so that socket connection is quickly closed*/ 3183 if (1 == SSL_do_handshake(hctx->ssl)) return -1; 3184 len = -1; 3185 break; 3186 } 3187 hctx->alpn = 0; 3188 } 3189 #endif 3190 } while (len > 0 3191 && (hctx->conf.ssl_read_ahead || SSL_pending(hctx->ssl) > 0)); 3192 3193 if (len < 0) { 3194 int oerrno = errno; 3195 int rc, ssl_err; 3196 switch ((rc = SSL_get_error(hctx->ssl, len))) { 3197 case SSL_ERROR_WANT_WRITE: 3198 con->is_writable = -1; 3199 __attribute_fallthrough__ 3200 case SSL_ERROR_WANT_READ: 3201 con->is_readable = 0; 3202 3203 /* the manual says we have to call SSL_read with the same arguments 3204 * next time. we ignore this restriction; no one has complained 3205 * about it in 1.5 yet, so it probably works anyway. 3206 */ 3207 3208 return 0; 3209 case SSL_ERROR_SYSCALL: 3210 /** 3211 * man SSL_get_error() 3212 * 3213 * SSL_ERROR_SYSCALL 3214 * Some I/O error occurred. The OpenSSL error queue may contain 3215 * more information on the error. If the error queue is empty 3216 * (i.e. ERR_get_error() returns 0), ret can be used to find out 3217 * more about the error: If ret == 0, an EOF was observed that 3218 * violates the protocol. If ret == -1, the underlying BIO 3219 * reported an I/O error (for socket I/O on Unix systems, consult 3220 * errno for details). 3221 * 3222 */ 3223 while((ssl_err = ERR_get_error())) { 3224 /* get all errors from the error-queue */ 3225 log_error(hctx->errh, __FILE__, __LINE__, 3226 "SSL: %d %s", rc, ERR_error_string(ssl_err, NULL)); 3227 } 3228 3229 switch(oerrno) { 3230 case ECONNRESET: 3231 if (!hctx->conf.ssl_log_noise) break; 3232 __attribute_fallthrough__ 3233 default: 3234 /* (oerrno should be something like ECONNABORTED not 0 3235 * if client disconnected before anything was sent 3236 * (e.g. TCP connection probe), but it does not appear 3237 * that openssl provides such notification, not even 3238 * something like SSL_R_SSL_HANDSHAKE_FAILURE) */ 3239 if (0==oerrno && 0==cq->bytes_in && !hctx->conf.ssl_log_noise) 3240 break; 3241 3242 errno = oerrno; /*(for log_perror())*/ 3243 log_perror(hctx->errh, __FILE__, __LINE__, 3244 "SSL: %d %d %d", len, rc, oerrno); 3245 break; 3246 } 3247 3248 break; 3249 case SSL_ERROR_ZERO_RETURN: 3250 /* clean shutdown on the remote side */ 3251 3252 if (rc == 0) { 3253 /* FIXME: later */ 3254 } 3255 3256 __attribute_fallthrough__ 3257 default: 3258 while((ssl_err = ERR_get_error())) { 3259 switch (ERR_GET_REASON(ssl_err)) { 3260 case SSL_R_SSL_HANDSHAKE_FAILURE: 3261 #ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING 3262 case SSL_R_UNEXPECTED_EOF_WHILE_READING: 3263 #endif 3264 #ifdef SSL_R_TLSV1_ALERT_UNKNOWN_CA 3265 case SSL_R_TLSV1_ALERT_UNKNOWN_CA: 3266 #endif 3267 #ifdef SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 3268 case SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN: 3269 #endif 3270 #ifdef SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 3271 case SSL_R_SSLV3_ALERT_BAD_CERTIFICATE: 3272 #endif 3273 if (!hctx->conf.ssl_log_noise) continue; 3274 break; 3275 default: 3276 break; 3277 } 3278 /* get all errors from the error-queue */ 3279 log_error(hctx->errh, __FILE__, __LINE__, 3280 "SSL: %d %s (%s)", rc, ERR_error_string(ssl_err, NULL), 3281 con->dst_addr_buf.ptr); 3282 } 3283 break; 3284 } 3285 return -1; 3286 } else if (len == 0) { 3287 con->is_readable = 0; 3288 /* the other end close the connection -> KEEP-ALIVE */ 3289 3290 return -2; 3291 } else { 3292 return 0; 3293 } 3294 } 3295 3296 3297 CONNECTION_FUNC(mod_openssl_handle_con_accept) 3298 { 3299 const server_socket *srv_sock = con->srv_socket; 3300 if (!srv_sock->is_ssl) return HANDLER_GO_ON; 3301 3302 plugin_data *p = p_d; 3303 handler_ctx * const hctx = handler_ctx_init(); 3304 request_st * const r = &con->request; 3305 hctx->r = r; 3306 hctx->con = con; 3307 hctx->tmp_buf = con->srv->tmp_buf; 3308 hctx->errh = r->conf.errh; 3309 con->plugin_ctx[p->id] = hctx; 3310 buffer_blank(&r->uri.authority); 3311 3312 plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx; 3313 hctx->ssl = SSL_new(s->ssl_ctx); 3314 if (NULL != hctx->ssl 3315 && SSL_set_app_data(hctx->ssl, hctx) 3316 && SSL_set_fd(hctx->ssl, con->fd)) { 3317 SSL_set_accept_state(hctx->ssl); 3318 con->network_read = connection_read_cq_ssl; 3319 con->network_write = connection_write_cq_ssl; 3320 con->proto_default_port = 443; /* "https" */ 3321 mod_openssl_patch_config(r, &hctx->conf); 3322 return HANDLER_GO_ON; 3323 } 3324 else { 3325 log_error(r->conf.errh, __FILE__, __LINE__, 3326 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 3327 return HANDLER_ERROR; 3328 } 3329 } 3330 3331 3332 static void 3333 mod_openssl_detach(handler_ctx *hctx) 3334 { 3335 /* step aside from further SSL processing 3336 * (used after handle_connection_shut_wr hook) */ 3337 /* future: might restore prior network_read and network_write fn ptrs */ 3338 hctx->con->is_ssl_sock = 0; 3339 /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */ 3340 if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR); 3341 hctx->close_notify = 1; 3342 } 3343 3344 3345 CONNECTION_FUNC(mod_openssl_handle_con_shut_wr) 3346 { 3347 plugin_data *p = p_d; 3348 handler_ctx *hctx = con->plugin_ctx[p->id]; 3349 if (NULL == hctx) return HANDLER_GO_ON; 3350 3351 hctx->close_notify = -2; 3352 if (SSL_is_init_finished(hctx->ssl)) { 3353 mod_openssl_close_notify(hctx); 3354 } 3355 else { 3356 mod_openssl_detach(hctx); 3357 } 3358 3359 return HANDLER_GO_ON; 3360 } 3361 3362 3363 static int 3364 mod_openssl_close_notify(handler_ctx *hctx) 3365 { 3366 int ret, ssl_r; 3367 unsigned long err; 3368 log_error_st *errh; 3369 3370 if (1 == hctx->close_notify) return -2; 3371 3372 ERR_clear_error(); 3373 switch ((ret = SSL_shutdown(hctx->ssl))) { 3374 case 1: 3375 mod_openssl_detach(hctx); 3376 return -2; 3377 case 0: 3378 /* Drain SSL read buffers in case pending records need processing. 3379 * Limit to reading next record to avoid denial of service when CPU 3380 * processing TLS is slower than arrival speed of TLS data packets. 3381 * (unless hctx->conf.ssl_read_ahead is set) 3382 * 3383 * references: 3384 * 3385 * "New session ticket breaks bidirectional shutdown of TLS 1.3 connection" 3386 * https://github.com/openssl/openssl/issues/6262 3387 * 3388 * The peer is still allowed to send data after receiving the 3389 * "close notify" event. If the peer did send data it need to be 3390 * processed by calling SSL_read() before calling SSL_shutdown() a 3391 * second time. SSL_read() will indicate the end of the peer data by 3392 * returning <= 0 and SSL_get_error() returning 3393 * SSL_ERROR_ZERO_RETURN. It is recommended to call SSL_read() 3394 * between SSL_shutdown() calls. 3395 * 3396 * Additional discussion in "Auto retry in shutdown" 3397 * https://github.com/openssl/openssl/pull/6340 3398 */ 3399 ssl_r = SSL_pending(hctx->ssl); 3400 if (ssl_r) { 3401 do { 3402 char buf[4096]; 3403 ret = SSL_read(hctx->ssl, buf, (int)sizeof(buf)); 3404 } while (ret > 0 && (hctx->conf.ssl_read_ahead||(ssl_r-=ret))); 3405 } 3406 3407 ERR_clear_error(); 3408 switch ((ret = SSL_shutdown(hctx->ssl))) { 3409 case 1: 3410 mod_openssl_detach(hctx); 3411 return -2; 3412 case 0: 3413 hctx->close_notify = -1; 3414 return 0; 3415 default: 3416 break; 3417 } 3418 3419 __attribute_fallthrough__ 3420 default: 3421 3422 if (!SSL_is_init_finished(hctx->ssl)) { 3423 mod_openssl_detach(hctx); 3424 return -2; 3425 } 3426 3427 switch ((ssl_r = SSL_get_error(hctx->ssl, ret))) { 3428 case SSL_ERROR_ZERO_RETURN: 3429 case SSL_ERROR_WANT_WRITE: 3430 case SSL_ERROR_WANT_READ: 3431 hctx->close_notify = -1; 3432 return 0; /* try again later */ 3433 case SSL_ERROR_SYSCALL: 3434 /* perhaps we have error waiting in our error-queue */ 3435 errh = hctx->r->conf.errh; 3436 if (0 != (err = ERR_get_error())) { 3437 do { 3438 log_error(errh, __FILE__, __LINE__, 3439 "SSL: %d %d %s",ssl_r,ret,ERR_error_string(err,NULL)); 3440 } while((err = ERR_get_error())); 3441 } else if (errno != 0) { 3442 /*ssl bug (see lighttpd ticket #2213): sometimes errno==0*/ 3443 switch(errno) { 3444 case EPIPE: 3445 case ECONNRESET: 3446 break; 3447 default: 3448 log_perror(errh, __FILE__, __LINE__, 3449 "SSL (error): %d %d", ssl_r, ret); 3450 break; 3451 } 3452 } 3453 3454 break; 3455 default: 3456 errh = hctx->r->conf.errh; 3457 while((err = ERR_get_error())) { 3458 log_error(errh, __FILE__, __LINE__, 3459 "SSL: %d %d %s", ssl_r, ret, ERR_error_string(err, NULL)); 3460 } 3461 3462 break; 3463 } 3464 } 3465 ERR_clear_error(); 3466 hctx->close_notify = -1; 3467 return ret; 3468 } 3469 3470 3471 CONNECTION_FUNC(mod_openssl_handle_con_close) 3472 { 3473 plugin_data *p = p_d; 3474 handler_ctx *hctx = con->plugin_ctx[p->id]; 3475 if (NULL != hctx) { 3476 con->plugin_ctx[p->id] = NULL; 3477 handler_ctx_free(hctx); 3478 } 3479 3480 return HANDLER_GO_ON; 3481 } 3482 3483 3484 static void 3485 https_add_ssl_client_subject (request_st * const r, X509_NAME *xn) 3486 { 3487 const size_t prelen = sizeof("SSL_CLIENT_S_DN_")-1; 3488 char key[64] = "SSL_CLIENT_S_DN_"; 3489 for (int i = 0, nentries = X509_NAME_entry_count(xn); i < nentries; ++i) { 3490 int xobjnid; 3491 const char * xobjsn; 3492 X509_NAME_ENTRY *xe; 3493 3494 if (!(xe = X509_NAME_get_entry(xn, i))) { 3495 continue; 3496 } 3497 xobjnid = OBJ_obj2nid((ASN1_OBJECT*)X509_NAME_ENTRY_get_object(xe)); 3498 xobjsn = OBJ_nid2sn(xobjnid); 3499 if (xobjsn) { 3500 const size_t len = strlen(xobjsn); 3501 if (prelen+len >= sizeof(key)) continue; 3502 memcpy(key+prelen, xobjsn, len); /*(not '\0'-terminated)*/ 3503 http_header_env_set(r, key, prelen+len, 3504 (const char*)X509_NAME_ENTRY_get_data(xe)->data, 3505 X509_NAME_ENTRY_get_data(xe)->length); 3506 } 3507 } 3508 } 3509 3510 3511 __attribute_cold__ 3512 static void 3513 https_add_ssl_client_verify_err (buffer * const b, long status) 3514 { 3515 char errstr[256]; 3516 ERR_error_string_n(status, errstr, sizeof(errstr)); 3517 buffer_append_string(b, errstr); 3518 } 3519 3520 3521 __attribute_noinline__ 3522 static void 3523 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx) 3524 { 3525 X509 *xs; 3526 X509_NAME *xn; 3527 buffer *vb = http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_VERIFY")); 3528 3529 long vr = SSL_get_verify_result(hctx->ssl); 3530 if (vr != X509_V_OK) { 3531 buffer_copy_string_len(vb, CONST_STR_LEN("FAILED:")); 3532 https_add_ssl_client_verify_err(vb, vr); 3533 return; 3534 } else if (!(xs = SSL_get_peer_certificate(hctx->ssl))) { 3535 buffer_copy_string_len(vb, CONST_STR_LEN("NONE")); 3536 return; 3537 } else { 3538 buffer_copy_string_len(vb, CONST_STR_LEN("SUCCESS")); 3539 } 3540 3541 xn = X509_get_subject_name(xs); 3542 { 3543 char buf[256]; 3544 int len = safer_X509_NAME_oneline(xn, buf, sizeof(buf)); 3545 if (len > 0) { 3546 if (len >= (int)sizeof(buf)) len = (int)sizeof(buf)-1; 3547 http_header_env_set(r, 3548 CONST_STR_LEN("SSL_CLIENT_S_DN"), 3549 buf, (size_t)len); 3550 } 3551 } 3552 3553 https_add_ssl_client_subject(r, xn); 3554 3555 { 3556 ASN1_INTEGER *xsn = X509_get_serialNumber(xs); 3557 BIGNUM *serialBN = ASN1_INTEGER_to_BN(xsn, NULL); 3558 char *serialHex = BN_bn2hex(serialBN); 3559 http_header_env_set(r, 3560 CONST_STR_LEN("SSL_CLIENT_M_SERIAL"), 3561 serialHex, strlen(serialHex)); 3562 OPENSSL_free(serialHex); 3563 BN_free(serialBN); 3564 } 3565 3566 if (hctx->conf.ssl_verifyclient_username) { 3567 /* pick one of the exported values as "REMOTE_USER", for example 3568 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID" 3569 * or 3570 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress" 3571 */ 3572 const buffer *varname = hctx->conf.ssl_verifyclient_username; 3573 vb = http_header_env_get(r, BUF_PTR_LEN(varname)); 3574 if (vb) { /* same as mod_auth_api.c:http_auth_setenv() */ 3575 http_header_env_set(r, 3576 CONST_STR_LEN("REMOTE_USER"), 3577 BUF_PTR_LEN(vb)); 3578 http_header_env_set(r, 3579 CONST_STR_LEN("AUTH_TYPE"), 3580 CONST_STR_LEN("SSL_CLIENT_VERIFY")); 3581 } 3582 } 3583 3584 if (hctx->conf.ssl_verifyclient_export_cert) { 3585 BIO *bio; 3586 if (NULL != (bio = BIO_new(BIO_s_mem()))) { 3587 PEM_write_bio_X509(bio, xs); 3588 const int n = BIO_pending(bio); 3589 3590 vb = http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_CERT")); 3591 buffer_extend(vb, (uint32_t)n); 3592 BIO_read(bio, vb->ptr, n); 3593 BIO_free(bio); 3594 } 3595 } 3596 X509_free(xs); 3597 } 3598 3599 3600 static void 3601 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx) 3602 { 3603 const char *s; 3604 const SSL_CIPHER *cipher; 3605 3606 s = SSL_get_version(hctx->ssl); 3607 http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s)); 3608 3609 if ((cipher = SSL_get_current_cipher(hctx->ssl))) { 3610 int usekeysize, algkeysize = 0; 3611 char buf[LI_ITOSTRING_LENGTH]; 3612 s = SSL_CIPHER_get_name(cipher); 3613 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s)); 3614 usekeysize = SSL_CIPHER_get_bits(cipher, &algkeysize); 3615 if (0 == algkeysize) algkeysize = usekeysize; 3616 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"), 3617 buf, li_itostrn(buf, sizeof(buf), usekeysize)); 3618 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"), 3619 buf, li_itostrn(buf, sizeof(buf), algkeysize)); 3620 } 3621 } 3622 3623 3624 REQUEST_FUNC(mod_openssl_handle_request_env) 3625 { 3626 plugin_data *p = p_d; 3627 /* simple flag for request_env_patched */ 3628 if (r->plugin_ctx[p->id]) return HANDLER_GO_ON; 3629 handler_ctx *hctx = r->con->plugin_ctx[p->id]; 3630 if (NULL == hctx) return HANDLER_GO_ON; 3631 r->plugin_ctx[p->id] = (void *)(uintptr_t)1u; 3632 3633 http_cgi_ssl_env(r, hctx); 3634 if (hctx->conf.ssl_verifyclient) { 3635 https_add_ssl_client_entries(r, hctx); 3636 } 3637 3638 return HANDLER_GO_ON; 3639 } 3640 3641 3642 REQUEST_FUNC(mod_openssl_handle_uri_raw) 3643 { 3644 /* mod_openssl must be loaded prior to mod_auth 3645 * if mod_openssl is configured to set REMOTE_USER based on client cert */ 3646 /* mod_openssl must be loaded after mod_extforward 3647 * if mod_openssl config is based on lighttpd.conf remote IP conditional 3648 * using remote IP address set by mod_extforward, *unless* PROXY protocol 3649 * is enabled with extforward.hap-PROXY = "enable", in which case the 3650 * reverse is true: mod_extforward must be loaded after mod_openssl */ 3651 plugin_data *p = p_d; 3652 handler_ctx *hctx = r->con->plugin_ctx[p->id]; 3653 if (NULL == hctx) return HANDLER_GO_ON; 3654 3655 mod_openssl_patch_config(r, &hctx->conf); 3656 if (hctx->conf.ssl_verifyclient) { 3657 mod_openssl_handle_request_env(r, p); 3658 } 3659 3660 return HANDLER_GO_ON; 3661 } 3662 3663 3664 REQUEST_FUNC(mod_openssl_handle_request_reset) 3665 { 3666 plugin_data *p = p_d; 3667 r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */ 3668 return HANDLER_GO_ON; 3669 } 3670 3671 3672 TRIGGER_FUNC(mod_openssl_handle_trigger) { 3673 const plugin_data * const p = p_d; 3674 const unix_time64_t cur_ts = log_epoch_secs; 3675 if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/ 3676 UNUSED(srv); 3677 UNUSED(p); 3678 3679 #ifdef TLSEXT_TYPE_session_ticket 3680 mod_openssl_session_ticket_key_check(p, cur_ts); 3681 #endif 3682 3683 #ifndef OPENSSL_NO_OCSP 3684 mod_openssl_refresh_stapling_files(srv, p, cur_ts); 3685 #endif 3686 3687 return HANDLER_GO_ON; 3688 } 3689 3690 3691 int mod_openssl_plugin_init (plugin *p); 3692 int mod_openssl_plugin_init (plugin *p) 3693 { 3694 p->version = LIGHTTPD_VERSION_ID; 3695 p->name = "openssl"; 3696 p->init = mod_openssl_init; 3697 p->cleanup = mod_openssl_free; 3698 p->priv_defaults= mod_openssl_set_defaults; 3699 3700 p->handle_connection_accept = mod_openssl_handle_con_accept; 3701 p->handle_connection_shut_wr = mod_openssl_handle_con_shut_wr; 3702 p->handle_connection_close = mod_openssl_handle_con_close; 3703 p->handle_uri_raw = mod_openssl_handle_uri_raw; 3704 p->handle_request_env = mod_openssl_handle_request_env; 3705 p->handle_request_reset = mod_openssl_handle_request_reset; 3706 p->handle_trigger = mod_openssl_handle_trigger; 3707 3708 return 0; 3709 } 3710 3711 3712 #if defined(BORINGSSL_API_VERSION) \ 3713 || defined(LIBRESSL_VERSION_NUMBER) 3714 3715 static int 3716 mod_openssl_ssl_conf_proto_val (server *srv, plugin_config_socket *s, const buffer *b, int max) 3717 { 3718 if (NULL == b) /* default: min TLSv1.2, max TLSv1.3 */ 3719 #ifdef TLS1_3_VERSION 3720 return max ? TLS1_3_VERSION : TLS1_2_VERSION; 3721 #else 3722 return TLS1_2_VERSION; 3723 #endif 3724 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("None"))) /*"disable" limit*/ 3725 return max 3726 ? 3727 #ifdef TLS1_3_VERSION 3728 TLS1_3_VERSION 3729 #else 3730 TLS1_2_VERSION 3731 #endif 3732 : (s->ssl_use_sslv3 ? SSL3_VERSION : TLS1_VERSION); 3733 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("SSLv3"))) 3734 return SSL3_VERSION; 3735 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.0"))) 3736 return TLS1_VERSION; 3737 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.1"))) 3738 return TLS1_1_VERSION; 3739 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.2"))) 3740 return TLS1_2_VERSION; 3741 #ifdef TLS1_3_VERSION 3742 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3"))) 3743 return TLS1_3_VERSION; 3744 #endif 3745 else { 3746 if (buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1")) 3747 || buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1.2"))) 3748 log_error(srv->errh, __FILE__, __LINE__, 3749 "SSL: ssl.openssl.ssl-conf-cmd %s %s ignored", 3750 max ? "MaxProtocol" : "MinProtocol", b->ptr); 3751 else 3752 log_error(srv->errh, __FILE__, __LINE__, 3753 "SSL: ssl.openssl.ssl-conf-cmd %s %s invalid; ignored", 3754 max ? "MaxProtocol" : "MinProtocol", b->ptr); 3755 } 3756 #ifdef TLS1_3_VERSION 3757 return max ? TLS1_3_VERSION : TLS1_2_VERSION; 3758 #else 3759 return TLS1_2_VERSION; 3760 #endif 3761 } 3762 3763 3764 static int 3765 mod_openssl_ssl_conf_cmd (server *srv, plugin_config_socket *s) 3766 { 3767 /* reference: 3768 * https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html */ 3769 int rc = 0; 3770 buffer *cipherstring = NULL; 3771 buffer *ciphersuites = NULL; 3772 buffer *minb = NULL; 3773 buffer *maxb = NULL; 3774 buffer *curves = NULL; 3775 3776 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) { 3777 data_string *ds = (data_string *)s->ssl_conf_cmd->data[i]; 3778 if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString"))) 3779 cipherstring = &ds->value; 3780 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites"))) 3781 ciphersuites = &ds->value; 3782 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves")) 3783 || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups"))) 3784 curves = &ds->value; 3785 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol"))) 3786 maxb = &ds->value; 3787 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol"))) 3788 minb = &ds->value; 3789 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) { 3790 /* openssl config for Protocol=... is complex and deprecated */ 3791 log_error(srv->errh, __FILE__, __LINE__, 3792 "SSL: ssl.openssl.ssl-conf-cmd %s ignored; " 3793 "use MinProtocol=... and MaxProtocol=... instead", 3794 ds->key.ptr); 3795 } 3796 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) { 3797 for (char *v = ds->value.ptr, *e; *v; v = e) { 3798 while (*v == ' ' || *v == '\t' || *v == ',') ++v; 3799 int flag = 1; 3800 if (*v == '-') { 3801 flag = 0; 3802 ++v; 3803 } 3804 for (e = v; light_isalpha(*e); ++e) ; 3805 switch ((int)(e-v)) { 3806 case 11: 3807 if (buffer_eq_icase_ssn(v, "Compression", 11)) { 3808 /* (force disabled, the default, if HTTP/2 enabled) */ 3809 if (srv->srvconf.h2proto) 3810 flag = 0; 3811 if (flag) 3812 SSL_CTX_clear_options(s->ssl_ctx, 3813 SSL_OP_NO_COMPRESSION); 3814 else 3815 SSL_CTX_set_options(s->ssl_ctx, 3816 SSL_OP_NO_COMPRESSION); 3817 continue; 3818 } 3819 break; 3820 case 13: 3821 if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) { 3822 if (flag) 3823 SSL_CTX_clear_options(s->ssl_ctx, 3824 SSL_OP_NO_TICKET); 3825 else 3826 SSL_CTX_set_options(s->ssl_ctx, 3827 SSL_OP_NO_TICKET); 3828 continue; 3829 } 3830 break; 3831 case 16: 3832 if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) { 3833 if (flag) 3834 SSL_CTX_set_options(s->ssl_ctx, 3835 SSL_OP_CIPHER_SERVER_PREFERENCE); 3836 else 3837 SSL_CTX_clear_options(s->ssl_ctx, 3838 SSL_OP_CIPHER_SERVER_PREFERENCE); 3839 s->ssl_honor_cipher_order = flag; 3840 continue; 3841 } 3842 break; 3843 default: 3844 break; 3845 } 3846 /* warn if not explicitly handled or ignored above */ 3847 if (!flag) --v; 3848 log_error(srv->errh, __FILE__, __LINE__, 3849 "SSL: ssl.openssl.ssl-conf-cmd Options %.*s " 3850 "ignored", (int)(e-v), v); 3851 } 3852 } 3853 #if 0 3854 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) { 3855 } 3856 #endif 3857 else { 3858 /* warn if not explicitly handled or ignored above */ 3859 log_error(srv->errh, __FILE__, __LINE__, 3860 "SSL: ssl.openssl.ssl-conf-cmd %s ignored", 3861 ds->key.ptr); 3862 } 3863 3864 } 3865 3866 if (minb) { 3867 int n = mod_openssl_ssl_conf_proto_val(srv, s, minb, 0); 3868 if (!SSL_CTX_set_min_proto_version(s->ssl_ctx, n)) 3869 rc = -1; 3870 } 3871 3872 if (maxb) { 3873 int x = mod_openssl_ssl_conf_proto_val(srv, s, maxb, 1); 3874 if (!SSL_CTX_set_max_proto_version(s->ssl_ctx, x)) 3875 rc = -1; 3876 } 3877 3878 if (ciphersuites && !buffer_is_blank(ciphersuites)) { 3879 #if defined(LIBRESSL_VERSION_NUMBER) && defined(LIBRESSL_HAS_TLS1_3) 3880 if (SSL_CTX_set_ciphersuites(s->ssl_ctx, ciphersuites->ptr) != 1) { 3881 log_error(srv->errh, __FILE__, __LINE__, 3882 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 3883 rc = -1; 3884 } 3885 #endif 3886 } 3887 3888 if (cipherstring && !buffer_is_blank(cipherstring)) { 3889 /* Disable support for low encryption ciphers */ 3890 buffer_append_string_len(cipherstring, 3891 CONST_STR_LEN(":!aNULL:!eNULL:!EXP")); 3892 if (SSL_CTX_set_cipher_list(s->ssl_ctx, cipherstring->ptr) != 1) { 3893 log_error(srv->errh, __FILE__, __LINE__, 3894 "SSL: %s", ERR_error_string(ERR_get_error(), NULL)); 3895 rc = -1; 3896 } 3897 3898 if (s->ssl_honor_cipher_order) 3899 SSL_CTX_set_options(s->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); 3900 } 3901 3902 if (curves && !buffer_is_blank(curves)) { 3903 if (!mod_openssl_ssl_conf_curves(srv, s, curves)) 3904 rc = -1; 3905 } 3906 3907 return rc; 3908 } 3909 3910 #endif /* BORINGSSL_API_VERSION || LIBRESSL_VERSION_NUMBER */ 3911