1 /* 2 * mod_gnutls - GnuTLS support for lighttpd 3 * 4 * Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com All rights reserved 5 * License: BSD 3-clause (same as lighttpd) 6 */ 7 /* 8 * GnuTLS manual: https://www.gnutls.org/documentation.html 9 * 10 * Note: If session tickets are -not- disabled with 11 * ssl.openssl.ssl-conf-cmd = ("Options" => "-SessionTicket") 12 * mod_gnutls rotates server ticket encryption key (STEK) every 18 hours. 13 * (https://gnutls.org/manual/html_node/Session-resumption.html) 14 * This is fine for use with a single lighttpd instance, but with multiple 15 * lighttpd workers, no coordinated STEK (server ticket encryption key) 16 * rotation occurs unless ssl.stek-file is defined and maintained (preferred), 17 * or if some external job restarts lighttpd. Restarting lighttpd generates a 18 * new key that is shared by lighttpd workers for the lifetime of the new key. 19 * If the rotation period expires and lighttpd has not been restarted, and if 20 * ssl.stek-file is not in use, then lighttpd workers will generate new 21 * independent keys, making session tickets less effective for session 22 * resumption, since clients have a lower chance for future connections to 23 * reach the same lighttpd worker. However, things will still work, and a new 24 * session will be created if session resumption fails. Admins should plan to 25 * restart lighttpd at least every 18 hours if session tickets are enabled and 26 * multiple lighttpd workers are configured. Since that is likely disruptive, 27 * if multiple lighttpd workers are configured, ssl.stek-file should be 28 * defined and the file maintained externally. 29 * 30 * future possible enhancements to lighttpd mod_gnutls: 31 * - session cache (though session tickets are implemented) 32 * See gnutls_db_set_store_function() and gnutls_db_set_retrieve_function() 33 * (and do not enable unless server.feature-flags ssl.session-cache enabled) 34 */ 35 #include "first.h" 36 37 #include <sys/types.h> 38 #include <sys/stat.h> 39 #include <errno.h> 40 #include <fcntl.h> 41 #include <stdarg.h> 42 #include <stdlib.h> 43 #include <stdio.h> /* vsnprintf() */ 44 #include <string.h> 45 46 #include <gnutls/gnutls.h> 47 #include <gnutls/ocsp.h> 48 #include <gnutls/x509.h> 49 #include <gnutls/x509-ext.h> 50 #include <gnutls/abstract.h> 51 52 #ifdef GNUTLS_SKIP_GLOBAL_INIT 53 GNUTLS_SKIP_GLOBAL_INIT 54 #endif 55 56 #include "base.h" 57 #include "fdevent.h" 58 #include "http_header.h" 59 #include "http_kv.h" 60 #include "log.h" 61 #include "plugin.h" 62 63 typedef struct { 64 /* SNI per host: with COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */ 65 gnutls_certificate_credentials_t ssl_cred; 66 char trust_inited; 67 char must_staple; 68 gnutls_datum_t *ssl_pemfile_x509; 69 gnutls_privkey_t ssl_pemfile_pkey; 70 const buffer *ssl_stapling_file; 71 unix_time64_t ssl_stapling_loadts; 72 unix_time64_t ssl_stapling_nextts; 73 } plugin_cert; 74 75 typedef struct { 76 int8_t ssl_session_ticket; 77 /*(preserved here for deinit at server shutdown)*/ 78 gnutls_priority_t priority_cache; 79 #if GNUTLS_VERSION_NUMBER < 0x030600 80 gnutls_dh_params_t dh_params; 81 #endif 82 } plugin_ssl_ctx; 83 84 typedef struct { 85 plugin_cert *pc; 86 87 /*(used only during startup; not patched)*/ 88 unsigned char ssl_enabled; /* only interesting for setting up listening sockets. don't use at runtime */ 89 unsigned char ssl_honor_cipher_order; /* determine SSL cipher in server-preferred order, not client-order */ 90 unsigned char ssl_empty_fragments; 91 unsigned char ssl_use_sslv2; 92 unsigned char ssl_use_sslv3; 93 const buffer *ssl_cipher_list; 94 const buffer *ssl_dh_file; 95 const buffer *ssl_ec_curve; 96 array *ssl_conf_cmd; 97 98 /*(copied from plugin_data for socket ssl_ctx config)*/ 99 gnutls_priority_t priority_cache; 100 unsigned char ssl_session_ticket; 101 unsigned char ssl_verifyclient; 102 unsigned char ssl_verifyclient_enforce; 103 unsigned char ssl_verifyclient_depth; 104 105 const char *priority_base; 106 buffer *priority_override; 107 buffer priority_str; 108 #if GNUTLS_VERSION_NUMBER < 0x030600 109 gnutls_dh_params_t dh_params; 110 #endif 111 } plugin_config_socket; /*(used at startup during configuration)*/ 112 113 typedef struct { 114 /* SNI per host: w/ COMP_SERVER_SOCKET, COMP_HTTP_SCHEME, COMP_HTTP_HOST */ 115 plugin_cert *pc; 116 gnutls_datum_t *ssl_ca_file; /* .data is (gnutls_x509_crt_t) */ 117 gnutls_datum_t *ssl_ca_dn_file; /* .data is (gnutls_x509_crt_t) */ 118 gnutls_datum_t *ssl_ca_crl_file;/* .data is (gnutls_x509_crl_t) */ 119 120 unsigned char ssl_verifyclient; 121 unsigned char ssl_verifyclient_enforce; 122 unsigned char ssl_verifyclient_depth; 123 unsigned char ssl_verifyclient_export_cert; 124 unsigned char ssl_read_ahead; 125 unsigned char ssl_log_noise; 126 unsigned char ssl_disable_client_renegotiation; 127 const buffer *ssl_verifyclient_username; 128 const buffer *ssl_acme_tls_1; 129 #if GNUTLS_VERSION_NUMBER < 0x030600 130 gnutls_dh_params_t dh_params; 131 #endif 132 } plugin_config; 133 134 typedef struct { 135 PLUGIN_DATA; 136 plugin_ssl_ctx *ssl_ctxs; 137 plugin_config defaults; 138 server *srv; 139 const char *ssl_stek_file; 140 } plugin_data; 141 142 static int ssl_is_init; 143 /* need assigned p->id for deep access of module handler_ctx for connection 144 * i.e. handler_ctx *hctx = con->plugin_ctx[plugin_data_singleton->id]; */ 145 static plugin_data *plugin_data_singleton; 146 #define LOCAL_SEND_BUFSIZE 16384 /* DEFAULT_MAX_RECORD_SIZE */ 147 static char *local_send_buffer; 148 149 typedef struct { 150 gnutls_session_t ssl; /* gnutls request/connection context */ 151 request_st *r; 152 connection *con; 153 int8_t close_notify; 154 uint8_t alpn; 155 int8_t ssl_session_ticket; 156 int handshake; 157 size_t pending_write; 158 plugin_config conf; 159 unsigned int verify_status; 160 buffer *tmp_buf; 161 log_error_st *errh; 162 gnutls_certificate_credentials_t acme_tls_1_cred; 163 } handler_ctx; 164 165 166 static handler_ctx * 167 handler_ctx_init (void) 168 { 169 handler_ctx *hctx = calloc(1, sizeof(*hctx)); 170 force_assert(hctx); 171 return hctx; 172 } 173 174 175 static void 176 handler_ctx_free (handler_ctx *hctx) 177 { 178 gnutls_deinit(hctx->ssl); 179 if (hctx->acme_tls_1_cred) 180 gnutls_certificate_free_credentials(hctx->acme_tls_1_cred); 181 free(hctx); 182 } 183 184 185 __attribute_cold__ 186 static void elog(log_error_st * const errh, 187 const char * const file, const int line, 188 const int rc, const char * const msg) 189 { 190 /* error logging convenience function that decodes gnutls result codes */ 191 log_error(errh, file, line, "GnuTLS: %s: (%s) %s", 192 msg, gnutls_strerror_name(rc), gnutls_strerror(rc)); 193 } 194 195 196 __attribute_cold__ 197 __attribute_format__((__printf__, 5, 6)) 198 static void elogf(log_error_st * const errh, 199 const char * const file, const int line, 200 const int rc, const char * const fmt, ...) 201 { 202 char msg[1024]; 203 va_list ap; 204 va_start(ap, fmt); 205 vsnprintf(msg, sizeof(msg), fmt, ap); 206 va_end(ap); 207 elog(errh, file, line, rc, msg); 208 } 209 210 211 /* gnutls func gnutls_load_file() loads file contents into a gnutls_datum_t. 212 * The data loaded could be sensitive, e.g. a private key included in a pemfile. 213 * However, gnutls_load_file() is not careful about zeroizing memory on error, 214 * might use realloc() (which does not guarantee to zeroize memory released), 215 * and silently continues on short read, so provide our own. Updates to 216 * gnutls 3.6.14 may be more careful with private key files, but do not 217 * extend the same care to pemfiles which might contain private keys. 218 * Related, see also mod_gnutls_datum_wipe() below. 219 * https://gitlab.com/gnutls/gnutls/-/issues/1001 220 * https://gitlab.com/gnutls/gnutls/-/issues/1002 221 * https://gitlab.com/gnutls/gnutls/-/merge_requests/1270 222 */ 223 static int 224 mod_gnutls_load_file (const char * const fn, gnutls_datum_t * const d, log_error_st *errh) 225 { 226 #if 0 227 int rc = gnutls_load_file(fn, d); 228 if (rc < 0) 229 elogf(errh, __FILE__, __LINE__, rc, "%s() %s", __func__, fn); 230 return rc; 231 #else 232 off_t dlen = 512*1024*1024;/*(arbitrary limit: 512 MB file; expect < 1 MB)*/ 233 char *data = fdevent_load_file(fn, &dlen, errh, gnutls_malloc, gnutls_free); 234 if (NULL == data) return GNUTLS_E_FILE_ERROR; 235 d->data = (unsigned char *)data; 236 d->size = (unsigned int)dlen; 237 return 0; 238 #endif 239 } 240 241 242 /* GnuTLS does not expose _gnutls_free_key_datum() so provide our own */ 243 static void 244 mod_gnutls_datum_wipe (gnutls_datum_t * const d) 245 { 246 if (NULL == d) return; 247 if (d->data) { 248 if (d->size) gnutls_memset(d->data, 0, d->size); 249 gnutls_free(d->data); 250 d->data = NULL; 251 } 252 d->size = 0; 253 } 254 255 256 /* session tickets 257 * 258 * gnutls expects 64 bytes of random data in gnutls_datum_t passed to 259 * gnutls_session_ticket_enable_server() 260 * 261 * (private) session ticket definitions from lib/gnutls_int.h 262 * #define TICKET_MASTER_KEY_SIZE (TICKET_KEY_NAME_SIZE+TICKET_CIPHER_KEY_SIZE+TICKET_MAC_SECRET_SIZE) 263 * #define TICKET_KEY_NAME_SIZE 16 264 * #define TICKET_CIPHER_KEY_SIZE 32 265 * #define TICKET_MAC_SECRET_SIZE 16 266 */ 267 #define TICKET_MASTER_KEY_SIZE 64 268 269 #define TLSEXT_KEYNAME_LENGTH 16 270 #define TLSEXT_TICK_KEY_LENGTH 32 271 272 /* construct our own session ticket encryption key structure 273 * to store keys that are not yet active 274 * (mirror from mod_openssl, even though not all bits are used here) */ 275 typedef struct tlsext_ticket_key_st { 276 unix_time64_t active_ts; /* tickets not issued w/ key until activation ts*/ 277 unix_time64_t expire_ts; /* key not valid after expiration timestamp */ 278 unsigned char tick_key_name[TLSEXT_KEYNAME_LENGTH]; 279 unsigned char tick_hmac_key[TLSEXT_TICK_KEY_LENGTH]; 280 unsigned char tick_aes_key[TLSEXT_TICK_KEY_LENGTH]; 281 } tlsext_ticket_key_t; 282 283 static tlsext_ticket_key_t session_ticket_keys[1]; /* temp store until active */ 284 static unix_time64_t stek_rotate_ts; 285 286 static gnutls_datum_t session_ticket_key; 287 288 289 static void 290 mod_gnutls_session_ticket_key_free (void) 291 { 292 mod_gnutls_datum_wipe(&session_ticket_key); 293 } 294 static void 295 mod_gnutls_session_ticket_key_init (server *srv) 296 { 297 int rc = gnutls_session_ticket_key_generate(&session_ticket_key); 298 if (rc < 0) { 299 /*(should not happen, but if it does, disable session ticket)*/ 300 session_ticket_key.size = 0; 301 elog(srv->errh, __FILE__, __LINE__, rc, 302 "gnutls_session_ticket_key_generate()"); 303 } 304 } 305 static void 306 mod_gnutls_session_ticket_key_rotate (server *srv) 307 { 308 mod_gnutls_session_ticket_key_free(); 309 mod_gnutls_session_ticket_key_init(srv); 310 } 311 312 313 static int 314 mod_gnutls_session_ticket_key_file (const char *fn) 315 { 316 /* session ticket encryption key (STEK) 317 * 318 * STEK file should be stored in non-persistent storage, 319 * e.g. /dev/shm/lighttpd/stek-file (in memory) 320 * with appropriate permissions set to keep stek-file from being 321 * read by other users. Where possible, systems should also be 322 * configured without swap. 323 * 324 * admin should schedule an independent job to periodically 325 * generate new STEK up to 3 times during key lifetime 326 * (lighttpd stores up to 3 keys) 327 * 328 * format of binary file is: 329 * 4-byte - format version (always 0; for use if format changes) 330 * 4-byte - activation timestamp 331 * 4-byte - expiration timestamp 332 * 16-byte - session ticket key name 333 * 32-byte - session ticket HMAC encrpytion key 334 * 32-byte - session ticket AES encrpytion key 335 * 336 * STEK file can be created with a command such as: 337 * dd if=/dev/random bs=1 count=80 status=none | \ 338 * perl -e 'print pack("iii",0,time()+300,time()+86400),<>' \ 339 * > STEK-file.$$ && mv STEK-file.$$ STEK-file 340 * 341 * The above delays activation time by 5 mins (+300 sec) to allow file to 342 * be propagated to other machines. (admin must handle this independently) 343 * If STEK generation is performed immediately prior to starting lighttpd, 344 * admin should activate keys immediately (without +300). 345 */ 346 int buf[23]; /* 92 bytes */ 347 int rc = 0; /*(will retry on next check interval upon any error)*/ 348 if (0 != fdevent_load_file_bytes((char *)buf,(off_t)sizeof(buf),0,fn,NULL)) 349 return rc; 350 if (buf[0] == 0) { /*(format version 0)*/ 351 session_ticket_keys[0].active_ts = TIME64_CAST(buf[1]); 352 session_ticket_keys[0].expire_ts = TIME64_CAST(buf[2]); 353 #ifndef __COVERITY__ 354 memcpy(&session_ticket_keys[0].tick_key_name, buf+3, 80); 355 #else 356 memcpy(&session_ticket_keys[0].tick_key_name, 357 buf+3, TLSEXT_KEYNAME_LENGTH); 358 memcpy(&session_ticket_keys[0].tick_hmac_key, 359 buf+7, TLSEXT_TICK_KEY_LENGTH); 360 memcpy(&session_ticket_keys[0].tick_aes_key, 361 buf+15, TLSEXT_TICK_KEY_LENGTH); 362 #endif 363 rc = 1; 364 } 365 366 gnutls_memset(buf, 0, sizeof(buf)); 367 return rc; 368 } 369 370 371 static void 372 mod_gnutls_session_ticket_key_check (server *srv, const plugin_data *p, const unix_time64_t cur_ts) 373 { 374 static unix_time64_t detect_retrograde_ts; 375 if (detect_retrograde_ts > cur_ts && detect_retrograde_ts - cur_ts > 28800) 376 stek_rotate_ts = 0; 377 detect_retrograde_ts = cur_ts; 378 379 if (p->ssl_stek_file) { 380 struct stat st; 381 if (0 == stat(p->ssl_stek_file, &st) 382 && TIME64_CAST(st.st_mtime) > stek_rotate_ts 383 && mod_gnutls_session_ticket_key_file(p->ssl_stek_file)) { 384 stek_rotate_ts = cur_ts; 385 } 386 387 tlsext_ticket_key_t *stek = session_ticket_keys; 388 if (stek->active_ts != 0 && stek->active_ts - 63 <= cur_ts) { 389 if (NULL == session_ticket_key.data) { 390 session_ticket_key.data = gnutls_malloc(TICKET_MASTER_KEY_SIZE); 391 if (NULL == session_ticket_key.data) return; 392 session_ticket_key.size = TICKET_MASTER_KEY_SIZE; 393 } 394 #ifndef __COVERITY__ 395 memcpy(session_ticket_key.data, 396 stek->tick_key_name, TICKET_MASTER_KEY_SIZE); 397 gnutls_memset(stek->tick_key_name, 0, TICKET_MASTER_KEY_SIZE); 398 #else 399 char * const data = (char *)session_ticket_key.data; 400 memcpy(data, 401 stek->tick_key_name, TLSEXT_KEYNAME_LENGTH); 402 memcpy(data+TLSEXT_KEYNAME_LENGTH, 403 stek->tick_hmac_key, TLSEXT_TICK_KEY_LENGTH); 404 memcpy(data+TLSEXT_KEYNAME_LENGTH+TLSEXT_TICK_KEY_LENGTH, 405 stek->tick_aes_key, 406 TICKET_MASTER_KEY_SIZE 407 - (TLSEXT_KEYNAME_LENGTH + TLSEXT_TICK_KEY_LENGTH)); 408 gnutls_memset(stek->tick_key_name, 0, TLSEXT_KEYNAME_LENGTH); 409 gnutls_memset(stek->tick_hmac_key, 0, TLSEXT_TICK_KEY_LENGTH); 410 gnutls_memset(stek->tick_aes_key, 0, TLSEXT_TICK_KEY_LENGTH); 411 #endif 412 } 413 if (stek->expire_ts < cur_ts) 414 mod_gnutls_session_ticket_key_free(); 415 } 416 else if (cur_ts - 86400 >= stek_rotate_ts /*(24 hours)*/ 417 || 0 == stek_rotate_ts) { 418 mod_gnutls_session_ticket_key_rotate(srv); 419 stek_rotate_ts = cur_ts; 420 } 421 } 422 423 424 INIT_FUNC(mod_gnutls_init) 425 { 426 plugin_data_singleton = (plugin_data *)calloc(1, sizeof(plugin_data)); 427 return plugin_data_singleton; 428 } 429 430 431 static int mod_gnutls_init_once_gnutls (void) 432 { 433 if (ssl_is_init) return 1; 434 ssl_is_init = 1; 435 436 /* Note: on systems with support for weak symbols, GNUTLS_SKIP_GLOBAL_INIT 437 * is set near top of this file to inhibit GnuTLS implicit initialization 438 * in a library constructor. On systems without support for weak symbols, 439 * set GNUTLS_NO_EXPLICIT_INIT=1 in the environment before starting lighttpd 440 * (GnuTLS 3.3.0 or later) */ 441 442 if (gnutls_global_init() != GNUTLS_E_SUCCESS) 443 return 0; 444 445 local_send_buffer = malloc(LOCAL_SEND_BUFSIZE); 446 force_assert(NULL != local_send_buffer); 447 448 return 1; 449 } 450 451 452 static void mod_gnutls_free_gnutls (void) 453 { 454 if (!ssl_is_init) return; 455 456 gnutls_memset(session_ticket_keys, 0, sizeof(session_ticket_keys)); 457 mod_gnutls_session_ticket_key_free(); 458 stek_rotate_ts = 0; 459 460 gnutls_global_deinit(); 461 462 free(local_send_buffer); 463 ssl_is_init = 0; 464 } 465 466 467 static void 468 mod_gnutls_free_config_crts (gnutls_datum_t *d) 469 { 470 if (NULL == d) return; 471 gnutls_x509_crt_t *crts = (gnutls_x509_crt_t *)(void *)d->data; 472 unsigned int u = d->size; 473 for (unsigned int i = 0; i < u; ++i) 474 gnutls_x509_crt_deinit(crts[i]); 475 gnutls_free(crts); 476 gnutls_free(d); 477 } 478 479 480 static void 481 mod_gnutls_free_config_crls (gnutls_datum_t *d) 482 { 483 if (NULL == d) return; 484 gnutls_x509_crl_t *crls = (gnutls_x509_crl_t *)(void *)d->data; 485 unsigned int u = d->size; 486 for (unsigned int i = 0; i < u; ++i) 487 gnutls_x509_crl_deinit(crls[i]); 488 gnutls_free(crls); 489 gnutls_free(d); 490 } 491 492 493 static gnutls_datum_t * 494 mod_gnutls_load_config_crts (const char *fn, log_error_st *errh) 495 { 496 /*(very similar to other mod_gnutls_load_config_*())*/ 497 if (!mod_gnutls_init_once_gnutls()) return NULL; 498 499 gnutls_datum_t f = { NULL, 0 }; 500 int rc = mod_gnutls_load_file(fn, &f, errh); 501 if (rc < 0) return NULL; 502 gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t)); 503 if (d == NULL) { 504 mod_gnutls_datum_wipe(&f); 505 return NULL; 506 } 507 d->data = NULL; 508 d->size = 0; 509 rc = gnutls_x509_crt_list_import2((gnutls_x509_crt_t **)&d->data, &d->size, 510 &f, GNUTLS_X509_FMT_PEM, 511 GNUTLS_X509_CRT_LIST_SORT); 512 mod_gnutls_datum_wipe(&f); 513 if (rc < 0) { 514 elogf(errh, __FILE__, __LINE__, rc, 515 "gnutls_x509_crt_list_import2() %s", fn); 516 mod_gnutls_free_config_crts(d); 517 return NULL; 518 } 519 520 return d; 521 } 522 523 524 static gnutls_datum_t * 525 mod_gnutls_load_config_crls (const char *fn, log_error_st *errh) 526 { 527 /*(very similar to other mod_gnutls_load_config_*())*/ 528 if (!mod_gnutls_init_once_gnutls()) return NULL; 529 530 gnutls_datum_t f = { NULL, 0 }; 531 int rc = mod_gnutls_load_file(fn, &f, errh); 532 if (rc < 0) return NULL; 533 gnutls_datum_t *d = gnutls_malloc(sizeof(gnutls_datum_t)); 534 if (d == NULL) { 535 mod_gnutls_datum_wipe(&f); 536 return NULL; 537 } 538 d->data = NULL; 539 d->size = 0; 540 rc = gnutls_x509_crl_list_import2((gnutls_x509_crl_t **)&d->data, &d->size, 541 &f, GNUTLS_X509_FMT_PEM, 0); 542 mod_gnutls_datum_wipe(&f); 543 if (rc < 0) { 544 elogf(errh, __FILE__, __LINE__, rc, 545 "gnutls_x509_crl_list_import2() %s", fn); 546 mod_gnutls_free_config_crls(d); 547 return NULL; 548 } 549 550 return d; 551 } 552 553 554 static gnutls_privkey_t 555 mod_gnutls_load_config_pkey (const char *fn, log_error_st *errh) 556 { 557 /*(very similar to other mod_gnutls_load_config_*())*/ 558 if (!mod_gnutls_init_once_gnutls()) return NULL; 559 560 gnutls_datum_t f = { NULL, 0 }; 561 int rc = mod_gnutls_load_file(fn, &f, errh); 562 if (rc < 0) return NULL; 563 gnutls_privkey_t pkey; 564 rc = gnutls_privkey_init(&pkey); 565 if (rc < 0) { 566 mod_gnutls_datum_wipe(&f); 567 return NULL; 568 } 569 rc = gnutls_privkey_import_x509_raw(pkey, &f, GNUTLS_X509_FMT_PEM, NULL, 0); 570 mod_gnutls_datum_wipe(&f); 571 if (rc < 0) { 572 elogf(errh, __FILE__, __LINE__, rc, 573 "gnutls_privkey_import_x509_raw() %s", fn); 574 gnutls_privkey_deinit(pkey); 575 return NULL; 576 } 577 578 return pkey; 579 } 580 581 582 static void 583 mod_gnutls_free_config (server *srv, plugin_data * const p) 584 { 585 if (NULL != p->ssl_ctxs) { 586 gnutls_priority_t pcache_global_scope = p->ssl_ctxs->priority_cache; 587 /* free from $SERVER["socket"] (if not copy of global scope) */ 588 for (uint32_t i = 1; i < srv->config_context->used; ++i) { 589 plugin_ssl_ctx * const s = p->ssl_ctxs + i; 590 if (s->priority_cache && s->priority_cache != pcache_global_scope) { 591 if (s->priority_cache) 592 gnutls_priority_deinit(s->priority_cache); 593 #if GNUTLS_VERSION_NUMBER < 0x030600 594 if (s->dh_params) 595 gnutls_dh_params_deinit(s->dh_params); 596 #endif 597 } 598 } 599 /* free from global scope */ 600 if (pcache_global_scope) { 601 if (p->ssl_ctxs[0].priority_cache) 602 gnutls_priority_deinit(p->ssl_ctxs[0].priority_cache); 603 #if GNUTLS_VERSION_NUMBER < 0x030600 604 if (p->ssl_ctxs[0].dh_params) 605 gnutls_dh_params_deinit(p->ssl_ctxs[0].dh_params); 606 #endif 607 } 608 free(p->ssl_ctxs); 609 } 610 611 if (NULL == p->cvlist) return; 612 /* (init i to 0 if global context; to 1 to skip empty global context) */ 613 for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) { 614 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 615 for (; -1 != cpv->k_id; ++cpv) { 616 switch (cpv->k_id) { 617 case 0: /* ssl.pemfile */ 618 if (cpv->vtype == T_CONFIG_LOCAL) { 619 plugin_cert *pc = cpv->v.v; 620 gnutls_certificate_free_credentials(pc->ssl_cred); 621 mod_gnutls_free_config_crts(pc->ssl_pemfile_x509); 622 gnutls_privkey_deinit(pc->ssl_pemfile_pkey); 623 free(pc); 624 } 625 break; 626 case 2: /* ssl.ca-file */ 627 case 3: /* ssl.ca-dn-file */ 628 if (cpv->vtype == T_CONFIG_LOCAL) 629 mod_gnutls_free_config_crts(cpv->v.v); 630 break; 631 case 4: /* ssl.ca-crl-file */ 632 if (cpv->vtype == T_CONFIG_LOCAL) 633 mod_gnutls_free_config_crls(cpv->v.v); 634 break; 635 default: 636 break; 637 } 638 } 639 } 640 } 641 642 643 FREE_FUNC(mod_gnutls_free) 644 { 645 plugin_data *p = p_d; 646 if (NULL == p->srv) return; 647 mod_gnutls_free_config(p->srv, p); 648 mod_gnutls_free_gnutls(); 649 } 650 651 652 static void 653 mod_gnutls_merge_config_cpv (plugin_config * const pconf, const config_plugin_value_t * const cpv) 654 { 655 switch (cpv->k_id) { /* index into static config_plugin_keys_t cpk[] */ 656 case 0: /* ssl.pemfile */ 657 if (cpv->vtype == T_CONFIG_LOCAL) 658 pconf->pc = cpv->v.v; 659 break; 660 case 1: /* ssl.privkey */ 661 break; 662 case 2: /* ssl.ca-file */ 663 if (cpv->vtype == T_CONFIG_LOCAL) 664 pconf->ssl_ca_file = cpv->v.v; 665 break; 666 case 3: /* ssl.ca-dn-file */ 667 if (cpv->vtype == T_CONFIG_LOCAL) 668 pconf->ssl_ca_dn_file = cpv->v.v; 669 break; 670 case 4: /* ssl.ca-crl-file */ 671 if (cpv->vtype == T_CONFIG_LOCAL) 672 pconf->ssl_ca_crl_file = cpv->v.v; 673 break; 674 case 5: /* ssl.read-ahead */ 675 pconf->ssl_read_ahead = (0 != cpv->v.u); 676 break; 677 case 6: /* ssl.disable-client-renegotiation */ 678 pconf->ssl_disable_client_renegotiation = (0 != cpv->v.u); 679 break; 680 case 7: /* ssl.verifyclient.activate */ 681 pconf->ssl_verifyclient = (0 != cpv->v.u); 682 break; 683 case 8: /* ssl.verifyclient.enforce */ 684 pconf->ssl_verifyclient_enforce = (0 != cpv->v.u); 685 break; 686 case 9: /* ssl.verifyclient.depth */ 687 pconf->ssl_verifyclient_depth = (unsigned char)cpv->v.shrt; 688 break; 689 case 10:/* ssl.verifyclient.username */ 690 pconf->ssl_verifyclient_username = cpv->v.b; 691 break; 692 case 11:/* ssl.verifyclient.exportcert */ 693 pconf->ssl_verifyclient_export_cert = (0 != cpv->v.u); 694 break; 695 case 12:/* ssl.acme-tls-1 */ 696 pconf->ssl_acme_tls_1 = cpv->v.b; 697 break; 698 case 13:/* ssl.stapling-file */ 699 break; 700 case 14:/* debug.log-ssl-noise */ 701 pconf->ssl_log_noise = (unsigned char)cpv->v.shrt; 702 break; 703 #if 0 /*(cpk->k_id remapped in mod_gnutls_set_defaults())*/ 704 case 15:/* ssl.verifyclient.ca-file */ 705 case 16:/* ssl.verifyclient.ca-dn-file */ 706 case 17:/* ssl.verifyclient.ca-crl-file */ 707 break; 708 #endif 709 default:/* should not happen */ 710 return; 711 } 712 } 713 714 715 static void 716 mod_gnutls_merge_config(plugin_config * const pconf, const config_plugin_value_t *cpv) 717 { 718 do { 719 mod_gnutls_merge_config_cpv(pconf, cpv); 720 } while ((++cpv)->k_id != -1); 721 } 722 723 724 static void 725 mod_gnutls_patch_config (request_st * const r, plugin_config * const pconf) 726 { 727 plugin_data * const p = plugin_data_singleton; 728 memcpy(pconf, &p->defaults, sizeof(plugin_config)); 729 for (int i = 1, used = p->nconfig; i < used; ++i) { 730 if (config_check_cond(r, (uint32_t)p->cvlist[i].k_id)) 731 mod_gnutls_merge_config(pconf, p->cvlist + p->cvlist[i].v.u2[0]); 732 } 733 } 734 735 736 static int 737 mod_gnutls_verify_set_tlist (handler_ctx *hctx, int req) 738 { 739 /* XXX GnuTLS interfaces appear to be better for client-side use than for 740 * server-side use. If gnutls_x509_trust_list_t were available to attach 741 * to a gnutls_session_t (without copying), then there would not be race 742 * conditions swapping trust lists on the credential *shared* between 743 * connections when ssl.ca-dn-file and ssl.ca-file are both set. If both 744 * are set, current code attempts to set ssl.ca-dn-file right before sending 745 * client cert request, and sets ssl.ca-file right before client cert verify 746 * 747 * Architecture would be cleaner if the trust list for verifying client cert 748 * (gnutls_x509_trust_list_t) were available to attach to a gnutls_session_t 749 * instead of attaching to a gnutls_certificate_credentials_t. 750 */ 751 if (hctx->conf.pc->trust_inited) return GNUTLS_E_SUCCESS; 752 753 gnutls_datum_t *d; 754 int rc; 755 756 /* set trust list using ssl_ca_dn_file, if set, for client cert request 757 * (when req is true) (for CAs sent by server to client in cert request) 758 * (trust is later replaced by ssl_ca_file for client cert verification) */ 759 d = req && hctx->conf.ssl_ca_dn_file 760 ? hctx->conf.ssl_ca_dn_file 761 : hctx->conf.ssl_ca_file; 762 if (NULL == d) { 763 log_error(hctx->r->conf.errh, __FILE__, __LINE__, 764 "GnuTLS: can't verify client without ssl.verifyclient.ca-file " 765 "for TLS server name %s", 766 hctx->r->uri.authority.ptr); /*(might not be set yet if no SNI)*/ 767 return GNUTLS_E_INTERNAL_ERROR; 768 } 769 770 gnutls_x509_trust_list_t tlist = NULL; 771 rc = gnutls_x509_trust_list_init(&tlist, 0); 772 if (rc < 0) { 773 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, 774 "gnutls_x509_trust_list_init()"); 775 return rc; 776 } 777 778 gnutls_x509_crt_t *clist = (gnutls_x509_crt_t *)(void *)d->data; 779 rc = gnutls_x509_trust_list_add_cas(tlist, clist, d->size, 0); 780 if (rc < 0) { 781 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, 782 "gnutls_x509_trust_list_add_cas()"); 783 gnutls_x509_trust_list_deinit(tlist, 0); 784 return rc; 785 } 786 787 d = hctx->conf.ssl_ca_crl_file; 788 if (NULL != d && req && hctx->conf.ssl_ca_dn_file) { 789 /*(check req and ssl_ca_dn_file to see if tlist will be replaced later, 790 * and, if so, defer setting crls until later)*/ 791 gnutls_x509_crl_t *crl_list = (gnutls_x509_crl_t *)(void *)d->data; 792 rc = gnutls_x509_trust_list_add_crls(tlist, crl_list, d->size, 0, 0); 793 if (rc < 0) { 794 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, 795 "gnutls_x509_trust_list_add_crls()"); 796 gnutls_x509_trust_list_deinit(tlist, 0); 797 return rc; 798 } 799 } 800 801 /* gnutls limitation; wasteful to have to copy into each cred */ 802 /* (would be better to share list with session, instead of with cred) */ 803 gnutls_certificate_credentials_t ssl_cred = hctx->conf.pc->ssl_cred; 804 gnutls_certificate_set_trust_list(ssl_cred, tlist, 0); /* transfer tlist */ 805 806 /* (must flip trust lists back and forth b/w DN names and verify CAs) */ 807 if (NULL == hctx->conf.ssl_ca_dn_file) 808 hctx->conf.pc->trust_inited = 1; 809 810 return GNUTLS_E_SUCCESS; 811 } 812 813 814 static int 815 mod_gnutls_verify_cb (gnutls_session_t ssl) 816 { 817 handler_ctx * const hctx = gnutls_session_get_ptr(ssl); 818 if (!hctx->conf.ssl_verifyclient) return 0; 819 820 if (gnutls_auth_client_get_type(ssl) != GNUTLS_CRD_CERTIFICATE) 821 return GNUTLS_E_SUCCESS; 822 823 int rc; 824 825 /* gnutls limitation; wasteful to have to copy into each cred */ 826 /* (would be better to share list with session, instead of with cred) */ 827 if (hctx->conf.ssl_ca_dn_file) { 828 rc = mod_gnutls_verify_set_tlist(hctx, 0); /* for client cert verify */ 829 if (rc < 0) return rc; 830 } 831 832 /* gnutls_certificate_verify_peers2() includes processing OCSP staping, 833 * as well as certificate depth verification before getting internal 834 * flags and calling gnutls_x509_trust_list_verify_crt2() 835 * advanced reference: 836 * gnutls lib/cert-sessions.c:_gnutls_x509_cert_verify_peers() 837 * XXX: if GnuTLS provided a more advanced interface which permitted 838 * providing trust list, verify depth, and flags, we could avoid copying 839 * ca chain and crls into each credential, using 840 * gnutls_x509_trust_list_add_cas() 841 * gnutls_x509_trust_list_add_crls() 842 * gnutls_x509_trust_list_verify_crt2() 843 * See also GnuTLS manual Section 7.3.4 Advanced certificate verification 844 */ 845 846 rc = gnutls_certificate_verify_peers2(ssl, &hctx->verify_status); 847 if (rc < 0) return rc; 848 849 if (hctx->verify_status == 0 && hctx->conf.ssl_ca_dn_file) { 850 /* verify that client cert is issued by CA in ssl.ca-dn-file 851 * if both ssl.ca-dn-file and ssl.ca-file were configured */ 852 gnutls_x509_crt_t *CA_list = 853 (gnutls_x509_crt_t *)(void *)hctx->conf.ssl_ca_dn_file->data; 854 unsigned int len = hctx->conf.ssl_ca_dn_file->size; 855 unsigned int i; 856 gnutls_x509_dn_t issuer, subject; 857 unsigned int crt_size = 0; 858 const gnutls_datum_t *crts; 859 gnutls_x509_crt_t crt = NULL; 860 crts = gnutls_certificate_get_peers(ssl, &crt_size); 861 if (0 == crt_size 862 || gnutls_x509_crt_init(&crt) < 0 863 || gnutls_x509_crt_import(crt, &crts[0], GNUTLS_X509_FMT_DER) < 0 864 || gnutls_x509_crt_get_subject(crt, &issuer) < 0) 865 len = 0; /*(trigger failure path below)*/ 866 for (i = 0; i < len; ++i) { 867 if (gnutls_x509_crt_get_subject(CA_list[i], &subject) >= 0 868 && 0 == memcmp(&subject, &issuer, sizeof(issuer))) 869 break; 870 } 871 if (i == len) 872 hctx->verify_status |= GNUTLS_CERT_SIGNER_NOT_CA; 873 if (crt) gnutls_x509_crt_deinit(crt); 874 } 875 876 if (hctx->verify_status != 0 && hctx->conf.ssl_verifyclient_enforce) { 877 /* (not looping on GNUTLS_E_INTERRUPTED or GNUTLS_E_AGAIN 878 * since we do not want to block here (and not expecting to have to))*/ 879 (void)gnutls_alert_send(ssl, GNUTLS_AL_FATAL, GNUTLS_A_ACCESS_DENIED); 880 return GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR; 881 } 882 883 return GNUTLS_E_SUCCESS; 884 } 885 886 887 #if GNUTLS_VERSION_NUMBER < 0x030603 888 static time_t 889 mod_gnutls_ocsp_next_update (plugin_cert *pc, log_error_st *errh) 890 { 891 gnutls_datum_t f = { NULL, 0 }; 892 int rc = mod_gnutls_load_file(pc->ssl_stapling_file->ptr, &f, errh); 893 if (rc < 0) return (time_t)-1; 894 895 gnutls_ocsp_resp_t resp = NULL; 896 time_t nextupd; 897 if ( gnutls_ocsp_resp_init(&resp) < 0 898 || gnutls_ocsp_resp_import(resp, &f) < 0 899 || gnutls_ocsp_resp_get_single(resp, 0, NULL, NULL, NULL, NULL, NULL, 900 NULL, &nextupd, NULL, NULL) < 0) 901 nextupd = (time_t)-1; 902 gnutls_ocsp_resp_deinit(resp); 903 mod_gnutls_datum_wipe(&f); 904 return nextupd; 905 } 906 #endif 907 908 909 __attribute_cold__ 910 static void 911 mod_gnutls_expire_stapling_file (server *srv, plugin_cert *pc) 912 { 913 #if 0 914 /* discard expired OCSP stapling response */ 915 /* Does GnuTLS detect expired OCSP response? */ 916 /* or must we rebuild gnutls_certificate_credentials_t ? */ 917 #endif 918 if (pc->must_staple) 919 log_error(srv->errh, __FILE__, __LINE__, 920 "certificate marked OCSP Must-Staple, " 921 "but OCSP response expired from ssl.stapling-file %s", 922 pc->ssl_stapling_file->ptr); 923 } 924 925 926 static int 927 mod_gnutls_reload_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts) 928 { 929 #if GNUTLS_VERSION_NUMBER < 0x030603 930 /* load file into gnutls_ocsp_resp_t before loading into 931 * gnutls_certificate_credentials_t for safety. Still ToC-ToU since file 932 * is loaded twice, but unlikely condition. (GnuTLS limitation does not 933 * expose access to OCSP response from gnutls_certificate_credentials_t 934 * before GnuTLS 3.6.3) */ 935 time_t nextupd = mod_gnutls_ocsp_next_update(pc, srv->errh); 936 #else 937 UNUSED(srv); 938 #endif 939 940 /* GnuTLS 3.5.6 added the ability to include multiple OCSP responses for 941 * certificate chain as allowed in TLSv1.3, but that is not utilized here. 942 * If implemented, it will probably operate on a new directive, 943 * e.g. ssl.stapling-pemfile 944 * GnuTLS 3.6.3 added gnutls_certificate_set_ocsp_status_request_file2() 945 * GnuTLS 3.6.3 added gnutls_certificate_set_ocsp_status_request_mem() 946 * GnuTLS 3.6.3 added gnutls_certificate_get_ocsp_expiration() */ 947 948 /* gnutls_certificate_get_ocsp_expiration() code comments: 949 * Note that the credentials structure should be read-only when in 950 * use, thus when reloading, either the credentials structure must not 951 * be in use by any sessions, or a new credentials structure should be 952 * allocated for new sessions. 953 * XXX: lighttpd is not threaded, so this is probably not an issue (?) 954 */ 955 956 #if 0 957 gnutls_certificate_set_flags(pc->ssl_cred, 958 GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK); 959 #endif 960 961 const char *fn = pc->ssl_stapling_file->ptr; 962 int rc = gnutls_certificate_set_ocsp_status_request_file(pc->ssl_cred,fn,0); 963 if (rc < 0) 964 return rc; 965 966 #if GNUTLS_VERSION_NUMBER >= 0x030603 967 time_t nextupd = 968 gnutls_certificate_get_ocsp_expiration(pc->ssl_cred, 0, 0, 0); 969 if (nextupd == (time_t)-2) nextupd = (time_t)-1; 970 #endif 971 972 pc->ssl_stapling_loadts = cur_ts; 973 pc->ssl_stapling_nextts = nextupd; 974 if (pc->ssl_stapling_nextts == -1) { 975 /* "Next Update" might not be provided by OCSP responder 976 * Use 3600 sec (1 hour) in that case. */ 977 /* retry in 1 hour if unable to determine Next Update */ 978 pc->ssl_stapling_nextts = cur_ts + 3600; 979 pc->ssl_stapling_loadts = 0; 980 } 981 else if (pc->ssl_stapling_nextts < cur_ts) 982 mod_gnutls_expire_stapling_file(srv, pc); 983 984 return 0; 985 } 986 987 988 static int 989 mod_gnutls_refresh_stapling_file (server *srv, plugin_cert *pc, const unix_time64_t cur_ts) 990 { 991 if (pc->ssl_stapling_nextts > cur_ts + 256) 992 return 0; /* skip check for refresh unless close to expire */ 993 struct stat st; 994 if (0 != stat(pc->ssl_stapling_file->ptr, &st) 995 || TIME64_CAST(st.st_mtime) <= pc->ssl_stapling_loadts) { 996 if (pc->ssl_stapling_nextts < cur_ts) 997 mod_gnutls_expire_stapling_file(srv, pc); 998 return 0; 999 } 1000 return mod_gnutls_reload_stapling_file(srv, pc, cur_ts); 1001 } 1002 1003 1004 static void 1005 mod_gnutls_refresh_stapling_files (server *srv, const plugin_data *p, const unix_time64_t cur_ts) 1006 { 1007 /* future: might construct array of (plugin_cert *) at startup 1008 * to avoid the need to search for them here */ 1009 /* (init i to 0 if global context; to 1 to skip empty global context) */ 1010 if (NULL == p->cvlist) return; 1011 for (int i = !p->cvlist[0].v.u2[1], used = p->nconfig; i < used; ++i) { 1012 const config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 1013 for (; cpv->k_id != -1; ++cpv) { 1014 if (cpv->k_id != 0) continue; /* k_id == 0 for ssl.pemfile */ 1015 if (cpv->vtype != T_CONFIG_LOCAL) continue; 1016 plugin_cert *pc = cpv->v.v; 1017 if (pc->ssl_stapling_file) 1018 mod_gnutls_refresh_stapling_file(srv, pc, cur_ts); 1019 } 1020 } 1021 } 1022 1023 1024 static int 1025 mod_gnutls_crt_must_staple (gnutls_x509_crt_t crt) 1026 { 1027 /* Look for TLS features X.509 extension with value 5 1028 * RFC 7633 https://tools.ietf.org/html/rfc7633#appendix-A 1029 * 5 = OCSP Must-Staple (security mechanism) */ 1030 1031 int rc; 1032 1033 #if GNUTLS_VERSION_NUMBER < 0x030501 1034 1035 unsigned int i; 1036 char oid[128]; 1037 size_t oidsz; 1038 for (i = 0; ; ++i) { 1039 oidsz = sizeof(oid); 1040 rc = gnutls_x509_crt_get_extension_info(crt, i, oid, &oidsz, NULL); 1041 if (rc < 0 || 0 == strcmp(oid, GNUTLS_X509EXT_OID_TLSFEATURES)) break; 1042 } 1043 /* ext not found if (rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) */ 1044 if (rc < 0) return rc; 1045 1046 gnutls_datum_t der = { NULL, 0 }; 1047 rc = gnutls_x509_crt_get_extension_data2(crt, i, &der); 1048 if (rc < 0) return rc; 1049 1050 /* DER encoding (Tag, Length, Value (TLV)) expecting: 30:03:02:01:05 1051 * [TL[TLV]] (30=Sequence, Len=03, (02=Integer, Len=01, Value=05)) 1052 * XXX: This is not future-proof if TLS feature list values are extended */ 1053 /*const char must_staple[] = { 0x30, 0x03, 0x02, 0x01, 0x05 };*/ 1054 /*rc = (der.size == 5 && 0 == memcmp(der.data, must_staple, 5))*/ 1055 rc = (der.size >= 5 && der.data[0] == 0x30 && der.data[1] >= 0x03 1056 && der.data[2] == 0x2 && der.data[3] == 0x1 && der.data[4] == 0x5) 1057 ? 1 1058 : 0; 1059 1060 gnutls_free(der.data); 1061 1062 #else 1063 1064 gnutls_x509_tlsfeatures_t f; 1065 rc = gnutls_x509_tlsfeatures_init(&f); 1066 if (rc < 0) return rc; 1067 rc = gnutls_x509_tlsfeatures_add(f, 5); /* 5 = OCSP Must-Staple */ 1068 if (rc < 0) return rc; 1069 rc = (0 != gnutls_x509_tlsfeatures_check_crt(f, crt)); 1070 gnutls_x509_tlsfeatures_deinit(f); 1071 1072 #endif 1073 1074 return rc; /* 1 if OCSP Must-Staple found; 0 if not */ 1075 } 1076 1077 1078 static int 1079 mod_gnutls_construct_crt_chain (plugin_cert *pc, gnutls_datum_t *d, log_error_st *errh) 1080 { 1081 /* Historically, openssl will use the cert chain in (SSL_CTX *) if a cert 1082 * does not have a chain configured in (SSL *). Attempt to provide 1083 * compatible behavior here. This may be called after startup since 1084 * ssl.pemfile might be defined in a config scope without ssl.ca-file, 1085 * and at runtime is when ssl.ca-file (e.g. from matching $SERVER["socket"]) 1086 * would be known along with ssl.pemfile (e.g. from $HTTP["host"]) */ 1087 1088 gnutls_certificate_credentials_t ssl_cred; 1089 int rc = gnutls_certificate_allocate_credentials(&ssl_cred); 1090 if (rc < 0) return rc; 1091 unsigned int ncrt = (d ? d->size : 0); 1092 unsigned int off = (d == pc->ssl_pemfile_x509) ? 0 : 1; 1093 gnutls_pcert_st * const pcert_list = 1094 gnutls_malloc(sizeof(gnutls_pcert_st) * (off+ncrt)); 1095 if (NULL == pcert_list) { 1096 gnutls_certificate_free_credentials(ssl_cred); 1097 return GNUTLS_E_MEMORY_ERROR; 1098 } 1099 memset(pcert_list, 0, sizeof(gnutls_pcert_st) * (off+ncrt)); 1100 rc = 0; 1101 1102 if (off) { /*(add crt to chain if different from d)*/ 1103 /*assert(pc->ssl_pemfile_x509->size == 1)*/ 1104 gnutls_x509_crt_t *crts = 1105 (gnutls_x509_crt_t *)(void *)pc->ssl_pemfile_x509->data; 1106 rc = gnutls_pcert_import_x509(pcert_list, crts[0], 0); 1107 } 1108 1109 if (0 == rc && ncrt) { 1110 gnutls_x509_crt_t *crts = (gnutls_x509_crt_t *)(void *)d->data; 1111 #if GNUTLS_VERSION_NUMBER < 0x030400 1112 /*(GNUTLS_X509_CRT_LIST_SORT not needed; crts sorted when file read)*/ 1113 rc = gnutls_pcert_import_x509_list(pcert_list+off, crts, &ncrt, 0); 1114 #else /* manually import list, but note that sorting is not implemented */ 1115 rc = 0; 1116 for (unsigned int i = 0; i < ncrt; ++i) { 1117 rc = gnutls_pcert_import_x509(pcert_list+off+i, crts[i], 0); 1118 if (rc < 0) break; 1119 } 1120 #endif 1121 } 1122 ncrt += off; 1123 if (0 == rc) 1124 rc = gnutls_certificate_set_key(ssl_cred, NULL, 0, pcert_list, ncrt, 1125 pc->ssl_pemfile_pkey); 1126 if (rc < 0) { 1127 for (unsigned int i = 0; i < ncrt; ++i) 1128 gnutls_pcert_deinit(pcert_list+i); 1129 gnutls_free(pcert_list); 1130 gnutls_certificate_free_credentials(ssl_cred); 1131 elog(errh, __FILE__, __LINE__, rc, "gnutls_certificate_set_key()"); 1132 return rc; 1133 } 1134 /* XXX: gnutls_certificate_set_key() has an inconsistent implementation. 1135 * On success, key ownership is transferred, and so should not be freed, 1136 * but pcert_list is a shallow memcpy(), so gnutls_pcert_deinit() should 1137 * not be run on gnutls_pcert_st in list, though top-level list storage 1138 * should be freed. On failure, ownership is not transferred for either. */ 1139 gnutls_free(pcert_list); 1140 pc->ssl_pemfile_pkey = NULL; 1141 pc->ssl_cred = ssl_cred; 1142 1143 /* release lists used to configure pc->ssl_cred */ 1144 mod_gnutls_free_config_crts(pc->ssl_pemfile_x509); 1145 pc->ssl_pemfile_x509 = NULL; 1146 1147 return 0; 1148 } 1149 1150 1151 static void * 1152 network_gnutls_load_pemfile (server *srv, const buffer *pemfile, const buffer *privkey, const buffer *ssl_stapling_file) 1153 { 1154 #if 0 /* see comments in mod_gnutls_construct_crt_chain() above */ 1155 1156 gnutls_certificate_credentials_t ssl_cred = NULL; 1157 int rc; 1158 1159 rc = gnutls_certificate_allocate_credentials(&ssl_cred); 1160 if (rc < 0) return NULL; 1161 1162 rc = gnutls_certificate_set_x509_key_file2(ssl_cred, 1163 pemfile->ptr, privkey->ptr, 1164 GNUTLS_X509_FMT_PEM, NULL, 0); 1165 if (rc < 0) { 1166 elogf(srv->errh, __FILE__, __LINE__, rc, 1167 "gnutls_certificate_set_x509_key_file2(%s, %s)", 1168 pemfile->ptr, privkey->ptr); 1169 gnutls_certificate_free_credentials(ssl_cred); 1170 return NULL; 1171 } 1172 1173 plugin_cert *pc = malloc(sizeof(plugin_cert)); 1174 force_assert(pc); 1175 pc->ssl_cred = ssl_cred; 1176 pc->trust_inited = 0; 1177 1178 return pc; 1179 1180 #else 1181 1182 gnutls_datum_t *d = mod_gnutls_load_config_crts(pemfile->ptr, srv->errh); 1183 if (NULL == d) return NULL; 1184 if (0 == d->size) { 1185 mod_gnutls_free_config_crts(d); 1186 return NULL; 1187 } 1188 1189 gnutls_privkey_t pkey = mod_gnutls_load_config_pkey(privkey->ptr,srv->errh); 1190 if (NULL == pkey) { 1191 mod_gnutls_free_config_crts(d); 1192 return NULL; 1193 } 1194 1195 plugin_cert *pc = malloc(sizeof(plugin_cert)); 1196 force_assert(pc); 1197 pc->ssl_cred = NULL; 1198 pc->trust_inited = 0; 1199 pc->ssl_pemfile_x509 = d; 1200 pc->ssl_pemfile_pkey = pkey; 1201 pc->ssl_stapling_file= ssl_stapling_file; 1202 pc->ssl_stapling_loadts = 0; 1203 pc->ssl_stapling_nextts = 0; 1204 pc->must_staple = 1205 mod_gnutls_crt_must_staple(((gnutls_x509_crt_t *)(void *)d->data)[0]); 1206 1207 if (d->size > 1) { /*(certificate chain provided)*/ 1208 int rc = mod_gnutls_construct_crt_chain(pc, d, srv->errh); 1209 if (rc < 0) { 1210 mod_gnutls_free_config_crts(d); 1211 gnutls_privkey_deinit(pkey); 1212 free(pc); 1213 return NULL; 1214 } 1215 } 1216 1217 if (pc->ssl_stapling_file) { 1218 if (mod_gnutls_reload_stapling_file(srv, pc, log_epoch_secs) < 0) { 1219 /* continue without OCSP response if there is an error */ 1220 } 1221 } 1222 else if (pc->must_staple) { 1223 log_error(srv->errh, __FILE__, __LINE__, 1224 "certificate %s marked OCSP Must-Staple, " 1225 "but ssl.stapling-file not provided", pemfile->ptr); 1226 } 1227 1228 return pc; 1229 1230 #endif 1231 } 1232 1233 1234 #if GNUTLS_VERSION_NUMBER >= 0x030200 1235 1236 static int 1237 mod_gnutls_acme_tls_1 (handler_ctx *hctx) 1238 { 1239 buffer * const b = hctx->tmp_buf; 1240 const buffer * const name = &hctx->r->uri.authority; 1241 log_error_st * const errh = hctx->r->conf.errh; 1242 int rc = GNUTLS_E_INVALID_REQUEST; 1243 1244 /* check if acme-tls/1 protocol is enabled (path to dir of cert(s) is set)*/ 1245 if (!hctx->conf.ssl_acme_tls_1) 1246 return 0; 1247 1248 /* check if SNI set server name (required for acme-tls/1 protocol) 1249 * and perform simple path checks for no '/' 1250 * and no leading '.' (e.g. ignore "." or ".." or anything beginning '.') */ 1251 if (buffer_is_blank(name)) return rc; 1252 if (NULL != strchr(name->ptr, '/')) return rc; 1253 if (name->ptr[0] == '.') return rc; 1254 #if 0 1255 if (0 != http_request_host_policy(name, hctx->r->conf.http_parseopts, 443)) 1256 return rc; 1257 #endif 1258 buffer_copy_path_len2(b, BUF_PTR_LEN(hctx->conf.ssl_acme_tls_1), 1259 BUF_PTR_LEN(name)); 1260 1261 #if 0 1262 1263 buffer * const privkey = buffer_init(); 1264 buffer_append_str2(b, BUF_PTR_LEN(b), CONST_STR_LEN(".crt.pem")); 1265 buffer_append_string_len(privkey, CONST_STR_LEN(".key.pem")); 1266 1267 /*(similar to network_gnutls_load_pemfile() but propagates rc)*/ 1268 gnutls_certificate_credentials_t ssl_cred = NULL; 1269 rc = gnutls_certificate_allocate_credentials(&ssl_cred); 1270 if (rc < 0) { buffer_free(privkey); return rc; } 1271 rc = gnutls_certificate_set_x509_key_file2(ssl_cred, 1272 b->ptr, privkey->ptr, 1273 GNUTLS_X509_FMT_PEM, NULL, 0); 1274 if (rc < 0) { 1275 elogf(errh, __FILE__, __LINE__, rc, 1276 "failed to load acme-tls/1 cert (%s, %s)", 1277 b->ptr, privkey->ptr); 1278 buffer_free(privkey); 1279 gnutls_certificate_free_credentials(ssl_cred); 1280 return rc; 1281 } 1282 buffer_free(privkey); 1283 1284 #else 1285 1286 /* gnutls_certificate_set_x509_key_file2() does not securely wipe 1287 * sensitive data from memory, so take a few extra steps */ 1288 1289 /* similar to network_gnutls_load_pemfile() */ 1290 1291 uint32_t len = buffer_clen(b); 1292 buffer_append_string_len(b, CONST_STR_LEN(".crt.pem")); 1293 1294 gnutls_datum_t *d = mod_gnutls_load_config_crts(b->ptr, errh); 1295 if (NULL == d) return GNUTLS_E_FILE_ERROR; 1296 if (0 == d->size) { 1297 mod_gnutls_free_config_crts(d); 1298 return GNUTLS_E_FILE_ERROR; 1299 } 1300 1301 buffer_truncate(b, len); 1302 buffer_append_string_len(b, CONST_STR_LEN(".key.pem")); 1303 1304 gnutls_privkey_t pkey = mod_gnutls_load_config_pkey(b->ptr, errh); 1305 if (NULL == pkey) { 1306 mod_gnutls_free_config_crts(d); 1307 return GNUTLS_E_FILE_ERROR; 1308 } 1309 1310 plugin_cert pc; 1311 pc.ssl_cred = NULL; 1312 pc.trust_inited = 0; 1313 pc.ssl_pemfile_x509 = d; 1314 pc.ssl_pemfile_pkey = pkey; 1315 1316 rc = mod_gnutls_construct_crt_chain(&pc, d, errh); 1317 if (rc < 0) { 1318 mod_gnutls_free_config_crts(d); 1319 gnutls_privkey_deinit(pkey); 1320 return rc; 1321 } 1322 1323 gnutls_certificate_credentials_t ssl_cred = pc.ssl_cred; 1324 1325 #endif 1326 1327 hctx->acme_tls_1_cred = ssl_cred; /*(save ptr and free later)*/ 1328 1329 gnutls_credentials_clear(hctx->ssl); 1330 rc = gnutls_credentials_set(hctx->ssl, GNUTLS_CRD_CERTIFICATE, ssl_cred); 1331 if (rc < 0) { 1332 elogf(hctx->r->conf.errh, __FILE__, __LINE__, rc, 1333 "failed to set acme-tls/1 certificate for TLS server name %s", 1334 hctx->r->uri.authority.ptr); 1335 return rc; 1336 } 1337 1338 /*(acme-tls/1 is separate from certificate auth access to website)*/ 1339 gnutls_certificate_server_set_request(hctx->ssl, GNUTLS_CERT_IGNORE); 1340 1341 return GNUTLS_E_SUCCESS; /* 0 */ 1342 } 1343 1344 1345 static int 1346 mod_gnutls_alpn_h2_policy (handler_ctx * const hctx) 1347 { 1348 /*(currently called after handshake has completed)*/ 1349 #if 0 /* SNI omitted by client when connecting to IP instead of to name */ 1350 if (buffer_is_blank(&hctx->r->uri.authority)) { 1351 log_error(hctx->errh, __FILE__, __LINE__, 1352 "SSL: error ALPN h2 without SNI"); 1353 return -1; 1354 } 1355 #endif 1356 if (gnutls_protocol_get_version(hctx->ssl) < GNUTLS_TLS1_2) { 1357 /*(future: if DTLS supported by lighttpd, add DTLS condition)*/ 1358 log_error(hctx->errh, __FILE__, __LINE__, 1359 "SSL: error ALPN h2 requires TLSv1.2 or later"); 1360 return -1; 1361 } 1362 1363 return 0; 1364 } 1365 1366 1367 enum { 1368 MOD_GNUTLS_ALPN_HTTP11 = 1 1369 ,MOD_GNUTLS_ALPN_HTTP10 = 2 1370 ,MOD_GNUTLS_ALPN_H2 = 3 1371 ,MOD_GNUTLS_ALPN_ACME_TLS_1 = 4 1372 }; 1373 1374 1375 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */ 1376 static int 1377 mod_gnutls_ALPN (handler_ctx * const hctx, const unsigned char * const in, const unsigned int inlen) 1378 { 1379 /*(skip first two bytes which should match inlen-2)*/ 1380 for (unsigned int i = 2, n; i < inlen; i += n) { 1381 n = in[i++]; 1382 if (i+n > inlen || 0 == n) break; 1383 1384 switch (n) { 1385 case 2: /* "h2" */ 1386 if (in[i] == 'h' && in[i+1] == '2') { 1387 if (!hctx->r->conf.h2proto) continue; 1388 hctx->alpn = MOD_GNUTLS_ALPN_H2; 1389 hctx->r->http_version = HTTP_VERSION_2; 1390 return GNUTLS_E_SUCCESS; 1391 } 1392 continue; 1393 case 8: /* "http/1.1" "http/1.0" */ 1394 if (0 == memcmp(in+i, "http/1.", 7)) { 1395 if (in[i+7] == '1') { 1396 hctx->alpn = MOD_GNUTLS_ALPN_HTTP11; 1397 return GNUTLS_E_SUCCESS; 1398 } 1399 if (in[i+7] == '0') { 1400 hctx->alpn = MOD_GNUTLS_ALPN_HTTP10; 1401 return GNUTLS_E_SUCCESS; 1402 } 1403 } 1404 continue; 1405 case 10: /* "acme-tls/1" */ 1406 if (0 == memcmp(in+i, "acme-tls/1", 10)) { 1407 int rc = mod_gnutls_acme_tls_1(hctx); 1408 if (0 == rc) { 1409 hctx->alpn = MOD_GNUTLS_ALPN_ACME_TLS_1; 1410 return GNUTLS_E_SUCCESS; 1411 } 1412 return rc; 1413 } 1414 continue; 1415 default: 1416 continue; 1417 } 1418 } 1419 1420 return GNUTLS_E_SUCCESS; 1421 } 1422 1423 #endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */ 1424 1425 1426 static int 1427 mod_gnutls_SNI(handler_ctx * const hctx, 1428 const unsigned char *servername, unsigned int len) 1429 { 1430 /* https://www.gnutls.org/manual/gnutls.html#Virtual-hosts-and-credentials 1431 * figure the advertized name - the following hack relies on the fact that 1432 * this extension only supports DNS names, and due to a protocol bug cannot 1433 * be extended to support anything else. */ 1434 if (len < 5) return 0; 1435 len -= 5; 1436 servername += 5; 1437 request_st * const r = hctx->r; 1438 buffer_copy_string_len(&r->uri.scheme, CONST_STR_LEN("https")); 1439 1440 if (len >= 1024) { /*(expecting < 256; TLSEXT_MAXLEN_host_name is 255)*/ 1441 log_error(r->conf.errh, __FILE__, __LINE__, 1442 "GnuTLS: SNI name too long %.*s", (int)len, servername); 1443 return GNUTLS_E_INVALID_REQUEST; 1444 } 1445 1446 /* use SNI to patch mod_gnutls config and then reset COMP_HTTP_HOST */ 1447 buffer_copy_string_len_lc(&r->uri.authority, (const char *)servername, len); 1448 #if 0 1449 /*(r->uri.authority used below for configuration before request read; 1450 * revisit for h2)*/ 1451 if (0 != http_request_host_policy(&r->uri.authority, 1452 r->conf.http_parseopts, 443)) 1453 return GNUTLS_E_INVALID_REQUEST; 1454 #endif 1455 1456 r->conditional_is_valid |= (1 << COMP_HTTP_SCHEME) 1457 | (1 << COMP_HTTP_HOST); 1458 1459 mod_gnutls_patch_config(r, &hctx->conf); 1460 /* reset COMP_HTTP_HOST so that conditions re-run after request hdrs read */ 1461 /*(done in configfile-glue.c:config_cond_cache_reset() after request hdrs read)*/ 1462 /*config_cond_cache_reset_item(r, COMP_HTTP_HOST);*/ 1463 /*buffer_clear(&r->uri.authority);*/ 1464 1465 return 0; 1466 } 1467 1468 1469 static int 1470 mod_gnutls_client_hello_ext_cb(void *ctx, unsigned int tls_id, 1471 const unsigned char *data, unsigned int dlen) 1472 { 1473 switch (tls_id) { 1474 case 0: /* Server Name */ 1475 return mod_gnutls_SNI((handler_ctx *)ctx, data, dlen); 1476 #if GNUTLS_VERSION_NUMBER >= 0x030200 1477 case 16: /* ALPN */ 1478 return mod_gnutls_ALPN((handler_ctx *)ctx, data, dlen); 1479 #endif 1480 /*case 35:*/ /* Session Ticket */ 1481 default: 1482 break; 1483 } 1484 1485 return GNUTLS_E_SUCCESS; /* 0 */ 1486 } 1487 1488 1489 static int 1490 mod_gnutls_client_hello_hook(gnutls_session_t ssl, unsigned int htype, 1491 unsigned when, unsigned int incoming, 1492 const gnutls_datum_t *msg) 1493 { 1494 /*assert(htype == GNUTLS_HANDSHAKE_CLIENT_HELLO);*/ 1495 /*assert(when == GNUTLS_HOOK_PRE);*/ 1496 UNUSED(htype); 1497 UNUSED(when); 1498 UNUSED(incoming); 1499 1500 handler_ctx * const hctx = gnutls_session_get_ptr(ssl); 1501 #if GNUTLS_VERSION_NUMBER >= 0x030200 1502 /*(do not repeat if acme-tls/1 creds have been set 1503 * and still in handshake (hctx->alpn not unset yet))*/ 1504 if (hctx->alpn == MOD_GNUTLS_ALPN_ACME_TLS_1) 1505 return GNUTLS_E_SUCCESS; /* 0 */ 1506 #endif 1507 /* ??? why might this be called more than once ??? renegotiation? */ 1508 void *existing_cred = NULL; 1509 if (0 == gnutls_credentials_get(ssl, GNUTLS_CRD_CERTIFICATE, &existing_cred) 1510 && existing_cred) 1511 return GNUTLS_E_SUCCESS; /* 0 */ 1512 1513 int rc = gnutls_ext_raw_parse(hctx, mod_gnutls_client_hello_ext_cb, msg, 1514 GNUTLS_EXT_RAW_FLAG_TLS_CLIENT_HELLO); 1515 if (rc < 0) { 1516 log_error_st *errh = hctx->r->conf.errh; 1517 elog(errh, __FILE__, __LINE__, rc, "gnutls_ext_raw_parse()"); 1518 return rc; 1519 } 1520 1521 #if GNUTLS_VERSION_NUMBER >= 0x030200 1522 /* https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */ 1523 static const gnutls_datum_t alpn_protos_http_acme[] = { 1524 { (unsigned char *)CONST_STR_LEN("h2") } 1525 ,{ (unsigned char *)CONST_STR_LEN("http/1.1") } 1526 ,{ (unsigned char *)CONST_STR_LEN("http/1.0") } 1527 ,{ (unsigned char *)CONST_STR_LEN("acme-tls/1") } 1528 }; 1529 unsigned int n = hctx->conf.ssl_acme_tls_1 ? 4 : 3; 1530 const gnutls_datum_t *alpn_protos = alpn_protos_http_acme; 1531 if (!hctx->r->conf.h2proto) { 1532 ++alpn_protos; 1533 --n; 1534 } 1535 /*unsigned int flags = GNUTLS_ALPN_SERVER_PRECEDENCE;*/ 1536 rc = gnutls_alpn_set_protocols(hctx->ssl, alpn_protos, n, 0); 1537 if (rc < 0) { 1538 log_error_st *errh = hctx->r->conf.errh; 1539 elog(errh, __FILE__, __LINE__, rc, "gnutls_alpn_set_protocols()"); 1540 return rc; 1541 } 1542 /*(skip below if creds already set for acme-tls/1 1543 * via mod_gnutls_client_hello_ext_cb())*/ 1544 if (hctx->alpn == MOD_GNUTLS_ALPN_ACME_TLS_1) 1545 return GNUTLS_E_SUCCESS; /* 0 */ 1546 #endif 1547 1548 #if 0 /* must enable before GnuTLS client hello hook */ 1549 /* GnuTLS returns an error here if TLSv1.3 (? key already set ?) */ 1550 /* see mod_gnutls_handle_con_accept() */ 1551 /* future: ? handle in mod_gnutls_client_hello_ext_cb() */ 1552 if (hctx->ssl_session_ticket && session_ticket_key.size) { 1553 /* XXX: NOT done: parse client hello for session ticket extension 1554 * and choose from among multiple keys */ 1555 rc = gnutls_session_ticket_enable_server(ssl, &session_ticket_key); 1556 if (rc < 0) { 1557 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, 1558 "gnutls_session_ticket_enable_server()"); 1559 return rc; 1560 } 1561 } 1562 #endif 1563 1564 if (NULL == hctx->conf.pc->ssl_cred) { 1565 rc = mod_gnutls_construct_crt_chain(hctx->conf.pc, 1566 hctx->conf.ssl_ca_file, 1567 hctx->r->conf.errh); 1568 if (rc < 0) return rc; 1569 } 1570 1571 gnutls_certificate_credentials_t ssl_cred = hctx->conf.pc->ssl_cred; 1572 1573 hctx->verify_status = ~0u; 1574 gnutls_certificate_request_t req = GNUTLS_CERT_IGNORE; 1575 if (hctx->conf.ssl_verifyclient) { 1576 /*(cred shared; settings should be consistent across site using cred)*/ 1577 /*(i.e. settings for client certs must not differ under this cred)*/ 1578 req = hctx->conf.ssl_verifyclient_enforce 1579 ? GNUTLS_CERT_REQUIRE 1580 : GNUTLS_CERT_REQUEST; 1581 gnutls_certificate_set_verify_function(ssl_cred, mod_gnutls_verify_cb); 1582 gnutls_certificate_set_verify_limits(ssl_cred, 8200 /*(default)*/, 1583 hctx->conf.ssl_verifyclient_depth); 1584 rc = mod_gnutls_verify_set_tlist(hctx, 1); /* for client cert request */ 1585 if (rc < 0) return rc; 1586 } 1587 gnutls_certificate_server_set_request(ssl, req); 1588 1589 #if GNUTLS_VERSION_NUMBER < 0x030600 1590 if (hctx->conf.dh_params) 1591 gnutls_certificate_set_dh_params(ssl_cred, hctx->conf.dh_params); 1592 #if GNUTLS_VERSION_NUMBER >= 0x030506 1593 else 1594 gnutls_certificate_set_known_dh_params(ssl_cred, GNUTLS_SEC_PARAM_HIGH); 1595 #endif 1596 #endif 1597 1598 rc = gnutls_credentials_set(ssl, GNUTLS_CRD_CERTIFICATE, ssl_cred); 1599 if (rc < 0) { 1600 elogf(hctx->r->conf.errh, __FILE__, __LINE__, rc, 1601 "failed to set SNI certificate for TLS server name %s", 1602 hctx->r->uri.authority.ptr); 1603 return rc; 1604 } 1605 1606 return GNUTLS_E_SUCCESS; /* 0 */ 1607 } 1608 1609 1610 static int 1611 mod_gnutls_ssl_conf_ciphersuites (server *srv, plugin_config_socket *s, buffer *ciphersuites, const buffer *cipherstring); 1612 1613 1614 static int 1615 mod_gnutls_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *curvelist); 1616 1617 1618 static void 1619 mod_gnutls_ssl_conf_proto (server *srv, plugin_config_socket *s, const buffer *minb, const buffer *maxb); 1620 1621 1622 static int 1623 mod_gnutls_ssl_conf_cmd (server *srv, plugin_config_socket *s) 1624 { 1625 /* reference: 1626 * https://www.openssl.org/docs/man1.1.1/man3/SSL_CONF_cmd.html */ 1627 int rc = 0; 1628 buffer *cipherstring = NULL; 1629 buffer *ciphersuites = NULL; 1630 buffer *minb = NULL; 1631 buffer *maxb = NULL; 1632 buffer *curves = NULL; 1633 1634 for (size_t i = 0; i < s->ssl_conf_cmd->used; ++i) { 1635 data_string *ds = (data_string *)s->ssl_conf_cmd->data[i]; 1636 if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("CipherString"))) 1637 cipherstring = &ds->value; 1638 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Ciphersuites"))) 1639 ciphersuites = &ds->value; 1640 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Curves")) 1641 || buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Groups"))) 1642 curves = &ds->value; 1643 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MaxProtocol"))) 1644 maxb = &ds->value; 1645 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("MinProtocol"))) 1646 minb = &ds->value; 1647 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Protocol"))) { 1648 /* openssl config for Protocol=... is complex and deprecated */ 1649 log_error(srv->errh, __FILE__, __LINE__, 1650 "GnuTLS: ssl.openssl.ssl-conf-cmd %s ignored; " 1651 "use MinProtocol=... and MaxProtocol=... instead", 1652 ds->key.ptr); 1653 } 1654 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("Options"))) { 1655 for (char *v = ds->value.ptr, *e; *v; v = e) { 1656 while (*v == ' ' || *v == '\t' || *v == ',') ++v; 1657 int flag = 1; 1658 if (*v == '-') { 1659 flag = 0; 1660 ++v; 1661 } 1662 for (e = v; light_isalpha(*e); ++e) ; 1663 switch ((int)(e-v)) { 1664 case 11: 1665 if (buffer_eq_icase_ssn(v, "Compression", 11)) { 1666 /* GnuTLS 3.6.0+ no longer implements 1667 * any support for compression */ 1668 if (!flag) continue; 1669 } 1670 break; 1671 case 13: 1672 if (buffer_eq_icase_ssn(v, "SessionTicket", 13)) { 1673 /*(translates to "%NO_TICKETS" priority str if !flag)*/ 1674 s->ssl_session_ticket = flag; 1675 continue; 1676 } 1677 break; 1678 case 16: 1679 if (buffer_eq_icase_ssn(v, "ServerPreference", 16)) { 1680 /*(translates to "%SERVER_PRECEDENCE" priority string)*/ 1681 s->ssl_honor_cipher_order = flag; 1682 continue; 1683 } 1684 break; 1685 default: 1686 break; 1687 } 1688 /* warn if not explicitly handled or ignored above */ 1689 if (!flag) --v; 1690 log_error(srv->errh, __FILE__, __LINE__, 1691 "GnuTLS: ssl.openssl.ssl-conf-cmd Options %.*s " 1692 "ignored", (int)(e-v), v); 1693 } 1694 } 1695 else if (buffer_eq_icase_slen(&ds->key, 1696 CONST_STR_LEN("gnutls-override"))) { 1697 s->priority_override = &ds->value; 1698 } 1699 #if 0 1700 else if (buffer_eq_icase_slen(&ds->key, CONST_STR_LEN("..."))) { 1701 } 1702 #endif 1703 else { 1704 /* warn if not explicitly handled or ignored above */ 1705 log_error(srv->errh, __FILE__, __LINE__, 1706 "GnuTLS: ssl.openssl.ssl-conf-cmd %s ignored", 1707 ds->key.ptr); 1708 } 1709 } 1710 1711 if (minb || maxb) /*(if at least one was set)*/ 1712 mod_gnutls_ssl_conf_proto(srv, s, minb, maxb); 1713 1714 if (!mod_gnutls_ssl_conf_ciphersuites(srv, s, ciphersuites, cipherstring)) 1715 rc = -1; 1716 1717 if (curves) { 1718 if (!s->ssl_ec_curve) 1719 buffer_append_string_len(&s->priority_str, 1720 CONST_STR_LEN("-CURVE-ALL:")); 1721 if (!mod_gnutls_ssl_conf_curves(srv, s, curves)) 1722 rc = -1; 1723 } 1724 1725 return rc; 1726 } 1727 1728 1729 static int 1730 network_init_ssl (server *srv, plugin_config_socket *s, plugin_data *p) 1731 { 1732 int rc; 1733 UNUSED(p); 1734 1735 /* construct GnuTLS "priority" string 1736 * 1737 * default: NORMAL (since GnuTLS 3.3.0, could also use NULL for defaults) 1738 * SUITEB128 and SUITEB192 are stricter than NORMAL 1739 * (and are attempted to be supported in mod_gnutls_ssl_conf_ciphersuites()) 1740 * 1741 * gnutls defaults to %PARTIAL_RENEGOTIATION (see manual) 1742 * mod_gnutls does not attempt to support 1743 * hctx->conf.ssl_disable_client_renegotiation == 0 1744 * though possible with %UNSAFE_RENEGOTATION 1745 */ 1746 1747 #if GNUTLS_VERSION_NUMBER < 0x030600 1748 /* GnuTLS 3.6.0+ no longer implements any support for compression, 1749 * but we still explicitly disable for earlier versions */ 1750 buffer_append_string_len(&s->priority_str, 1751 CONST_STR_LEN("-COMP_ALL:+COMP-NULL:")); 1752 #endif 1753 1754 if (s->ssl_cipher_list) { 1755 if (!mod_gnutls_ssl_conf_ciphersuites(srv,s,NULL,s->ssl_cipher_list)) 1756 return -1; 1757 } 1758 1759 #if GNUTLS_VERSION_NUMBER < 0x030600 1760 if (s->ssl_dh_file) { 1761 /* "Prior to GnuTLS 3.6.0 for the ephemeral or anonymous Diffie-Hellman 1762 * (DH) TLS ciphersuites the application was required to generate or 1763 * provide DH parameters. That is no longer necessary as GnuTLS utilizes 1764 * DH parameters and negotiation from [RFC7919]." 1765 */ 1766 /* In other words, the following should not be used in 3.6.0 or later: 1767 * gnutls_certificate_set_dh_params() 1768 * gnutls_certificate_set_known_dh_params() 1769 * However, if support is implemented in mod_gnutls, must also free in 1770 * mod_gnutls_free_config() as gnutls_certificate_free_credentials() 1771 * does not free RSA or DH params manually associated with credential */ 1772 gnutls_datum_t f = { NULL, 0 }; 1773 rc = gnutls_dh_params_init(&s->dh_params); 1774 if (rc < 0) return -1; 1775 rc = mod_gnutls_load_file(s->ssl_dh_file->ptr, &f, srv->errh); 1776 if (rc < 0) return -1; 1777 rc = gnutls_dh_params_import_pkcs3(s->dh_params,&f,GNUTLS_X509_FMT_PEM); 1778 mod_gnutls_datum_wipe(&f); 1779 if (rc < 0) { 1780 elogf(srv->errh, __FILE__, __LINE__, rc, 1781 "gnutls_dh_params_import_pkcs3() %s", s->ssl_dh_file->ptr); 1782 return -1; 1783 } 1784 } 1785 else { 1786 #if GNUTLS_VERSION_NUMBER < 0x030506 1787 /* (this might take a while; you should upgrade to newer gnutls) */ 1788 rc = gnutls_dh_params_init(&s->dh_params); 1789 if (rc < 0) return -1; 1790 unsigned int bits = 1791 gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, GNUTLS_SEC_PARAM_HIGH); 1792 rc = gnutls_dh_params_generate2(s->dh_params, bits); 1793 if (rc < 0) { 1794 elogf(srv->errh, __FILE__, __LINE__, rc, 1795 "gnutls_dh_params_generate2()"); 1796 return -1; 1797 } 1798 #endif 1799 } 1800 #endif /* GNUTLS_VERSION_NUMBER < 0x030600 */ 1801 1802 if (s->ssl_ec_curve) { 1803 buffer_append_string_len(&s->priority_str, 1804 CONST_STR_LEN("-CURVE-ALL:")); 1805 if (!mod_gnutls_ssl_conf_curves(srv, s, s->ssl_ec_curve)) 1806 return -1; 1807 } 1808 1809 if (s->ssl_conf_cmd && s->ssl_conf_cmd->used) { 1810 if (0 != mod_gnutls_ssl_conf_cmd(srv, s)) return -1; 1811 } 1812 1813 if (s->ssl_honor_cipher_order) 1814 buffer_append_string_len(&s->priority_str, 1815 CONST_STR_LEN("%SERVER_PRECEDENCE:")); 1816 1817 if (!s->ssl_session_ticket) 1818 buffer_append_string_len(&s->priority_str, 1819 CONST_STR_LEN("%NO_TICKETS:")); 1820 1821 if (!s->ssl_use_sslv3 && !s->ssl_use_sslv2 1822 && NULL == strstr(s->priority_str.ptr, "-VERS-ALL:")) 1823 mod_gnutls_ssl_conf_proto(srv, s, NULL, NULL); 1824 1825 /* explicitly disable SSLv3 unless enabled in config 1826 * (gnutls library would also need to be compiled with legacy support) */ 1827 if (!s->ssl_use_sslv3) 1828 buffer_append_string_len(&s->priority_str, 1829 CONST_STR_LEN("-VERS-SSL3.0:")); 1830 1831 /* gnutls_priority_init2() is available since GnuTLS 3.6.3 and could be 1832 * called once with s->priority_base, and a second time with s->priority_str 1833 * and GNUTLS_PRIORITY_INIT_DEF_APPEND, but preserve compat with earlier 1834 * GnuTLS by concatenating into a single priority string */ 1835 1836 buffer *b = srv->tmp_buf; 1837 if (NULL == s->priority_base) s->priority_base = "NORMAL"; 1838 buffer_copy_string_len(b, s->priority_base, strlen(s->priority_base)); 1839 if (!buffer_is_blank(&s->priority_str)) { 1840 buffer_append_string_len(b, CONST_STR_LEN(":")); 1841 uint32_t len = buffer_clen(&s->priority_str); 1842 if (s->priority_str.ptr[len-1] == ':') 1843 --len; /* remove trailing ':' */ 1844 buffer_append_string_len(b, s->priority_str.ptr, len); 1845 } 1846 1847 if (s->priority_override && !buffer_is_blank(s->priority_override)) { 1848 b = s->priority_override; 1849 s->ssl_session_ticket = (NULL == strstr(b->ptr, "%NO_TICKET")); 1850 } 1851 1852 if (p->defaults.ssl_log_noise) 1853 log_error(srv->errh, __FILE__, __LINE__, 1854 "debug: GnuTLS priority string: %s", b->ptr); 1855 1856 const char *err_pos; 1857 rc = gnutls_priority_init(&s->priority_cache, b->ptr, &err_pos); 1858 if (rc < 0) { 1859 elogf(srv->errh, __FILE__, __LINE__, rc, 1860 "gnutls_priority_init() error near %s", err_pos); 1861 return -1; 1862 } 1863 1864 return 0; 1865 } 1866 1867 1868 static int 1869 mod_gnutls_set_defaults_sockets(server *srv, plugin_data *p) 1870 { 1871 static const config_plugin_keys_t cpk[] = { 1872 { CONST_STR_LEN("ssl.engine"), 1873 T_CONFIG_BOOL, 1874 T_CONFIG_SCOPE_CONNECTION } 1875 ,{ CONST_STR_LEN("ssl.cipher-list"), 1876 T_CONFIG_STRING, 1877 T_CONFIG_SCOPE_CONNECTION } 1878 ,{ CONST_STR_LEN("ssl.honor-cipher-order"), 1879 T_CONFIG_BOOL, 1880 T_CONFIG_SCOPE_CONNECTION } 1881 ,{ CONST_STR_LEN("ssl.dh-file"), 1882 T_CONFIG_STRING, 1883 T_CONFIG_SCOPE_CONNECTION } 1884 ,{ CONST_STR_LEN("ssl.ec-curve"), 1885 T_CONFIG_STRING, 1886 T_CONFIG_SCOPE_CONNECTION } 1887 ,{ CONST_STR_LEN("ssl.openssl.ssl-conf-cmd"), 1888 T_CONFIG_ARRAY_KVSTRING, 1889 T_CONFIG_SCOPE_CONNECTION } 1890 ,{ CONST_STR_LEN("ssl.pemfile"), /* included to process global scope */ 1891 T_CONFIG_STRING, 1892 T_CONFIG_SCOPE_CONNECTION } 1893 ,{ CONST_STR_LEN("ssl.empty-fragments"), 1894 T_CONFIG_BOOL, 1895 T_CONFIG_SCOPE_CONNECTION } 1896 ,{ CONST_STR_LEN("ssl.use-sslv2"), 1897 T_CONFIG_BOOL, 1898 T_CONFIG_SCOPE_CONNECTION } 1899 ,{ CONST_STR_LEN("ssl.use-sslv3"), 1900 T_CONFIG_BOOL, 1901 T_CONFIG_SCOPE_CONNECTION } 1902 ,{ CONST_STR_LEN("ssl.stek-file"), 1903 T_CONFIG_STRING, 1904 T_CONFIG_SCOPE_SERVER } 1905 ,{ NULL, 0, 1906 T_CONFIG_UNSET, 1907 T_CONFIG_SCOPE_UNSET } 1908 }; 1909 static const buffer default_ssl_cipher_list = { CONST_STR_LEN("HIGH"), 0 }; 1910 1911 p->ssl_ctxs = calloc(srv->config_context->used, sizeof(plugin_ssl_ctx)); 1912 force_assert(p->ssl_ctxs); 1913 1914 int rc = HANDLER_GO_ON; 1915 plugin_data_base srvplug; 1916 memset(&srvplug, 0, sizeof(srvplug)); 1917 plugin_data_base * const ps = &srvplug; 1918 if (!config_plugin_values_init(srv, ps, cpk, "mod_gnutls")) 1919 return HANDLER_ERROR; 1920 1921 plugin_config_socket defaults; 1922 memset(&defaults, 0, sizeof(defaults)); 1923 defaults.ssl_honor_cipher_order = 1; /* default server preference for PFS */ 1924 defaults.ssl_session_ticket = 1; /* enabled by default */ 1925 defaults.ssl_cipher_list = &default_ssl_cipher_list; 1926 1927 /* process and validate config directives for global and $SERVER["socket"] 1928 * (init i to 0 if global context; to 1 to skip empty global context) */ 1929 for (int i = !ps->cvlist[0].v.u2[1]; i < ps->nconfig; ++i) { 1930 config_cond_info cfginfo; 1931 config_get_config_cond_info(&cfginfo, (uint32_t)ps->cvlist[i].k_id); 1932 int is_socket_scope = (0 == i || cfginfo.comp == COMP_SERVER_SOCKET); 1933 int count_not_engine = 0; 1934 1935 plugin_config_socket conf; 1936 memcpy(&conf, &defaults, sizeof(conf)); 1937 1938 /*(preserve prior behavior; not inherited)*/ 1939 /*(forcing inheritance might break existing configs where SSL is enabled 1940 * by default in the global scope, but not $SERVER["socket"]=="*:80") */ 1941 conf.ssl_enabled = 0; 1942 1943 config_plugin_value_t *cpv = ps->cvlist + ps->cvlist[i].v.u2[0]; 1944 for (; -1 != cpv->k_id; ++cpv) { 1945 /* ignore ssl.pemfile (k_id=6); included to process global scope */ 1946 if (!is_socket_scope && cpv->k_id != 6) { 1947 log_error(srv->errh, __FILE__, __LINE__, 1948 "GnuTLS: %s is valid only in global scope or " 1949 "$SERVER[\"socket\"] condition", cpk[cpv->k_id].k); 1950 continue; 1951 } 1952 ++count_not_engine; 1953 switch (cpv->k_id) { 1954 case 0: /* ssl.engine */ 1955 conf.ssl_enabled = (0 != cpv->v.u); 1956 --count_not_engine; 1957 break; 1958 case 1: /* ssl.cipher-list */ 1959 if (!buffer_is_blank(cpv->v.b)) 1960 conf.ssl_cipher_list = cpv->v.b; 1961 break; 1962 case 2: /* ssl.honor-cipher-order */ 1963 conf.ssl_honor_cipher_order = (0 != cpv->v.u); 1964 break; 1965 case 3: /* ssl.dh-file */ 1966 #if GNUTLS_VERSION_NUMBER < 0x030600 1967 if (!buffer_is_blank(cpv->v.b)) 1968 conf.ssl_dh_file = cpv->v.b; 1969 #else 1970 log_error(srv->errh, __FILE__, __LINE__, 1971 "GnuTLS: ignoring ssl.dh-file; " 1972 "obsoleted in GnuTLS 3.6.0 and later implementing RFC7919"); 1973 #endif 1974 break; 1975 case 4: /* ssl.ec-curve */ 1976 if (!buffer_is_blank(cpv->v.b)) 1977 conf.ssl_ec_curve = cpv->v.b; 1978 break; 1979 case 5: /* ssl.openssl.ssl-conf-cmd */ 1980 *(const array **)&conf.ssl_conf_cmd = cpv->v.a; 1981 break; 1982 case 6: /* ssl.pemfile */ 1983 /* ignore here; included to process global scope when 1984 * ssl.pemfile is set, but ssl.engine is not "enable" */ 1985 break; 1986 case 7: /* ssl.empty-fragments */ 1987 conf.ssl_empty_fragments = (0 != cpv->v.u); 1988 log_error(srv->errh, __FILE__, __LINE__, 1989 "GnuTLS: ignoring ssl.empty-fragments; openssl-specific " 1990 "counter-measure against a SSL 3.0/TLS 1.0 protocol " 1991 "vulnerability affecting CBC ciphers, which cannot be handled" 1992 " by some broken (Microsoft) SSL implementations."); 1993 break; 1994 case 8: /* ssl.use-sslv2 */ 1995 conf.ssl_use_sslv2 = (0 != cpv->v.u); 1996 log_error(srv->errh, __FILE__, __LINE__, "GnuTLS: " 1997 "ssl.use-sslv2 is deprecated and will soon be removed. " 1998 "Many modern TLS libraries no longer support SSLv2."); 1999 break; 2000 case 9: /* ssl.use-sslv3 */ 2001 conf.ssl_use_sslv3 = (0 != cpv->v.u); 2002 log_error(srv->errh, __FILE__, __LINE__, "GnuTLS: " 2003 "ssl.use-sslv3 is deprecated and will soon be removed. " 2004 "Many modern TLS libraries no longer support SSLv3. " 2005 "If needed, use: " 2006 "ssl.openssl.ssl-conf-cmd = (\"MinProtocol\" => \"SSLv3\")"); 2007 break; 2008 case 10:/* ssl.stek-file */ 2009 if (!buffer_is_blank(cpv->v.b)) 2010 p->ssl_stek_file = cpv->v.b->ptr; 2011 break; 2012 default:/* should not happen */ 2013 break; 2014 } 2015 } 2016 if (HANDLER_GO_ON != rc) break; 2017 if (0 == i) memcpy(&defaults, &conf, sizeof(conf)); 2018 2019 if (0 != i && !conf.ssl_enabled) continue; 2020 2021 /* fill plugin_config_socket with global context then $SERVER["socket"] 2022 * only for directives directly in current $SERVER["socket"] condition*/ 2023 2024 /*conf.pc = p->defaults.pc;*/ 2025 conf.ssl_verifyclient = p->defaults.ssl_verifyclient; 2026 conf.ssl_verifyclient_enforce = p->defaults.ssl_verifyclient_enforce; 2027 conf.ssl_verifyclient_depth = p->defaults.ssl_verifyclient_depth; 2028 2029 int sidx = ps->cvlist[i].k_id; 2030 for (int j = !p->cvlist[0].v.u2[1]; j < p->nconfig; ++j) { 2031 if (p->cvlist[j].k_id != sidx) continue; 2032 /*if (0 == sidx) break;*//*(repeat to get ssl_pemfile,ssl_privkey)*/ 2033 cpv = p->cvlist + p->cvlist[j].v.u2[0]; 2034 for (; -1 != cpv->k_id; ++cpv) { 2035 ++count_not_engine; 2036 switch (cpv->k_id) { 2037 case 0: /* ssl.pemfile */ 2038 if (cpv->vtype == T_CONFIG_LOCAL) 2039 conf.pc = cpv->v.v; 2040 break; 2041 case 7: /* ssl.verifyclient.activate */ 2042 conf.ssl_verifyclient = (0 != cpv->v.u); 2043 break; 2044 case 8: /* ssl.verifyclient.enforce */ 2045 conf.ssl_verifyclient_enforce = (0 != cpv->v.u); 2046 break; 2047 case 9: /* ssl.verifyclient.depth */ 2048 conf.ssl_verifyclient_depth = (unsigned char)cpv->v.shrt; 2049 break; 2050 default: 2051 break; 2052 } 2053 } 2054 break; 2055 } 2056 2057 if (NULL == conf.pc) { 2058 if (0 == i && !conf.ssl_enabled) continue; 2059 if (0 != i) { 2060 /* inherit ssl settings from global scope 2061 * (if only ssl.engine = "enable" and no other ssl.* settings) 2062 * (This is for convenience when defining both IPv4 and IPv6 2063 * and desiring to inherit the ssl config from global context 2064 * without having to duplicate the directives)*/ 2065 if (count_not_engine 2066 || (conf.ssl_enabled 2067 && NULL == p->ssl_ctxs[0].priority_cache)) { 2068 log_error(srv->errh, __FILE__, __LINE__, 2069 "GnuTLS: ssl.pemfile has to be set in same " 2070 "$SERVER[\"socket\"] scope as other ssl.* directives, " 2071 "unless only ssl.engine is set, inheriting ssl.* from " 2072 "global scope"); 2073 rc = HANDLER_ERROR; 2074 continue; 2075 } 2076 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx; 2077 *s = *p->ssl_ctxs;/*(copy struct of ssl_ctx from global scope)*/ 2078 continue; 2079 } 2080 /* PEM file is required */ 2081 log_error(srv->errh, __FILE__, __LINE__, 2082 "GnuTLS: ssl.pemfile has to be set when ssl.engine = \"enable\""); 2083 rc = HANDLER_ERROR; 2084 continue; 2085 } 2086 2087 /* (initialize once if module enabled) */ 2088 if (!mod_gnutls_init_once_gnutls()) { 2089 rc = HANDLER_ERROR; 2090 break; 2091 } 2092 2093 /* configure ssl_ctx for socket */ 2094 2095 /*conf.ssl_ctx = NULL;*//*(filled by network_init_ssl() even on error)*/ 2096 if (0 == network_init_ssl(srv, &conf, p)) { 2097 plugin_ssl_ctx * const s = p->ssl_ctxs + sidx; 2098 s->ssl_session_ticket = conf.ssl_session_ticket; 2099 s->priority_cache = conf.priority_cache; 2100 #if GNUTLS_VERSION_NUMBER < 0x030600 2101 s->dh_params = conf.dh_params; 2102 #endif 2103 } 2104 else { 2105 gnutls_priority_deinit(conf.priority_cache); 2106 #if GNUTLS_VERSION_NUMBER < 0x030600 2107 gnutls_dh_params_deinit(conf.dh_params); 2108 #endif 2109 rc = HANDLER_ERROR; 2110 } 2111 free(conf.priority_str.ptr); 2112 } 2113 2114 if (rc == HANDLER_GO_ON && ssl_is_init) 2115 mod_gnutls_session_ticket_key_check(srv, p, log_epoch_secs); 2116 2117 free(srvplug.cvlist); 2118 return rc; 2119 } 2120 2121 2122 SETDEFAULTS_FUNC(mod_gnutls_set_defaults) 2123 { 2124 static const config_plugin_keys_t cpk[] = { 2125 { CONST_STR_LEN("ssl.pemfile"), 2126 T_CONFIG_STRING, 2127 T_CONFIG_SCOPE_CONNECTION } 2128 ,{ CONST_STR_LEN("ssl.privkey"), 2129 T_CONFIG_STRING, 2130 T_CONFIG_SCOPE_CONNECTION } 2131 ,{ CONST_STR_LEN("ssl.ca-file"), 2132 T_CONFIG_STRING, 2133 T_CONFIG_SCOPE_CONNECTION } 2134 ,{ CONST_STR_LEN("ssl.ca-dn-file"), 2135 T_CONFIG_STRING, 2136 T_CONFIG_SCOPE_CONNECTION } 2137 ,{ CONST_STR_LEN("ssl.ca-crl-file"), 2138 T_CONFIG_STRING, 2139 T_CONFIG_SCOPE_CONNECTION } 2140 ,{ CONST_STR_LEN("ssl.read-ahead"), 2141 T_CONFIG_BOOL, 2142 T_CONFIG_SCOPE_CONNECTION } 2143 ,{ CONST_STR_LEN("ssl.disable-client-renegotiation"), 2144 T_CONFIG_BOOL, 2145 T_CONFIG_SCOPE_CONNECTION } 2146 ,{ CONST_STR_LEN("ssl.verifyclient.activate"), 2147 T_CONFIG_BOOL, 2148 T_CONFIG_SCOPE_CONNECTION } 2149 ,{ CONST_STR_LEN("ssl.verifyclient.enforce"), 2150 T_CONFIG_BOOL, 2151 T_CONFIG_SCOPE_CONNECTION } 2152 ,{ CONST_STR_LEN("ssl.verifyclient.depth"), 2153 T_CONFIG_SHORT, 2154 T_CONFIG_SCOPE_CONNECTION } 2155 ,{ CONST_STR_LEN("ssl.verifyclient.username"), 2156 T_CONFIG_STRING, 2157 T_CONFIG_SCOPE_CONNECTION } 2158 ,{ CONST_STR_LEN("ssl.verifyclient.exportcert"), 2159 T_CONFIG_BOOL, 2160 T_CONFIG_SCOPE_CONNECTION } 2161 ,{ CONST_STR_LEN("ssl.acme-tls-1"), 2162 T_CONFIG_STRING, 2163 T_CONFIG_SCOPE_CONNECTION } 2164 ,{ CONST_STR_LEN("ssl.stapling-file"), 2165 T_CONFIG_STRING, 2166 T_CONFIG_SCOPE_CONNECTION } 2167 ,{ CONST_STR_LEN("debug.log-ssl-noise"), 2168 T_CONFIG_BOOL, 2169 T_CONFIG_SCOPE_CONNECTION } 2170 ,{ CONST_STR_LEN("ssl.verifyclient.ca-file"), 2171 T_CONFIG_STRING, 2172 T_CONFIG_SCOPE_CONNECTION } 2173 ,{ CONST_STR_LEN("ssl.verifyclient.ca-dn-file"), 2174 T_CONFIG_STRING, 2175 T_CONFIG_SCOPE_CONNECTION } 2176 ,{ CONST_STR_LEN("ssl.verifyclient.ca-crl-file"), 2177 T_CONFIG_STRING, 2178 T_CONFIG_SCOPE_CONNECTION } 2179 ,{ NULL, 0, 2180 T_CONFIG_UNSET, 2181 T_CONFIG_SCOPE_UNSET } 2182 }; 2183 2184 plugin_data * const p = p_d; 2185 p->srv = srv; 2186 if (!config_plugin_values_init(srv, p, cpk, "mod_gnutls")) 2187 return HANDLER_ERROR; 2188 2189 /* process and validate config directives 2190 * (init i to 0 if global context; to 1 to skip empty global context) */ 2191 for (int i = !p->cvlist[0].v.u2[1]; i < p->nconfig; ++i) { 2192 config_plugin_value_t *cpv = p->cvlist + p->cvlist[i].v.u2[0]; 2193 config_plugin_value_t *pemfile = NULL; 2194 config_plugin_value_t *privkey = NULL; 2195 const buffer *ssl_stapling_file = NULL; 2196 for (; -1 != cpv->k_id; ++cpv) { 2197 switch (cpv->k_id) { 2198 case 0: /* ssl.pemfile */ 2199 if (!buffer_is_blank(cpv->v.b)) pemfile = cpv; 2200 break; 2201 case 1: /* ssl.privkey */ 2202 if (!buffer_is_blank(cpv->v.b)) privkey = cpv; 2203 break; 2204 case 15:/* ssl.verifyclient.ca-file */ 2205 if (cpv->k_id == 15) cpv->k_id = 2; 2206 __attribute_fallthrough__ 2207 case 16:/* ssl.verifyclient.ca-dn-file */ 2208 if (cpv->k_id == 16) cpv->k_id = 3; 2209 __attribute_fallthrough__ 2210 case 2: /* ssl.ca-file */ 2211 case 3: /* ssl.ca-dn-file */ 2212 if (!buffer_is_blank(cpv->v.b)) { 2213 gnutls_datum_t *d = 2214 mod_gnutls_load_config_crts(cpv->v.b->ptr, srv->errh); 2215 if (d != NULL) { 2216 cpv->vtype = T_CONFIG_LOCAL; 2217 cpv->v.v = d; 2218 } 2219 else { 2220 log_error(srv->errh, __FILE__, __LINE__, 2221 "%s = %s", cpk[cpv->k_id].k, cpv->v.b->ptr); 2222 return HANDLER_ERROR; 2223 } 2224 } 2225 break; 2226 case 17:/* ssl.verifyclient.ca-crl-file */ 2227 cpv->k_id = 4; 2228 __attribute_fallthrough__ 2229 case 4: /* ssl.ca-crl-file */ 2230 if (!buffer_is_blank(cpv->v.b)) { 2231 gnutls_datum_t *d = 2232 mod_gnutls_load_config_crls(cpv->v.b->ptr, srv->errh); 2233 if (d != NULL) { 2234 cpv->vtype = T_CONFIG_LOCAL; 2235 cpv->v.v = d; 2236 } 2237 else { 2238 log_error(srv->errh, __FILE__, __LINE__, 2239 "%s = %s", cpk[cpv->k_id].k, cpv->v.b->ptr); 2240 return HANDLER_ERROR; 2241 } 2242 } 2243 break; 2244 case 5: /* ssl.read-ahead */ 2245 break; 2246 case 6: /* ssl.disable-client-renegotiation */ 2247 /* (force disabled, the default, if HTTP/2 enabled in server) */ 2248 if (srv->srvconf.h2proto) 2249 cpv->v.u = 1; /* disable client renegotiation */ 2250 break; 2251 case 7: /* ssl.verifyclient.activate */ 2252 case 8: /* ssl.verifyclient.enforce */ 2253 break; 2254 case 9: /* ssl.verifyclient.depth */ 2255 if (cpv->v.shrt > 255) { 2256 log_error(srv->errh, __FILE__, __LINE__, 2257 "GnuTLS: %s is absurdly large (%hu); limiting to 255", 2258 cpk[cpv->k_id].k, cpv->v.shrt); 2259 cpv->v.shrt = 255; 2260 } 2261 break; 2262 case 10:/* ssl.verifyclient.username */ 2263 if (buffer_is_blank(cpv->v.b)) 2264 cpv->v.b = NULL; 2265 break; 2266 case 11:/* ssl.verifyclient.exportcert */ 2267 break; 2268 case 12:/* ssl.acme-tls-1 */ 2269 if (buffer_is_blank(cpv->v.b)) 2270 cpv->v.b = NULL; 2271 break; 2272 case 13:/* ssl.stapling-file */ 2273 if (!buffer_is_blank(cpv->v.b)) 2274 ssl_stapling_file = cpv->v.b; 2275 break; 2276 case 14:/* debug.log-ssl-noise */ 2277 #if 0 /*(handled further above)*/ 2278 case 15:/* ssl.verifyclient.ca-file */ 2279 case 16:/* ssl.verifyclient.ca-dn-file */ 2280 case 17:/* ssl.verifyclient.ca-crl-file */ 2281 #endif 2282 break; 2283 default:/* should not happen */ 2284 break; 2285 } 2286 } 2287 2288 if (pemfile) { 2289 if (NULL == privkey) privkey = pemfile; 2290 pemfile->v.v = 2291 network_gnutls_load_pemfile(srv, pemfile->v.b, privkey->v.b, 2292 ssl_stapling_file); 2293 if (pemfile->v.v) 2294 pemfile->vtype = T_CONFIG_LOCAL; 2295 else 2296 return HANDLER_ERROR; 2297 } 2298 } 2299 2300 p->defaults.ssl_verifyclient = 0; 2301 p->defaults.ssl_verifyclient_enforce = 1; 2302 p->defaults.ssl_verifyclient_depth = 9; 2303 p->defaults.ssl_verifyclient_export_cert = 0; 2304 p->defaults.ssl_disable_client_renegotiation = 1; 2305 p->defaults.ssl_read_ahead = 0; 2306 2307 /* initialize p->defaults from global config context */ 2308 if (p->nconfig > 0 && p->cvlist->v.u2[1]) { 2309 const config_plugin_value_t *cpv = p->cvlist + p->cvlist->v.u2[0]; 2310 if (-1 != cpv->k_id) 2311 mod_gnutls_merge_config(&p->defaults, cpv); 2312 } 2313 2314 return mod_gnutls_set_defaults_sockets(srv, p); 2315 } 2316 2317 2318 /* local_send_buffer is a static buffer of size (LOCAL_SEND_BUFSIZE) 2319 * 2320 * buffer is allocated once, is NOT realloced (note: not thread-safe) 2321 * */ 2322 2323 /* copy small mem chunks into single large buffer 2324 * before gnutls_record_send() to reduce number times 2325 * write() called underneath gnutls_record_send() and 2326 * potentially reduce number of packets generated if TCP_NODELAY 2327 * Alternatively, GnuTLS provides gnutls_record_cork() and 2328 * gnutls_record_uncork(), not currently used by mod_gnutls */ 2329 2330 2331 __attribute_cold__ 2332 static int 2333 mod_gnutls_write_err(connection *con, handler_ctx *hctx, int wr, size_t wr_len) 2334 { 2335 switch (wr) { 2336 case GNUTLS_E_AGAIN: 2337 case GNUTLS_E_INTERRUPTED: 2338 if (gnutls_record_get_direction(hctx->ssl)) 2339 con->is_writable = -1; 2340 else 2341 con->is_readable = -1; 2342 break; /* try again later */ 2343 default: 2344 #if 0 2345 /* ??? how to check for EPIPE or ECONNRESET and skip logging ??? */ 2346 if (hctx->conf.ssl_log_noise) 2347 elog(hctx->r->conf.errh, __FILE__, __LINE__, wr, __func__); 2348 #endif 2349 elog(hctx->r->conf.errh, __FILE__, __LINE__, wr, __func__); 2350 return -1; 2351 } 2352 2353 /* partial write; save attempted wr_len */ 2354 hctx->pending_write = wr_len; 2355 2356 return 0; /* try again later */ 2357 } 2358 2359 2360 __attribute_cold__ 2361 static int 2362 mod_gnutls_read_err(connection *con, handler_ctx *hctx, int rc) 2363 { 2364 switch (rc) { 2365 case GNUTLS_E_AGAIN: 2366 case GNUTLS_E_INTERRUPTED: 2367 if (gnutls_record_get_direction(hctx->ssl)) 2368 con->is_writable = -1; 2369 con->is_readable = 0; 2370 return 0; 2371 #if 0 2372 case GNUTLS_E_SESSION_EOF: /*(not exposed by library)*/ 2373 /* XXX: future: save state to avoid future read after response? */ 2374 con->is_readable = 0; 2375 r->keep_alive = 0; 2376 return (hctx->handshake ? -2 : -1); /*(-1 error if during handshake)*/ 2377 #endif 2378 case GNUTLS_E_REHANDSHAKE: 2379 if (!hctx->handshake) return -1; /*(not expected during handshake)*/ 2380 if (hctx->conf.ssl_disable_client_renegotiation)/*(mod_gnutls default)*/ 2381 return -1; 2382 #if 0 2383 if (gnutls_safe_renegotiation_status(hctx->ssl)) { 2384 hctx->handshake = 0; 2385 return con->network_read(con, cq, max_bytes); 2386 } 2387 #else 2388 return 0; /*(ignore client renegotiation request; generally unsafe)*/ 2389 #endif 2390 case GNUTLS_E_WARNING_ALERT_RECEIVED: 2391 case GNUTLS_E_FATAL_ALERT_RECEIVED: 2392 { 2393 const char *str; 2394 gnutls_alert_description_t alert = gnutls_alert_get(hctx->ssl); 2395 switch (alert) { 2396 case GNUTLS_A_NO_RENEGOTIATION: 2397 return 0; /*(ignore non-fatal alert from client)*/ 2398 case GNUTLS_A_HANDSHAKE_FAILURE: 2399 case GNUTLS_A_CLOSE_NOTIFY: /*(not exposed by library)*/ 2400 case GNUTLS_A_UNKNOWN_CA: 2401 case GNUTLS_A_CERTIFICATE_UNKNOWN: 2402 case GNUTLS_A_BAD_CERTIFICATE: 2403 if (!hctx->conf.ssl_log_noise) return -1; 2404 __attribute_fallthrough__ 2405 default: 2406 str = gnutls_alert_get_name(alert); 2407 elogf(hctx->r->conf.errh, __FILE__, __LINE__, rc, 2408 "%s(): alert %s", __func__, str ? str : "(unknown)"); 2409 return -1; 2410 } 2411 } 2412 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET: 2413 case GNUTLS_E_UNKNOWN_CIPHER_SUITE: /* GNUTLS_A_HANDSHAKE_FAILURE */ 2414 case GNUTLS_E_PREMATURE_TERMINATION: 2415 if (!hctx->conf.ssl_log_noise) return -1; 2416 __attribute_fallthrough__ 2417 case GNUTLS_E_GOT_APPLICATION_DATA: /*(not expected with current use)*/ 2418 /*if (hctx->handshake) return -1;*//*(accept only during handshake)*/ 2419 default: 2420 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, __func__); 2421 return -1; 2422 } 2423 } 2424 2425 2426 static int 2427 mod_gnutls_close_notify(handler_ctx *hctx); 2428 2429 2430 static int 2431 connection_write_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes) 2432 { 2433 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id]; 2434 gnutls_session_t const ssl = hctx->ssl; 2435 if (!hctx->handshake) return 0; 2436 2437 if (hctx->pending_write) { 2438 int wr = gnutls_record_send(ssl, NULL, 0); 2439 if (wr <= 0) 2440 return mod_gnutls_write_err(con, hctx, wr, hctx->pending_write); 2441 max_bytes -= wr; 2442 hctx->pending_write = 0; 2443 chunkqueue_mark_written(cq, wr); 2444 } 2445 2446 if (__builtin_expect( (0 != hctx->close_notify), 0)) 2447 return mod_gnutls_close_notify(hctx); 2448 2449 const size_t lim = gnutls_record_get_max_size(ssl); 2450 2451 /* future: for efficiency/performance might consider using GnuTLS corking 2452 * gnutls_record_cork() 2453 * gnutls_record_uncork() 2454 * gnutls_record_check_corked() 2455 * though chunkqueue_peek_data() already will read a mix of MEM_CHUNK and 2456 * FILE_CHUNK into the buffer before sending, e.g. to send header response 2457 * headers and beginning of files, but does so for LOCAL_SEND_BUFSIZE (16k) 2458 * More might be possible to send before uncorking. 2459 */ 2460 2461 log_error_st * const errh = hctx->errh; 2462 while (max_bytes > 0 && !chunkqueue_is_empty(cq)) { 2463 char *data = local_send_buffer; 2464 uint32_t data_len = LOCAL_SEND_BUFSIZE < max_bytes 2465 ? LOCAL_SEND_BUFSIZE 2466 : (uint32_t)max_bytes; 2467 int wr; 2468 2469 if (0 != chunkqueue_peek_data(cq, &data, &data_len, errh)) return -1; 2470 if (__builtin_expect( (0 == data_len), 0)) { 2471 chunkqueue_remove_finished_chunks(cq); 2472 continue; 2473 } 2474 2475 /* gnutls_record_send() copies the data, up to max record size, but if 2476 * (temporarily) unable to write the entire record, it is documented 2477 * that the caller must call gnutls_record_send() again, later, with the 2478 * same arguments, or with NULL ptr and 0 data_len. The func may return 2479 * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED to indicate that caller should 2480 * wait for fd to be readable/writable before calling the func again, 2481 * which is why those (temporary) errors are returned instead of telling 2482 * the caller that the data was successfully copied. 2483 * Additionally, to be accurate, the size must fit into a record which 2484 * is why we restrict ourselves to sending max out record payload each 2485 * iteration. 2486 * XXX: above comments modified from mod_mbedtls; should be verified 2487 */ 2488 2489 int wr_total = 0; 2490 do { 2491 size_t wr_len = (data_len > lim) ? lim : data_len; 2492 wr = gnutls_record_send(ssl, data, wr_len); 2493 if (wr <= 0) { 2494 if (wr_total) chunkqueue_mark_written(cq, wr_total); 2495 return mod_gnutls_write_err(con, hctx, wr, wr_len); 2496 } 2497 wr_total += wr; 2498 data += wr; 2499 } while ((data_len -= wr)); 2500 chunkqueue_mark_written(cq, wr_total); 2501 max_bytes -= wr_total; 2502 } 2503 2504 return 0; 2505 } 2506 2507 2508 static int 2509 mod_gnutls_ssl_handshake (handler_ctx *hctx) 2510 { 2511 int rc = gnutls_handshake(hctx->ssl); 2512 if (rc < 0) 2513 return mod_gnutls_read_err(hctx->con, hctx, rc); 2514 2515 /*(rc == GNUTLS_E_SUCCESS)*/ 2516 2517 hctx->handshake = 1; 2518 #if GNUTLS_VERSION_NUMBER >= 0x030200 2519 if (hctx->alpn == MOD_GNUTLS_ALPN_H2) { 2520 if (0 != mod_gnutls_alpn_h2_policy(hctx)) 2521 return -1; 2522 } 2523 else if (hctx->alpn == MOD_GNUTLS_ALPN_ACME_TLS_1) { 2524 /* Once TLS handshake is complete, return -1 to result in 2525 * CON_STATE_ERROR so that socket connection is quickly closed */ 2526 return -1; 2527 } 2528 hctx->alpn = 0; 2529 #endif 2530 return 1; /* continue reading */ 2531 } 2532 2533 2534 static int 2535 connection_read_cq_ssl (connection * const con, chunkqueue * const cq, off_t max_bytes) 2536 { 2537 handler_ctx * const hctx = con->plugin_ctx[plugin_data_singleton->id]; 2538 2539 UNUSED(max_bytes); 2540 2541 if (__builtin_expect( (0 != hctx->close_notify), 0)) 2542 return mod_gnutls_close_notify(hctx); 2543 2544 if (!hctx->handshake) { 2545 int rc = mod_gnutls_ssl_handshake(hctx); 2546 if (1 != rc) return rc; /* !hctx->handshake; not done, or error */ 2547 } 2548 2549 gnutls_session_t ssl = hctx->ssl; 2550 ssize_t len; 2551 char *mem = NULL; 2552 size_t mem_len = 0; 2553 size_t pend = gnutls_record_check_pending(ssl); 2554 do { 2555 mem_len = pend < 2048 ? 2048 : pend; 2556 chunk * const ckpt = cq->last; 2557 mem = chunkqueue_get_memory(cq, &mem_len); 2558 2559 len = gnutls_record_recv(ssl, mem, mem_len); 2560 if (len > 0) { 2561 chunkqueue_use_memory(cq, ckpt, len); 2562 con->bytes_read += len; 2563 } else { 2564 chunkqueue_use_memory(cq, ckpt, 0); 2565 } 2566 } while (len > 0 && (pend = gnutls_record_check_pending(ssl))); 2567 2568 if (len < 0) { 2569 return mod_gnutls_read_err(con, hctx, (int)len); 2570 } else if (len == 0) { 2571 con->is_readable = 0; 2572 /* the other end closed the connection -> KEEP-ALIVE */ 2573 2574 return -2; 2575 } else { 2576 return 0; 2577 } 2578 } 2579 2580 2581 static void 2582 mod_gnutls_debug_cb(int level, const char *str) 2583 { 2584 UNUSED(level); 2585 log_error_st *errh = plugin_data_singleton->srv->errh; 2586 log_error(errh, __FILE__, __LINE__, "GnuTLS: %s", str); 2587 } 2588 2589 2590 CONNECTION_FUNC(mod_gnutls_handle_con_accept) 2591 { 2592 const server_socket *srv_sock = con->srv_socket; 2593 if (!srv_sock->is_ssl) return HANDLER_GO_ON; 2594 2595 plugin_data *p = p_d; 2596 handler_ctx * const hctx = handler_ctx_init(); 2597 request_st * const r = &con->request; 2598 hctx->r = r; 2599 hctx->con = con; 2600 hctx->tmp_buf = con->srv->tmp_buf; 2601 hctx->errh = r->conf.errh; 2602 con->plugin_ctx[p->id] = hctx; 2603 buffer_blank(&r->uri.authority); 2604 2605 plugin_ssl_ctx * const s = p->ssl_ctxs + srv_sock->sidx; 2606 hctx->ssl_session_ticket = s->ssl_session_ticket; 2607 int flags = GNUTLS_SERVER | GNUTLS_NO_SIGNAL | GNUTLS_NONBLOCK; 2608 /* ??? add feature: GNUTLS_ENABLE_EARLY_START ??? */ 2609 int rc = gnutls_init(&hctx->ssl, flags); 2610 if (rc < 0) { 2611 elog(r->conf.errh, __FILE__, __LINE__, rc, "gnutls_init()"); 2612 return HANDLER_ERROR; 2613 } 2614 2615 rc = gnutls_priority_set(hctx->ssl, s->priority_cache); 2616 if (rc < 0) { 2617 elog(r->conf.errh, __FILE__, __LINE__, rc, "gnutls_priority_set()"); 2618 return HANDLER_ERROR; 2619 } 2620 2621 /* generic func replaces gnutls_handshake_set_post_client_hello_function()*/ 2622 gnutls_handshake_set_hook_function(hctx->ssl, GNUTLS_HANDSHAKE_CLIENT_HELLO, 2623 GNUTLS_HOOK_PRE, 2624 mod_gnutls_client_hello_hook); 2625 2626 gnutls_session_set_ptr(hctx->ssl, hctx); 2627 gnutls_transport_set_int(hctx->ssl, con->fd); 2628 2629 con->network_read = connection_read_cq_ssl; 2630 con->network_write = connection_write_cq_ssl; 2631 con->proto_default_port = 443; /* "https" */ 2632 mod_gnutls_patch_config(r, &hctx->conf); 2633 2634 #if GNUTLS_VERSION_NUMBER < 0x030600 2635 hctx->conf.dh_params = s->dh_params; 2636 #endif 2637 2638 /* debug logging is global. Once enabled, debug hook will remain so, though 2639 * different connection might overwrite level, if configured differently. 2640 * If GNUTLS_DEBUG_LEVEL is set in environment (and ssl_log_noise not set), 2641 * then debugging will go to stderr */ 2642 if (hctx->conf.ssl_log_noise) {/* volume level for debug message callback */ 2643 gnutls_global_set_log_function(mod_gnutls_debug_cb); 2644 gnutls_global_set_log_level(hctx->conf.ssl_log_noise); 2645 } 2646 2647 /* GnuTLS limitation: must set session ticket encryption key before GnuTLS 2648 * client hello hook runs if TLSv1.3 (? key already set by then ?) */ 2649 if (hctx->ssl_session_ticket && session_ticket_key.size) { 2650 rc = gnutls_session_ticket_enable_server(hctx->ssl,&session_ticket_key); 2651 if (rc < 0) { 2652 elog(r->conf.errh, __FILE__, __LINE__, rc, 2653 "gnutls_session_ticket_enable_server()"); 2654 return HANDLER_ERROR; 2655 } 2656 } 2657 2658 return HANDLER_GO_ON; 2659 } 2660 2661 2662 static void 2663 mod_gnutls_detach(handler_ctx *hctx) 2664 { 2665 /* step aside from further SSL processing 2666 * (used after handle_connection_shut_wr hook) */ 2667 /* future: might restore prior network_read and network_write fn ptrs */ 2668 hctx->con->is_ssl_sock = 0; 2669 /* if called after handle_connection_shut_wr hook, shutdown SHUT_WR */ 2670 if (-1 == hctx->close_notify) shutdown(hctx->con->fd, SHUT_WR); 2671 hctx->close_notify = 1; 2672 } 2673 2674 2675 CONNECTION_FUNC(mod_gnutls_handle_con_shut_wr) 2676 { 2677 plugin_data *p = p_d; 2678 handler_ctx *hctx = con->plugin_ctx[p->id]; 2679 if (NULL == hctx) return HANDLER_GO_ON; 2680 2681 hctx->close_notify = -2; 2682 if (hctx->handshake) { 2683 mod_gnutls_close_notify(hctx); 2684 } 2685 else { 2686 mod_gnutls_detach(hctx); 2687 } 2688 2689 return HANDLER_GO_ON; 2690 } 2691 2692 2693 static int 2694 mod_gnutls_close_notify (handler_ctx *hctx) 2695 { 2696 if (1 == hctx->close_notify) return -2; 2697 2698 int rc = gnutls_bye(hctx->ssl, GNUTLS_SHUT_WR); 2699 switch (rc) { 2700 case GNUTLS_E_SUCCESS: 2701 mod_gnutls_detach(hctx); 2702 return -2; 2703 case GNUTLS_E_AGAIN: 2704 case GNUTLS_E_INTERRUPTED: 2705 return 0; 2706 default: 2707 elog(hctx->r->conf.errh, __FILE__, __LINE__, rc, 2708 "mod_gnutls_close_notify()"); 2709 __attribute_fallthrough__ 2710 case GNUTLS_E_PUSH_ERROR: /*(noisy; probably connection reset)*/ 2711 mod_gnutls_detach(hctx); 2712 return -1; 2713 } 2714 } 2715 2716 2717 CONNECTION_FUNC(mod_gnutls_handle_con_close) 2718 { 2719 plugin_data *p = p_d; 2720 handler_ctx *hctx = con->plugin_ctx[p->id]; 2721 if (NULL != hctx) { 2722 con->plugin_ctx[p->id] = NULL; 2723 if (1 != hctx->close_notify) 2724 mod_gnutls_close_notify(hctx); /*(one final try)*/ 2725 handler_ctx_free(hctx); 2726 } 2727 2728 return HANDLER_GO_ON; 2729 } 2730 2731 2732 __attribute_noinline__ 2733 static void 2734 https_add_ssl_client_cert (request_st * const r, const gnutls_x509_crt_t peer) 2735 { 2736 gnutls_datum_t d; 2737 if (gnutls_x509_crt_export2(peer, GNUTLS_X509_FMT_PEM, &d) >= 0) 2738 http_header_env_set(r, 2739 CONST_STR_LEN("SSL_CLIENT_CERT"), 2740 (char *)d.data, d.size); 2741 if (d.data) gnutls_free(d.data); 2742 } 2743 2744 2745 /* modified from gnutls tests/dn.c:print_dn() */ 2746 static void 2747 https_add_ssl_client_subject (request_st * const r, gnutls_x509_dn_t dn) 2748 { 2749 int irdn = 0, i, rc; 2750 gnutls_x509_ava_st ava; 2751 const size_t prelen = sizeof("SSL_CLIENT_S_DN_")-1; 2752 char key[64] = "SSL_CLIENT_S_DN_"; 2753 char buf[512]; /*(expecting element value len <= 256)*/ 2754 2755 /* add components of client Subject DN */ 2756 2757 /* man gnutls_x509_dn_get_rdn_ava() 2758 * The X.509 distinguished name is a sequence of sequences of strings and 2759 * this is what the irdn and iava indexes model. 2760 * This is a low-level function that requires the caller to do the value 2761 * conversions when necessary (e.g. from UCS-2). 2762 * XXX: value conversions not done below; unprintable chars replaced w/ '?' 2763 */ 2764 2765 do { 2766 for (i=0; (rc = gnutls_x509_dn_get_rdn_ava(dn,irdn,i,&ava)) == 0; ++i) { 2767 const char *name = 2768 gnutls_x509_dn_oid_name((char *)ava.oid.data, 2769 GNUTLS_X509_DN_OID_RETURN_OID); 2770 const size_t len = strlen(name); 2771 if (prelen+len >= sizeof(key)) continue; 2772 memcpy(key+prelen, name, len); /*(not '\0'-terminated)*/ 2773 2774 unsigned int n, vlen = ava.value.size; 2775 if (vlen > sizeof(buf)-1) 2776 vlen = sizeof(buf)-1; 2777 for (n = 0; n < vlen; ++n) { 2778 unsigned char c = ava.value.data[n]; 2779 buf[n] = (c >= 32 && c != 127) ? c : '?'; 2780 } 2781 2782 http_header_env_set(r, key, prelen+len, buf, n); 2783 } 2784 ++irdn; 2785 } while (rc == GNUTLS_E_ASN1_ELEMENT_NOT_FOUND && i > 0); 2786 2787 if (rc != GNUTLS_E_ASN1_ELEMENT_NOT_FOUND) 2788 elog(r->conf.errh, __FILE__, __LINE__, rc, 2789 "gnutls_x509_dn_get_rdn_ava()"); 2790 } 2791 2792 2793 __attribute_cold__ 2794 static void 2795 https_add_ssl_client_verify_err (buffer * const b, unsigned int status) 2796 { 2797 #if GNUTLS_VERSION_NUMBER >= 0x030104 2798 /* get failure string and translate newline to ':', removing last one */ 2799 /* (preserving behavior from mod_openssl) */ 2800 gnutls_datum_t msg = { NULL, 0 }; 2801 if (gnutls_certificate_verification_status_print(status, GNUTLS_CRT_X509, 2802 &msg, 0) >= 0) { 2803 size_t sz = msg.size-1; /* '\0'-terminated string */ 2804 for (char *nl=(char *)msg.data; NULL != (nl=strchr(nl, '\n')); ++nl) 2805 nl[0] = ('\0' == nl[1] ? (--sz, '\0') : ':'); 2806 buffer_append_string_len(b, (char *)msg.data, sz); 2807 } 2808 if (msg.data) gnutls_free(msg.data); 2809 #else 2810 UNUSED(b); 2811 UNUSED(status); 2812 #endif 2813 } 2814 2815 2816 __attribute_noinline__ 2817 static void 2818 https_add_ssl_client_entries (request_st * const r, handler_ctx * const hctx) 2819 { 2820 gnutls_session_t ssl = hctx->ssl; 2821 unsigned int crt_size = 0; 2822 const gnutls_datum_t *crts = NULL; 2823 buffer *vb = http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_VERIFY")); 2824 2825 if (hctx->verify_status != ~0u) 2826 crts = gnutls_certificate_get_peers(ssl, &crt_size); 2827 if (0 == crt_size) { /* || hctx->verify_status == ~0u) */ 2828 /*(e.g. no cert, or verify result not available)*/ 2829 buffer_copy_string_len(vb, CONST_STR_LEN("NONE")); 2830 return; 2831 } 2832 else if (0 != hctx->verify_status) { 2833 buffer_copy_string_len(vb, CONST_STR_LEN("FAILED:")); 2834 https_add_ssl_client_verify_err(vb, hctx->verify_status); 2835 return; 2836 } 2837 else { 2838 buffer_copy_string_len(vb, CONST_STR_LEN("SUCCESS")); 2839 } 2840 2841 gnutls_x509_crt_t crt; 2842 if (gnutls_x509_crt_init(&crt) < 0) 2843 return; 2844 if (crts && gnutls_x509_crt_import(crt, &crts[0], GNUTLS_X509_FMT_DER) < 0){ 2845 gnutls_x509_crt_deinit(crt); 2846 return; 2847 } 2848 2849 int rc; 2850 gnutls_datum_t d = { NULL, 0 }; 2851 char buf[512]; 2852 /*rc = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_ONELINE, &d);*//* ??? */ 2853 #if GNUTLS_VERSION_NUMBER < 0x030507 2854 d.data = buf; 2855 d.size = sizeof(buf); 2856 rc = gnutls_x509_crt_get_dn(crt, buf, &d.size); 2857 #else 2858 rc = gnutls_x509_crt_get_dn3(crt, &d, 0); 2859 #endif 2860 if (rc >= 0) 2861 http_header_env_set(r, 2862 CONST_STR_LEN("SSL_CLIENT_S_DN"), 2863 (char *)d.data, d.size); 2864 if (d.data && d.data != (void *)buf) gnutls_free(d.data); 2865 2866 gnutls_x509_dn_t dn; 2867 rc = gnutls_x509_crt_get_subject(crt, &dn); 2868 if (rc >= 0) 2869 https_add_ssl_client_subject(r, dn); 2870 2871 size_t sz = sizeof(buf); 2872 if (gnutls_x509_crt_get_serial(crt, buf, &sz) >= 0) 2873 buffer_append_string_encoded_hex_uc( 2874 http_header_env_set_ptr(r, CONST_STR_LEN("SSL_CLIENT_M_SERIAL")), 2875 buf, sz); 2876 2877 if (hctx->conf.ssl_verifyclient_username) { 2878 /* pick one of the exported values as "REMOTE_USER", for example 2879 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_UID" 2880 * or 2881 * ssl.verifyclient.username = "SSL_CLIENT_S_DN_emailAddress" 2882 */ 2883 const buffer *varname = hctx->conf.ssl_verifyclient_username; 2884 vb = http_header_env_get(r, BUF_PTR_LEN(varname)); 2885 if (vb) { /* same as mod_auth_api.c:http_auth_setenv() */ 2886 http_header_env_set(r, 2887 CONST_STR_LEN("REMOTE_USER"), 2888 BUF_PTR_LEN(vb)); 2889 http_header_env_set(r, 2890 CONST_STR_LEN("AUTH_TYPE"), 2891 CONST_STR_LEN("SSL_CLIENT_VERIFY")); 2892 } 2893 } 2894 2895 /* if (NULL != crt) (e.g. not PSK-based ciphersuite) */ 2896 if (hctx->conf.ssl_verifyclient_export_cert && NULL != crt) 2897 https_add_ssl_client_cert(r, crt); 2898 2899 gnutls_x509_crt_deinit(crt); 2900 } 2901 2902 2903 static void 2904 http_cgi_ssl_env (request_st * const r, handler_ctx * const hctx) 2905 { 2906 gnutls_session_t ssl = hctx->ssl; 2907 gnutls_protocol_t version = gnutls_protocol_get_version(ssl); 2908 gnutls_cipher_algorithm_t cipher = gnutls_cipher_get(ssl); 2909 gnutls_kx_algorithm_t kx = gnutls_kx_get(ssl); 2910 gnutls_mac_algorithm_t mac = gnutls_mac_get(ssl); 2911 const char *s; 2912 2913 s = gnutls_protocol_get_name(version); 2914 if (s) http_header_env_set(r, CONST_STR_LEN("SSL_PROTOCOL"), s, strlen(s)); 2915 2916 s = gnutls_cipher_suite_get_name(kx, cipher, mac); 2917 if (s) http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER"), s, strlen(s)); 2918 2919 /* SSL_CIPHER_ALGKEYSIZE - Number of cipher bits (possible) */ 2920 /* SSL_CIPHER_USEKEYSIZE - Number of cipher bits (actually used) */ 2921 /* (always the same in extra/gnutls_openssl.c:SSL_CIPHER_get_bits()) 2922 * (The values are the same except for very old, weak ciphers, i.e. if you 2923 * care about this, then you instead ought to be using stronger ciphers)*/ 2924 /* ??? gnutls_x509_crt_get_pk_algorithm(crt, &usekeysize); ??? */ 2925 size_t algkeysize = 8 * gnutls_cipher_get_key_size(cipher); 2926 size_t usekeysize = algkeysize; 2927 char buf[LI_ITOSTRING_LENGTH]; 2928 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_USEKEYSIZE"), 2929 buf, li_utostrn(buf, sizeof(buf), usekeysize)); 2930 http_header_env_set(r, CONST_STR_LEN("SSL_CIPHER_ALGKEYSIZE"), 2931 buf, li_utostrn(buf, sizeof(buf), algkeysize)); 2932 } 2933 2934 2935 REQUEST_FUNC(mod_gnutls_handle_request_env) 2936 { 2937 plugin_data *p = p_d; 2938 /* simple flag for request_env_patched */ 2939 if (r->plugin_ctx[p->id]) return HANDLER_GO_ON; 2940 handler_ctx *hctx = r->con->plugin_ctx[p->id]; 2941 if (NULL == hctx) return HANDLER_GO_ON; 2942 r->plugin_ctx[p->id] = (void *)(uintptr_t)1u; 2943 2944 http_cgi_ssl_env(r, hctx); 2945 if (hctx->conf.ssl_verifyclient) { 2946 https_add_ssl_client_entries(r, hctx); 2947 } 2948 2949 return HANDLER_GO_ON; 2950 } 2951 2952 2953 REQUEST_FUNC(mod_gnutls_handle_uri_raw) 2954 { 2955 /* mod_gnutls must be loaded prior to mod_auth 2956 * if mod_gnutls is configured to set REMOTE_USER based on client cert */ 2957 /* mod_gnutls must be loaded after mod_extforward 2958 * if mod_gnutls config is based on lighttpd.conf remote IP conditional 2959 * using remote IP address set by mod_extforward, *unless* PROXY protocol 2960 * is enabled with extforward.hap-PROXY = "enable", in which case the 2961 * reverse is true: mod_extforward must be loaded after mod_gnutls */ 2962 plugin_data *p = p_d; 2963 handler_ctx *hctx = r->con->plugin_ctx[p->id]; 2964 if (NULL == hctx) return HANDLER_GO_ON; 2965 2966 mod_gnutls_patch_config(r, &hctx->conf); 2967 if (hctx->conf.ssl_verifyclient) { 2968 mod_gnutls_handle_request_env(r, p); 2969 } 2970 2971 return HANDLER_GO_ON; 2972 } 2973 2974 2975 REQUEST_FUNC(mod_gnutls_handle_request_reset) 2976 { 2977 plugin_data *p = p_d; 2978 r->plugin_ctx[p->id] = NULL; /* simple flag for request_env_patched */ 2979 return HANDLER_GO_ON; 2980 } 2981 2982 2983 TRIGGER_FUNC(mod_gnutls_handle_trigger) { 2984 const plugin_data * const p = p_d; 2985 const unix_time64_t cur_ts = log_epoch_secs; 2986 if (cur_ts & 0x3f) return HANDLER_GO_ON; /*(continue once each 64 sec)*/ 2987 2988 mod_gnutls_session_ticket_key_check(srv, p, cur_ts); 2989 mod_gnutls_refresh_stapling_files(srv, p, cur_ts); 2990 2991 return HANDLER_GO_ON; 2992 } 2993 2994 2995 int mod_gnutls_plugin_init (plugin *p); 2996 int mod_gnutls_plugin_init (plugin *p) 2997 { 2998 p->version = LIGHTTPD_VERSION_ID; 2999 p->name = "gnutls"; 3000 p->init = mod_gnutls_init; 3001 p->cleanup = mod_gnutls_free; 3002 p->priv_defaults= mod_gnutls_set_defaults; 3003 3004 p->handle_connection_accept = mod_gnutls_handle_con_accept; 3005 p->handle_connection_shut_wr = mod_gnutls_handle_con_shut_wr; 3006 p->handle_connection_close = mod_gnutls_handle_con_close; 3007 p->handle_uri_raw = mod_gnutls_handle_uri_raw; 3008 p->handle_request_env = mod_gnutls_handle_request_env; 3009 p->handle_request_reset = mod_gnutls_handle_request_reset; 3010 p->handle_trigger = mod_gnutls_handle_trigger; 3011 3012 return 0; 3013 } 3014 3015 3016 /* cipher suites 3017 * 3018 * (extremely coarse (and very possibly incorrect) mapping to openssl labels) 3019 */ 3020 3021 /* TLSv1.3 cipher list (supported in gnutls) */ 3022 static const char suite_TLSv13[] = 3023 "+CHACHA20-POLY1305:" 3024 "+AES-256-GCM:" 3025 "+AES-256-CCM:" 3026 "+AES-256-CCM-8:" 3027 "+AES-128-GCM:" 3028 "+AES-128-CCM:" 3029 "+AES-128-CCM-8:" 3030 ; 3031 3032 /* TLSv1.2 cipher list (supported in gnutls) */ 3033 static const char suite_TLSv12[] = 3034 "+CHACHA20-POLY1305:" 3035 "+AES-256-GCM:" 3036 "+AES-256-CCM:" 3037 "+AES-256-CBC:" 3038 "+AES-256-CCM-8:" 3039 "+CAMELLIA-256-GCM:" 3040 "+CAMELLIA-256-CBC:" 3041 "+AES-128-GCM:" 3042 "+AES-128-CCM:" 3043 "+AES-128-CBC:" 3044 "+AES-128-CCM-8:" 3045 "+CAMELLIA-128-GCM:" 3046 "+CAMELLIA-128-CBC:" 3047 ; 3048 3049 /* TLSv1.0 cipher list (supported in gnutls) */ 3050 /* XXX: intentionally not including overlapping eNULL ciphers */ 3051 static const char suite_TLSv10[] = 3052 "+AES-256-CBC:" 3053 "+AES-128-CBC:" 3054 "+CAMELLIA-256-CBC:" 3055 "+CAMELLIA-128-CBC:" 3056 ; 3057 3058 /* SSLv3 cipher list (supported in gnutls) */ 3059 /* XXX: intentionally not including overlapping eNULL ciphers */ 3060 static const char suite_SSLv3[] = 3061 "+AES-256-CBC:" 3062 "+AES-128-CBC:" 3063 "+CAMELLIA-256-CBC:" 3064 "+CAMELLIA-128-CBC:" 3065 "+3DES-CBC:" 3066 "+DES-CBC:" 3067 ; 3068 3069 /* HIGH cipher list (mapped from openssl list to gnutls) */ 3070 static const char suite_HIGH[] = 3071 "+CHACHA20-POLY1305:" 3072 "+AES-256-GCM:" 3073 "+AES-256-CCM:" 3074 "+AES-256-CBC:" 3075 "+AES-256-CCM-8:" 3076 "+CAMELLIA-256-CBC:" 3077 "+AES-128-GCM:" 3078 "+AES-128-CCM:" 3079 "+AES-128-CBC:" 3080 "+AES-128-CCM-8:" 3081 "+CAMELLIA-128-CBC:" 3082 ; 3083 3084 3085 static int 3086 mod_gnutls_ssl_conf_ciphersuites (server *srv, plugin_config_socket *s, buffer *ciphersuites, const buffer *cipherstring) 3087 { 3088 /* reference: https://www.openssl.org/docs/man1.1.1/man1/ciphers.html 3089 * Attempt to parse *some* keywords from Ciphersuites and CipherString 3090 * !!! openssl uses a *different* naming scheme than does GnuTLS !!! 3091 * Ciphersuites in openssl takes only TLSv1.3 suites. 3092 * Note that CipherString does allow cipher suites to be listed, 3093 * and this code does not currently attempt to provide mapping */ 3094 3095 buffer * const plist = &s->priority_str; 3096 char n[128]; /*(most ciphersuite names are about 40 chars)*/ 3097 3098 if (ciphersuites) { 3099 buffer *b = ciphersuites; 3100 buffer_to_upper(b); /*(ciphersuites are all uppercase (currently))*/ 3101 for (const char *e = b->ptr-1; e; ) { 3102 const char * const p = e+1; 3103 e = strchr(p, ':'); 3104 size_t len = e ? (size_t)(e - p) : strlen(p); 3105 3106 if (buffer_eq_icase_ss(p, len, 3107 CONST_STR_LEN("TLS_CHACHA20_POLY1305_SHA256"))) 3108 buffer_append_string_len(plist, 3109 CONST_STR_LEN("+CHACHA20-POLY1305:")); 3110 else if (buffer_eq_icase_ss(p, len, 3111 CONST_STR_LEN("TLS_AES_256_GCM_SHA384"))) 3112 buffer_append_string_len(plist, 3113 CONST_STR_LEN("+AES-256-GCM:")); 3114 else if (buffer_eq_icase_ss(p, len, 3115 CONST_STR_LEN("TLS_AES_128_GCM_SHA256"))) 3116 buffer_append_string_len(plist, 3117 CONST_STR_LEN("+AES-128-GCM:")); 3118 else if (buffer_eq_icase_ss(p, len, 3119 CONST_STR_LEN("TLS_AES_128_CCM_SHA256"))) 3120 buffer_append_string_len(plist, 3121 CONST_STR_LEN("+AES-128-CCM:")); 3122 else if (buffer_eq_icase_ss(p, len, 3123 CONST_STR_LEN("TLS_AES_128_CCM_8_SHA256"))) 3124 buffer_append_string_len(plist, 3125 CONST_STR_LEN("+AES-128-CCM-8:")); 3126 else 3127 log_error(srv->errh, __FILE__, __LINE__, 3128 "GnuTLS: skipped ciphersuite; not recognized: %.*s", 3129 (int)len, p); 3130 } 3131 } 3132 3133 /* XXX: openssl config for CipherString=... is excessively complex. 3134 * If there is a need to enable specific ciphersuites, then that 3135 * can be accomplished with mod_gnutls by specifying the list in 3136 * Ciphersuites=... in the ssl.openssl.ssl-conf-cmd directive. 3137 * 3138 * The tokens parsed here are a quick attempt to handle a few cases 3139 * 3140 * XXX: not done: could make a list of ciphers with bitflag of attributes 3141 * to make future combining easier */ 3142 if (cipherstring && !buffer_is_blank(cipherstring)) { 3143 const buffer *b = cipherstring; 3144 const char *e = b->ptr; 3145 3146 /* XXX: not done: no checking for duplication of ciphersuites 3147 * even if tokens overlap or are repeated */ 3148 3149 /* XXX: not done: might walk string and build up exclude list of !xxxxx 3150 * ciphersuites and walk string again, excluding as result list built */ 3151 3152 /* manually handle first token, since one-offs apply */ 3153 /* (openssl syntax NOT fully supported) */ 3154 #define strncmp_const(s,cs) strncmp((s),(cs),sizeof(cs)-1) 3155 if (0 == strncmp_const(e, "!ALL") || 0 == strncmp_const(e, "-ALL")) { 3156 /* "!ALL" excluding all ciphers is empty list */ 3157 e += sizeof("!ALL")-1; /* same as sizeof("-ALL")-1 */ 3158 buffer_append_string_len(plist, CONST_STR_LEN("-CIPHER-ALL:")); 3159 } 3160 else if (0 == strncmp_const(e, "!DEFAULT") 3161 || 0 == strncmp_const(e, "-DEFAULT")) { 3162 /* "!DEFAULT" excluding default ciphers is empty list */ 3163 e += sizeof("!DEFAULT")-1; /* same as sizeof("-DEFAULT")-1 */ 3164 buffer_append_string_len(plist, CONST_STR_LEN("-CIPHER-ALL:")); 3165 } 3166 else if (0 == strncmp_const(e, "DEFAULT")) { 3167 e += sizeof("DEFAULT")-1; 3168 s->priority_base = "NORMAL"; 3169 } 3170 else if (0 == /* effectively the same as "DEFAULT" */ 3171 strncmp_const(e, "ALL:!COMPLEMENTOFDEFAULT:!eNULL")) { 3172 e += sizeof("ALL:!COMPLEMENTOFDEFAULT:!eNULL")-1; 3173 s->priority_base = "NORMAL"; 3174 } 3175 else if (0 == strncmp_const(e, "SUITEB128") 3176 || 0 == strncmp_const(e, "SUITEB128ONLY") 3177 || 0 == strncmp_const(e, "SUITEB192")) { 3178 s->priority_base = (0 == strncmp_const(e, "SUITEB192")) 3179 ? "SUITEB192" 3180 : "SUITEB128"; 3181 e += (0 == strncmp_const(e, "SUITEB128ONLY")) 3182 ? sizeof("SUITEB128ONLY")-1 3183 : sizeof("SUITEB128")-1; 3184 if (*e) 3185 log_error(srv->errh, __FILE__, __LINE__, 3186 "GnuTLS: ignoring cipher string after SUITEB: %s", e); 3187 return 1; 3188 } 3189 else if (0 == strncmp_const(e, 3190 "ECDHE+AESGCM:ECDHE+AES256:CHACHA20:!SHA1:!SHA256:!SHA384") 3191 || 0 == strncmp_const(e, 3192 "EECDH+AESGCM:AES256+EECDH:CHACHA20:!SHA1:!SHA256:!SHA384")) { 3193 e += sizeof( 3194 "EECDH+AESGCM:AES256+EECDH:CHACHA20:!SHA1:!SHA256:!SHA384")-1; 3195 buffer_append_string_len(plist, 3196 CONST_STR_LEN("+AES-256-GCM:+AES-128-GCM:+AES-256-CCM:+AES-256-CCM-8:+CHACHA20-POLY1305:")); 3197 } 3198 3199 if (e != b->ptr && *e != ':' && *e != '\0') { 3200 log_error(srv->errh, __FILE__, __LINE__, 3201 "GnuTLS: error: missing support for cipher list: %s", b->ptr); 3202 return 0; 3203 } 3204 3205 /* not handled: "ALL" is "DEFAULT" and "RC4" */ 3206 /* not handled: "COMPLEMENTOFALL" is "eNULL" */ 3207 3208 int rc = 1; 3209 if (e == b->ptr || *e == '\0') --e; /*initial condition for loop below*/ 3210 do { 3211 const char * const p = e+1; 3212 e = strchr(p, ':'); 3213 size_t len = e ? (size_t)(e - p) : strlen(p); 3214 if (0 == len) continue; 3215 if (len >= sizeof(n)) { 3216 log_error(srv->errh, __FILE__, __LINE__, 3217 "GnuTLS: skipped ciphersuite; too long: %.*s", 3218 (int)len, p); 3219 continue; 3220 } 3221 char c = (*p == '!' || *p == '-' || *p == '+') ? *p : 0; 3222 size_t nlen = c ? len-1 : len; 3223 memcpy(n, c ? p+1 : p, nlen); 3224 n[nlen] = '\0'; 3225 3226 /* not handled: !xxxxx -xxxxx and most +xxxxx */ 3227 if (c) { 3228 log_error(srv->errh, __FILE__, __LINE__, 3229 "GnuTLS: error: missing support for cipher list: %s", b->ptr); 3230 } 3231 3232 /* ignore @STRENGTH sorting and ignore @SECLEVEL=n */ 3233 char *a = strchr(n, '@'); 3234 if (a) { 3235 log_error(srv->errh, __FILE__, __LINE__, 3236 "GnuTLS: ignored %s in %.*s", a, (int)len, p); 3237 *a = '\0'; 3238 nlen = (size_t)(a - n); 3239 } 3240 3241 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("TLSv1.3"))) { 3242 buffer_append_string_len(plist, 3243 CONST_STR_LEN(suite_TLSv13)); 3244 continue; 3245 } 3246 3247 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("TLSv1.2"))) { 3248 buffer_append_string_len(plist, 3249 CONST_STR_LEN(suite_TLSv12)); 3250 continue; 3251 } 3252 3253 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("TLSv1.0"))) { 3254 buffer_append_string_len(plist, 3255 CONST_STR_LEN(suite_TLSv10)); 3256 continue; 3257 } 3258 3259 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("SSLv3"))) { 3260 buffer_append_string_len(plist, 3261 CONST_STR_LEN(suite_SSLv3)); 3262 continue; 3263 } 3264 3265 /* handle a popular recommendations 3266 * ssl.cipher-list = "EECDH+AESGCM:EDH+AESGCM" 3267 * ssl.cipher-list = "AES256+EECDH:AES256+EDH" 3268 * which uses AES hardware acceleration built into popular CPUs */ 3269 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("ECDHE+AESGCM")) 3270 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("EECDH+AESGCM"))) { 3271 buffer_append_string_len(plist, 3272 CONST_STR_LEN("+AES-256-GCM:+AES-128-GCM:")); 3273 continue; 3274 } 3275 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("DHE+AESGCM")) 3276 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("EDH+AESGCM"))) { 3277 buffer_append_string_len(plist, 3278 CONST_STR_LEN("+AES-256-GCM:+AES-128-GCM:")); 3279 continue; 3280 } 3281 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256+EECDH"))) { 3282 buffer_append_string_len(plist, 3283 CONST_STR_LEN("+AES-256-GCM:+AES-256-CCM:+AES-256-CBC:+AES-256-CCM-8:")); 3284 continue; 3285 } 3286 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256+EDH"))) { 3287 buffer_append_string_len(plist, 3288 CONST_STR_LEN("+AES-256-GCM:+AES-256-CCM:+AES-256-CBC:+AES-256-CCM-8:")); 3289 continue; 3290 } 3291 3292 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("HIGH"))) { 3293 buffer_append_string_len(plist, 3294 CONST_STR_LEN(suite_HIGH)); 3295 continue; 3296 } 3297 3298 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES256")) 3299 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES"))) { 3300 buffer_append_string_len(plist, 3301 CONST_STR_LEN("+AES-256-GCM:+AES-256-CCM:+AES-256-CBC:+AES-256-CCM-8:")); 3302 if (nlen == sizeof("AES256")-1) continue; 3303 } 3304 3305 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES128")) 3306 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("AES"))) { 3307 buffer_append_string_len(plist, 3308 CONST_STR_LEN("+AES-128-GCM:+AES-128-CCM:+AES-128-CBC:+AES-128-CCM-8:")); 3309 continue; 3310 } 3311 3312 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA256")) 3313 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA"))) { 3314 buffer_append_string_len(plist, 3315 CONST_STR_LEN("+CAMELLIA-256-GCM:+CAMELLIA-256-CBC:")); 3316 if (nlen == sizeof("CAMELLIA256")-1) continue; 3317 } 3318 3319 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA128")) 3320 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CAMELLIA"))) { 3321 buffer_append_string_len(plist, 3322 CONST_STR_LEN("+CAMELLIA-128-GCM:+CAMELLIA-128-CBC:")); 3323 continue; 3324 } 3325 3326 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("CHACHA20"))) { 3327 buffer_append_string_len(plist, 3328 CONST_STR_LEN("+CHACHA20-POLY1305:")); 3329 continue; 3330 } 3331 3332 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("3DES"))) { 3333 buffer_append_string_len(plist, 3334 CONST_STR_LEN("+3DES-CBC:")); 3335 continue; 3336 } 3337 3338 /* not recommended, but permitted if explicitly requested */ 3339 if (buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("NULL")) 3340 || buffer_eq_icase_ss(n, nlen, CONST_STR_LEN("eNULL"))) { 3341 buffer_append_string_len(plist, 3342 CONST_STR_LEN("+NULL:")); 3343 continue; 3344 } 3345 3346 { 3347 log_error(srv->errh, __FILE__, __LINE__, 3348 "GnuTLS: error: missing support for cipher list: %.*s", 3349 (int)len, p); 3350 rc = 0; 3351 continue; 3352 } 3353 } while (e); 3354 if (0 == rc) return 0; 3355 } 3356 3357 return 1; 3358 } 3359 3360 3361 static int 3362 mod_gnutls_ssl_conf_curves(server *srv, plugin_config_socket *s, const buffer *curvelist) 3363 { 3364 /* map NIST name (e.g. P-256) or OpenSSL OID name (e.g. prime256v1) 3365 * to GnuTLS name of supported curves/groups */ 3366 static const char *names[] = { 3367 "P-192", "CURVE-SECP192R1", 3368 "P-224", "CURVE-SECP224R1", 3369 "P-256", "GROUP-SECP256R1", /* CURVE-SECP256R1 */ 3370 "P-384", "GROUP-SECP384R1", /* CURVE-SECP384R1 */ 3371 "P-521", "GROUP-SECP521R1", /* CURVE-SECP521R1 */ 3372 "X25519", "GROUP-X25519", /* CURVE-X25519 */ 3373 "X448", "GROUP-X448", /* CURVE-X448 */ 3374 "prime192v1", "CURVE-SECP192R1", 3375 "secp224r1", "CURVE-SECP224R1", 3376 "prime256v1", "GROUP-SECP256R1", /* CURVE-SECP256R1 */ 3377 "secp384r1", "GROUP-SECP384R1", /* CURVE-SECP384R1 */ 3378 "secp521r1", "GROUP-SECP521R1", /* CURVE-SECP521R1 */ 3379 "ffdhe2048", "GROUP-FFDHE2048", 3380 "ffdhe3072", "GROUP-FFDHE3072", 3381 "ffdhe4096", "GROUP-FFDHE4096", 3382 "ffdhe6144", "GROUP-FFDHE6144", 3383 "ffdhe8192", "GROUP-FFDHE8192", 3384 }; 3385 3386 buffer * const plist = &s->priority_str; 3387 const buffer * const b = curvelist; 3388 for (const char *e = b->ptr-1; e; ) { 3389 const char * const n = e+1; 3390 e = strchr(n, ':'); 3391 size_t len = e ? (size_t)(e - n) : strlen(n); 3392 uint32_t i; 3393 for (i = 0; i < sizeof(names)/sizeof(*names)/2; i += 2) { 3394 if (0 == strncmp(names[i], n, len) && names[i][len] == '\0') 3395 break; 3396 } 3397 if (i == sizeof(names)/sizeof(*names)/2) { 3398 log_error(srv->errh, __FILE__, __LINE__, 3399 "GnuTLS: unrecognized curve: %.*s; ignored", (int)len, n); 3400 continue; 3401 } 3402 3403 buffer_append_string_len(plist, CONST_STR_LEN("+")); 3404 buffer_append_string_len(plist, names[i+1], strlen(names[i+1])); 3405 buffer_append_string_len(plist, CONST_STR_LEN(":")); 3406 } 3407 3408 return 1; 3409 } 3410 3411 3412 static int 3413 mod_gnutls_ssl_conf_proto_val (server *srv, plugin_config_socket *s, const buffer *b, int max) 3414 { 3415 if (NULL == b) /* default: min TLSv1.2, max TLSv1.3 */ 3416 return max ? GNUTLS_TLS1_3 : GNUTLS_TLS1_2; 3417 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("None"))) /*"disable" limit*/ 3418 return max 3419 ? GNUTLS_TLS1_3 3420 : (s->ssl_use_sslv3 ? GNUTLS_SSL3 : GNUTLS_TLS1_0); 3421 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("SSLv3"))) 3422 return GNUTLS_SSL3; 3423 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.0"))) 3424 return GNUTLS_TLS1_0; 3425 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.1"))) 3426 return GNUTLS_TLS1_1; 3427 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.2"))) 3428 return GNUTLS_TLS1_2; 3429 else if (buffer_eq_icase_slen(b, CONST_STR_LEN("TLSv1.3"))) 3430 return GNUTLS_TLS1_3; 3431 else { 3432 if (buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1")) 3433 || buffer_eq_icase_slen(b, CONST_STR_LEN("DTLSv1.2"))) 3434 log_error(srv->errh, __FILE__, __LINE__, 3435 "GnuTLS: ssl.openssl.ssl-conf-cmd %s %s ignored", 3436 max ? "MaxProtocol" : "MinProtocol", b->ptr); 3437 else 3438 log_error(srv->errh, __FILE__, __LINE__, 3439 "GnuTLS: ssl.openssl.ssl-conf-cmd %s %s invalid; ignored", 3440 max ? "MaxProtocol" : "MinProtocol", b->ptr); 3441 } 3442 return max ? GNUTLS_TLS1_3 : GNUTLS_TLS1_2; 3443 } 3444 3445 3446 static void 3447 mod_gnutls_ssl_conf_proto (server *srv, plugin_config_socket *s, const buffer *minb, const buffer *maxb) 3448 { 3449 /* use of SSL v3 should be avoided, and SSL v2 is not supported */ 3450 int n = mod_gnutls_ssl_conf_proto_val(srv, s, minb, 0); 3451 int x = mod_gnutls_ssl_conf_proto_val(srv, s, maxb, 1); 3452 if (n < 0) return; 3453 if (x < 0) return; 3454 buffer * const b = &s->priority_str; 3455 buffer_append_string_len(b, CONST_STR_LEN("-VERS-ALL:")); 3456 switch (n) { 3457 case GNUTLS_SSL3: 3458 buffer_append_string_len(b, CONST_STR_LEN("+VERS-SSL3.0:")); 3459 __attribute_fallthrough__ 3460 case GNUTLS_TLS1_0: 3461 if (x < GNUTLS_TLS1_0) break; 3462 buffer_append_string_len(b, CONST_STR_LEN("+VERS-TLS1.0:")); 3463 __attribute_fallthrough__ 3464 case GNUTLS_TLS1_1: 3465 if (x < GNUTLS_TLS1_1) break; 3466 buffer_append_string_len(b, CONST_STR_LEN("+VERS-TLS1.1:")); 3467 __attribute_fallthrough__ 3468 case GNUTLS_TLS1_2: 3469 if (x < GNUTLS_TLS1_2) break; 3470 buffer_append_string_len(b, CONST_STR_LEN("+VERS-TLS1.2:")); 3471 __attribute_fallthrough__ 3472 case GNUTLS_TLS1_3: 3473 if (x < GNUTLS_TLS1_3) break; 3474 buffer_append_string_len(b, CONST_STR_LEN("+VERS-TLS1.3:")); 3475 break; 3476 } 3477 } 3478