2 * Copyright (c) 2000-2006, 2008, 2009, 2011, 2013 Sendmail, Inc. and its suppliers.
5 * By using this file, you agree to the terms and conditions set
6 * forth in the LICENSE file which can be found at the top level of
7 * the sendmail distribution.
13 SM_RCSID("@(#)$Id: tls.c,v 8.121 2013/01/02 23:54:17 ca Exp $")
16 # include <openssl/err.h>
17 # include <openssl/bio.h>
18 # include <openssl/pem.h>
19 # ifndef HASURANDOMDEV
20 # include <openssl/rand.h>
21 # endif /* ! HASURANDOMDEV */
23 static RSA *rsa_tmp = NULL; /* temporary RSA key */
24 static RSA *tmp_rsa_key __P((SSL *, int, int));
25 # endif /* !TLS_NO_RSA */
26 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
27 static int tls_verify_cb __P((X509_STORE_CTX *));
28 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
29 static int tls_verify_cb __P((X509_STORE_CTX *, void *));
30 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
32 # if OPENSSL_VERSION_NUMBER > 0x00907000L
33 static int x509_verify_cb __P((int, X509_STORE_CTX *));
34 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
36 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
38 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
39 # define CONST097 const
40 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
41 static void apps_ssl_info_cb __P((CONST097 SSL *, int , int));
42 static bool tls_ok_f __P((char *, char *, int));
43 static bool tls_safe_f __P((char *, long, bool));
44 static int tls_verify_log __P((int, X509_STORE_CTX *, char *));
47 static DH *get_dh512 __P((void));
49 static unsigned char dh512_p[] =
51 0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
52 0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
53 0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
54 0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
55 0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
58 static unsigned char dh512_g[] =
68 if ((dh = DH_new()) == NULL)
70 dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
71 dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
72 if ((dh->p == NULL) || (dh->g == NULL))
80 ** TLS_RAND_INIT -- initialize STARTTLS random generator
83 ** randfile -- name of file with random data
90 ** initializes PRNG for tls library.
93 # define MIN_RAND_BYTES 128 /* 1024 bits */
95 # define RF_OK 0 /* randfile OK */
96 # define RF_MISS 1 /* randfile == NULL || *randfile == '\0' */
97 # define RF_UNKNOWN 2 /* unknown prefix for randfile */
99 # define RI_NONE 0 /* no init yet */
100 # define RI_SUCCESS 1 /* init was successful */
101 # define RI_FAIL 2 /* init failed */
103 static bool tls_rand_init __P((char *, int));
106 tls_rand_init(randfile, logl)
110 # ifndef HASURANDOMDEV
111 /* not required if /dev/urandom exists, OpenSSL does it internally */
115 static int done = RI_NONE;
121 /* did we try this before? if yes: return old value */
123 return done == RI_SUCCESS;
125 /* set default values */
128 randdef = (randfile == NULL || *randfile == '\0') ? RF_MISS : RF_OK;
130 if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0)
133 if (RAND_egd(randfile) < 0)
135 sm_syslog(LOG_WARNING, NOQID,
136 "STARTTLS: RAND_egd(%s) failed: random number generator not seeded",
144 if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0)
151 sff = SFF_SAFEDIRPATH | SFF_NOWLINK
152 | SFF_NOGWFILES | SFF_NOWWFILES
153 | SFF_NOGRFILES | SFF_NOWRFILES
154 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
155 if (DontLockReadFiles)
157 if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0)
159 if (fstat(fd, &st) < 0)
162 sm_syslog(LOG_ERR, NOQID,
163 "STARTTLS: can't fstat(%s)",
173 /* max. age of file: 10 minutes */
174 if (st.st_mtime + 600 < curtime())
176 use = bitnset(DBS_INSUFFICIENTENTROPY,
180 sm_syslog(LOG_ERR, NOQID,
181 "STARTTLS: RandFile %s too old: %s",
186 if (use && st.st_size < MIN_RAND_BYTES)
188 use = bitnset(DBS_INSUFFICIENTENTROPY,
192 sm_syslog(LOG_ERR, NOQID,
193 "STARTTLS: size(%s) < %d: %s",
200 ok = RAND_load_file(randfile, -1) >=
205 sm_syslog(LOG_WARNING, NOQID,
206 "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded",
212 if (ok || bitnset(DBS_INSUFFICIENTENTROPY,
215 /* add this even if fstat() failed */
216 RAND_seed((void *) &st, sizeof(st));
223 sm_syslog(LOG_WARNING, NOQID,
224 "STARTTLS: Warning: safeopen(%s) failed",
228 else if (randdef == RF_OK)
231 sm_syslog(LOG_WARNING, NOQID,
232 "STARTTLS: Error: no proper random file definition %s",
234 randdef = RF_UNKNOWN;
236 if (randdef == RF_MISS)
239 sm_syslog(LOG_WARNING, NOQID,
240 "STARTTLS: Error: missing random file definition");
242 if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail))
246 unsigned char buf[MIN_RAND_BYTES];
248 /* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */
249 for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long))
252 (void) memcpy(buf + i, (void *) &r, sizeof(long));
254 RAND_seed(buf, sizeof(buf));
256 sm_syslog(LOG_WARNING, NOQID,
257 "STARTTLS: Warning: random number generator not properly seeded");
260 done = ok ? RI_SUCCESS : RI_FAIL;
262 # else /* ! HASURANDOMDEV */
264 # endif /* ! HASURANDOMDEV */
267 ** INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
270 ** fipsmode -- use FIPS?
277 init_tls_library(fipsmode)
282 /* basic TLS initialization, ignore result for now */
284 SSL_load_error_strings();
286 /* this is currently a macro for SSL_library_init */
287 SSLeay_add_ssl_algorithms();
290 bv = tls_rand_init(RandFile, 7);
294 if (!FIPS_mode_set(1))
298 err = ERR_get_error();
300 sm_syslog(LOG_ERR, NOQID,
301 "STARTTLS=init, FIPSMode=%s",
302 ERR_error_string(err, NULL));
308 sm_syslog(LOG_INFO, NOQID,
309 "STARTTLS=init, FIPSMode=ok");
312 #endif /* _FFR_FIPSMODE */
316 ** TLS_SET_VERIFY -- request client certificate?
319 ** ctx -- TLS context
320 ** ssl -- TLS structure
321 ** vrfy -- require certificate?
327 ** Sets verification state for TLS
329 # if TLS_VRFY_PER_CTX
331 ** This is per TLS context, not per TLS structure;
332 ** the former is global, the latter per connection.
333 ** It would be nice to do this per connection, but this
334 ** doesn't work in the current TLS libraries :-(
335 # endif * TLS_VRFY_PER_CTX *
339 tls_set_verify(ctx, ssl, vrfy)
344 # if !TLS_VRFY_PER_CTX
345 SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
346 # else /* !TLS_VRFY_PER_CTX */
347 SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
349 # endif /* !TLS_VRFY_PER_CTX */
353 ** status in initialization
354 ** these flags keep track of the status of the initialization
355 ** i.e., whether a file exists (_EX) and whether it can be used (_OK)
356 ** [due to permissions]
359 # define TLS_S_NONE 0x00000000 /* none yet */
360 # define TLS_S_CERT_EX 0x00000001 /* cert file exists */
361 # define TLS_S_CERT_OK 0x00000002 /* cert file is ok */
362 # define TLS_S_KEY_EX 0x00000004 /* key file exists */
363 # define TLS_S_KEY_OK 0x00000008 /* key file is ok */
364 # define TLS_S_CERTP_EX 0x00000010 /* CA cert path exists */
365 # define TLS_S_CERTP_OK 0x00000020 /* CA cert path is ok */
366 # define TLS_S_CERTF_EX 0x00000040 /* CA cert file exists */
367 # define TLS_S_CERTF_OK 0x00000080 /* CA cert file is ok */
368 # define TLS_S_CRLF_EX 0x00000100 /* CRL file exists */
369 # define TLS_S_CRLF_OK 0x00000200 /* CRL file is ok */
372 # define TLS_S_CERT2_EX 0x00001000 /* 2nd cert file exists */
373 # define TLS_S_CERT2_OK 0x00002000 /* 2nd cert file is ok */
374 # define TLS_S_KEY2_EX 0x00004000 /* 2nd key file exists */
375 # define TLS_S_KEY2_OK 0x00008000 /* 2nd key file is ok */
376 # endif /* _FFR_TLS_1 */
378 # define TLS_S_DH_OK 0x00200000 /* DH cert is ok */
379 # define TLS_S_DHPAR_EX 0x00400000 /* DH param file exists */
380 # define TLS_S_DHPAR_OK 0x00800000 /* DH param file is ok to use */
382 /* Type of variable */
383 # define TLS_T_OTHER 0
388 ** TLS_OK_F -- can var be an absolute filename?
392 ** fn -- what is the filename used for?
393 ** type -- type of variable
400 tls_ok_f(var, fn, type)
405 /* must be absolute pathname */
406 if (var != NULL && *var == '/')
409 sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
410 type == TLS_T_SRV ? "Server" :
411 (type == TLS_T_CLT ? "Client" : ""), fn);
415 ** TLS_SAFE_F -- is a file safe to use?
419 ** sff -- flags for safefile()
420 ** srv -- server side?
427 tls_safe_f(var, sff, srv)
434 if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
435 S_IRUSR, NULL)) == 0)
438 sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
439 srv ? "server" : "client", var, sm_errstring(ret));
444 ** TLS_OK_F -- macro to simplify calls to tls_ok_f
448 ** fn -- what is the filename used for?
449 ** req -- is the file required?
450 ** st -- status bit to set if ok
451 ** type -- type of variable
454 ** uses r, ok; may change ok and status.
458 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
460 r = tls_ok_f(var, fn, type); \
468 ** TLS_UNR -- macro to return whether a file should be unreadable
471 ** bit -- flag to test
477 # define TLS_UNR(bit, req) (bitset(bit, req) ? SFF_NORFILES : 0)
478 # define TLS_OUNR(bit, req) (bitset(bit, req) ? SFF_NOWRFILES : 0)
479 # define TLS_KEYSFF(req) \
480 (bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ? \
481 TLS_OUNR(TLS_I_KEY_OUNR, req) : \
482 TLS_UNR(TLS_I_KEY_UNR, req))
485 ** TLS_SAFE_F -- macro to simplify calls to tls_safe_f
489 ** sff -- flags for safefile()
490 ** req -- is the file required?
491 ** ex -- does the file exist?
492 ** st -- status bit to set if ok
493 ** srv -- server side?
496 ** uses r, ok, ex; may change ok and status.
500 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
502 r = tls_safe_f(var, sff, srv); \
510 ** INITTLS -- initialize TLS
513 ** ctx -- pointer to context
514 ** req -- requirements for initialization (see sendmail.h)
515 ** options -- options
516 ** srv -- server side?
517 ** certfile -- filename of certificate
518 ** keyfile -- filename of private key
519 ** cacertpath -- path to CAs
520 ** cacertfile -- file with CA(s)
521 ** dhparam -- parameters for DH
528 ** The session_id_context identifies the service that created a session.
529 ** This information is used to distinguish between multiple TLS-based
530 ** servers running on the same server. We use the name of the mail system.
531 ** Note: the session cache is not persistent.
534 static char server_session_id_context[] = "sendmail8";
536 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
537 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
538 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 1
540 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 0
544 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
549 char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
552 static DH *dh = NULL;
560 # endif /* _FFR_TLS_1 */
563 # endif /* SM_CONF_SHM */
564 # if OPENSSL_VERSION_NUMBER > 0x00907000L
568 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
569 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
571 STACK_OF(SSL_COMP) *comp_methods;
575 who = srv ? "server" : "client";
578 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
580 SM_ASSERT(ctx != NULL);
583 /* already initialized? (we could re-init...) */
590 ** look for a second filename: it must be separated by a ','
591 ** no blanks allowed (they won't be skipped).
592 ** we change a global variable here! this change will be undone
593 ** before return from the function but only if it returns true.
594 ** this isn't a problem since in a failure case this function
595 ** won't be called again with the same (overwritten) values.
596 ** otherwise each return must be replaced with a goto endinittls.
601 if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
604 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
607 # endif /* _FFR_TLS_1 */
610 ** Check whether files/paths are defined
613 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
614 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
615 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
616 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
617 TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
618 TLS_S_CERTP_EX, TLS_T_OTHER);
619 TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
620 TLS_S_CERTF_EX, TLS_T_OTHER);
622 # if OPENSSL_VERSION_NUMBER > 0x00907000L
623 TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
624 TLS_S_CRLF_EX, TLS_T_OTHER);
625 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
629 ** if the second file is specified it must exist
630 ** XXX: it is possible here to define only one of those files
635 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
636 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
640 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
641 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
643 # endif /* _FFR_TLS_1 */
646 ** valid values for dhparam are (only the first char is checked)
647 ** none no parameters: don't use DH
648 ** 512 generate 512 bit parameters (fixed)
649 ** 1024 generate 1024 bit parameters
650 ** /file/name read parameters from /file/name
651 ** default is: 1024 for server, 512 for client (OK? XXX)
654 if (bitset(TLS_I_TRY_DH, req))
664 else if (c != 'n' && c != 'N' && c != '/')
667 sm_syslog(LOG_WARNING, NOQID,
668 "STARTTLS=%s, error: illegal value '%s' for DHParam",
675 dhparam = srv ? "1" : "5";
676 req |= (srv ? TLS_I_DH1024 : TLS_I_DH512);
678 else if (*dhparam == '/')
680 TLS_OK_F(dhparam, "DHParameters",
681 bitset(TLS_I_DHPAR_EX, req),
682 TLS_S_DHPAR_EX, TLS_T_OTHER);
688 /* certfile etc. must be "safe". */
689 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
690 | SFF_NOGWFILES | SFF_NOWWFILES
691 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
692 if (DontLockReadFiles)
695 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
696 bitset(TLS_I_CERT_EX, req),
697 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
698 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
699 bitset(TLS_I_KEY_EX, req),
700 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
701 TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
702 bitset(TLS_I_CERTF_EX, req),
703 bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
704 TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
705 bitset(TLS_I_DHPAR_EX, req),
706 bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
707 # if OPENSSL_VERSION_NUMBER > 0x00907000L
708 TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
709 bitset(TLS_I_CRLF_EX, req),
710 bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
711 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
717 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
718 bitset(TLS_I_CERT_EX, req),
719 bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
723 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
724 bitset(TLS_I_KEY_EX, req),
725 bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
727 # endif /* _FFR_TLS_1 */
729 /* create a method and a new context */
730 if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
731 SSLv23_client_method())) == NULL)
734 sm_syslog(LOG_WARNING, NOQID,
735 "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
738 tlslogerr(LOG_WARNING, who);
742 # if OPENSSL_VERSION_NUMBER > 0x00907000L
745 /* get a pointer to the current certificate validation store */
746 store = SSL_CTX_get_cert_store(*ctx); /* does not fail */
747 crl_file = BIO_new(BIO_s_file_internal());
748 if (crl_file != NULL)
750 if (BIO_read_filename(crl_file, CRLFile) >= 0)
752 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
755 X509_STORE_add_crl(store, crl);
757 X509_STORE_set_flags(store,
758 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
759 X509_STORE_set_verify_cb_func(store,
766 sm_syslog(LOG_WARNING, NOQID,
767 "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
771 /* avoid memory leaks */
777 else if (LogLevel > 9)
778 sm_syslog(LOG_WARNING, NOQID,
779 "STARTTLS=%s, error: BIO_new=failed", who);
784 if (CRLPath != NULL && store != NULL)
788 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
793 sm_syslog(LOG_WARNING, NOQID,
794 "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
799 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
800 X509_STORE_set_flags(store,
801 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
803 # endif /* _FFR_CRLPATH */
804 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
807 /* turn off backward compatibility, required for no-rsa */
808 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
809 # endif /* TLS_NO_RSA */
814 ** Create a temporary RSA key
815 ** XXX Maybe we shouldn't create this always (even though it
816 ** is only at startup).
817 ** It is a time-consuming operation and it is not always necessary.
818 ** maybe we should do it only on demand...
821 if (bitset(TLS_I_RSA_TMP, req)
823 && ShmId != SM_SHM_NO_ID &&
824 (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL,
826 # else /* SM_CONF_SHM */
827 && 0 /* no shared memory: no need to generate key now */
828 # endif /* SM_CONF_SHM */
833 sm_syslog(LOG_WARNING, NOQID,
834 "STARTTLS=%s, error: RSA_generate_key failed",
837 tlslogerr(LOG_WARNING, who);
841 # endif /* !TLS_NO_RSA */
845 ** XXX change this for DSA-only version
848 if (bitset(TLS_S_KEY_OK, status) &&
849 SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
850 SSL_FILETYPE_PEM) <= 0)
854 sm_syslog(LOG_WARNING, NOQID,
855 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
858 tlslogerr(LOG_WARNING, who);
860 if (bitset(TLS_I_USE_KEY, req))
864 /* get the certificate file */
865 if (bitset(TLS_S_CERT_OK, status) &&
866 SSL_CTX_use_certificate_file(*ctx, certfile,
867 SSL_FILETYPE_PEM) <= 0)
871 sm_syslog(LOG_WARNING, NOQID,
872 "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
875 tlslogerr(LOG_WARNING, who);
877 if (bitset(TLS_I_USE_CERT, req))
881 /* check the private key */
882 if (bitset(TLS_S_KEY_OK, status) &&
883 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
885 /* Private key does not match the certificate public key */
888 sm_syslog(LOG_WARNING, NOQID,
889 "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
892 tlslogerr(LOG_WARNING, who);
894 if (bitset(TLS_I_USE_KEY, req))
899 /* XXX this code is pretty much duplicated from above! */
901 /* load private key */
902 if (bitset(TLS_S_KEY2_OK, status) &&
903 SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
907 sm_syslog(LOG_WARNING, NOQID,
908 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
911 tlslogerr(LOG_WARNING, who);
915 /* get the certificate file */
916 if (bitset(TLS_S_CERT2_OK, status) &&
917 SSL_CTX_use_certificate_file(*ctx, cf2, SSL_FILETYPE_PEM) <= 0)
921 sm_syslog(LOG_WARNING, NOQID,
922 "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
925 tlslogerr(LOG_WARNING, who);
929 /* also check the private key */
930 if (bitset(TLS_S_KEY2_OK, status) &&
931 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
933 /* Private key does not match the certificate public key */
936 sm_syslog(LOG_WARNING, NOQID,
937 "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
940 tlslogerr(LOG_WARNING, who);
943 # endif /* _FFR_TLS_1 */
945 /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
947 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
950 ** In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
951 ** padding bug work-around, leading to false positives and
952 ** failed connections. We may not interoperate with systems
953 ** with the bug, but this is better than breaking on all 0.9.8[ab]
954 ** systems that have zlib support enabled.
955 ** Note: this checks the runtime version of the library, not
956 ** just the compile time version.
959 rt_version = SSLeay();
960 if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
962 comp_methods = SSL_COMP_get_compression_methods();
963 if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
964 options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
967 SSL_CTX_set_options(*ctx, options);
970 /* Diffie-Hellman initialization */
971 if (bitset(TLS_I_TRY_DH, req))
973 if (bitset(TLS_S_DHPAR_OK, status))
977 if ((bio = BIO_new_file(dhparam, "r")) != NULL)
979 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
981 if (dh == NULL && LogLevel > 7)
985 err = ERR_get_error();
986 sm_syslog(LOG_WARNING, NOQID,
987 "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
989 ERR_error_string(err, NULL));
991 tlslogerr(LOG_WARNING, who);
998 sm_syslog(LOG_WARNING, NOQID,
999 "STARTTLS=%s, error: BIO_new_file(%s) failed",
1002 tlslogerr(LOG_WARNING, who);
1006 if (dh == NULL && bitset(TLS_I_DH1024, req))
1010 /* this takes a while! (7-130s on a 450MHz AMD K6-2) */
1011 dsa = DSA_generate_parameters(1024, NULL, 0, NULL,
1013 dh = DSA_dup_DH(dsa);
1017 if (dh == NULL && bitset(TLS_I_DH512, req))
1026 err = ERR_get_error();
1027 sm_syslog(LOG_WARNING, NOQID,
1028 "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1030 ERR_error_string(err, NULL));
1032 if (bitset(TLS_I_REQ_DH, req))
1037 SSL_CTX_set_tmp_dh(*ctx, dh);
1039 /* important to avoid small subgroup attacks */
1040 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
1042 sm_syslog(LOG_INFO, NOQID,
1043 "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
1044 who, 8 * DH_size(dh), *dhparam);
1048 # endif /* !NO_DH */
1051 /* XXX do we need this cache here? */
1052 if (bitset(TLS_I_CACHE, req))
1054 SSL_CTX_sess_set_cache_size(*ctx, 1);
1055 SSL_CTX_set_timeout(*ctx, 1);
1056 SSL_CTX_set_session_id_context(*ctx,
1057 (void *) &server_session_id_context,
1058 sizeof(server_session_id_context));
1059 (void) SSL_CTX_set_session_cache_mode(*ctx,
1060 SSL_SESS_CACHE_SERVER);
1064 (void) SSL_CTX_set_session_cache_mode(*ctx,
1065 SSL_SESS_CACHE_OFF);
1068 /* load certificate locations and default CA paths */
1069 if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1071 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1075 if (bitset(TLS_I_RSA_TMP, req))
1076 SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1077 # endif /* !TLS_NO_RSA */
1080 ** We have to install our own verify callback:
1081 ** SSL_VERIFY_PEER requests a client cert but even
1082 ** though *FAIL_IF* isn't set, the connection
1083 ** will be aborted if the client presents a cert
1084 ** that is not "liked" (can't be verified?) by
1085 ** the TLS library :-(
1089 ** XXX currently we could call tls_set_verify()
1090 ** but we hope that that function will later on
1091 ** only set the mode per connection.
1093 SSL_CTX_set_verify(*ctx,
1094 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1098 /* install verify callback */
1099 SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb,
1101 SSL_CTX_set_client_CA_list(*ctx,
1102 SSL_load_client_CA_file(cacertfile));
1107 ** can't load CA data; do we care?
1108 ** the data is necessary to authenticate the client,
1109 ** which in turn would be necessary
1110 ** if we want to allow relaying based on it.
1114 sm_syslog(LOG_WARNING, NOQID,
1115 "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1116 who, cacertpath, cacertfile, r);
1118 tlslogerr(LOG_WARNING, who);
1120 if (bitset(TLS_I_VRFY_LOC, req))
1125 /* XXX: make this dependent on an option? */
1127 SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1130 /* install our own cipher list */
1131 if (CipherList != NULL && *CipherList != '\0')
1133 if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1137 sm_syslog(LOG_WARNING, NOQID,
1138 "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1142 tlslogerr(LOG_WARNING, who);
1144 /* failure if setting to this list is required? */
1147 # endif /* _FFR_TLS_1 */
1149 sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1154 ** this label is required if we want to have a "clean" exit
1155 ** see the comments above at the initialization of cf2
1161 /* undo damage to global variables */
1166 # endif /* _FFR_TLS_1 */
1171 ** TLS_GET_INFO -- get information about TLS connection
1174 ** ssl -- TLS connection structure
1175 ** srv -- server or client
1176 ** host -- hostname of other side
1177 ** mac -- macro storage
1178 ** certreq -- did we ask for a cert?
1181 ** result of authentication.
1184 ** sets macros: {cipher}, {tls_version}, {verify},
1185 ** {cipher_bits}, {alg_bits}, {cert}, {cert_subject},
1186 ** {cert_issuer}, {cn_subject}, {cn_issuer}
1190 tls_get_info(ssl, srv, host, mac, certreq)
1197 const SSL_CIPHER *c;
1204 c = SSL_get_current_cipher(ssl);
1206 /* cast is just workaround for compiler warning */
1207 macdefine(mac, A_TEMP, macid("{cipher}"),
1208 (char *) SSL_CIPHER_get_name(c));
1209 b = SSL_CIPHER_get_bits(c, &r);
1210 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1211 macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1212 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1213 macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1214 s = SSL_CIPHER_get_version(c);
1217 macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1219 who = srv ? "server" : "client";
1220 cert = SSL_get_peer_certificate(ssl);
1221 verifyok = SSL_get_verify_result(ssl);
1223 sm_syslog(LOG_INFO, NOQID,
1224 "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1225 who, verifyok, (unsigned long) cert);
1229 X509_NAME *subj, *issuer;
1230 unsigned char md[EVP_MAX_MD_SIZE];
1233 subj = X509_get_subject_name(cert);
1234 issuer = X509_get_issuer_name(cert);
1235 X509_NAME_oneline(subj, buf, sizeof(buf));
1236 macdefine(mac, A_TEMP, macid("{cert_subject}"),
1237 xtextify(buf, "<>\")"));
1238 X509_NAME_oneline(issuer, buf, sizeof(buf));
1239 macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1240 xtextify(buf, "<>\")"));
1242 # define LL_BADCERT 8
1244 #define CHECK_X509_NAME(which) \
1248 sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \
1249 if (LogLevel > LL_BADCERT) \
1250 sm_syslog(LOG_INFO, NOQID, \
1251 "STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN", \
1253 host == NULL ? "local" : host, \
1256 else if ((size_t)r >= sizeof(buf) - 1) \
1258 sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \
1260 sm_syslog(LOG_INFO, NOQID, \
1261 "STARTTLS=%s, relay=%.100s, field=%s, status=CN too long", \
1263 host == NULL ? "local" : host, \
1266 else if ((size_t)r > strlen(buf)) \
1268 sm_strlcpy(buf, "BadCertificateContainsNUL", \
1271 sm_syslog(LOG_INFO, NOQID, \
1272 "STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL", \
1274 host == NULL ? "local" : host, \
1279 r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf,
1281 CHECK_X509_NAME("cn_subject");
1282 macdefine(mac, A_TEMP, macid("{cn_subject}"),
1283 xtextify(buf, "<>\")"));
1284 r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf,
1286 CHECK_X509_NAME("cn_issuer");
1287 macdefine(mac, A_TEMP, macid("{cn_issuer}"),
1288 xtextify(buf, "<>\")"));
1290 if (X509_digest(cert, EVP_md5(), md, &n) != 0 && n > 0)
1292 char md5h[EVP_MAX_MD_SIZE * 3];
1293 static const char hexcodes[] = "0123456789ABCDEF";
1295 SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1296 for (r = 0; r < (int) n; r++)
1298 md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1299 md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1300 md5h[(r * 3) + 2] = ':';
1302 md5h[(n * 3) - 1] = '\0';
1303 macdefine(mac, A_TEMP, macid("{cert_md5}"), md5h);
1306 macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1310 macdefine(mac, A_PERM, macid("{cert_subject}"), "");
1311 macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
1312 macdefine(mac, A_PERM, macid("{cn_subject}"), "");
1313 macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
1314 macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1326 s = certreq ? "NO" : "NOT",
1335 macdefine(mac, A_PERM, macid("{verify}"), s);
1339 /* do some logging */
1342 char *vers, *s1, *s2, *cbits, *algbits;
1344 vers = macget(mac, macid("{tls_version}"));
1345 cbits = macget(mac, macid("{cipher_bits}"));
1346 algbits = macget(mac, macid("{alg_bits}"));
1347 s1 = macget(mac, macid("{verify}"));
1348 s2 = macget(mac, macid("{cipher}"));
1350 /* XXX: maybe cut off ident info? */
1351 sm_syslog(LOG_INFO, NOQID,
1352 "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s",
1354 host == NULL ? "local" : host,
1355 vers, s1, s2, /* sm_snprintf() can deal with NULL */
1356 algbits == NULL ? "0" : algbits,
1357 cbits == NULL ? "0" : cbits);
1361 ** Maybe run xuntextify on the strings?
1362 ** That is easier to read but makes it maybe a bit
1363 ** more complicated to figure out the right values
1364 ** for the access map...
1367 s1 = macget(mac, macid("{cert_subject}"));
1368 s2 = macget(mac, macid("{cert_issuer}"));
1369 sm_syslog(LOG_INFO, NOQID,
1370 "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
1372 X509_verify_cert_error_string(verifyok));
1378 ** ENDTLS -- shutdown secure connection
1381 ** ssl -- SSL connection information.
1382 ** side -- server/client (for logging).
1385 ** success? (EX_* code)
1399 if ((r = SSL_shutdown(ssl)) < 0)
1403 sm_syslog(LOG_WARNING, NOQID,
1404 "STARTTLS=%s, SSL_shutdown failed: %d",
1406 tlslogerr(LOG_WARNING, side);
1410 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1413 ** Bug in OpenSSL (at least up to 0.9.6b):
1414 ** From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1415 ** Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1416 ** To: openssl-users@openssl.org
1417 ** Subject: Re: SSL_shutdown() woes (fwd)
1419 ** The side sending the shutdown alert first will
1420 ** not care about the answer of the peer but will
1421 ** immediately return with a return value of "0"
1422 ** (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1423 ** the value of "0" and as the shutdown alert of the peer was
1424 ** not received (actually, the program did not even wait for
1425 ** the answer), an SSL_ERROR_SYSCALL is flagged, because this
1426 ** is the default rule in case everything else does not apply.
1428 ** For your server the problem is different, because it
1429 ** receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1430 ** then sends its response (SSL_SENT_SHUTDOWN), so for the
1431 ** server the shutdown was successfull.
1433 ** As is by know, you would have to call SSL_shutdown() once
1434 ** and ignore an SSL_ERROR_SYSCALL returned. Then call
1435 ** SSL_shutdown() again to actually get the server's response.
1437 ** In the last discussion, Bodo Moeller concluded that a
1438 ** rewrite of the shutdown code would be necessary, but
1439 ** probably with another API, as the change would not be
1440 ** compatible to the way it is now. Things do not become
1441 ** easier as other programs do not follow the shutdown
1442 ** guidelines anyway, so that a lot error conditions and
1443 ** compitibility issues would have to be caught.
1445 ** For now the recommondation is to ignore the error message.
1452 sm_syslog(LOG_WARNING, NOQID,
1453 "STARTTLS=%s, SSL_shutdown not done",
1455 tlslogerr(LOG_WARNING, side);
1459 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1468 ** TMP_RSA_KEY -- return temporary RSA key
1471 ** s -- TLS connection structure
1476 ** temporary RSA key.
1479 # ifndef MAX_RSA_TMP_CNT
1480 # define MAX_RSA_TMP_CNT 1000 /* XXX better value? */
1481 # endif /* ! MAX_RSA_TMP_CNT */
1485 tmp_rsa_key(s, export, keylength)
1492 extern int *PRSATmpCnt;
1494 if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1495 ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1497 # endif /* SM_CONF_SHM */
1499 if (rsa_tmp != NULL)
1501 rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL);
1502 if (rsa_tmp == NULL)
1505 sm_syslog(LOG_ERR, NOQID,
1506 "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1513 ** XXX we can't (yet) share the new key...
1514 ** The RSA structure contains pointers hence it can't be
1515 ** easily kept in shared memory. It must be transformed
1516 ** into a continous memory region first, then stored,
1517 ** and later read out again (each time re-transformed).
1520 if (ShmId != SM_SHM_NO_ID)
1523 # endif /* SM_CONF_SHM */
1525 sm_syslog(LOG_ERR, NOQID,
1526 "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1530 # endif /* !TLS_NO_RSA */
1532 ** APPS_SSL_INFO_CB -- info callback for TLS connections
1535 ** s -- TLS connection structure
1536 ** where -- state in handshake
1537 ** ret -- return code of last operation
1544 apps_ssl_info_cb(s, where, ret)
1551 BIO *bio_err = NULL;
1554 sm_syslog(LOG_INFO, NOQID,
1555 "STARTTLS: info_callback where=0x%x, ret=%d",
1558 w = where & ~SSL_ST_MASK;
1559 if (bio_err == NULL)
1560 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
1562 if (bitset(SSL_ST_CONNECT, w))
1563 str = "SSL_connect";
1564 else if (bitset(SSL_ST_ACCEPT, w))
1569 if (bitset(SSL_CB_LOOP, where))
1572 sm_syslog(LOG_NOTICE, NOQID,
1574 str, SSL_state_string_long(s));
1576 else if (bitset(SSL_CB_ALERT, where))
1578 str = bitset(SSL_CB_READ, where) ? "read" : "write";
1580 sm_syslog(LOG_NOTICE, NOQID,
1581 "STARTTLS: SSL3 alert %s:%s:%s",
1582 str, SSL_alert_type_string_long(ret),
1583 SSL_alert_desc_string_long(ret));
1585 else if (bitset(SSL_CB_EXIT, where))
1590 sm_syslog(LOG_WARNING, NOQID,
1591 "STARTTLS: %s:failed in %s",
1592 str, SSL_state_string_long(s));
1597 sm_syslog(LOG_WARNING, NOQID,
1598 "STARTTLS: %s:error in %s",
1599 str, SSL_state_string_long(s));
1604 ** TLS_VERIFY_LOG -- log verify error for TLS certificates
1608 ** ctx -- x509 context
1616 tls_verify_log(ok, ctx, name)
1618 X509_STORE_CTX *ctx;
1626 cert = X509_STORE_CTX_get_current_cert(ctx);
1627 reason = X509_STORE_CTX_get_error(ctx);
1628 depth = X509_STORE_CTX_get_error_depth(ctx);
1629 ssl = (SSL *) X509_STORE_CTX_get_ex_data(ctx,
1630 SSL_get_ex_data_X509_STORE_CTX_idx());
1634 /* internal error */
1635 sm_syslog(LOG_ERR, NOQID,
1636 "STARTTLS: internal error: tls_verify_cb: ssl == NULL");
1640 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1641 sm_syslog(LOG_INFO, NOQID,
1642 "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1643 name, depth, buf, ok, X509_verify_cert_error_string(reason));
1648 ** TLS_VERIFY_CB -- verify callback for TLS certificates
1651 ** ctx -- x509 context
1654 ** accept connection?
1655 ** currently: always yes.
1659 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1661 X509_STORE_CTX *ctx;
1662 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1663 tls_verify_cb(ctx, unused)
1664 X509_STORE_CTX *ctx;
1666 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1671 ** man SSL_CTX_set_cert_verify_callback():
1672 ** callback should return 1 to indicate verification success
1673 ** and 0 to indicate verification failure.
1676 ok = X509_verify_cert(ctx);
1680 return tls_verify_log(ok, ctx, "TLS");
1685 ** TLSLOGERR -- log the errors from the TLS error stack
1688 ** level -- syslog level
1689 ** who -- server/client (for logging).
1696 tlslogerr(level, who)
1705 # define CP (const char **)
1707 es = CRYPTO_thread_id();
1708 while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags))
1711 sm_syslog(level, NOQID,
1712 "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1713 ERR_error_string(l, buf),
1715 bitset(ERR_TXT_STRING, flags) ? data : "");
1719 # if OPENSSL_VERSION_NUMBER > 0x00907000L
1721 ** X509_VERIFY_CB -- verify callback
1724 ** ctx -- x509 context
1727 ** accept connection?
1728 ** currently: always yes.
1732 x509_verify_cb(ok, ctx)
1734 X509_STORE_CTX *ctx;
1739 tls_verify_log(ok, ctx, "x509");
1740 if (ctx->error == X509_V_ERR_UNABLE_TO_GET_CRL)
1743 return 1; /* override it */
1748 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1749 #endif /* STARTTLS */