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