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