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