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