1 /* $NetBSD: tls_client.c,v 1.11 2020/03/18 19:05:21 christos Exp $ */ 2 3 /*++ 4 /* NAME 5 /* tls_client 6 /* SUMMARY 7 /* client-side TLS engine 8 /* SYNOPSIS 9 /* #include <tls.h> 10 /* 11 /* TLS_APPL_STATE *tls_client_init(init_props) 12 /* const TLS_CLIENT_INIT_PROPS *init_props; 13 /* 14 /* TLS_SESS_STATE *tls_client_start(start_props) 15 /* const TLS_CLIENT_START_PROPS *start_props; 16 /* 17 /* TLS_SESS_STATE *tls_client_post_connect(TLScontext, start_props) 18 /* TLS_SESS_STATE *TLScontext; 19 /* const TLS_CLIENT_START_PROPS *start_props; 20 /* 21 /* void tls_client_stop(app_ctx, stream, failure, TLScontext) 22 /* TLS_APPL_STATE *app_ctx; 23 /* VSTREAM *stream; 24 /* int failure; 25 /* TLS_SESS_STATE *TLScontext; 26 /* DESCRIPTION 27 /* This module is the interface between Postfix TLS clients, 28 /* the OpenSSL library and the TLS entropy and cache manager. 29 /* 30 /* The SMTP client will attempt to verify the server hostname 31 /* against the names listed in the server certificate. When 32 /* a hostname match is required, the verification fails 33 /* on certificate verification or hostname mis-match errors. 34 /* When no hostname match is required, hostname verification 35 /* failures are logged but they do not affect the TLS handshake 36 /* or the SMTP session. 37 /* 38 /* The rules for peer name wild-card matching differ between 39 /* RFC 2818 (HTTP over TLS) and RFC 2830 (LDAP over TLS), while 40 /* RFC RFC3207 (SMTP over TLS) does not specify a rule at all. 41 /* Postfix uses a restrictive match algorithm. One asterisk 42 /* ('*') is allowed as the left-most component of a wild-card 43 /* certificate name; it matches the left-most component of 44 /* the peer hostname. 45 /* 46 /* Another area where RFCs aren't always explicit is the 47 /* handling of dNSNames in peer certificates. RFC 3207 (SMTP 48 /* over TLS) does not mention dNSNames. Postfix follows the 49 /* strict rules in RFC 2818 (HTTP over TLS), section 3.1: The 50 /* Subject Alternative Name/dNSName has precedence over 51 /* CommonName. If at least one dNSName is provided, Postfix 52 /* verifies those against the peer hostname and ignores the 53 /* CommonName, otherwise Postfix verifies the CommonName 54 /* against the peer hostname. 55 /* 56 /* tls_client_init() is called once when the SMTP client 57 /* initializes. 58 /* Certificate details are also decided during this phase, 59 /* so peer-specific certificate selection is not possible. 60 /* 61 /* tls_client_start() activates the TLS session over an established 62 /* stream. We expect that network buffers are flushed and 63 /* the TLS handshake can begin immediately. 64 /* 65 /* tls_client_stop() sends the "close notify" alert via 66 /* SSL_shutdown() to the peer and resets all connection specific 67 /* TLS data. As RFC2487 does not specify a separate shutdown, it 68 /* is assumed that the underlying TCP connection is shut down 69 /* immediately afterwards. Any further writes to the channel will 70 /* be discarded, and any further reads will report end-of-file. 71 /* If the failure flag is set, no SSL_shutdown() handshake is performed. 72 /* 73 /* Once the TLS connection is initiated, information about the TLS 74 /* state is available via the TLScontext structure: 75 /* .IP TLScontext->protocol 76 /* the protocol name (SSLv2, SSLv3, TLSv1), 77 /* .IP TLScontext->cipher_name 78 /* the cipher name (e.g. RC4/MD5), 79 /* .IP TLScontext->cipher_usebits 80 /* the number of bits actually used (e.g. 40), 81 /* .IP TLScontext->cipher_algbits 82 /* the number of bits the algorithm is based on (e.g. 128). 83 /* .PP 84 /* The last two values may differ from each other when export-strength 85 /* encryption is used. 86 /* 87 /* If the peer offered a certificate, part of the certificate data are 88 /* available as: 89 /* .IP TLScontext->peer_status 90 /* A bitmask field that records the status of the peer certificate 91 /* verification. This consists of one or more of 92 /* TLS_CERT_FLAG_PRESENT, TLS_CERT_FLAG_ALTNAME, TLS_CERT_FLAG_TRUSTED, 93 /* TLS_CERT_FLAG_MATCHED and TLS_CERT_FLAG_SECURED. 94 /* .IP TLScontext->peer_CN 95 /* Extracted CommonName of the peer, or zero-length string if the 96 /* information could not be extracted. 97 /* .IP TLScontext->issuer_CN 98 /* Extracted CommonName of the issuer, or zero-length string if the 99 /* information could not be extracted. 100 /* .IP TLScontext->peer_cert_fprint 101 /* At the fingerprint security level, if the peer presented a certificate 102 /* the fingerprint of the certificate. 103 /* .PP 104 /* If no peer certificate is presented the peer_status is set to 0. 105 /* EVENT_DRIVEN APPLICATIONS 106 /* .ad 107 /* .fi 108 /* Event-driven programs manage multiple I/O channels. Such 109 /* programs cannot use the synchronous VSTREAM-over-TLS 110 /* implementation that the TLS library historically provides, 111 /* including tls_client_stop() and the underlying tls_stream(3) 112 /* and tls_bio_ops(3) routines. 113 /* 114 /* With the current TLS library implementation, this means 115 /* that an event-driven application is responsible for calling 116 /* and retrying SSL_connect(), SSL_read(), SSL_write() and 117 /* SSL_shutdown(). 118 /* 119 /* To maintain control over TLS I/O, an event-driven client 120 /* invokes tls_client_start() with a null VSTREAM argument and 121 /* with an fd argument that specifies the I/O file descriptor. 122 /* Then, tls_client_start() performs all the necessary 123 /* preparations before the TLS handshake and returns a partially 124 /* populated TLS context. The event-driven application is then 125 /* responsible for invoking SSL_connect(), and if successful, 126 /* for invoking tls_client_post_connect() to finish the work 127 /* that was started by tls_client_start(). In case of unrecoverable 128 /* failure, tls_client_post_connect() destroys the TLS context 129 /* and returns a null pointer value. 130 /* LICENSE 131 /* .ad 132 /* .fi 133 /* This software is free. You can do with it whatever you want. 134 /* The original author kindly requests that you acknowledge 135 /* the use of his software. 136 /* AUTHOR(S) 137 /* Originally written by: 138 /* Lutz Jaenicke 139 /* BTU Cottbus 140 /* Allgemeine Elektrotechnik 141 /* Universitaetsplatz 3-4 142 /* D-03044 Cottbus, Germany 143 /* 144 /* Updated by: 145 /* Wietse Venema 146 /* IBM T.J. Watson Research 147 /* P.O. Box 704 148 /* Yorktown Heights, NY 10598, USA 149 /* 150 /* Wietse Venema 151 /* Google, Inc. 152 /* 111 8th Avenue 153 /* New York, NY 10011, USA 154 /* 155 /* Victor Duchovni 156 /* Morgan Stanley 157 /*--*/ 158 159 /* System library. */ 160 161 #include <sys_defs.h> 162 163 #ifdef USE_TLS 164 #include <string.h> 165 166 #ifdef STRCASECMP_IN_STRINGS_H 167 #include <strings.h> 168 #endif 169 170 /* Utility library. */ 171 172 #include <argv.h> 173 #include <mymalloc.h> 174 #include <vstring.h> 175 #include <vstream.h> 176 #include <stringops.h> 177 #include <msg.h> 178 #include <iostuff.h> /* non-blocking */ 179 #include <midna_domain.h> 180 181 /* Global library. */ 182 183 #include <mail_params.h> 184 185 /* TLS library. */ 186 187 #include <tls_mgr.h> 188 #define TLS_INTERNAL 189 #include <tls.h> 190 191 /* Application-specific. */ 192 193 #define STR vstring_str 194 #define LEN VSTRING_LEN 195 196 /* load_clnt_session - load session from client cache (non-callback) */ 197 198 static SSL_SESSION *load_clnt_session(TLS_SESS_STATE *TLScontext) 199 { 200 const char *myname = "load_clnt_session"; 201 SSL_SESSION *session = 0; 202 VSTRING *session_data = vstring_alloc(2048); 203 204 /* 205 * Prepare the query. 206 */ 207 if (TLScontext->log_mask & TLS_LOG_CACHE) 208 /* serverid contains transport:addr:port information */ 209 msg_info("looking for session %s in %s cache", 210 TLScontext->serverid, TLScontext->cache_type); 211 212 /* 213 * We only get here if the cache_type is not empty. This code is not 214 * called unless caching is enabled and the cache_type is stored in the 215 * server SSL context. 216 */ 217 if (TLScontext->cache_type == 0) 218 msg_panic("%s: null client session cache type in session lookup", 219 myname); 220 221 /* 222 * Look up and activate the SSL_SESSION object. Errors are non-fatal, 223 * since caching is only an optimization. 224 */ 225 if (tls_mgr_lookup(TLScontext->cache_type, TLScontext->serverid, 226 session_data) == TLS_MGR_STAT_OK) { 227 session = tls_session_activate(STR(session_data), LEN(session_data)); 228 if (session) { 229 if (TLScontext->log_mask & TLS_LOG_CACHE) 230 /* serverid contains transport:addr:port information */ 231 msg_info("reloaded session %s from %s cache", 232 TLScontext->serverid, TLScontext->cache_type); 233 } 234 } 235 236 /* 237 * Clean up. 238 */ 239 vstring_free(session_data); 240 241 return (session); 242 } 243 244 /* new_client_session_cb - name new session and save it to client cache */ 245 246 static int new_client_session_cb(SSL *ssl, SSL_SESSION *session) 247 { 248 const char *myname = "new_client_session_cb"; 249 TLS_SESS_STATE *TLScontext; 250 VSTRING *session_data; 251 252 /* 253 * The cache name (if caching is enabled in tlsmgr(8)) and the cache ID 254 * string for this session are stored in the TLScontext. It cannot be 255 * null at this point. 256 */ 257 if ((TLScontext = SSL_get_ex_data(ssl, TLScontext_index)) == 0) 258 msg_panic("%s: null TLScontext in new session callback", myname); 259 260 /* 261 * We only get here if the cache_type is not empty. This callback is not 262 * set unless caching is enabled and the cache_type is stored in the 263 * server SSL context. 264 */ 265 if (TLScontext->cache_type == 0) 266 msg_panic("%s: null session cache type in new session callback", 267 myname); 268 269 if (TLScontext->log_mask & TLS_LOG_CACHE) 270 /* serverid contains transport:addr:port information */ 271 msg_info("save session %s to %s cache", 272 TLScontext->serverid, TLScontext->cache_type); 273 274 /* 275 * Passivate and save the session object. Errors are non-fatal, since 276 * caching is only an optimization. 277 */ 278 if ((session_data = tls_session_passivate(session)) != 0) { 279 tls_mgr_update(TLScontext->cache_type, TLScontext->serverid, 280 STR(session_data), LEN(session_data)); 281 vstring_free(session_data); 282 } 283 284 /* 285 * Clean up. 286 */ 287 SSL_SESSION_free(session); /* 200502 */ 288 289 return (1); 290 } 291 292 /* uncache_session - remove session from the external cache */ 293 294 static void uncache_session(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext) 295 { 296 SSL_SESSION *session = SSL_get_session(TLScontext->con); 297 298 SSL_CTX_remove_session(ctx, session); 299 if (TLScontext->cache_type == 0 || TLScontext->serverid == 0) 300 return; 301 302 if (TLScontext->log_mask & TLS_LOG_CACHE) 303 /* serverid contains transport:addr:port information */ 304 msg_info("remove session %s from client cache", TLScontext->serverid); 305 306 tls_mgr_delete(TLScontext->cache_type, TLScontext->serverid); 307 } 308 309 /* tls_client_init - initialize client-side TLS engine */ 310 311 TLS_APPL_STATE *tls_client_init(const TLS_CLIENT_INIT_PROPS *props) 312 { 313 long off = 0; 314 int cachable; 315 int scache_timeout; 316 SSL_CTX *client_ctx; 317 TLS_APPL_STATE *app_ctx; 318 int log_mask; 319 320 /* 321 * Convert user loglevel to internal logmask. 322 */ 323 log_mask = tls_log_mask(props->log_param, props->log_level); 324 325 if (log_mask & TLS_LOG_VERBOSE) 326 msg_info("initializing the client-side TLS engine"); 327 328 /* 329 * Load (mostly cipher related) TLS-library internal main.cf parameters. 330 */ 331 tls_param_init(); 332 333 /* 334 * Detect mismatch between compile-time headers and run-time library. 335 */ 336 tls_check_version(); 337 338 #if OPENSSL_VERSION_NUMBER < 0x10100000L 339 340 /* 341 * Initialize the OpenSSL library by the book! To start with, we must 342 * initialize the algorithms. We want cleartext error messages instead of 343 * just error codes, so we load the error_strings. 344 */ 345 SSL_load_error_strings(); 346 OpenSSL_add_ssl_algorithms(); 347 #endif 348 349 /* 350 * Create an application data index for SSL objects, so that we can 351 * attach TLScontext information; this information is needed inside 352 * tls_verify_certificate_callback(). 353 */ 354 if (TLScontext_index < 0) { 355 if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) { 356 msg_warn("Cannot allocate SSL application data index: " 357 "disabling TLS support"); 358 return (0); 359 } 360 } 361 362 /* 363 * If the administrator specifies an unsupported digest algorithm, fail 364 * now, rather than in the middle of a TLS handshake. 365 */ 366 if (!tls_validate_digest(props->mdalg)) { 367 msg_warn("disabling TLS support"); 368 return (0); 369 } 370 371 /* 372 * Initialize the PRNG (Pseudo Random Number Generator) with some seed 373 * from external and internal sources. Don't enable TLS without some real 374 * entropy. 375 */ 376 if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) { 377 msg_warn("no entropy for TLS key generation: disabling TLS support"); 378 return (0); 379 } 380 tls_int_seed(); 381 382 /* 383 * The SSL/TLS specifications require the client to send a message in the 384 * oldest specification it understands with the highest level it 385 * understands in the message. RFC2487 is only specified for TLSv1, but 386 * we want to be as compatible as possible, so we will start off with a 387 * SSLv2 greeting allowing the best we can offer: TLSv1. We can restrict 388 * this with the options setting later, anyhow. 389 */ 390 ERR_clear_error(); 391 client_ctx = SSL_CTX_new(TLS_client_method()); 392 if (client_ctx == 0) { 393 msg_warn("cannot allocate client SSL_CTX: disabling TLS support"); 394 tls_print_errors(); 395 return (0); 396 } 397 #ifdef SSL_SECOP_PEER 398 /* Backwards compatible security as a base for opportunistic TLS. */ 399 SSL_CTX_set_security_level(client_ctx, 0); 400 #endif 401 402 /* 403 * See the verify callback in tls_verify.c 404 */ 405 SSL_CTX_set_verify_depth(client_ctx, props->verifydepth + 1); 406 407 /* 408 * Protocol selection is destination dependent, so we delay the protocol 409 * selection options to the per-session SSL object. 410 */ 411 off |= tls_bug_bits(); 412 SSL_CTX_set_options(client_ctx, off); 413 414 /* 415 * Set the call-back routine for verbose logging. 416 */ 417 if (log_mask & TLS_LOG_DEBUG) 418 SSL_CTX_set_info_callback(client_ctx, tls_info_callback); 419 420 /* 421 * Load the CA public key certificates for both the client cert and for 422 * the verification of server certificates. As provided by OpenSSL we 423 * support two types of CA certificate handling: One possibility is to 424 * add all CA certificates to one large CAfile, the other possibility is 425 * a directory pointed to by CApath, containing separate files for each 426 * CA with softlinks named after the hash values of the certificate. The 427 * first alternative has the advantage that the file is opened and read 428 * at startup time, so that you don't have the hassle to maintain another 429 * copy of the CApath directory for chroot-jail. 430 */ 431 if (tls_set_ca_certificate_info(client_ctx, 432 props->CAfile, props->CApath) < 0) { 433 /* tls_set_ca_certificate_info() already logs a warning. */ 434 SSL_CTX_free(client_ctx); /* 200411 */ 435 return (0); 436 } 437 438 /* 439 * We do not need a client certificate, so the certificates are only 440 * loaded (and checked) if supplied. A clever client would handle 441 * multiple client certificates and decide based on the list of 442 * acceptable CAs, sent by the server, which certificate to submit. 443 * OpenSSL does however not do this and also has no call-back hooks to 444 * easily implement it. 445 * 446 * Load the client public key certificate and private key from file and 447 * check whether the cert matches the key. We can use RSA certificates 448 * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert"). 449 * All three can be made available at the same time. The CA certificates 450 * for all three are handled in the same setup already finished. Which 451 * one is used depends on the cipher negotiated (that is: the first 452 * cipher listed by the client which does match the server). The client 453 * certificate is presented after the server chooses the session cipher, 454 * so we will just present the right cert for the chosen cipher (if it 455 * uses certificates). 456 */ 457 if (tls_set_my_certificate_key_info(client_ctx, 458 props->chain_files, 459 props->cert_file, 460 props->key_file, 461 props->dcert_file, 462 props->dkey_file, 463 props->eccert_file, 464 props->eckey_file) < 0) { 465 /* tls_set_my_certificate_key_info() already logs a warning. */ 466 SSL_CTX_free(client_ctx); /* 200411 */ 467 return (0); 468 } 469 470 /* 471 * 2015-12-05: Ephemeral RSA removed from OpenSSL 1.1.0-dev 472 */ 473 #if OPENSSL_VERSION_NUMBER < 0x10100000L 474 475 /* 476 * According to the OpenSSL documentation, temporary RSA key is needed 477 * export ciphers are in use. We have to provide one, so well, we just do 478 * it. 479 */ 480 SSL_CTX_set_tmp_rsa_callback(client_ctx, tls_tmp_rsa_cb); 481 #endif 482 483 /* 484 * With OpenSSL 1.0.2 and later the client EECDH curve list becomes 485 * configurable with the preferred curve negotiated via the supported 486 * curves extension. 487 */ 488 tls_auto_eecdh_curves(client_ctx, var_tls_eecdh_auto); 489 490 /* 491 * Finally, the setup for the server certificate checking, done "by the 492 * book". 493 */ 494 SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE, 495 tls_verify_certificate_callback); 496 497 /* 498 * Initialize the session cache. 499 * 500 * Since the client does not search an internal cache, we simply disable it. 501 * It is only useful for expiring old sessions, but we do that in the 502 * tlsmgr(8). 503 * 504 * This makes SSL_CTX_remove_session() not useful for flushing broken 505 * sessions from the external cache, so we must delete them directly (not 506 * via a callback). 507 */ 508 if (tls_mgr_policy(props->cache_type, &cachable, 509 &scache_timeout) != TLS_MGR_STAT_OK) 510 scache_timeout = 0; 511 if (scache_timeout <= 0) 512 cachable = 0; 513 514 /* 515 * Allocate an application context, and populate with mandatory protocol 516 * and cipher data. 517 */ 518 app_ctx = tls_alloc_app_context(client_ctx, 0, log_mask); 519 520 /* 521 * The external session cache is implemented by the tlsmgr(8) process. 522 */ 523 if (cachable) { 524 525 app_ctx->cache_type = mystrdup(props->cache_type); 526 527 /* 528 * OpenSSL does not use callbacks to load sessions from a client 529 * cache, so we must invoke that function directly. Apparently, 530 * OpenSSL does not provide a way to pass session names from here to 531 * call-back routines that do session lookup. 532 * 533 * OpenSSL can, however, automatically save newly created sessions for 534 * us by callback (we create the session name in the call-back 535 * function). 536 * 537 * XXX gcc 2.95 can't compile #ifdef .. #endif in the expansion of 538 * SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE | 539 * SSL_SESS_CACHE_NO_AUTO_CLEAR. 540 */ 541 #ifndef SSL_SESS_CACHE_NO_INTERNAL_STORE 542 #define SSL_SESS_CACHE_NO_INTERNAL_STORE 0 543 #endif 544 545 SSL_CTX_set_session_cache_mode(client_ctx, 546 SSL_SESS_CACHE_CLIENT | 547 SSL_SESS_CACHE_NO_INTERNAL_STORE | 548 SSL_SESS_CACHE_NO_AUTO_CLEAR); 549 SSL_CTX_sess_set_new_cb(client_ctx, new_client_session_cb); 550 551 /* 552 * OpenSSL ignores timed-out sessions. We need to set the internal 553 * cache timeout at least as high as the external cache timeout. This 554 * applies even if no internal cache is used. We set the session to 555 * twice the cache lifetime. This way a session always lasts longer 556 * than its lifetime in the cache. 557 */ 558 SSL_CTX_set_timeout(client_ctx, 2 * scache_timeout); 559 } 560 return (app_ctx); 561 } 562 563 /* match_servername - match servername against pattern */ 564 565 static int match_servername(const char *certid, 566 const TLS_CLIENT_START_PROPS *props) 567 { 568 const ARGV *cmatch_argv; 569 const char *nexthop = props->nexthop; 570 const char *hname = props->host; 571 const char *domain; 572 const char *parent; 573 const char *aname; 574 int match_subdomain; 575 int i; 576 int idlen; 577 int domlen; 578 579 if ((cmatch_argv = props->matchargv) == 0) 580 return 0; 581 582 #ifndef NO_EAI 583 584 /* 585 * DNS subjectAltNames are required to be ASCII. 586 * 587 * Per RFC 6125 Section 6.4.4 Matching the CN-ID, follows the same rules 588 * (6.4.1, 6.4.2 and 6.4.3) that apply to subjectAltNames. In 589 * particular, 6.4.2 says that the reference identifier is coerced to 590 * ASCII, but no conversion is stated or implied for the CN-ID, so it 591 * seems it only matches if it is all ASCII. Otherwise, it is some other 592 * sort of name. 593 */ 594 if (!allascii(certid)) 595 return (0); 596 if (!allascii(nexthop) && (aname = midna_domain_to_ascii(nexthop)) != 0) { 597 if (msg_verbose) 598 msg_info("%s asciified to %s", nexthop, aname); 599 nexthop = aname; 600 } 601 #endif 602 603 /* 604 * Match the certid against each pattern until we find a match. 605 */ 606 for (i = 0; i < cmatch_argv->argc; ++i) { 607 match_subdomain = 0; 608 if (!strcasecmp(cmatch_argv->argv[i], "nexthop")) 609 domain = nexthop; 610 else if (!strcasecmp(cmatch_argv->argv[i], "hostname")) 611 domain = hname; 612 else if (!strcasecmp(cmatch_argv->argv[i], "dot-nexthop")) { 613 domain = nexthop; 614 match_subdomain = 1; 615 } else { 616 domain = cmatch_argv->argv[i]; 617 if (*domain == '.') { 618 if (domain[1]) { 619 ++domain; 620 match_subdomain = 1; 621 } 622 } 623 #ifndef NO_EAI 624 625 /* 626 * Besides U+002E (full stop) IDNA2003 allows labels to be 627 * separated by any of the Unicode variants U+3002 (ideographic 628 * full stop), U+FF0E (fullwidth full stop), and U+FF61 629 * (halfwidth ideographic full stop). Their respective UTF-8 630 * encodings are: E38082, EFBC8E and EFBDA1. 631 * 632 * IDNA2008 does not permit (upper) case and other variant 633 * differences in U-labels. The midna_domain_to_ascii() function, 634 * based on UTS46, normalizes such differences away. 635 * 636 * The IDNA to_ASCII conversion does not allow empty leading labels, 637 * so we handle these explicitly here. 638 */ 639 else { 640 unsigned char *cp = (unsigned char *) domain; 641 642 if ((cp[0] == 0xe3 && cp[1] == 0x80 && cp[2] == 0x82) 643 || (cp[0] == 0xef && cp[1] == 0xbc && cp[2] == 0x8e) 644 || (cp[0] == 0xef && cp[1] == 0xbd && cp[2] == 0xa1)) { 645 if (domain[3]) { 646 domain = domain + 3; 647 match_subdomain = 1; 648 } 649 } 650 } 651 if (!allascii(domain) 652 && (aname = midna_domain_to_ascii(domain)) != 0) { 653 if (msg_verbose) 654 msg_info("%s asciified to %s", domain, aname); 655 domain = aname; 656 } 657 #endif 658 } 659 660 /* 661 * Sub-domain match: certid is any sub-domain of hostname. 662 */ 663 if (match_subdomain) { 664 if ((idlen = strlen(certid)) > (domlen = strlen(domain)) + 1 665 && certid[idlen - domlen - 1] == '.' 666 && !strcasecmp(certid + (idlen - domlen), domain)) 667 return (1); 668 else 669 continue; 670 } 671 672 /* 673 * Exact match and initial "*" match. The initial "*" in a certid 674 * matches one (if var_tls_multi_label is false) or more hostname 675 * components under the condition that the certid contains multiple 676 * hostname components. 677 */ 678 if (!strcasecmp(certid, domain) 679 || (certid[0] == '*' && certid[1] == '.' && certid[2] != 0 680 && (parent = strchr(domain, '.')) != 0 681 && (idlen = strlen(certid + 1)) <= (domlen = strlen(parent)) 682 && strcasecmp(var_tls_multi_wildcard == 0 ? parent : 683 parent + domlen - idlen, 684 certid + 1) == 0)) 685 return (1); 686 } 687 return (0); 688 } 689 690 /* verify_extract_name - verify peer name and extract peer information */ 691 692 static void verify_extract_name(TLS_SESS_STATE *TLScontext, X509 *peercert, 693 const TLS_CLIENT_START_PROPS *props) 694 { 695 int i; 696 int r; 697 int matched = 0; 698 int dnsname_match; 699 int verify_peername = 0; 700 int log_certmatch; 701 int verbose; 702 const char *dnsname; 703 const GENERAL_NAME *gn; 704 general_name_stack_t *gens; 705 706 /* 707 * On exit both peer_CN and issuer_CN should be set. 708 */ 709 TLScontext->issuer_CN = tls_issuer_CN(peercert, TLScontext); 710 711 /* 712 * Is the certificate trust chain valid and trusted? 713 */ 714 if (SSL_get_verify_result(TLScontext->con) == X509_V_OK) 715 TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED; 716 717 /* 718 * With fingerprint or dane we may already be done. Otherwise, verify the 719 * peername if using traditional PKI or DANE with trust-anchors. 720 */ 721 if (!TLS_CERT_IS_MATCHED(TLScontext) 722 && TLS_CERT_IS_TRUSTED(TLScontext) 723 && TLS_MUST_TRUST(props->tls_level)) 724 verify_peername = 1; 725 726 /* Force cert processing so we can log the data? */ 727 log_certmatch = TLScontext->log_mask & TLS_LOG_CERTMATCH; 728 729 /* Log cert details when processing? */ 730 verbose = log_certmatch || (TLScontext->log_mask & TLS_LOG_VERBOSE); 731 732 if (verify_peername || log_certmatch) { 733 734 /* 735 * Verify the dNSName(s) in the peer certificate against the nexthop 736 * and hostname. 737 * 738 * If DNS names are present, we use the first matching (or else simply 739 * the first) DNS name as the subject CN. The CommonName in the 740 * issuer DN is obsolete when SubjectAltName is available. This 741 * yields much less surprising logs, because we log the name we 742 * verified or a name we checked and failed to match. 743 * 744 * XXX: The nexthop and host name may both be the same network address 745 * rather than a DNS name. In this case we really should be looking 746 * for GEN_IPADD entries, not GEN_DNS entries. 747 * 748 * XXX: In ideal world the caller who used the address to build the 749 * connection would tell us that the nexthop is the connection 750 * address, but if that is not practical, we can parse the nexthop 751 * again here. 752 */ 753 gens = X509_get_ext_d2i(peercert, NID_subject_alt_name, 0, 0); 754 if (gens) { 755 r = sk_GENERAL_NAME_num(gens); 756 for (i = 0; i < r; ++i) { 757 gn = sk_GENERAL_NAME_value(gens, i); 758 if (gn->type != GEN_DNS) 759 continue; 760 761 /* 762 * Even if we have an invalid DNS name, we still ultimately 763 * ignore the CommonName, because subjectAltName:DNS is 764 * present (though malformed). Replace any previous peer_CN 765 * if empty or we get a match. 766 * 767 * We always set at least an empty peer_CN if the ALTNAME cert 768 * flag is set. If not, we set peer_CN from the cert 769 * CommonName below, so peer_CN is always non-null on return. 770 */ 771 TLScontext->peer_status |= TLS_CERT_FLAG_ALTNAME; 772 dnsname = tls_dns_name(gn, TLScontext); 773 if (dnsname && *dnsname) { 774 if ((dnsname_match = match_servername(dnsname, props)) != 0) 775 matched++; 776 /* Keep the first matched name. */ 777 if (TLScontext->peer_CN 778 && ((dnsname_match && matched == 1) 779 || *TLScontext->peer_CN == 0)) { 780 myfree(TLScontext->peer_CN); 781 TLScontext->peer_CN = 0; 782 } 783 if (verbose) 784 msg_info("%s: %ssubjectAltName: %s", props->namaddr, 785 dnsname_match ? "Matched " : "", dnsname); 786 } 787 if (TLScontext->peer_CN == 0) 788 TLScontext->peer_CN = mystrdup(dnsname ? dnsname : ""); 789 if (matched && !log_certmatch) 790 break; 791 } 792 if (verify_peername && matched) 793 TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED; 794 795 /* 796 * (Sam Rushing, Ironport) Free stack *and* member GENERAL_NAME 797 * objects 798 */ 799 sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); 800 } 801 802 /* 803 * No subjectAltNames, peer_CN is taken from CommonName. 804 */ 805 if (TLScontext->peer_CN == 0) { 806 TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext); 807 if (*TLScontext->peer_CN) 808 matched = match_servername(TLScontext->peer_CN, props); 809 if (verify_peername && matched) 810 TLScontext->peer_status |= TLS_CERT_FLAG_MATCHED; 811 if (verbose) 812 msg_info("%s %sCommonName %s", props->namaddr, 813 matched ? "Matched " : "", TLScontext->peer_CN); 814 } else if (verbose) { 815 char *tmpcn = tls_peer_CN(peercert, TLScontext); 816 817 /* 818 * Though the CommonName was superceded by a subjectAltName, log 819 * it when certificate match debugging was requested. 820 */ 821 msg_info("%s CommonName %s", TLScontext->namaddr, tmpcn); 822 myfree(tmpcn); 823 } 824 } else 825 TLScontext->peer_CN = tls_peer_CN(peercert, TLScontext); 826 827 /* 828 * Give them a clue. Problems with trust chain verification are logged 829 * when the session is first negotiated, before the session is stored 830 * into the cache. We don't want mystery failures, so log the fact the 831 * real problem is to be found in the past. 832 */ 833 if (!TLS_CERT_IS_TRUSTED(TLScontext) 834 && (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) { 835 if (TLScontext->session_reused == 0) 836 tls_log_verify_error(TLScontext); 837 else 838 msg_info("%s: re-using session with untrusted certificate, " 839 "look for details earlier in the log", props->namaddr); 840 } 841 } 842 843 /* verify_extract_print - extract and verify peer fingerprint */ 844 845 static void verify_extract_print(TLS_SESS_STATE *TLScontext, X509 *peercert, 846 const TLS_CLIENT_START_PROPS *props) 847 { 848 TLScontext->peer_cert_fprint = tls_cert_fprint(peercert, props->mdalg); 849 TLScontext->peer_pkey_fprint = tls_pkey_fprint(peercert, props->mdalg); 850 851 /* 852 * Whether the level is "dane" or "fingerprint" when the peer certificate 853 * is matched without resorting to a separate CA, we set both the trusted 854 * and matched bits. This simplifies logic in smtp_proto.c where "dane" 855 * must be trusted and matched, since some "dane" TLSA RRsets do use CAs. 856 * 857 * This also suppresses spurious logging of the peer certificate as 858 * untrusted in verify_extract_name(). 859 */ 860 if (TLS_DANE_HASEE(props->dane) 861 && tls_dane_match(TLScontext, TLS_DANE_EE, peercert, 0)) 862 TLScontext->peer_status |= 863 TLS_CERT_FLAG_TRUSTED | TLS_CERT_FLAG_MATCHED; 864 } 865 866 /* 867 * This is the actual startup routine for the connection. We expect that the 868 * buffers are flushed and the "220 Ready to start TLS" was received by us, 869 * so that we can immediately start the TLS handshake process. 870 */ 871 TLS_SESS_STATE *tls_client_start(const TLS_CLIENT_START_PROPS *props) 872 { 873 int sts; 874 int protomask; 875 const char *cipher_list; 876 SSL_SESSION *session = 0; 877 TLS_SESS_STATE *TLScontext; 878 TLS_APPL_STATE *app_ctx = props->ctx; 879 const char *sni = 0; 880 char *myserverid; 881 int log_mask = app_ctx->log_mask; 882 883 /* 884 * When certificate verification is required, log trust chain validation 885 * errors even when disabled by default for opportunistic sessions. For 886 * DANE this only applies when using trust-anchor associations. 887 */ 888 if (TLS_MUST_TRUST(props->tls_level) 889 && (!TLS_DANE_BASED(props->tls_level) || TLS_DANE_HASTA(props->dane))) 890 log_mask |= TLS_LOG_UNTRUSTED; 891 892 if (log_mask & TLS_LOG_VERBOSE) 893 msg_info("setting up TLS connection to %s", props->namaddr); 894 895 /* 896 * First make sure we have valid protocol and cipher parameters 897 * 898 * Per-session protocol restrictions must be applied to the SSL connection, 899 * as restrictions in the global context cannot be cleared. 900 */ 901 protomask = tls_protocol_mask(props->protocols); 902 if (protomask == TLS_PROTOCOL_INVALID) { 903 /* tls_protocol_mask() logs no warning. */ 904 msg_warn("%s: Invalid TLS protocol list \"%s\": aborting TLS session", 905 props->namaddr, props->protocols); 906 return (0); 907 } 908 /* DANE requires SSLv3 or later, not SSLv2. */ 909 if (TLS_DANE_BASED(props->tls_level)) 910 protomask |= TLS_PROTOCOL_SSLv2; 911 912 /* 913 * Allocate a new TLScontext for the new connection and get an SSL 914 * structure. Add the location of TLScontext to the SSL to later retrieve 915 * the information inside the tls_verify_certificate_callback(). 916 * 917 * If session caching was enabled when TLS was initialized, the cache type 918 * is stored in the client SSL context. 919 */ 920 TLScontext = tls_alloc_sess_context(log_mask, props->namaddr); 921 TLScontext->cache_type = app_ctx->cache_type; 922 923 if ((TLScontext->con = SSL_new(app_ctx->ssl_ctx)) == NULL) { 924 msg_warn("Could not allocate 'TLScontext->con' with SSL_new()"); 925 tls_print_errors(); 926 tls_free_context(TLScontext); 927 return (0); 928 } 929 930 /* 931 * Per session cipher selection for sessions with mandatory encryption 932 * 933 * The cipherlist is applied to the global SSL context, since it is likely 934 * to stay the same between connections, so we make use of a 1-element 935 * cache to return the same result for identical inputs. 936 */ 937 cipher_list = tls_set_ciphers(TLScontext, props->cipher_grade, 938 props->cipher_exclusions); 939 if (cipher_list == 0) { 940 /* already warned */ 941 tls_free_context(TLScontext); 942 return (0); 943 } 944 if (log_mask & TLS_LOG_VERBOSE) 945 msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list); 946 947 /* 948 * OpenSSL will ignore cached sessions that use the wrong protocol. So we 949 * do not need to filter out cached sessions with the "wrong" protocol, 950 * rather OpenSSL will simply negotiate a new session. 951 * 952 * We salt the session lookup key with the protocol list, so that sessions 953 * found in the cache are plausibly acceptable. 954 * 955 * By the time a TLS client is negotiating ciphers it has already offered to 956 * re-use a session, it is too late to renege on the offer. So we must 957 * not attempt to re-use sessions whose ciphers are too weak. We salt the 958 * session lookup key with the cipher list, so that sessions found in the 959 * cache are always acceptable. 960 * 961 * With DANE, (more generally any TLScontext where we specified explicit 962 * trust-anchor or end-entity certificates) the verification status of 963 * the SSL session depends on the specified list. Since we verify the 964 * certificate only during the initial handshake, we must segregate 965 * sessions with different TA lists. Note, that TA re-verification is 966 * not possible with cached sessions, since these don't hold the complete 967 * peer trust chain. Therefore, we compute a digest of the sorted TA 968 * parameters and append it to the serverid. 969 */ 970 myserverid = tls_serverid_digest(props, protomask, cipher_list); 971 972 TLScontext->serverid = myserverid; 973 TLScontext->stream = props->stream; 974 TLScontext->mdalg = props->mdalg; 975 976 /* Alias DANE digest info from props */ 977 TLScontext->dane = props->dane; 978 979 if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) { 980 msg_warn("Could not set application data for 'TLScontext->con'"); 981 tls_print_errors(); 982 tls_free_context(TLScontext); 983 return (0); 984 } 985 986 /* 987 * Apply session protocol restrictions. 988 */ 989 if (protomask != 0) 990 SSL_set_options(TLScontext->con, TLS_SSL_OP_PROTOMASK(protomask)); 991 992 #ifdef SSL_SECOP_PEER 993 /* When authenticating the peer, use 80-bit plus OpenSSL security level */ 994 if (TLS_MUST_MATCH(props->tls_level)) 995 SSL_set_security_level(TLScontext->con, 1); 996 #endif 997 998 /* 999 * XXX To avoid memory leaks we must always call SSL_SESSION_free() after 1000 * calling SSL_set_session(), regardless of whether or not the session 1001 * will be reused. 1002 */ 1003 if (TLScontext->cache_type) { 1004 session = load_clnt_session(TLScontext); 1005 if (session) { 1006 SSL_set_session(TLScontext->con, session); 1007 SSL_SESSION_free(session); /* 200411 */ 1008 } 1009 } 1010 #ifdef TLSEXT_MAXLEN_host_name 1011 if (TLS_DANE_BASED(props->tls_level)) { 1012 1013 /* 1014 * With DANE sessions, send an SNI hint. We don't care whether the 1015 * server reports finding a matching certificate or not, so no 1016 * callback is required to process the server response. Our use of 1017 * SNI is limited to giving servers that are (mis)configured to use 1018 * SNI the best opportunity to find the certificate they promised via 1019 * the associated TLSA RRs. (Generally, server administrators should 1020 * avoid SNI, and there are no plans to support SNI in the Postfix 1021 * SMTP server). 1022 * 1023 * Since the hostname is DNSSEC-validated, it must be a DNS FQDN and 1024 * thererefore valid for use with SNI. 1025 */ 1026 sni = props->host; 1027 } else if (props->sni && *props->sni) { 1028 if (strcmp(props->sni, "hostname") == 0) 1029 sni = props->host; 1030 else if (strcmp(props->sni, "nexthop") == 0) 1031 sni = props->nexthop; 1032 else 1033 sni = props->sni; 1034 } 1035 if (sni && strlen(sni) <= TLSEXT_MAXLEN_host_name) { 1036 1037 /* 1038 * Failure to set a valid SNI hostname is a memory allocation error, 1039 * and thus transient. Since we must not cache the session if we 1040 * failed to send the SNI name, we have little choice but to abort. 1041 */ 1042 if (!SSL_set_tlsext_host_name(TLScontext->con, sni)) { 1043 msg_warn("%s: error setting SNI hostname to: %s", props->namaddr, 1044 sni); 1045 tls_free_context(TLScontext); 1046 return (0); 1047 } 1048 1049 /* 1050 * The saved value is not presently used client-side, but could later 1051 * be logged if acked by the server (requires new client-side 1052 * callback to detect the ack). For now this just maintains symmetry 1053 * with the server code, where do record the received SNI for 1054 * logging. 1055 */ 1056 TLScontext->peer_sni = mystrdup(sni); 1057 if (log_mask & TLS_LOG_DEBUG) 1058 msg_info("%s: SNI hostname: %s", props->namaddr, sni); 1059 } 1060 #endif 1061 1062 /* 1063 * Before really starting anything, try to seed the PRNG a little bit 1064 * more. 1065 */ 1066 tls_int_seed(); 1067 (void) tls_ext_seed(var_tls_daemon_rand_bytes); 1068 1069 /* 1070 * Connect the SSL connection with the network socket. 1071 */ 1072 if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd : 1073 vstream_fileno(props->stream)) != 1) { 1074 msg_info("SSL_set_fd error to %s", props->namaddr); 1075 tls_print_errors(); 1076 uncache_session(app_ctx->ssl_ctx, TLScontext); 1077 tls_free_context(TLScontext); 1078 return (0); 1079 } 1080 1081 /* 1082 * If the debug level selected is high enough, all of the data is dumped: 1083 * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will 1084 * dump everything. 1085 * 1086 * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called? 1087 * Well there is a BIO below the SSL routines that is automatically 1088 * created for us, so we can use it for debugging purposes. 1089 */ 1090 if (log_mask & TLS_LOG_TLSPKTS) 1091 BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb); 1092 1093 tls_dane_set_callback(app_ctx->ssl_ctx, TLScontext); 1094 1095 /* 1096 * If we don't trigger the handshake in the library, leave control over 1097 * SSL_connect/read/write/etc with the application. 1098 */ 1099 if (props->stream == 0) 1100 return (TLScontext); 1101 1102 /* 1103 * Turn on non-blocking I/O so that we can enforce timeouts on network 1104 * I/O. 1105 */ 1106 non_blocking(vstream_fileno(props->stream), NON_BLOCKING); 1107 1108 /* 1109 * Start TLS negotiations. This process is a black box that invokes our 1110 * call-backs for certificate verification. 1111 * 1112 * Error handling: If the SSL handshake fails, we print out an error message 1113 * and remove all TLS state concerning this session. 1114 */ 1115 sts = tls_bio_connect(vstream_fileno(props->stream), props->timeout, 1116 TLScontext); 1117 if (sts <= 0) { 1118 if (ERR_peek_error() != 0) { 1119 msg_info("SSL_connect error to %s: %d", props->namaddr, sts); 1120 tls_print_errors(); 1121 } else if (errno != 0) { 1122 msg_info("SSL_connect error to %s: %m", props->namaddr); 1123 } else { 1124 msg_info("SSL_connect error to %s: lost connection", 1125 props->namaddr); 1126 } 1127 uncache_session(app_ctx->ssl_ctx, TLScontext); 1128 tls_free_context(TLScontext); 1129 return (0); 1130 } 1131 return (tls_client_post_connect(TLScontext, props)); 1132 } 1133 1134 /* tls_client_post_connect - post-handshake processing */ 1135 1136 TLS_SESS_STATE *tls_client_post_connect(TLS_SESS_STATE *TLScontext, 1137 const TLS_CLIENT_START_PROPS *props) 1138 { 1139 const SSL_CIPHER *cipher; 1140 X509 *peercert; 1141 1142 /* Turn off packet dump if only dumping the handshake */ 1143 if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0) 1144 BIO_set_callback(SSL_get_rbio(TLScontext->con), 0); 1145 1146 /* 1147 * The caller may want to know if this session was reused or if a new 1148 * session was negotiated. 1149 */ 1150 TLScontext->session_reused = SSL_session_reused(TLScontext->con); 1151 if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused) 1152 msg_info("%s: Reusing old session", TLScontext->namaddr); 1153 1154 /* 1155 * Do peername verification if requested and extract useful information 1156 * from the certificate for later use. 1157 */ 1158 if ((peercert = SSL_get_peer_certificate(TLScontext->con)) != 0) { 1159 TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT; 1160 1161 /* 1162 * Peer name or fingerprint verification as requested. 1163 * Unconditionally set peer_CN, issuer_CN and peer_cert_fprint. Check 1164 * fingerprint first, and avoid logging verified as untrusted in the 1165 * call to verify_extract_name(). 1166 */ 1167 verify_extract_print(TLScontext, peercert, props); 1168 verify_extract_name(TLScontext, peercert, props); 1169 1170 if (TLScontext->log_mask & 1171 (TLS_LOG_CERTMATCH | TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) 1172 msg_info("%s: subject_CN=%s, issuer_CN=%s, " 1173 "fingerprint=%s, pkey_fingerprint=%s", props->namaddr, 1174 TLScontext->peer_CN, TLScontext->issuer_CN, 1175 TLScontext->peer_cert_fprint, 1176 TLScontext->peer_pkey_fprint); 1177 X509_free(peercert); 1178 } else { 1179 TLScontext->issuer_CN = mystrdup(""); 1180 TLScontext->peer_CN = mystrdup(""); 1181 TLScontext->peer_cert_fprint = mystrdup(""); 1182 TLScontext->peer_pkey_fprint = mystrdup(""); 1183 } 1184 1185 /* 1186 * Finally, collect information about protocol and cipher for logging 1187 */ 1188 TLScontext->protocol = SSL_get_version(TLScontext->con); 1189 cipher = SSL_get_current_cipher(TLScontext->con); 1190 TLScontext->cipher_name = SSL_CIPHER_get_name(cipher); 1191 TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher, 1192 &(TLScontext->cipher_algbits)); 1193 1194 /* 1195 * The TLS engine is active. Switch to the tls_timed_read/write() 1196 * functions and make the TLScontext available to those functions. 1197 */ 1198 if (TLScontext->stream != 0) 1199 tls_stream_start(props->stream, TLScontext); 1200 1201 /* 1202 * Fully secured only if trusted, matched and not insecure like halfdane. 1203 * Should perhaps also exclude "verify" (as opposed to "secure") here, 1204 * because that can be subject to insecure MX indirection, but that's 1205 * rather incompatible. Users have been warned. 1206 */ 1207 if (TLS_CERT_IS_PRESENT(TLScontext) 1208 && TLS_CERT_IS_TRUSTED(TLScontext) 1209 && TLS_CERT_IS_MATCHED(TLScontext) 1210 && !TLS_NEVER_SECURED(props->tls_level)) 1211 TLScontext->peer_status |= TLS_CERT_FLAG_SECURED; 1212 1213 /* 1214 * With the handshake done, extract TLS 1.3 signature metadata. 1215 */ 1216 tls_get_signature_params(TLScontext); 1217 1218 if (TLScontext->log_mask & TLS_LOG_SUMMARY) 1219 tls_log_summary(TLS_ROLE_CLIENT, TLS_USAGE_NEW, TLScontext); 1220 1221 tls_int_seed(); 1222 1223 return (TLScontext); 1224 } 1225 1226 #endif /* USE_TLS */ 1227