Postfix3.3.1
tls_server.c
[詳解]
1 /*++
2 /* NAME
3 /* tls_server 3
4 /* SUMMARY
5 /* server-side TLS engine
6 /* SYNOPSIS
7 /* #include <tls.h>
8 /*
9 /* TLS_APPL_STATE *tls_server_init(props)
10 /* const TLS_SERVER_INIT_PROPS *props;
11 /*
12 /* TLS_SESS_STATE *tls_server_start(props)
13 /* const TLS_SERVER_START_PROPS *props;
14 /*
15 /* TLS_SESS_STATE *tls_server_post_accept(TLScontext)
16 /* TLS_SESS_STATE *TLScontext;
17 /*
18 /* void tls_server_stop(app_ctx, stream, failure, TLScontext)
19 /* TLS_APPL_STATE *app_ctx;
20 /* VSTREAM *stream;
21 /* int failure;
22 /* TLS_SESS_STATE *TLScontext;
23 /* DESCRIPTION
24 /* This module is the interface between Postfix TLS servers,
25 /* the OpenSSL library, and the TLS entropy and cache manager.
26 /*
27 /* See "EVENT_DRIVEN APPLICATIONS" below for using this code
28 /* in event-driven programs.
29 /*
30 /* tls_server_init() is called once when the SMTP server
31 /* initializes.
32 /* Certificate details are also decided during this phase,
33 /* so that peer-specific behavior is not possible.
34 /*
35 /* tls_server_start() activates the TLS feature for the VSTREAM
36 /* passed as argument. We assume that network buffers are flushed
37 /* and the TLS handshake can begin immediately.
38 /*
39 /* tls_server_stop() sends the "close notify" alert via
40 /* SSL_shutdown() to the peer and resets all connection specific
41 /* TLS data. As RFC2487 does not specify a separate shutdown, it
42 /* is assumed that the underlying TCP connection is shut down
43 /* immediately afterwards. Any further writes to the channel will
44 /* be discarded, and any further reads will report end-of-file.
45 /* If the failure flag is set, no SSL_shutdown() handshake is performed.
46 /*
47 /* Once the TLS connection is initiated, information about the TLS
48 /* state is available via the TLScontext structure:
49 /* .IP TLScontext->protocol
50 /* the protocol name (SSLv2, SSLv3, TLSv1),
51 /* .IP TLScontext->cipher_name
52 /* the cipher name (e.g. RC4/MD5),
53 /* .IP TLScontext->cipher_usebits
54 /* the number of bits actually used (e.g. 40),
55 /* .IP TLScontext->cipher_algbits
56 /* the number of bits the algorithm is based on (e.g. 128).
57 /* .PP
58 /* The last two values may differ from each other when export-strength
59 /* encryption is used.
60 /*
61 /* If the peer offered a certificate, part of the certificate data are
62 /* available as:
63 /* .IP TLScontext->peer_status
64 /* A bitmask field that records the status of the peer certificate
65 /* verification. One or more of TLS_CERT_FLAG_PRESENT and
66 /* TLS_CERT_FLAG_TRUSTED.
67 /* .IP TLScontext->peer_CN
68 /* Extracted CommonName of the peer, or zero-length string
69 /* when information could not be extracted.
70 /* .IP TLScontext->issuer_CN
71 /* Extracted CommonName of the issuer, or zero-length string
72 /* when information could not be extracted.
73 /* .IP TLScontext->peer_cert_fprint
74 /* Fingerprint of the certificate, or zero-length string when no peer
75 /* certificate is available.
76 /* .PP
77 /* If no peer certificate is presented the peer_status is set to 0.
78 /* EVENT_DRIVEN APPLICATIONS
79 /* .ad
80 /* .fi
81 /* Event-driven programs manage multiple I/O channels. Such
82 /* programs cannot use the synchronous VSTREAM-over-TLS
83 /* implementation that the current TLS library provides,
84 /* including tls_server_stop() and the underlying tls_stream(3)
85 /* and tls_bio_ops(3) routines.
86 /*
87 /* With the current TLS library implementation, this means
88 /* that the application is responsible for calling and retrying
89 /* SSL_accept(), SSL_read(), SSL_write() and SSL_shutdown().
90 /*
91 /* To maintain control over TLS I/O, an event-driven server
92 /* invokes tls_server_start() with a null VSTREAM argument and
93 /* with an fd argument that specifies the I/O file descriptor.
94 /* Then, tls_server_start() performs all the necessary
95 /* preparations before the TLS handshake and returns a partially
96 /* populated TLS context. The event-driven application is then
97 /* responsible for invoking SSL_accept(), and if successful,
98 /* for invoking tls_server_post_accept() to finish the work
99 /* that was started by tls_server_start(). In case of unrecoverable
100 /* failure, tls_server_post_accept() destroys the TLS context
101 /* and returns a null pointer value.
102 /* LICENSE
103 /* .ad
104 /* .fi
105 /* This software is free. You can do with it whatever you want.
106 /* The original author kindly requests that you acknowledge
107 /* the use of his software.
108 /* AUTHOR(S)
109 /* Originally written by:
110 /* Lutz Jaenicke
111 /* BTU Cottbus
112 /* Allgemeine Elektrotechnik
113 /* Universitaetsplatz 3-4
114 /* D-03044 Cottbus, Germany
115 /*
116 /* Updated by:
117 /* Wietse Venema
118 /* IBM T.J. Watson Research
119 /* P.O. Box 704
120 /* Yorktown Heights, NY 10598, USA
121 /*
122 /* Victor Duchovni
123 /* Morgan Stanley
124 /*--*/
125 
126 /* System library. */
127 
128 #include <sys_defs.h>
129 
130 #ifdef USE_TLS
131 #include <unistd.h>
132 #include <string.h>
133 
134 /* Utility library. */
135 
136 #include <mymalloc.h>
137 #include <vstring.h>
138 #include <vstream.h>
139 #include <dict.h>
140 #include <stringops.h>
141 #include <msg.h>
142 #include <hex_code.h>
143 #include <iostuff.h> /* non-blocking */
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 #define STR(x) vstring_str(x)
156 #define LEN(x) VSTRING_LEN(x)
157 
158 /* Application-specific. */
159 
160  /*
161  * The session_id_context indentifies the service that created a session.
162  * This information is used to distinguish between multiple TLS-based
163  * servers running on the same server. We use the name of the mail system.
164  */
165 static const char server_session_id_context[] = "Postfix/TLS";
166 
167 #if OPENSSL_VERSION_NUMBER >= 0x1000000fL
168 #define GET_SID(s, v, lptr) ((v) = SSL_SESSION_get_id((s), (lptr)))
169 
170 #else /* Older OpenSSL releases */
171 #define GET_SID(s, v, lptr) \
172  do { (v) = (s)->session_id; *(lptr) = (s)->session_id_length; } while (0)
173 
174 #endif /* OPENSSL_VERSION_NUMBER */
175 
176  /* OpenSSL 1.1.0 bitrot */
177 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
178 typedef const unsigned char *session_id_t;
179 
180 #else
181 typedef unsigned char *session_id_t;
182 
183 #endif
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 /* ticket_cb - configure tls session ticket encrypt/decrypt context */
308 
309 #if defined(SSL_OP_NO_TICKET) \
310  && !defined(OPENSSL_NO_TLSEXT) \
311  && OPENSSL_VERSION_NUMBER >= 0x0090808fL
312 
313 static int ticket_cb(SSL *con, unsigned char name[], unsigned char iv[],
314  EVP_CIPHER_CTX * ctx, HMAC_CTX * hctx, int create)
315 {
316  static const EVP_MD *sha256;
317  static const EVP_CIPHER *ciph;
318  TLS_TICKET_KEY *key;
319  TLS_SESS_STATE *TLScontext = SSL_get_ex_data(con, TLScontext_index);
320  int timeout = ((int) SSL_CTX_get_timeout(SSL_get_SSL_CTX(con))) / 2;
321 
322  if ((!sha256 && (sha256 = EVP_sha256()) == 0)
323  || (!ciph && (ciph = EVP_get_cipherbyname(var_tls_tkt_cipher)) == 0)
324  || (key = tls_mgr_key(create ? 0 : name, timeout)) == 0
325  || (create && RAND_bytes(iv, TLS_TICKET_IVLEN) <= 0))
326  return (create ? TLS_TKT_NOKEYS : TLS_TKT_STALE);
327 
328  HMAC_Init_ex(hctx, key->hmac, TLS_TICKET_MACLEN, sha256, NOENGINE);
329 
330  if (create) {
331  EVP_EncryptInit_ex(ctx, ciph, NOENGINE, key->bits, iv);
332  memcpy((void *) name, (void *) key->name, TLS_TICKET_NAMELEN);
333  if (TLScontext->log_mask & TLS_LOG_CACHE)
334  msg_info("%s: Issuing session ticket, key expiration: %ld",
335  TLScontext->namaddr, (long) key->tout);
336  } else {
337  EVP_DecryptInit_ex(ctx, ciph, NOENGINE, key->bits, iv);
338  if (TLScontext->log_mask & TLS_LOG_CACHE)
339  msg_info("%s: Decrypting session ticket, key expiration: %ld",
340  TLScontext->namaddr, (long) key->tout);
341  }
342  TLScontext->ticketed = 1;
343  return (TLS_TKT_ACCEPT);
344 }
345 
346 #endif
347 
348 /* tls_server_init - initialize the server-side TLS engine */
349 
350 TLS_APPL_STATE *tls_server_init(const TLS_SERVER_INIT_PROPS *props)
351 {
352  SSL_CTX *server_ctx;
353  long off = 0;
354  int verify_flags = SSL_VERIFY_NONE;
355  int cachable;
356  int scache_timeout;
357  int ticketable = 0;
358  int protomask;
359  TLS_APPL_STATE *app_ctx;
360  int log_mask;
361 
362  /*
363  * Convert user loglevel to internal logmask.
364  */
365  log_mask = tls_log_mask(props->log_param, props->log_level);
366 
367  if (log_mask & TLS_LOG_VERBOSE)
368  msg_info("initializing the server-side TLS engine");
369 
370  /*
371  * Load (mostly cipher related) TLS-library internal main.cf parameters.
372  */
373  tls_param_init();
374 
375  /*
376  * Detect mismatch between compile-time headers and run-time library.
377  */
378  tls_check_version();
379 
380 #if OPENSSL_VERSION_NUMBER < 0x10100000L
381 
382  /*
383  * Initialize the OpenSSL library by the book! To start with, we must
384  * initialize the algorithms. We want cleartext error messages instead of
385  * just error codes, so we load the error_strings.
386  */
387  SSL_load_error_strings();
388  OpenSSL_add_ssl_algorithms();
389 #endif
390 
391  /*
392  * First validate the protocols. If these are invalid, we can't continue.
393  */
394  protomask = tls_protocol_mask(props->protocols);
395  if (protomask == TLS_PROTOCOL_INVALID) {
396  /* tls_protocol_mask() logs no warning. */
397  msg_warn("Invalid TLS protocol list \"%s\": disabling TLS support",
398  props->protocols);
399  return (0);
400  }
401 
402  /*
403  * Create an application data index for SSL objects, so that we can
404  * attach TLScontext information; this information is needed inside
405  * tls_verify_certificate_callback().
406  */
407  if (TLScontext_index < 0) {
408  if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0) {
409  msg_warn("Cannot allocate SSL application data index: "
410  "disabling TLS support");
411  return (0);
412  }
413  }
414 
415  /*
416  * If the administrator specifies an unsupported digest algorithm, fail
417  * now, rather than in the middle of a TLS handshake.
418  */
419  if (!tls_validate_digest(props->mdalg)) {
420  msg_warn("disabling TLS support");
421  return (0);
422  }
423 
424  /*
425  * Initialize the PRNG (Pseudo Random Number Generator) with some seed
426  * from external and internal sources. Don't enable TLS without some real
427  * entropy.
428  */
429  if (tls_ext_seed(var_tls_daemon_rand_bytes) < 0) {
430  msg_warn("no entropy for TLS key generation: disabling TLS support");
431  return (0);
432  }
433  tls_int_seed();
434 
435  /*
436  * The SSL/TLS specifications require the client to send a message in the
437  * oldest specification it understands with the highest level it
438  * understands in the message. Netscape communicator can still
439  * communicate with SSLv2 servers, so it sends out a SSLv2 client hello.
440  * To deal with it, our server must be SSLv2 aware (even if we don't like
441  * SSLv2), so we need to have the SSLv23 server here. If we want to limit
442  * the protocol level, we can add an option to not use SSLv2/v3/TLSv1
443  * later.
444  */
445  ERR_clear_error();
446  server_ctx = SSL_CTX_new(TLS_server_method());
447  if (server_ctx == 0) {
448  msg_warn("cannot allocate server SSL_CTX: disabling TLS support");
449  tls_print_errors();
450  return (0);
451  }
452 #ifdef SSL_SECOP_PEER
453  /* Backwards compatible security as a base for opportunistic TLS. */
454  SSL_CTX_set_security_level(server_ctx, 0);
455 #endif
456 
457  /*
458  * See the verify callback in tls_verify.c
459  */
460  SSL_CTX_set_verify_depth(server_ctx, props->verifydepth + 1);
461 
462  /*
463  * The session cache is implemented by the tlsmgr(8) server.
464  *
465  * XXX 200502 Surprise: when OpenSSL purges an entry from the in-memory
466  * cache, it also attempts to purge the entry from the on-disk cache.
467  * This is undesirable, especially when we set the in-memory cache size
468  * to 1. For this reason we don't allow OpenSSL to purge on-disk cache
469  * entries, and leave it up to the tlsmgr process instead. Found by
470  * Victor Duchovni.
471  */
472  if (tls_mgr_policy(props->cache_type, &cachable,
473  &scache_timeout) != TLS_MGR_STAT_OK)
474  scache_timeout = 0;
475  if (scache_timeout <= 0)
476  cachable = 0;
477 
478  /*
479  * Protocol work-arounds, OpenSSL version dependent.
480  */
481  off |= tls_bug_bits();
482 
483  /*
484  * Add SSL_OP_NO_TICKET when the timeout is zero or library support is
485  * incomplete. The SSL_CTX_set_tlsext_ticket_key_cb feature was added in
486  * OpenSSL 0.9.8h, while SSL_NO_TICKET was added in 0.9.8f.
487  */
488 #ifdef SSL_OP_NO_TICKET
489 #if !defined(OPENSSL_NO_TLSEXT) && OPENSSL_VERSION_NUMBER >= 0x0090808fL
490  ticketable = (*var_tls_tkt_cipher && scache_timeout > 0
491  && !(off & SSL_OP_NO_TICKET));
492  if (ticketable) {
493  const EVP_CIPHER *ciph;
494 
495  if ((ciph = EVP_get_cipherbyname(var_tls_tkt_cipher)) == 0
496  || EVP_CIPHER_mode(ciph) != EVP_CIPH_CBC_MODE
497  || EVP_CIPHER_iv_length(ciph) != TLS_TICKET_IVLEN
498  || EVP_CIPHER_key_length(ciph) < TLS_TICKET_IVLEN
499  || EVP_CIPHER_key_length(ciph) > TLS_TICKET_KEYLEN) {
500  msg_warn("%s: invalid value: %s; session tickets disabled",
502  ticketable = 0;
503  }
504  }
505  if (ticketable)
506  SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, ticket_cb);
507 #endif
508  if (!ticketable)
509  off |= SSL_OP_NO_TICKET;
510 #endif
511 
512  SSL_CTX_set_options(server_ctx, off);
513 
514  /*
515  * Global protocol selection.
516  */
517  if (protomask != 0)
518  SSL_CTX_set_options(server_ctx, TLS_SSL_OP_PROTOMASK(protomask));
519 
520  /*
521  * Some sites may want to give the client less rope. On the other hand,
522  * this could trigger inter-operability issues, the client should not
523  * offer ciphers it implements poorly, but this hasn't stopped some
524  * vendors from getting it wrong.
525  *
526  * XXX: Given OpenSSL's security history, nobody should still be using
527  * 0.9.7, let alone 0.9.6 or earlier. Warning added to TLS_README.html.
528  */
530  SSL_CTX_set_options(server_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
531 
532  /*
533  * Set the call-back routine to debug handshake progress.
534  */
535  if (log_mask & TLS_LOG_DEBUG)
536  SSL_CTX_set_info_callback(server_ctx, tls_info_callback);
537 
538  /*
539  * Load the CA public key certificates for both the server cert and for
540  * the verification of client certificates. As provided by OpenSSL we
541  * support two types of CA certificate handling: One possibility is to
542  * add all CA certificates to one large CAfile, the other possibility is
543  * a directory pointed to by CApath, containing separate files for each
544  * CA with softlinks named after the hash values of the certificate. The
545  * first alternative has the advantage that the file is opened and read
546  * at startup time, so that you don't have the hassle to maintain another
547  * copy of the CApath directory for chroot-jail.
548  */
549  if (tls_set_ca_certificate_info(server_ctx,
550  props->CAfile, props->CApath) < 0) {
551  /* tls_set_ca_certificate_info() already logs a warning. */
552  SSL_CTX_free(server_ctx); /* 200411 */
553  return (0);
554  }
555 
556  /*
557  * Load the server public key certificate and private key from file and
558  * check whether the cert matches the key. We can use RSA certificates
559  * ("cert") DSA certificates ("dcert") or ECDSA certificates ("eccert").
560  * All three can be made available at the same time. The CA certificates
561  * for all three are handled in the same setup already finished. Which
562  * one is used depends on the cipher negotiated (that is: the first
563  * cipher listed by the client which does match the server). A client
564  * with RSA only (e.g. Netscape) will use the RSA certificate only. A
565  * client with openssl-library will use RSA first if not especially
566  * changed in the cipher setup.
567  */
568  if (tls_set_my_certificate_key_info(server_ctx,
569  props->cert_file,
570  props->key_file,
571  props->dcert_file,
572  props->dkey_file,
573  props->eccert_file,
574  props->eckey_file) < 0) {
575  /* tls_set_my_certificate_key_info() already logs a warning. */
576  SSL_CTX_free(server_ctx); /* 200411 */
577  return (0);
578  }
579 
580  /*
581  * 2015-12-05: Ephemeral RSA removed from OpenSSL 1.1.0-dev
582  */
583 #if OPENSSL_VERSION_NUMBER < 0x10100000L
584 
585  /*
586  * According to OpenSSL documentation, a temporary RSA key is needed when
587  * export ciphers are in use, because the certified key cannot be
588  * directly used.
589  */
590  SSL_CTX_set_tmp_rsa_callback(server_ctx, tls_tmp_rsa_cb);
591 #endif
592 
593  /*
594  * Diffie-Hellman key generation parameters can either be loaded from
595  * files (preferred) or taken from compiled in values. First, set the
596  * callback that will select the values when requested, then load the
597  * (possibly) available DH parameters from files. We are generous with
598  * the error handling, since we do have default values compiled in, so we
599  * will not abort but just log the error message.
600  */
601  SSL_CTX_set_tmp_dh_callback(server_ctx, tls_tmp_dh_cb);
602  if (*props->dh1024_param_file != 0)
603  tls_set_dh_from_file(props->dh1024_param_file, 1024);
604  if (*props->dh512_param_file != 0)
605  tls_set_dh_from_file(props->dh512_param_file, 512);
606 
607  /*
608  * Enable EECDH if available, errors are not fatal, we just keep going
609  * with any remaining key-exchange algorithms.
610  */
611  tls_set_eecdh_curve(server_ctx, props->eecdh_grade);
612 
613  /*
614  * If we want to check client certificates, we have to indicate it in
615  * advance. By now we only allow to decide on a global basis. If we want
616  * to allow certificate based relaying, we must ask the client to provide
617  * one with SSL_VERIFY_PEER. The client now can decide, whether it
618  * provides one or not. We can enforce a failure of the negotiation with
619  * SSL_VERIFY_FAIL_IF_NO_PEER_CERT, if we do not allow a connection
620  * without one. In the "server hello" following the initialization by the
621  * "client hello" the server must provide a list of CAs it is willing to
622  * accept. Some clever clients will then select one from the list of
623  * available certificates matching these CAs. Netscape Communicator will
624  * present the list of certificates for selecting the one to be sent, or
625  * it will issue a warning, if there is no certificate matching the
626  * available CAs.
627  *
628  * With regard to the purpose of the certificate for relaying, we might like
629  * a later negotiation, maybe relaying would already be allowed for other
630  * reasons, but this would involve severe changes in the internal postfix
631  * logic, so we have to live with it the way it is.
632  */
633  if (props->ask_ccert)
634  verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
635  SSL_CTX_set_verify(server_ctx, verify_flags,
636  tls_verify_certificate_callback);
637  if (*props->CAfile)
638  SSL_CTX_set_client_CA_list(server_ctx,
639  SSL_load_client_CA_file(props->CAfile));
640 
641  /*
642  * Initialize our own TLS server handle, before diving into the details
643  * of TLS session cache management.
644  */
645  app_ctx = tls_alloc_app_context(server_ctx, log_mask);
646 
647  if (cachable || ticketable || props->set_sessid) {
648 
649  /*
650  * Initialize the session cache.
651  *
652  * With a large number of concurrent smtpd(8) processes, it is not a
653  * good idea to cache multiple large session objects in each process.
654  * We set the internal cache size to 1, and don't register a
655  * "remove_cb" so as to avoid deleting good sessions from the
656  * external cache prematurely (when the internal cache is full,
657  * OpenSSL removes sessions from the external cache also)!
658  *
659  * This makes SSL_CTX_remove_session() not useful for flushing broken
660  * sessions from the external cache, so we must delete them directly
661  * (not via a callback).
662  *
663  * Set a session id context to identify to what type of server process
664  * created a session. In our case, the context is simply the name of
665  * the mail system: "Postfix/TLS".
666  */
667  SSL_CTX_sess_set_cache_size(server_ctx, 1);
668  SSL_CTX_set_session_id_context(server_ctx,
669  (void *) &server_session_id_context,
670  sizeof(server_session_id_context));
671  SSL_CTX_set_session_cache_mode(server_ctx,
672  SSL_SESS_CACHE_SERVER |
673  SSL_SESS_CACHE_NO_AUTO_CLEAR);
674  if (cachable) {
675  app_ctx->cache_type = mystrdup(props->cache_type);
676 
677  SSL_CTX_sess_set_get_cb(server_ctx, get_server_session_cb);
678  SSL_CTX_sess_set_new_cb(server_ctx, new_server_session_cb);
679  }
680 
681  /*
682  * OpenSSL ignores timed-out sessions. We need to set the internal
683  * cache timeout at least as high as the external cache timeout. This
684  * applies even if no internal cache is used. We set the session
685  * lifetime to twice the cache lifetime, which is also the issuing
686  * and retired key validation lifetime of session tickets keys. This
687  * way a session always lasts longer than the server's ability to
688  * decrypt its session ticket. Otherwise, a bug in OpenSSL may fail
689  * to re-issue tickets when sessions decrypt, but are expired.
690  */
691  SSL_CTX_set_timeout(server_ctx, 2 * scache_timeout);
692  } else {
693 
694  /*
695  * If we have no external cache, disable all caching. No use wasting
696  * server memory resources with sessions they are unlikely to be able
697  * to reuse.
698  */
699  SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
700  }
701 
702  return (app_ctx);
703 }
704 
705  /*
706  * This is the actual startup routine for a new connection. We expect that
707  * the SMTP buffers are flushed and the "220 Ready to start TLS" was sent to
708  * the client, so that we can immediately start the TLS handshake process.
709  */
710 TLS_SESS_STATE *tls_server_start(const TLS_SERVER_START_PROPS *props)
711 {
712  int sts;
713  TLS_SESS_STATE *TLScontext;
714  const char *cipher_list;
715  TLS_APPL_STATE *app_ctx = props->ctx;
716  int log_mask = app_ctx->log_mask;
717 
718  /*
719  * Implicitly enable logging of trust chain errors when verified certs
720  * are required.
721  */
722  if (props->requirecert)
723  log_mask |= TLS_LOG_UNTRUSTED;
724 
725  if (log_mask & TLS_LOG_VERBOSE)
726  msg_info("setting up TLS connection from %s", props->namaddr);
727 
728  cipher_list = tls_set_ciphers(app_ctx, "TLS", props->cipher_grade,
729  props->cipher_exclusions);
730  if (cipher_list == 0) {
731  msg_warn("%s: %s: aborting TLS session", props->namaddr,
732  vstring_str(app_ctx->why));
733  return (0);
734  }
735  if (log_mask & TLS_LOG_VERBOSE)
736  msg_info("%s: TLS cipher list \"%s\"", props->namaddr, cipher_list);
737 
738  /*
739  * Allocate a new TLScontext for the new connection and get an SSL
740  * structure. Add the location of TLScontext to the SSL to later retrieve
741  * the information inside the tls_verify_certificate_callback().
742  */
743  TLScontext = tls_alloc_sess_context(log_mask, props->namaddr);
744  TLScontext->cache_type = app_ctx->cache_type;
745 
746  TLScontext->serverid = mystrdup(props->serverid);
747  TLScontext->am_server = 1;
748  TLScontext->stream = props->stream;
749  TLScontext->mdalg = props->mdalg;
750 
751  ERR_clear_error();
752  if ((TLScontext->con = (SSL *) SSL_new(app_ctx->ssl_ctx)) == 0) {
753  msg_warn("Could not allocate 'TLScontext->con' with SSL_new()");
754  tls_print_errors();
755  tls_free_context(TLScontext);
756  return (0);
757  }
758  if (!SSL_set_ex_data(TLScontext->con, TLScontext_index, TLScontext)) {
759  msg_warn("Could not set application data for 'TLScontext->con'");
760  tls_print_errors();
761  tls_free_context(TLScontext);
762  return (0);
763  }
764 #ifdef SSL_SECOP_PEER
765  /* When authenticating the peer, use 80-bit plus OpenSSL security level */
766  if (props->requirecert)
767  SSL_set_security_level(TLScontext->con, 1);
768 #endif
769 
770  /*
771  * Before really starting anything, try to seed the PRNG a little bit
772  * more.
773  */
774  tls_int_seed();
775  (void) tls_ext_seed(var_tls_daemon_rand_bytes);
776 
777  /*
778  * Initialize the SSL connection to accept state. This should not be
779  * necessary anymore since 0.9.3, but the call is still in the library
780  * and maintaining compatibility never hurts.
781  */
782  SSL_set_accept_state(TLScontext->con);
783 
784  /*
785  * Connect the SSL connection with the network socket.
786  */
787  if (SSL_set_fd(TLScontext->con, props->stream == 0 ? props->fd :
788  vstream_fileno(props->stream)) != 1) {
789  msg_info("SSL_set_fd error to %s", props->namaddr);
790  tls_print_errors();
791  uncache_session(app_ctx->ssl_ctx, TLScontext);
792  tls_free_context(TLScontext);
793  return (0);
794  }
795 
796  /*
797  * If the debug level selected is high enough, all of the data is dumped:
798  * TLS_LOG_TLSPKTS will dump the SSL negotiation, TLS_LOG_ALLPKTS will
799  * dump everything.
800  *
801  * We do have an SSL_set_fd() and now suddenly a BIO_ routine is called?
802  * Well there is a BIO below the SSL routines that is automatically
803  * created for us, so we can use it for debugging purposes.
804  */
805  if (log_mask & TLS_LOG_TLSPKTS)
806  BIO_set_callback(SSL_get_rbio(TLScontext->con), tls_bio_dump_cb);
807 
808  /*
809  * If we don't trigger the handshake in the library, leave control over
810  * SSL_accept/read/write/etc with the application.
811  */
812  if (props->stream == 0)
813  return (TLScontext);
814 
815  /*
816  * Turn on non-blocking I/O so that we can enforce timeouts on network
817  * I/O.
818  */
819  non_blocking(vstream_fileno(props->stream), NON_BLOCKING);
820 
821  /*
822  * Start TLS negotiations. This process is a black box that invokes our
823  * call-backs for session caching and certificate verification.
824  *
825  * Error handling: If the SSL handhake fails, we print out an error message
826  * and remove all TLS state concerning this session.
827  */
828  sts = tls_bio_accept(vstream_fileno(props->stream), props->timeout,
829  TLScontext);
830  if (sts <= 0) {
831  if (ERR_peek_error() != 0) {
832  msg_info("SSL_accept error from %s: %d", props->namaddr, sts);
833  tls_print_errors();
834  } else if (errno != 0) {
835  msg_info("SSL_accept error from %s: %m", props->namaddr);
836  } else {
837  msg_info("SSL_accept error from %s: lost connection",
838  props->namaddr);
839  }
840  tls_free_context(TLScontext);
841  return (0);
842  }
843  return (tls_server_post_accept(TLScontext));
844 }
845 
846 /* tls_server_post_accept - post-handshake processing */
847 
848 TLS_SESS_STATE *tls_server_post_accept(TLS_SESS_STATE *TLScontext)
849 {
850  SSL_CIPHER_const SSL_CIPHER *cipher;
851  X509 *peer;
852  char buf[CCERT_BUFSIZ];
853 
854  /* Turn off packet dump if only dumping the handshake */
855  if ((TLScontext->log_mask & TLS_LOG_ALLPKTS) == 0)
856  BIO_set_callback(SSL_get_rbio(TLScontext->con), 0);
857 
858  /*
859  * The caller may want to know if this session was reused or if a new
860  * session was negotiated.
861  */
862  TLScontext->session_reused = SSL_session_reused(TLScontext->con);
863  if ((TLScontext->log_mask & TLS_LOG_CACHE) && TLScontext->session_reused)
864  msg_info("%s: Reusing old session%s", TLScontext->namaddr,
865  TLScontext->ticketed ? " (RFC 5077 session ticket)" : "");
866 
867  /*
868  * Let's see whether a peer certificate is available and what is the
869  * actual information. We want to save it for later use.
870  */
871  peer = SSL_get_peer_certificate(TLScontext->con);
872  if (peer != NULL) {
873  TLScontext->peer_status |= TLS_CERT_FLAG_PRESENT;
874  if (SSL_get_verify_result(TLScontext->con) == X509_V_OK)
875  TLScontext->peer_status |= TLS_CERT_FLAG_TRUSTED;
876 
877  if (TLScontext->log_mask & TLS_LOG_VERBOSE) {
878  X509_NAME_oneline(X509_get_subject_name(peer),
879  buf, sizeof(buf));
880  msg_info("subject=%s", printable(buf, '?'));
881  X509_NAME_oneline(X509_get_issuer_name(peer),
882  buf, sizeof(buf));
883  msg_info("issuer=%s", printable(buf, '?'));
884  }
885  TLScontext->peer_CN = tls_peer_CN(peer, TLScontext);
886  TLScontext->issuer_CN = tls_issuer_CN(peer, TLScontext);
887  TLScontext->peer_cert_fprint = tls_cert_fprint(peer, TLScontext->mdalg);
888  TLScontext->peer_pkey_fprint = tls_pkey_fprint(peer, TLScontext->mdalg);
889 
890  if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_PEERCERT)) {
891  msg_info("%s: subject_CN=%s, issuer=%s, fingerprint=%s"
892  ", pkey_fingerprint=%s",
893  TLScontext->namaddr,
894  TLScontext->peer_CN, TLScontext->issuer_CN,
895  TLScontext->peer_cert_fprint,
896  TLScontext->peer_pkey_fprint);
897  }
898  X509_free(peer);
899 
900  /*
901  * Give them a clue. Problems with trust chain verification are
902  * logged when the session is first negotiated, before the session is
903  * stored into the cache. We don't want mystery failures, so log the
904  * fact the real problem is to be found in the past.
905  */
906  if (!TLS_CERT_IS_TRUSTED(TLScontext)
907  && (TLScontext->log_mask & TLS_LOG_UNTRUSTED)) {
908  if (TLScontext->session_reused == 0)
909  tls_log_verify_error(TLScontext);
910  else
911  msg_info("%s: re-using session with untrusted certificate, "
912  "look for details earlier in the log",
913  TLScontext->namaddr);
914  }
915  } else {
916  TLScontext->peer_CN = mystrdup("");
917  TLScontext->issuer_CN = mystrdup("");
918  TLScontext->peer_cert_fprint = mystrdup("");
919  TLScontext->peer_pkey_fprint = mystrdup("");
920  }
921 
922  /*
923  * Finally, collect information about protocol and cipher for logging
924  */
925  TLScontext->protocol = SSL_get_version(TLScontext->con);
926  cipher = SSL_get_current_cipher(TLScontext->con);
927  TLScontext->cipher_name = SSL_CIPHER_get_name(cipher);
928  TLScontext->cipher_usebits = SSL_CIPHER_get_bits(cipher,
929  &(TLScontext->cipher_algbits));
930 
931  /*
932  * If the library triggered the SSL handshake, switch to the
933  * tls_timed_read/write() functions and make the TLScontext available to
934  * those functions. Otherwise, leave control over SSL_read/write/etc.
935  * with the application.
936  */
937  if (TLScontext->stream != 0)
938  tls_stream_start(TLScontext->stream, TLScontext);
939 
940  /*
941  * All the key facts in a single log entry.
942  */
943  if (TLScontext->log_mask & TLS_LOG_SUMMARY)
944  msg_info("%s TLS connection established from %s: %s with cipher %s "
945  "(%d/%d bits)", !TLS_CERT_IS_PRESENT(TLScontext) ? "Anonymous"
946  : TLS_CERT_IS_TRUSTED(TLScontext) ? "Trusted" : "Untrusted",
947  TLScontext->namaddr, TLScontext->protocol, TLScontext->cipher_name,
948  TLScontext->cipher_usebits, TLScontext->cipher_algbits);
949 
950  tls_int_seed();
951 
952  return (TLScontext);
953 }
954 
955 #endif /* USE_TLS */
char * mystrdup(const char *str)
Definition: mymalloc.c:225
char * var_tls_tkt_cipher
#define TLS_TICKET_NAMELEN
Definition: tls_scache.h:32
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
int tls_mgr_lookup(const char *, const char *, VSTRING *)
#define LEN
Definition: cleanup_addr.c:106
#define TLS_TICKET_IVLEN
Definition: tls_scache.h:33
int tls_mgr_update(const char *, const char *, const char *, ssize_t)
unsigned char hmac[TLS_TICKET_MACLEN]
Definition: tls_scache.h:41
unsigned char name[TLS_TICKET_NAMELEN]
Definition: tls_scache.h:39
#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 VAR_TLS_TKT_CIPHER
Definition: mail_params.h:3305
int tls_mgr_delete(const char *, const char *)
TLS_TICKET_KEY * tls_mgr_key(unsigned char *, int)
int tls_mgr_policy(const char *, int *, int *)
unsigned char bits[TLS_TICKET_KEYLEN]
Definition: tls_scache.h:40
bool var_tls_preempt_clist
#define NON_BLOCKING
Definition: iostuff.h:49
int int
Definition: smtpd_proxy.h:21
int non_blocking(int, int)
Definition: non_blocking.c:55
VSTRING * vstring_free(VSTRING *vp)
Definition: vstring.c:380
#define TLS_TICKET_MACLEN
Definition: tls_scache.h:35
#define vstream_fileno(vp)
Definition: vstream.h:115
#define TLS_TICKET_KEYLEN
Definition: tls_scache.h:34
char * printable(char *string, int replacement)
Definition: printable.c:49
void msg_info(const char *fmt,...)
Definition: msg.c:199