1 /* $NetBSD: tls_server.c,v 1.14 2026/05/09 18:49:21 christos Exp $ */ 2 3 /*++ 4 /* NAME 5 /* tls_server 3 6 /* SUMMARY 7 /* server-side TLS engine 8 /* SYNOPSIS 9 /* #include <tls.h> 10 /* 11 /* TLS_APPL_STATE *tls_server_init(props) 12 /* const TLS_SERVER_INIT_PROPS *props; 13 /* 14 /* TLS_SESS_STATE *tls_server_start(props) 15 /* const TLS_SERVER_START_PROPS *props; 16 /* 17 /* TLS_SESS_STATE *tls_server_post_accept(TLScontext) 18 /* TLS_SESS_STATE *TLScontext; 19 /* 20 /* void tls_server_stop(app_ctx, stream, failure, TLScontext) 21 /* TLS_APPL_STATE *app_ctx; 22 /* VSTREAM *stream; 23 /* int failure; 24 /* TLS_SESS_STATE *TLScontext; 25 /* DESCRIPTION 26 /* This module is the interface between Postfix TLS servers, 27 /* the OpenSSL library, and the TLS entropy and cache manager. 28 /* 29 /* See "EVENT_DRIVEN APPLICATIONS" below for using this code 30 /* in event-driven programs. 31 /* 32 /* tls_server_init() is called once when the SMTP server 33 /* initializes. 34 /* Certificate details are also decided during this phase, 35 /* so that peer-specific behavior is not possible. 36 /* 37 /* tls_server_start() activates the TLS feature for the VSTREAM 38 /* passed as argument. We assume that network buffers are flushed 39 /* and the TLS handshake can begin immediately. 40 /* 41 /* tls_server_stop() sends the "close notify" alert via 42 /* SSL_shutdown() to the peer and resets all connection specific 43 /* TLS data. As RFC2487 does not specify a separate shutdown, it 44 /* is assumed that the underlying TCP connection is shut down 45 /* immediately afterwards. Any further writes to the channel will 46 /* be discarded, and any further reads will report end-of-file. 47 /* If the failure flag is set, no SSL_shutdown() handshake is performed. 48 /* 49 /* Once the TLS connection is initiated, information about the TLS 50 /* state is available via the TLScontext structure: 51 /* .IP TLScontext->protocol 52 /* the protocol name (SSLv2, SSLv3, TLSv1), 53 /* .IP TLScontext->cipher_name 54 /* the cipher name (e.g. RC4/MD5), 55 /* .IP TLScontext->cipher_usebits 56 /* the number of bits actually used (e.g. 40), 57 /* .IP TLScontext->cipher_algbits 58 /* the number of bits the algorithm is based on (e.g. 128). 59 /* .PP 60 /* The last two values may differ from each other when export-strength 61 /* encryption is used. 62 /* 63 /* If the peer offered a certificate, part of the certificate data are 64 /* available as: 65 /* .IP TLScontext->peer_status 66 /* A bitmask field that records the status of the peer certificate 67 /* verification. One or more of TLS_CRED_FLAG_CERT, TLS_CRED_FLAG_RPK 68 /* and TLS_CERT_FLAG_TRUSTED. 69 /* .IP TLScontext->peer_CN 70 /* Extracted CommonName of the peer, or zero-length string 71 /* when information could not be extracted. 72 /* .IP TLScontext->issuer_CN 73 /* Extracted CommonName of the issuer, or zero-length string 74 /* when information could not be extracted. 75 /* .IP TLScontext->peer_cert_fprint 76 /* Fingerprint of the certificate, or zero-length string when no peer 77 /* certificate is available. 78 /* .PP 79 /* If no peer certificate is presented the peer_status is set to 0. 80 /* EVENT_DRIVEN APPLICATIONS 81 /* .ad 82 /* .fi 83 /* Event-driven programs manage multiple I/O channels. Such 84 /* programs cannot use the synchronous VSTREAM-over-TLS 85 /* implementation that the current TLS library provides, 86 /* including tls_server_stop() and the underlying tls_stream(3) 87 /* and tls_bio_ops(3) routines. 88 /* 89 /* With the current TLS library implementation, this means 90 /* that the application is responsible for calling and retrying 91 /* SSL_accept(), SSL_read(), SSL_write() and SSL_shutdown(). 92 /* 93 /* To maintain control over TLS I/O, an event-driven server 94 /* invokes tls_server_start() with a null VSTREAM argument and 95 /* with an fd argument that specifies the I/O file descriptor. 96 /* Then, tls_server_start() performs all the necessary 97 /* preparations before the TLS handshake and returns a partially 98 /* populated TLS context. The event-driven application is then 99 /* responsible for invoking SSL_accept(), and if successful, 100 /* for invoking tls_server_post_accept() to finish the work 101 /* that was started by tls_server_start(). In case of unrecoverable 102 /* failure, tls_server_post_accept() destroys the TLS context 103 /* and returns a null pointer value. 104 /* LICENSE 105 /* .ad 106 /* .fi 107 /* This software is free. You can do with it whatever you want. 108 /* The original author kindly requests that you acknowledge 109 /* the use of his software. 110 /* AUTHOR(S) 111 /* Originally written by: 112 /* Lutz Jaenicke 113 /* BTU Cottbus 114 /* Allgemeine Elektrotechnik 115 /* Universitaetsplatz 3-4 116 /* D-03044 Cottbus, Germany 117 /* 118 /* Updated by: 119 /* Wietse Venema 120 /* IBM T.J. Watson Research 121 /* P.O. Box 704 122 /* Yorktown Heights, NY 10598, USA 123 /* 124 /* Victor Duchovni 125 /* Morgan Stanley 126 /*--*/ 127 128 /* System library. */ 129 130 #include <sys_defs.h> 131 132 #ifdef USE_TLS 133 #include <unistd.h> 134 #include <string.h> 135 136 /* Utility library. */ 137 138 #include <mymalloc.h> 139 #include <vstring.h> 140 #include <vstream.h> 141 #include <dict.h> 142 #include <stringops.h> 143 #include <msg.h> 144 #include <hex_code.h> 145 #include <iostuff.h> /* non-blocking */ 146 147 /* Global library. */ 148 149 #include <mail_params.h> 150 151 /* TLS library. */ 152 153 #include <tls_mgr.h> 154 #define TLS_INTERNAL 155 #include <tls.h> 156 #if OPENSSL_VERSION_PREREQ(3,0) 157 #include <openssl/core_names.h> /* EVP_MAC parameters */ 158 #endif 159 160 #define STR(x) vstring_str(x) 161 #define LEN(x) VSTRING_LEN(x) 162 163 /* Application-specific. */ 164 165 /* 166 * The session_id_context identifies the service that created a session. 167 * This information is used to distinguish between multiple TLS-based 168 * servers running on the same server. We use the name of the mail system. 169 */ 170 static const char server_session_id_context[] = "Postfix/TLS"; 171 172 #ifndef OPENSSL_NO_TLSEXT 173 174 /* 175 * We retain the cipher handle for the lifetime of the process. 176 */ 177 static const EVP_CIPHER *tkt_cipher; 178 179 #endif 180 181 #define GET_SID(s, v, lptr) ((v) = SSL_SESSION_get_id((s), (lptr))) 182 183 typedef const unsigned char *session_id_t; 184 185 /* get_server_session_cb - callback to retrieve session from server cache */ 186 187 static SSL_SESSION *get_server_session_cb(SSL *ssl, session_id_t session_id, 188 int session_id_length, 189 int *unused_copy) 190 { 191 const char *myname = "get_server_session_cb"; 192 TLS_SESS_STATE *TLScontext; 193 VSTRING *cache_id; 194 VSTRING *session_data = vstring_alloc(2048); 195 SSL_SESSION *session = 0; 196 197 if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0) 198 msg_panic("%s: null TLScontext in session lookup callback", myname); 199 200 #define GEN_CACHE_ID(buf, id, len, service) \ 201 do { \ 202 buf = vstring_alloc(2 * (len + strlen(service))); \ 203 hex_encode(buf, (char *) (id), (len)); \ 204 vstring_sprintf_append(buf, "&s=%s", (service)); \ 205 vstring_sprintf_append(buf, "&l=%ld", (long) OpenSSL_version_num()); \ 206 } while (0) 207 208 209 GEN_CACHE_ID(cache_id, session_id, session_id_length, TLScontext->serverid); 210 211 if (TLScontext->log_mask & TLS_LOG_CACHE) 212 msg_info("%s: looking up session %s in %s cache", TLScontext->namaddr, 213 STR(cache_id), TLScontext->cache_type); 214 215 /* 216 * Load the session from cache and decode it. 217 */ 218 if (tls_mgr_lookup(TLScontext->cache_type, STR(cache_id), 219 session_data) == TLS_MGR_STAT_OK) { 220 session = tls_session_activate(STR(session_data), LEN(session_data)); 221 if (session && (TLScontext->log_mask & TLS_LOG_CACHE)) 222 msg_info("%s: reloaded session %s from %s cache", 223 TLScontext->namaddr, STR(cache_id), 224 TLScontext->cache_type); 225 } 226 227 /* 228 * Clean up. 229 */ 230 vstring_free(cache_id); 231 vstring_free(session_data); 232 233 return (session); 234 } 235 236 /* uncache_session - remove session from internal & external cache */ 237 238 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext) 239 { 240 VSTRING *cache_id; 241 SSL_SESSION *session = SSL_get_session(TLScontext->con); 242 const unsigned char *sid; 243 unsigned int sid_length; 244 245 SSL_CTX_remove_session(ctx, session); 246 247 if (TLScontext->cache_type == 0) 248 return; 249 250 GET_SID(session, sid, &sid_length); 251 GEN_CACHE_ID(cache_id, sid, sid_length, TLScontext->serverid); 252 253 if (TLScontext->log_mask & TLS_LOG_CACHE) 254 msg_info("%s: remove session %s from %s cache", TLScontext->namaddr, 255 STR(cache_id), TLScontext->cache_type); 256 257 tls_mgr_delete(TLScontext->cache_type, STR(cache_id)); 258 vstring_free(cache_id); 259 } 260 261 /* new_server_session_cb - callback to save session to server cache */ 262 263 static int new_server_session_cb(SSL *ssl, SSL_SESSION *session) 264 { 265 const char *myname = "new_server_session_cb"; 266 VSTRING *cache_id; 267 TLS_SESS_STATE *TLScontext; 268 VSTRING *session_data; 269 const unsigned char *sid; 270 unsigned int sid_length; 271 272 if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0) 273 msg_panic("%s: null TLScontext in new session callback", myname); 274 275 GET_SID(session, sid, &sid_length); 276 GEN_CACHE_ID(cache_id, sid, sid_length, TLScontext->serverid); 277 278 if (TLScontext->log_mask & TLS_LOG_CACHE) 279 msg_info("%s: save session %s to %s cache", TLScontext->namaddr, 280 STR(cache_id), TLScontext->cache_type); 281 282 /* 283 * Passivate and save the session state. 284 */ 285 session_data = tls_session_passivate(session); 286 if (session_data) 287 tls_mgr_update(TLScontext->cache_type, STR(cache_id), 288 STR(session_data), LEN(session_data)); 289 290 /* 291 * Clean up. 292 */ 293 if (session_data) 294 vstring_free(session_data); 295 vstring_free(cache_id); 296 SSL_SESSION_free(session); /* 200502 */ 297 298 return (1); 299 } 300 301 #define NOENGINE ((ENGINE *) 0) 302 #define TLS_TKT_NOKEYS -1 /* No keys for encryption */ 303 #define TLS_TKT_STALE 0 /* No matching keys for decryption */ 304 #define TLS_TKT_ACCEPT 1 /* Ticket decryptable and re-usable */ 305 #define TLS_TKT_REISSUE 2 /* Ticket decryptable, not re-usable */ 306 307 #if !defined(OPENSSL_NO_TLSEXT) 308 309 #if OPENSSL_VERSION_PREREQ(3,0) 310 311 /* ticket_cb - configure tls session ticket encrypt/decrypt context */ 312 313 static int ticket_cb(SSL *con, unsigned char name[], unsigned char iv[], 314 EVP_CIPHER_CTX *ctx, EVP_MAC_CTX *hctx, int create) 315 { 316 OSSL_PARAM params[3]; 317 TLS_TICKET_KEY *key; 318 TLS_SESS_STATE *TLScontext = SSL_get_ex_data(con, TLScontext_index); 319 int timeout = ((int) SSL_CTX_get_timeout(SSL_get_SSL_CTX(con))) / 2; 320 321 if ((key = tls_mgr_key(create ? 0 : name, timeout)) == 0 322 || (create && RAND_bytes(iv, TLS_TICKET_IVLEN) <= 0)) 323 return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE); 324 325 params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, 326 LN_sha256, 0); 327 params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, 328 (char *) key->hmac, 329 TLS_TICKET_MACLEN); 330 params[2] = OSSL_PARAM_construct_end(); 331 if (!EVP_MAC_CTX_set_params(hctx, params)) 332 return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE); 333 334 if (create) { 335 EVP_EncryptInit_ex(ctx, tkt_cipher, NOENGINE, key->bits, iv); 336 memcpy((void *) name, (void *) key->name, TLS_TICKET_NAMELEN); 337 if (TLScontext->log_mask & TLS_LOG_CACHE) 338 msg_info("%s: Issuing session ticket, key expiration: %ld", 339 TLScontext->namaddr, (long) key->tout); 340 } else { 341 EVP_DecryptInit_ex(ctx, tkt_cipher, NOENGINE, key->bits, iv); 342 if (TLScontext->log_mask & TLS_LOG_CACHE) 343 msg_info("%s: Decrypting session ticket, key expiration: %ld", 344 TLScontext->namaddr, (long) key->tout); 345 TLScontext->ticketed = 1; 346 } 347 return (TLS_TKT_ACCEPT); 348 } 349 350 #else /* OPENSSL_VERSION_PREREQ(3,0) */ 351 352 /* ticket_cb - configure tls session ticket encrypt/decrypt context */ 353 354 static int ticket_cb(SSL *con, unsigned char name[], unsigned char iv[], 355 EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int create) 356 { 357 static const EVP_MD *sha256; 358 TLS_TICKET_KEY *key; 359 TLS_SESS_STATE *TLScontext = SSL_get_ex_data(con, TLScontext_index); 360 int timeout = ((int) SSL_CTX_get_timeout(SSL_get_SSL_CTX(con))) / 2; 361 362 if ((!sha256 && (sha256 = EVP_sha256()) == 0) 363 || (key = tls_mgr_key(create ? 0 : name, timeout)) == 0 364 || (create && RAND_bytes(iv, TLS_TICKET_IVLEN) <= 0)) 365 return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE); 366 367 HMAC_Init_ex(hctx, key->hmac, TLS_TICKET_MACLEN, sha256, NOENGINE); 368 369 if (create) { 370 EVP_EncryptInit_ex(ctx, tkt_cipher, NOENGINE, key->bits, iv); 371 memcpy((void *) name, (void *) key->name, TLS_TICKET_NAMELEN); 372 if (TLScontext->log_mask & TLS_LOG_CACHE) 373 msg_info("%s: Issuing session ticket, key expiration: %ld", 374 TLScontext->namaddr, (long) key->tout); 375 } else { 376 EVP_DecryptInit_ex(ctx, tkt_cipher, NOENGINE, key->bits, iv); 377 if (TLScontext->log_mask & TLS_LOG_CACHE) 378 msg_info("%s: Decrypting session ticket, key expiration: %ld", 379 TLScontext->namaddr, (long) key->tout); 380 TLScontext->ticketed = 1; 381 } 382 return (TLS_TKT_ACCEPT); 383 } 384 385 #endif /* OPENSSL_VERSION_PREREQ(3,0) */ 386 387 #endif /* defined(SSL_OP_NO_TICKET) && 388 * !defined(OPENSSL_NO_TLSEXT) */ 389 390 /* tls_server_init - initialize the server-side TLS engine */ 391 392 TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props) 393 { 394 SSL_CTX *server_ctx; 395 SSL_CTX *sni_ctx; 396 X509_STORE *cert_store; 397 long off = 0; 398 int verify_flags = SSL_VERIFY_NONE; 399 int cachable; 400 int scache_timeout; 401 int ticketable = 0; 402 int protomask; 403 int min_proto; 404 int max_proto; 405 TLS_APPL_STATE *app_ctx; 406 int log_mask; 407 408 /* 409 * Convert user loglevel to internal logmask. 410 */ 411 log_mask = tls_log_mask(props->log_param, props->log_level); 412 413 if (log_mask & TLS_LOG_VERBOSE) 414 msg_info("initializing the server-side TLS engine"); 415 416 /* 417 * Load (mostly cipher related) TLS-library internal main.cf parameters. 418 */ 419 tls_param_init(); 420 421 /* 422 * Detect mismatch between compile-time headers and run-time library. 423 */ 424 tls_check_version(); 425 426 /* 427 * Initialize the OpenSSL library, possibly loading its configuration 428 * file. 429 */ 430 if (tls_library_init() == 0) 431 return (0); 432 433 /* 434 * First validate the protocols. If these are invalid, we can't continue. 435 */ 436 protomask = tls_proto_mask_lims(props->protocols, &min_proto, &max_proto); 437 if (protomask == TLS_PROTOCOL_INVALID) { 438 /* tls_protocol_mask() logs no warning. */ 439 msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support", 440 props->protocols); 441 return (0); 442 } 443 444 /* 445 * Create an application data index for SSL objects, so that we can 446 * attach TLScontext information; this information is needed inside 447 * tls_verify_certificate_callback(). 448 */ 449 if (TLScontext_index < 0) { 450 if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) { 451 msg_warn("Cannot allocate SSL application data index: " 452 "disabling TLS support"); 453 return (0); 454 } 455 } 456 457 /* 458 * If the administrator specifies an unsupported digest algorithm, fail 459 * now, rather than in the middle of a TLS handshake. 460 */ 461 if (!tls_validate_digest(props->mdalg)) { 462 msg_warn("disabling TLS support"); 463 return (0); 464 } 465 466 /* 467 * Initialize the PRNG (Pseudo Random Number Generator) with some seed 468 * from external and internal sources. Don't enable TLS without some real 469 * entropy. 470 */ 471 if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) { 472 msg_warn("no entropy for TLS key generation: disabling TLS support"); 473 return (0); 474 } 475 tls_int_seed(); 476 477 /* 478 * The SSL/TLS specifications require the client to send a message in the 479 * oldest specification it understands with the highest level it 480 * understands in the message. Netscape communicator can still 481 * communicate with SSLv2 servers, so it sends out a SSLv2 client hello. 482 * To deal with it, our server must be SSLv2 aware (even if we don't like 483 * SSLv2), so we need to have the SSLv23 server here. If we want to limit 484 * the protocol level, we can add an option to not use SSLv2/v3/TLSv1 485 * later. 486 */ 487 ERR_clear_error(); 488 server_ctx = SSL_CTX_new(TLS_server_method()); 489 if (server_ctx == 0) { 490 msg_warn("cannot allocate server SSL_CTX: disabling TLS support"); 491 tls_print_errors(); 492 return (0); 493 } 494 sni_ctx = SSL_CTX_new(TLS_server_method()); 495 if (sni_ctx == 0) { 496 SSL_CTX_free(server_ctx); 497 msg_warn("cannot allocate server SNI SSL_CTX: disabling TLS support"); 498 tls_print_errors(); 499 return (0); 500 } 501 #ifdef SSL_SECOP_PEER 502 /* Backwards compatible security as a base for opportunistic TLS. */ 503 SSL_CTX_set_security_level(server_ctx, 0); 504 SSL_CTX_set_security_level(sni_ctx, 0); 505 #endif 506 507 /* 508 * See the verify callback in tls_verify.c 509 */ 510 SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1); 511 SSL_CTX_set_verify_depth(sni_ctx, props->verifydepth + 1); 512 513 /* 514 * The session cache is implemented by the tlsmgr(8) server. 515 * 516 * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory 517 * cache, it also attempts to purge the entry from the on-disk cache. 518 * This is undesirable, especially when we set the in-memory cache size 519 * to 1. For this reason we don't allow OpenSSL to purge on-disk cache 520 * entries, and leave it up to the tlsmgr process instead. Found by 521 * Victor Duchovni. 522 */ 523 if (tls_mgr_policy(props->cache_type, &cachable, 524 &scache_timeout) != TLS_MGR_STAT_OK) 525 scache_timeout = 0; 526 if (scache_timeout <= 0) 527 cachable = 0; 528 529 /* 530 * Presently we use TLS only with SMTP where truncation attacks are not 531 * possible as a result of application framing. If we ever use TLS in 532 * some other application protocol where truncation could be relevant, 533 * we'd need to disable truncation detection conditionally, or explicitly 534 * clear the option in that code path. 535 */ 536 off |= SSL_OP_IGNORE_UNEXPECTED_EOF; 537 538 /* 539 * Protocol work-arounds, OpenSSL version dependent. 540 */ 541 off |= tls_bug_bits(); 542 543 /* 544 * Add SSL_OP_NO_TICKET when the timeout is zero or library support is 545 * incomplete. 546 */ 547 #ifndef OPENSSL_NO_TLSEXT 548 ticketable = (*var_tls_tkt_cipher && scache_timeout > 0 549 && !(off & SSL_OP_NO_TICKET)); 550 if (ticketable) { 551 #if OPENSSL_VERSION_PREREQ(3,0) 552 tkt_cipher = EVP_CIPHER_fetch(NULL, var_tls_tkt_cipher, NULL); 553 #else 554 tkt_cipher = EVP_get_cipherbyname(var_tls_tkt_cipher); 555 #endif 556 if (tkt_cipher == 0 557 || EVP_CIPHER_mode(tkt_cipher) != EVP_CIPH_CBC_MODE 558 || EVP_CIPHER_iv_length(tkt_cipher) != TLS_TICKET_IVLEN 559 || EVP_CIPHER_key_length(tkt_cipher) < TLS_TICKET_IVLEN 560 || EVP_CIPHER_key_length(tkt_cipher) > TLS_TICKET_KEYLEN) { 561 msg_warn("%s: invalid value: %s; session tickets disabled", 562 VAR_TLS_TKT_CIPHER, var_tls_tkt_cipher); 563 ticketable = 0; 564 } 565 } 566 if (ticketable) { 567 #if OPENSSL_VERSION_PREREQ(3,0) 568 SSL_CTX_set_tlsext_ticket_key_evp_cb(server_ctx, ticket_cb); 569 #else 570 SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_cb); 571 #endif 572 573 /* 574 * OpenSSL 1.1.1 introduces support for TLS 1.3, which can issue more 575 * than one ticket per handshake. While this may be appropriate for 576 * communication between browsers and webservers, it is not terribly 577 * useful for MTAs, many of which other than Postfix don't do TLS 578 * session caching at all, and Postfix has no mechanism for storing 579 * multiple session tickets, if more than one sent, the second 580 * clobbers the first. OpenSSL 1.1.1 servers default to issuing two 581 * tickets for non-resumption handshakes, we reduce this to one. Our 582 * ticket decryption callback already (since 2.11) asks OpenSSL to 583 * avoid issuing new tickets when the presented ticket is re-usable. 584 */ 585 SSL_CTX_set_num_tickets(server_ctx, 1); 586 } 587 #endif 588 if (!ticketable) 589 off |= SSL_OP_NO_TICKET; 590 591 SSL_CTX_set_options(server_ctx, off); 592 593 /* 594 * Global protocol selection. 595 */ 596 if (protomask != 0) 597 SSL_CTX_set_options(server_ctx, TLS_SSL_OP_PROTOMASK(protomask)); 598 SSL_CTX_set_min_proto_version(server_ctx, min_proto); 599 SSL_CTX_set_max_proto_version(server_ctx, max_proto); 600 SSL_CTX_set_min_proto_version(sni_ctx, min_proto); 601 SSL_CTX_set_max_proto_version(sni_ctx, max_proto); 602 603 /* 604 * Some sites may want to give the client less rope. On the other hand, 605 * this could trigger inter-operability issues, the client should not 606 * offer ciphers it implements poorly, but this hasn't stopped some 607 * vendors from getting it wrong. 608 */ 609 if (var_tls_preempt_clist) 610 SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); 611 612 /* Done with server_ctx options, clone to sni_ctx */ 613 SSL_CTX_clear_options(sni_ctx, ~0); 614 SSL_CTX_set_options(sni_ctx, SSL_CTX_get_options(server_ctx)); 615 616 /* 617 * Set the call-back routine to debug handshake progress. 618 */ 619 if (log_mask & TLS_LOG_DEBUG) { 620 SSL_CTX_set_info_callback(server_ctx, tls_info_callback); 621 SSL_CTX_set_info_callback(sni_ctx, tls_info_callback); 622 } 623 624 /* 625 * Load the CA public key certificates for both the server cert and for 626 * the verification of client certificates. As provided by OpenSSL we 627 * support two types of CA certificate handling: One possibility is to 628 * add all CA certificates to one large CAfile, the other possibility is 629 * a directory pointed to by CApath, containing separate files for each 630 * CA with softlinks named after the hash values of the certificate. The 631 * first alternative has the advantage that the file is opened and read 632 * at startup time, so that you don't have the hassle to maintain another 633 * copy of the CApath directory for chroot-jail. 634 */ 635 if (tls_set_ca_certificate_info(server_ctx, 636 props->CAfile, props->CApath) < 0) { 637 /* tls_set_ca_certificate_info() already logs a warning. */ 638 SSL_CTX_free(server_ctx); /* 200411 */ 639 SSL_CTX_free(sni_ctx); 640 return (0); 641 } 642 643 /* 644 * Always support server->client raw public keys, if they're good enough 645 * for the client, they're good enough for us. 646 */ 647 tls_enable_server_rpk(server_ctx, NULL); 648 tls_enable_server_rpk(sni_ctx, NULL); 649 650 /* 651 * Upref and share the cert store. Sadly we can't yet use 652 * SSL_CTX_set1_cert_store(3) which was added in OpenSSL 1.1.0. 653 */ 654 cert_store = SSL_CTX_get_cert_store(server_ctx); 655 X509_STORE_up_ref(cert_store); 656 SSL_CTX_set_cert_store(sni_ctx, cert_store); 657 658 /* 659 * Load the server public key certificate and private key from file and 660 * check whether the cert matches the key. We can use RSA certificates 661 * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert"). 662 * All three can be made available at the same time. The CA certificates 663 * for all three are handled in the same setup already finished. Which 664 * one is used depends on the cipher negotiated (that is: the first 665 * cipher listed by the client which does match the server). A client 666 * with RSA only (e.g. Netscape) will use the RSA certificate only. A 667 * client with openssl-library will use RSA first if not especially 668 * changed in the cipher setup. 669 */ 670 if (tls_set_my_certificate_key_info(server_ctx, 671 props->chain_files, 672 props->cert_file, 673 props->key_file, 674 props->dcert_file, 675 props->dkey_file, 676 props->eccert_file, 677 props->eckey_file) < 0) { 678 /* tls_set_my_certificate_key_info() already logs a warning. */ 679 SSL_CTX_free(server_ctx); /* 200411 */ 680 SSL_CTX_free(sni_ctx); 681 return (0); 682 } 683 684 /* 685 * Diffie-Hellman key generation parameters can either be loaded from 686 * files (preferred) or taken from compiled in values. First, set the 687 * callback that will select the values when requested, then load the 688 * (possibly) available DH parameters from files. We are generous with 689 * the error handling, since we do have default values compiled in, so we 690 * will not abort but just log the error message. 691 */ 692 if (*props->dh1024_param_file != 0) 693 tls_set_dh_from_file(props->dh1024_param_file); 694 tls_tmp_dh(server_ctx, 1); 695 tls_tmp_dh(sni_ctx, 1); 696 697 /* 698 * Enable EECDH if available, errors are not fatal, we just keep going 699 * with any remaining key-exchange algorithms. With OpenSSL 3.0 and TLS 700 * 1.3, the same applies to the FFDHE groups which become part of a 701 * unified "groups" list. 702 */ 703 tls_auto_groups(server_ctx, var_tls_eecdh_auto, var_tls_ffdhe_auto); 704 tls_auto_groups(sni_ctx, var_tls_eecdh_auto, var_tls_ffdhe_auto); 705 706 /* 707 * If we want to check client certificates, we have to indicate it in 708 * advance. By now we only allow to decide on a global basis. If we want 709 * to allow certificate based relaying, we must ask the client to provide 710 * one with SSL_VERIFY_PEER. The client now can decide, whether it 711 * provides one or not. We can enforce a failure of the negotiation with 712 * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection 713 * without one. In the "server hello" following the initialization by the 714 * "client hello" the server must provide a list of CAs it is willing to 715 * accept. Some clever clients will then select one from the list of 716 * available certificates matching these CAs. Netscape Communicator will 717 * present the list of certificates for selecting the one to be sent, or 718 * it will issue a warning, if there is no certificate matching the 719 * available CAs. 720 * 721 * With regard to the purpose of the certificate for relaying, we might like 722 * a later negotiation, maybe relaying would already be allowed for other 723 * reasons, but this would involve severe changes in the internal postfix 724 * logic, so we have to live with it the way it is. 725 */ 726 if (props->ask_ccert) 727 verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; 728 SSL_CTX_set_verify(server_ctx, verify_flags, 729 tls_verify_certificate_callback); 730 SSL_CTX_set_verify(sni_ctx, verify_flags, 731 tls_verify_certificate_callback); 732 if (props->ask_ccert && *props->CAfile) { 733 STACK_OF(X509_NAME) *calist = SSL_load_client_CA_file(props->CAfile); 734 735 if (calist == 0) { 736 /* Not generally critical */ 737 msg_warn("error loading client CA names from: %s", 738 props->CAfile); 739 tls_print_errors(); 740 } 741 SSL_CTX_set_client_CA_list(server_ctx, calist); 742 743 if (calist != 0 && sk_X509_NAME_num(calist) > 0) { 744 calist = SSL_dup_CA_list(calist); 745 746 if (calist == 0) { 747 msg_warn("error duplicating client CA names for SNI"); 748 tls_print_errors(); 749 } else { 750 SSL_CTX_set_client_CA_list(sni_ctx, calist); 751 } 752 } 753 } 754 755 /* 756 * Initialize our own TLS server handle, before diving into the details 757 * of TLS session cache management. 758 */ 759 app_ctx = tls_alloc_app_context(server_ctx, sni_ctx, log_mask); 760 761 if (cachable || ticketable || props->set_sessid) { 762 763 /* 764 * Initialize the session cache. 765 * 766 * With a large number of concurrent smtpd(8) processes, it is not a 767 * good idea to cache multiple large session objects in each process. 768 * We set the internal cache size to 1, and don't register a 769 * "remove_cb" so as to avoid deleting good sessions from the 770 * external cache prematurely (when the internal cache is full, 771 * OpenSSL removes sessions from the external cache also)! 772 * 773 * This makes SSL_CTX_remove_session() not useful for flushing broken 774 * sessions from the external cache, so we must delete them directly 775 * (not via a callback). 776 * 777 * Set a session id context to identify to what type of server process 778 * created a session. In our case, the context is simply the name of 779 * the mail system: "Postfix/TLS". 780 */ 781 SSL_CTX_sess_set_cache_size(server_ctx, 1); 782 SSL_CTX_set_session_id_context(server_ctx, 783 (void *) &server_session_id_context, 784 sizeof(server_session_id_context)); 785 SSL_CTX_set_session_cache_mode(server_ctx, 786 SSL_SESS_CACHE_SERVER | 787 SSL_SESS_CACHE_NO_INTERNAL | 788 SSL_SESS_CACHE_NO_AUTO_CLEAR); 789 if (cachable) { 790 app_ctx->cache_type = mystrdup(props->cache_type); 791 792 SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb); 793 SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb); 794 } 795 796 /* 797 * OpenSSL ignores timed-out sessions. We need to set the internal 798 * cache timeout at least as high as the external cache timeout. This 799 * applies even if no internal cache is used. We set the session 800 * lifetime to twice the cache lifetime, which is also the issuing 801 * and retired key validation lifetime of session tickets keys. This 802 * way a session always lasts longer than the server's ability to 803 * decrypt its session ticket. Otherwise, a bug in OpenSSL may fail 804 * to re-issue tickets when sessions decrypt, but are expired. 805 */ 806 SSL_CTX_set_timeout(server_ctx, 2 * scache_timeout); 807 } else { 808 809 /* 810 * If we have no external cache, disable all caching. No use wasting 811 * server memory resources with sessions they are unlikely to be able 812 * to reuse. 813 */ 814 SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF); 815 } 816 817 return (app_ctx); 818 } 819 820 /* 821 * This is the actual startup routine for a new connection. We expect that 822 * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to 823 * the client, so that we can immediately start the TLS handshake process. 824 */ 825 TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props) 826 { 827 int sts; 828 TLS_SESS_STATE *TLScontext; 829 const char *cipher_list; 830 TLS_APPL_STATE *app_ctx = props->ctx; 831 int log_mask = app_ctx->log_mask; 832 833 /* 834 * Implicitly enable logging of trust chain errors when verified certs 835 * are required. 836 */ 837 if (props->requirecert) 838 log_mask |= TLS_LOG_UNTRUSTED; 839 840 if (log_mask & TLS_LOG_VERBOSE) 841 msg_info("setting up TLS connection from %s", props->namaddr); 842 843 /* 844 * Allocate a new TLScontext for the new connection and get an SSL 845 * structure. Add the location of TLScontext to the SSL to later retrieve 846 * the information inside the tls_verify_certificate_callback(). 847 */ 848 TLScontext = tls_alloc_sess_context(log_mask, props->namaddr); 849 TLScontext->cache_type = app_ctx->cache_type; 850 851 ERR_clear_error(); 852 if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) { 853 msg_warn("Could not allocate 'TLScontext->con' with SSL_new()"); 854 tls_print_errors(); 855 tls_free_context(TLScontext); 856 return (0); 857 } 858 cipher_list = tls_set_ciphers(TLScontext, props->cipher_grade, 859 props->cipher_exclusions); 860 if (cipher_list == 0) { 861 /* already warned */ 862 tls_free_context(TLScontext); 863 return (0); 864 } 865 if (log_mask & TLS_LOG_VERBOSE) 866 msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list); 867 868 TLScontext->serverid = mystrdup(props->serverid); 869 TLScontext->am_server = 1; 870 TLScontext->stream = props->stream; 871 TLScontext->mdalg = props->mdalg; 872 873 if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) { 874 msg_warn("Could not set application data for 'TLScontext->con'"); 875 tls_print_errors(); 876 tls_free_context(TLScontext); 877 return (0); 878 } 879 880 /* 881 * When encryption is mandatory use the 80-bit plus OpenSSL security 882 * level. 883 */ 884 if (props->requirecert) 885 SSL_set_security_level(TLScontext->con, 1); 886 887 /* 888 * Also enable client->server raw public keys, provided we're not 889 * interested in client certificate fingerprints. 890 */ 891 if (props->enable_rpk) 892 tls_enable_client_rpk(NULL, TLScontext->con); 893 894 /* 895 * Before really starting anything, try to seed the PRNG a little bit 896 * more. 897 */ 898 tls_int_seed(); 899 (void) tls_ext_seed(var_tls_daemon_rand_bytes); 900 901 /* 902 * Connect the SSL connection with the network socket. 903 */ 904 if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd : 905 vstream_fileno(props->stream)) != 1) { 906 msg_info("SSL_set_fd error to %s", props->namaddr); 907 tls_print_errors(); 908 uncache_session(app_ctx->ssl_ctx, TLScontext); 909 tls_free_context(TLScontext); 910 return (0); 911 } 912 913 /* 914 * If the debug level selected is high enough, all of the data is dumped: 915 * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will 916 * dump everything. 917 * 918 * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called? 919 * Well there is a BIO below the SSL routines that is automatically 920 * created for us, so we can use it for debugging purposes. 921 */ 922 if (log_mask & TLS_LOG_TLSPKTS) 923 tls_set_bio_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb); 924 925 /* 926 * If we don't trigger the handshake in the library, leave control over 927 * SSL_accept/read/write/etc with the application. 928 */ 929 if (props->stream == 0) 930 return (TLScontext); 931 932 /* 933 * Turn on non-blocking I/O so that we can enforce timeouts on network 934 * I/O. 935 */ 936 non_blocking(vstream_fileno(props->stream), NON_BLOCKING); 937 938 /* 939 * Start TLS negotiations. This process is a black box that invokes our 940 * call-backs for session caching and certificate verification. 941 * 942 * Error handling: If the SSL handshake fails, we print out an error message 943 * and remove all TLS state concerning this session. 944 */ 945 sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout, 946 TLScontext); 947 if (sts <= 0) { 948 if (ERR_peek_error() != 0) { 949 msg_info("SSL_accept error from %s: %d", props->namaddr, sts); 950 tls_print_errors(); 951 } else if (errno != 0) { 952 msg_info("SSL_accept error from %s: %m", props->namaddr); 953 } else { 954 msg_info("SSL_accept error from %s: lost connection", 955 props->namaddr); 956 } 957 tls_free_context(TLScontext); 958 return (0); 959 } 960 return (tls_server_post_accept(TLScontext)); 961 } 962 963 /* tls_server_post_accept - post-handshake processing */ 964 965 TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext) 966 { 967 const SSL_CIPHER *cipher; 968 X509 *peer; 969 EVP_PKEY *pkey = 0; 970 char buf[CCERT_BUFSIZ]; 971 972 /* Turn off packet dump if only dumping the handshake */ 973 if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0) 974 tls_set_bio_callback(SSL_get_rbio(TLScontext->con), 0); 975 976 /* 977 * The caller may want to know if this session was reused or if a new 978 * session was negotiated. 979 */ 980 TLScontext->session_reused = SSL_session_reused(TLScontext->con); 981 if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused) 982 msg_info("%s: Reusing old session%s", TLScontext->namaddr, 983 TLScontext->ticketed ? " (RFC 5077 session ticket)" : ""); 984 985 /* 986 * Let's see whether a peer certificate is available and what is the 987 * actual information. We want to save it for later use. 988 */ 989 peer = TLS_PEEK_PEER_CERT(TLScontext->con); 990 if (peer) { 991 pkey = X509_get0_pubkey(peer); 992 } 993 #if OPENSSL_VERSION_PREREQ(3,2) 994 else { 995 pkey = SSL_get0_peer_rpk(TLScontext->con); 996 } 997 #endif 998 999 if (peer != NULL) { 1000 TLScontext->peer_status |= TLS_CRED_FLAG_CERT; 1001 if (SSL_get_verify_result(TLScontext->con) == X509_V_OK) 1002 TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED; 1003 1004 if (TLScontext->log_mask & TLS_LOG_VERBOSE) { 1005 X509_NAME_oneline(X509_get_subject_name(peer), 1006 buf, sizeof(buf)); 1007 msg_info("subject=%s", printable(buf, '?')); 1008 X509_NAME_oneline(X509_get_issuer_name(peer), 1009 buf, sizeof(buf)); 1010 msg_info("issuer=%s", printable(buf, '?')); 1011 } 1012 TLScontext->peer_CN = tls_peer_CN(peer, TLScontext); 1013 TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext); 1014 TLScontext->peer_cert_fprint = 1015 tls_cert_fprint(peer, TLScontext->mdalg); 1016 TLScontext->peer_pkey_fprint = 1017 tls_pkey_fprint(pkey, TLScontext->mdalg); 1018 1019 if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) { 1020 msg_info("%s: subject_CN=%s, issuer=%s%s%s%s%s", 1021 TLScontext->namaddr, 1022 TLScontext->peer_CN, TLScontext->issuer_CN, 1023 *TLScontext->peer_cert_fprint ? 1024 ", cert fingerprint=" : "", 1025 *TLScontext->peer_cert_fprint ? 1026 TLScontext->peer_cert_fprint : "", 1027 *TLScontext->peer_pkey_fprint ? 1028 ", pkey fingerprint=" : "", 1029 *TLScontext->peer_pkey_fprint ? 1030 TLScontext->peer_pkey_fprint : ""); 1031 } 1032 TLS_FREE_PEER_CERT(peer); 1033 1034 /* 1035 * Give them a clue. Problems with trust chain verification are 1036 * logged when the session is first negotiated, before the session is 1037 * stored into the cache. We don't want mystery failures, so log the 1038 * fact the real problem is to be found in the past. 1039 */ 1040 if (!TLS_CERT_IS_TRUSTED(TLScontext) 1041 && (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) { 1042 if (TLScontext->session_reused == 0) 1043 tls_log_verify_error(TLScontext, (struct TLSRPT_WRAPPER *) 0); 1044 else 1045 msg_info("%s: re-using session with untrusted certificate, " 1046 "look for details earlier in the log", 1047 TLScontext->namaddr); 1048 } 1049 } else { 1050 TLScontext->peer_CN = mystrdup(""); 1051 TLScontext->issuer_CN = mystrdup(""); 1052 TLScontext->peer_cert_fprint = mystrdup(""); 1053 if (!pkey) { 1054 TLScontext->peer_pkey_fprint = mystrdup(""); 1055 } else { 1056 1057 /* 1058 * Raw public keys don't involve CA trust, and we don't have a 1059 * way to associate DANE TLSA RRs with clients just yet, we just 1060 * make the fingerprint available to the access(5) layer. 1061 */ 1062 TLScontext->peer_status |= TLS_CRED_FLAG_RPK; 1063 TLScontext->peer_pkey_fprint = 1064 tls_pkey_fprint(pkey, TLScontext->mdalg); 1065 if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) 1066 msg_info("%s: raw public key fingerprint=%s", 1067 TLScontext->namaddr, TLScontext->peer_pkey_fprint); 1068 } 1069 } 1070 1071 /* 1072 * Finally, collect information about protocol and cipher for logging 1073 */ 1074 TLScontext->protocol = SSL_get_version(TLScontext->con); 1075 cipher = SSL_get_current_cipher(TLScontext->con); 1076 TLScontext->cipher_name = SSL_CIPHER_get_name(cipher); 1077 TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher, 1078 &(TLScontext->cipher_algbits)); 1079 1080 /* 1081 * If the library triggered the SSL handshake, switch to the 1082 * tls_timed_read/write() functions and make the TLScontext available to 1083 * those functions. Otherwise, leave control over SSL_read/write/etc. 1084 * with the application. 1085 */ 1086 if (TLScontext->stream != 0) 1087 tls_stream_start(TLScontext->stream, TLScontext); 1088 1089 /* 1090 * With the handshake done, extract TLS 1.3 signature metadata. 1091 */ 1092 tls_get_signature_params(TLScontext); 1093 1094 /* 1095 * All the key facts in a single log entry. 1096 */ 1097 if (TLScontext->log_mask & TLS_LOG_SUMMARY) 1098 tls_log_summary(TLS_ROLE_SERVER, TLS_USAGE_NEW, TLScontext); 1099 1100 tls_int_seed(); 1101 1102 return (TLScontext); 1103 } 1104 1105 #endif /* USE_TLS */ 1106