2 * Copyright (c) 2000-2005 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.97 2005/03/08 22:20:52 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.
279 /* basic TLS initialization, ignore result for now */
281 SSL_load_error_strings();
283 /* this is currently a macro for SSL_library_init */
284 SSLeay_add_ssl_algorithms();
287 return tls_rand_init(RandFile, 7);
290 ** TLS_SET_VERIFY -- request client certificate?
293 ** ctx -- TLS context
294 ** ssl -- TLS structure
295 ** vrfy -- require certificate?
301 ** Sets verification state for TLS
303 # if TLS_VRFY_PER_CTX
305 ** This is per TLS context, not per TLS structure;
306 ** the former is global, the latter per connection.
307 ** It would be nice to do this per connection, but this
308 ** doesn't work in the current TLS libraries :-(
309 # endif * TLS_VRFY_PER_CTX *
313 tls_set_verify(ctx, ssl, vrfy)
318 # if !TLS_VRFY_PER_CTX
319 SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
320 # else /* !TLS_VRFY_PER_CTX */
321 SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
323 # endif /* !TLS_VRFY_PER_CTX */
327 ** status in initialization
328 ** these flags keep track of the status of the initialization
329 ** i.e., whether a file exists (_EX) and whether it can be used (_OK)
330 ** [due to permissions]
333 # define TLS_S_NONE 0x00000000 /* none yet */
334 # define TLS_S_CERT_EX 0x00000001 /* cert file exists */
335 # define TLS_S_CERT_OK 0x00000002 /* cert file is ok */
336 # define TLS_S_KEY_EX 0x00000004 /* key file exists */
337 # define TLS_S_KEY_OK 0x00000008 /* key file is ok */
338 # define TLS_S_CERTP_EX 0x00000010 /* CA cert path exists */
339 # define TLS_S_CERTP_OK 0x00000020 /* CA cert path is ok */
340 # define TLS_S_CERTF_EX 0x00000040 /* CA cert file exists */
341 # define TLS_S_CERTF_OK 0x00000080 /* CA cert file is ok */
342 # define TLS_S_CRLF_EX 0x00000100 /* CRL file exists */
343 # define TLS_S_CRLF_OK 0x00000200 /* CRL file is ok */
346 # define TLS_S_CERT2_EX 0x00001000 /* 2nd cert file exists */
347 # define TLS_S_CERT2_OK 0x00002000 /* 2nd cert file is ok */
348 # define TLS_S_KEY2_EX 0x00004000 /* 2nd key file exists */
349 # define TLS_S_KEY2_OK 0x00008000 /* 2nd key file is ok */
350 # endif /* _FFR_TLS_1 */
352 # define TLS_S_DH_OK 0x00200000 /* DH cert is ok */
353 # define TLS_S_DHPAR_EX 0x00400000 /* DH param file exists */
354 # define TLS_S_DHPAR_OK 0x00800000 /* DH param file is ok to use */
356 /* Type of variable */
357 # define TLS_T_OTHER 0
362 ** TLS_OK_F -- can var be an absolute filename?
366 ** fn -- what is the filename used for?
367 ** type -- type of variable
374 tls_ok_f(var, fn, type)
379 /* must be absolute pathname */
380 if (var != NULL && *var == '/')
383 sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
384 type == TLS_T_SRV ? "Server" :
385 (type == TLS_T_CLT ? "Client" : ""), fn);
389 ** TLS_SAFE_F -- is a file safe to use?
393 ** sff -- flags for safefile()
394 ** srv -- server side?
401 tls_safe_f(var, sff, srv)
408 if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
409 S_IRUSR, NULL)) == 0)
412 sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
413 srv ? "server" : "client", var, sm_errstring(ret));
418 ** TLS_OK_F -- macro to simplify calls to tls_ok_f
422 ** fn -- what is the filename used for?
423 ** req -- is the file required?
424 ** st -- status bit to set if ok
425 ** type -- type of variable
428 ** uses r, ok; may change ok and status.
432 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
434 r = tls_ok_f(var, fn, type); \
442 ** TLS_UNR -- macro to return whether a file should be unreadable
445 ** bit -- flag to test
451 # define TLS_UNR(bit, req) (bitset(bit, req) ? SFF_NORFILES : 0)
452 # define TLS_OUNR(bit, req) (bitset(bit, req) ? SFF_NOWRFILES : 0)
453 # define TLS_KEYSFF(req) \
454 (bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ? \
455 TLS_OUNR(TLS_I_KEY_OUNR, req) : \
456 TLS_UNR(TLS_I_KEY_UNR, req))
459 ** TLS_SAFE_F -- macro to simplify calls to tls_safe_f
463 ** sff -- flags for safefile()
464 ** req -- is the file required?
465 ** ex -- does the file exist?
466 ** st -- status bit to set if ok
467 ** srv -- server side?
470 ** uses r, ok, ex; may change ok and status.
474 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
476 r = tls_safe_f(var, sff, srv); \
484 ** INITTLS -- initialize TLS
487 ** ctx -- pointer to context
488 ** req -- requirements for initialization (see sendmail.h)
489 ** srv -- server side?
490 ** certfile -- filename of certificate
491 ** keyfile -- filename of private key
492 ** cacertpath -- path to CAs
493 ** cacertfile -- file with CA(s)
494 ** dhparam -- parameters for DH
501 inittls(ctx, req, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
505 char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
508 static DH *dh = NULL;
516 # endif /* _FFR_TLS_1 */
519 # endif /* SM_CONF_SHM */
520 # if OPENSSL_VERSION_NUMBER > 0x00907000L
524 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
527 who = srv ? "server" : "client";
529 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
531 /* already initialized? (we could re-init...) */
538 ** look for a second filename: it must be separated by a ','
539 ** no blanks allowed (they won't be skipped).
540 ** we change a global variable here! this change will be undone
541 ** before return from the function but only if it returns true.
542 ** this isn't a problem since in a failure case this function
543 ** won't be called again with the same (overwritten) values.
544 ** otherwise each return must be replaced with a goto endinittls.
549 if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
552 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
555 # endif /* _FFR_TLS_1 */
558 ** Check whether files/paths are defined
561 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
562 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
563 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
564 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
565 TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
566 TLS_S_CERTP_EX, TLS_T_OTHER);
567 TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
568 TLS_S_CERTF_EX, TLS_T_OTHER);
570 # if OPENSSL_VERSION_NUMBER > 0x00907000L
571 TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
572 TLS_S_CRLF_EX, TLS_T_OTHER);
573 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
577 ** if the second file is specified it must exist
578 ** XXX: it is possible here to define only one of those files
583 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
584 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
588 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
589 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
591 # endif /* _FFR_TLS_1 */
594 ** valid values for dhparam are (only the first char is checked)
595 ** none no parameters: don't use DH
596 ** 512 generate 512 bit parameters (fixed)
597 ** 1024 generate 1024 bit parameters
598 ** /file/name read parameters from /file/name
599 ** default is: 1024 for server, 512 for client (OK? XXX)
602 if (bitset(TLS_I_TRY_DH, req))
612 else if (c != 'n' && c != 'N' && c != '/')
615 sm_syslog(LOG_WARNING, NOQID,
616 "STARTTLS=%s, error: illegal value '%s' for DHParam",
622 dhparam = srv ? "1" : "5";
623 else if (*dhparam == '/')
625 TLS_OK_F(dhparam, "DHParameters",
626 bitset(TLS_I_DHPAR_EX, req),
627 TLS_S_DHPAR_EX, TLS_T_OTHER);
633 /* certfile etc. must be "safe". */
634 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
635 | SFF_NOGWFILES | SFF_NOWWFILES
636 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
637 if (DontLockReadFiles)
640 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
641 bitset(TLS_I_CERT_EX, req),
642 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
643 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
644 bitset(TLS_I_KEY_EX, req),
645 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
646 TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
647 bitset(TLS_I_CERTF_EX, req),
648 bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
649 TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
650 bitset(TLS_I_DHPAR_EX, req),
651 bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
652 # if OPENSSL_VERSION_NUMBER > 0x00907000L
653 TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
654 bitset(TLS_I_CRLF_EX, req),
655 bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
656 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
662 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
663 bitset(TLS_I_CERT_EX, req),
664 bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
668 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
669 bitset(TLS_I_KEY_EX, req),
670 bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
672 # endif /* _FFR_TLS_1 */
674 /* create a method and a new context */
675 if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
676 SSLv23_client_method())) == NULL)
679 sm_syslog(LOG_WARNING, NOQID,
680 "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
687 # if OPENSSL_VERSION_NUMBER > 0x00907000L
690 /* get a pointer to the current certificate validation store */
691 store = SSL_CTX_get_cert_store(*ctx); /* does not fail */
692 crl_file = BIO_new(BIO_s_file_internal());
693 if (crl_file != NULL)
695 if (BIO_read_filename(crl_file, CRLFile) >= 0)
697 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
700 X509_STORE_add_crl(store, crl);
702 X509_STORE_set_flags(store,
703 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
704 X509_STORE_set_verify_cb_func(store,
711 sm_syslog(LOG_WARNING, NOQID,
712 "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
716 /* avoid memory leaks */
722 else if (LogLevel > 9)
723 sm_syslog(LOG_WARNING, NOQID,
724 "STARTTLS=%s, error: BIO_new=failed", who);
731 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
736 sm_syslog(LOG_WARNING, NOQID,
737 "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
742 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
743 X509_STORE_set_flags(store,
744 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
746 # endif /* _FFR_CRLPATH */
747 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
750 /* turn off backward compatibility, required for no-rsa */
751 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
752 # endif /* TLS_NO_RSA */
757 ** Create a temporary RSA key
758 ** XXX Maybe we shouldn't create this always (even though it
759 ** is only at startup).
760 ** It is a time-consuming operation and it is not always necessary.
761 ** maybe we should do it only on demand...
764 if (bitset(TLS_I_RSA_TMP, req)
766 && ShmId != SM_SHM_NO_ID &&
767 (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL,
769 # else /* SM_CONF_SHM */
770 && 0 /* no shared memory: no need to generate key now */
771 # endif /* SM_CONF_SHM */
776 sm_syslog(LOG_WARNING, NOQID,
777 "STARTTLS=%s, error: RSA_generate_key failed",
784 # endif /* !TLS_NO_RSA */
788 ** XXX change this for DSA-only version
791 if (bitset(TLS_S_KEY_OK, status) &&
792 SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
793 SSL_FILETYPE_PEM) <= 0)
797 sm_syslog(LOG_WARNING, NOQID,
798 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
803 if (bitset(TLS_I_USE_KEY, req))
807 /* get the certificate file */
808 if (bitset(TLS_S_CERT_OK, status) &&
809 SSL_CTX_use_certificate_file(*ctx, certfile,
810 SSL_FILETYPE_PEM) <= 0)
814 sm_syslog(LOG_WARNING, NOQID,
815 "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
820 if (bitset(TLS_I_USE_CERT, req))
824 /* check the private key */
825 if (bitset(TLS_S_KEY_OK, status) &&
826 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
828 /* Private key does not match the certificate public key */
831 sm_syslog(LOG_WARNING, NOQID,
832 "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
837 if (bitset(TLS_I_USE_KEY, req))
842 /* XXX this code is pretty much duplicated from above! */
844 /* load private key */
845 if (bitset(TLS_S_KEY2_OK, status) &&
846 SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
850 sm_syslog(LOG_WARNING, NOQID,
851 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
858 /* get the certificate file */
859 if (bitset(TLS_S_CERT2_OK, status) &&
860 SSL_CTX_use_certificate_file(*ctx, cf2, SSL_FILETYPE_PEM) <= 0)
864 sm_syslog(LOG_WARNING, NOQID,
865 "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
872 /* also check the private key */
873 if (bitset(TLS_S_KEY2_OK, status) &&
874 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
876 /* Private key does not match the certificate public key */
879 sm_syslog(LOG_WARNING, NOQID,
880 "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
886 # endif /* _FFR_TLS_1 */
888 /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
889 SSL_CTX_set_options(*ctx, SSL_OP_ALL); /* XXX bug compatibility? */
892 /* Diffie-Hellman initialization */
893 if (bitset(TLS_I_TRY_DH, req))
895 if (bitset(TLS_S_DHPAR_OK, status))
899 if ((bio = BIO_new_file(dhparam, "r")) != NULL)
901 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
903 if (dh == NULL && LogLevel > 7)
907 err = ERR_get_error();
908 sm_syslog(LOG_WARNING, NOQID,
909 "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
911 ERR_error_string(err, NULL));
920 sm_syslog(LOG_WARNING, NOQID,
921 "STARTTLS=%s, error: BIO_new_file(%s) failed",
928 if (dh == NULL && bitset(TLS_I_DH1024, req))
932 /* this takes a while! (7-130s on a 450MHz AMD K6-2) */
933 dsa = DSA_generate_parameters(1024, NULL, 0, NULL,
935 dh = DSA_dup_DH(dsa);
939 if (dh == NULL && bitset(TLS_I_DH512, req))
948 err = ERR_get_error();
949 sm_syslog(LOG_WARNING, NOQID,
950 "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
952 ERR_error_string(err, NULL));
954 if (bitset(TLS_I_REQ_DH, req))
959 SSL_CTX_set_tmp_dh(*ctx, dh);
961 /* important to avoid small subgroup attacks */
962 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
964 sm_syslog(LOG_INFO, NOQID,
965 "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
966 who, 8 * DH_size(dh), *dhparam);
973 /* XXX do we need this cache here? */
974 if (bitset(TLS_I_CACHE, req))
975 SSL_CTX_sess_set_cache_size(*ctx, 128);
976 /* timeout? SSL_CTX_set_timeout(*ctx, TimeOut...); */
978 /* load certificate locations and default CA paths */
979 if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
981 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
985 if (bitset(TLS_I_RSA_TMP, req))
986 SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
987 # endif /* !TLS_NO_RSA */
990 ** We have to install our own verify callback:
991 ** SSL_VERIFY_PEER requests a client cert but even
992 ** though *FAIL_IF* isn't set, the connection
993 ** will be aborted if the client presents a cert
994 ** that is not "liked" (can't be verified?) by
995 ** the TLS library :-(
999 ** XXX currently we could call tls_set_verify()
1000 ** but we hope that that function will later on
1001 ** only set the mode per connection.
1003 SSL_CTX_set_verify(*ctx,
1004 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1008 /* install verify callback */
1009 SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb,
1011 SSL_CTX_set_client_CA_list(*ctx,
1012 SSL_load_client_CA_file(cacertfile));
1017 ** can't load CA data; do we care?
1018 ** the data is necessary to authenticate the client,
1019 ** which in turn would be necessary
1020 ** if we want to allow relaying based on it.
1024 sm_syslog(LOG_WARNING, NOQID,
1025 "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1026 who, cacertpath, cacertfile, r);
1030 if (bitset(TLS_I_VRFY_LOC, req))
1035 /* XXX: make this dependent on an option? */
1037 SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1040 /* install our own cipher list */
1041 if (CipherList != NULL && *CipherList != '\0')
1043 if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1047 sm_syslog(LOG_WARNING, NOQID,
1048 "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1054 /* failure if setting to this list is required? */
1057 # endif /* _FFR_TLS_1 */
1059 sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1064 ** this label is required if we want to have a "clean" exit
1065 ** see the comments above at the initialization of cf2
1071 /* undo damage to global variables */
1076 # endif /* _FFR_TLS_1 */
1081 ** TLS_GET_INFO -- get information about TLS connection
1084 ** ssl -- TLS connection structure
1085 ** srv -- server or client
1086 ** host -- hostname of other side
1087 ** mac -- macro storage
1088 ** certreq -- did we ask for a cert?
1091 ** result of authentication.
1094 ** sets macros: {cipher}, {tls_version}, {verify},
1095 ** {cipher_bits}, {alg_bits}, {cert}, {cert_subject},
1096 ** {cert_issuer}, {cn_subject}, {cn_issuer}
1100 tls_get_info(ssl, srv, host, mac, certreq)
1114 c = SSL_get_current_cipher(ssl);
1116 /* cast is just workaround for compiler warning */
1117 macdefine(mac, A_TEMP, macid("{cipher}"),
1118 (char *) SSL_CIPHER_get_name(c));
1119 b = SSL_CIPHER_get_bits(c, &r);
1120 (void) sm_snprintf(bitstr, sizeof bitstr, "%d", b);
1121 macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1122 (void) sm_snprintf(bitstr, sizeof bitstr, "%d", r);
1123 macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1124 s = SSL_CIPHER_get_version(c);
1127 macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1129 who = srv ? "server" : "client";
1130 cert = SSL_get_peer_certificate(ssl);
1131 verifyok = SSL_get_verify_result(ssl);
1133 sm_syslog(LOG_INFO, NOQID,
1134 "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1135 who, verifyok, (unsigned long) cert);
1139 unsigned char md[EVP_MAX_MD_SIZE];
1142 X509_NAME_oneline(X509_get_subject_name(cert),
1144 macdefine(mac, A_TEMP, macid("{cert_subject}"),
1145 xtextify(buf, "<>\")"));
1146 X509_NAME_oneline(X509_get_issuer_name(cert),
1148 macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1149 xtextify(buf, "<>\")"));
1150 X509_NAME_get_text_by_NID(X509_get_subject_name(cert),
1151 NID_commonName, buf, sizeof buf);
1152 macdefine(mac, A_TEMP, macid("{cn_subject}"),
1153 xtextify(buf, "<>\")"));
1154 X509_NAME_get_text_by_NID(X509_get_issuer_name(cert),
1155 NID_commonName, buf, sizeof buf);
1156 macdefine(mac, A_TEMP, macid("{cn_issuer}"),
1157 xtextify(buf, "<>\")"));
1159 if (X509_digest(cert, EVP_md5(), md, &n) != 0 && n > 0)
1161 char md5h[EVP_MAX_MD_SIZE * 3];
1162 static const char hexcodes[] = "0123456789ABCDEF";
1164 SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1165 for (r = 0; r < (int) n; r++)
1167 md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1168 md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1169 md5h[(r * 3) + 2] = ':';
1171 md5h[(n * 3) - 1] = '\0';
1172 macdefine(mac, A_TEMP, macid("{cert_md5}"), md5h);
1175 macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1179 macdefine(mac, A_PERM, macid("{cert_subject}"), "");
1180 macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
1181 macdefine(mac, A_PERM, macid("{cn_subject}"), "");
1182 macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
1183 macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1195 s = certreq ? "NO" : "NOT",
1204 macdefine(mac, A_PERM, macid("{verify}"), s);
1208 /* do some logging */
1211 char *vers, *s1, *s2, *cbits, *algbits;
1213 vers = macget(mac, macid("{tls_version}"));
1214 cbits = macget(mac, macid("{cipher_bits}"));
1215 algbits = macget(mac, macid("{alg_bits}"));
1216 s1 = macget(mac, macid("{verify}"));
1217 s2 = macget(mac, macid("{cipher}"));
1219 /* XXX: maybe cut off ident info? */
1220 sm_syslog(LOG_INFO, NOQID,
1221 "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s",
1223 host == NULL ? "local" : host,
1224 vers, s1, s2, /* sm_snprintf() can deal with NULL */
1225 algbits == NULL ? "0" : algbits,
1226 cbits == NULL ? "0" : cbits);
1230 ** Maybe run xuntextify on the strings?
1231 ** That is easier to read but makes it maybe a bit
1232 ** more complicated to figure out the right values
1233 ** for the access map...
1236 s1 = macget(mac, macid("{cert_subject}"));
1237 s2 = macget(mac, macid("{cert_issuer}"));
1238 sm_syslog(LOG_INFO, NOQID,
1239 "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
1241 X509_verify_cert_error_string(verifyok));
1247 ** ENDTLS -- shutdown secure connection
1250 ** ssl -- SSL connection information.
1251 ** side -- server/client (for logging).
1254 ** success? (EX_* code)
1268 if ((r = SSL_shutdown(ssl)) < 0)
1272 sm_syslog(LOG_WARNING, NOQID,
1273 "STARTTLS=%s, SSL_shutdown failed: %d",
1279 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1282 ** Bug in OpenSSL (at least up to 0.9.6b):
1283 ** From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1284 ** Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1285 ** To: openssl-users@openssl.org
1286 ** Subject: Re: SSL_shutdown() woes (fwd)
1288 ** The side sending the shutdown alert first will
1289 ** not care about the answer of the peer but will
1290 ** immediately return with a return value of "0"
1291 ** (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1292 ** the value of "0" and as the shutdown alert of the peer was
1293 ** not received (actually, the program did not even wait for
1294 ** the answer), an SSL_ERROR_SYSCALL is flagged, because this
1295 ** is the default rule in case everything else does not apply.
1297 ** For your server the problem is different, because it
1298 ** receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1299 ** then sends its response (SSL_SENT_SHUTDOWN), so for the
1300 ** server the shutdown was successfull.
1302 ** As is by know, you would have to call SSL_shutdown() once
1303 ** and ignore an SSL_ERROR_SYSCALL returned. Then call
1304 ** SSL_shutdown() again to actually get the server's response.
1306 ** In the last discussion, Bodo Moeller concluded that a
1307 ** rewrite of the shutdown code would be necessary, but
1308 ** probably with another API, as the change would not be
1309 ** compatible to the way it is now. Things do not become
1310 ** easier as other programs do not follow the shutdown
1311 ** guidelines anyway, so that a lot error conditions and
1312 ** compitibility issues would have to be caught.
1314 ** For now the recommondation is to ignore the error message.
1321 sm_syslog(LOG_WARNING, NOQID,
1322 "STARTTLS=%s, SSL_shutdown not done",
1328 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1337 ** TMP_RSA_KEY -- return temporary RSA key
1340 ** s -- TLS connection structure
1345 ** temporary RSA key.
1348 # ifndef MAX_RSA_TMP_CNT
1349 # define MAX_RSA_TMP_CNT 1000 /* XXX better value? */
1350 # endif /* ! MAX_RSA_TMP_CNT */
1354 tmp_rsa_key(s, export, keylength)
1361 extern int *PRSATmpCnt;
1363 if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1364 ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1366 # endif /* SM_CONF_SHM */
1368 if (rsa_tmp != NULL)
1370 rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL);
1371 if (rsa_tmp == NULL)
1374 sm_syslog(LOG_ERR, NOQID,
1375 "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1382 ** XXX we can't (yet) share the new key...
1383 ** The RSA structure contains pointers hence it can't be
1384 ** easily kept in shared memory. It must be transformed
1385 ** into a continous memory region first, then stored,
1386 ** and later read out again (each time re-transformed).
1389 if (ShmId != SM_SHM_NO_ID)
1392 # endif /* SM_CONF_SHM */
1394 sm_syslog(LOG_ERR, NOQID,
1395 "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1399 # endif /* !TLS_NO_RSA */
1401 ** APPS_SSL_INFO_CB -- info callback for TLS connections
1404 ** s -- TLS connection structure
1405 ** where -- state in handshake
1406 ** ret -- return code of last operation
1413 apps_ssl_info_cb(s, where, ret)
1420 BIO *bio_err = NULL;
1423 sm_syslog(LOG_INFO, NOQID,
1424 "STARTTLS: info_callback where=0x%x, ret=%d",
1427 w = where & ~SSL_ST_MASK;
1428 if (bio_err == NULL)
1429 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
1431 if (bitset(SSL_ST_CONNECT, w))
1432 str = "SSL_connect";
1433 else if (bitset(SSL_ST_ACCEPT, w))
1438 if (bitset(SSL_CB_LOOP, where))
1441 sm_syslog(LOG_NOTICE, NOQID,
1443 str, SSL_state_string_long(s));
1445 else if (bitset(SSL_CB_ALERT, where))
1447 str = bitset(SSL_CB_READ, where) ? "read" : "write";
1449 sm_syslog(LOG_NOTICE, NOQID,
1450 "STARTTLS: SSL3 alert %s:%s:%s",
1451 str, SSL_alert_type_string_long(ret),
1452 SSL_alert_desc_string_long(ret));
1454 else if (bitset(SSL_CB_EXIT, where))
1459 sm_syslog(LOG_WARNING, NOQID,
1460 "STARTTLS: %s:failed in %s",
1461 str, SSL_state_string_long(s));
1466 sm_syslog(LOG_WARNING, NOQID,
1467 "STARTTLS: %s:error in %s",
1468 str, SSL_state_string_long(s));
1473 ** TLS_VERIFY_LOG -- log verify error for TLS certificates
1477 ** ctx -- x509 context
1485 tls_verify_log(ok, ctx, name)
1487 X509_STORE_CTX *ctx;
1495 cert = X509_STORE_CTX_get_current_cert(ctx);
1496 reason = X509_STORE_CTX_get_error(ctx);
1497 depth = X509_STORE_CTX_get_error_depth(ctx);
1498 ssl = (SSL *) X509_STORE_CTX_get_ex_data(ctx,
1499 SSL_get_ex_data_X509_STORE_CTX_idx());
1503 /* internal error */
1504 sm_syslog(LOG_ERR, NOQID,
1505 "STARTTLS: internal error: tls_verify_cb: ssl == NULL");
1509 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof buf);
1510 sm_syslog(LOG_INFO, NOQID,
1511 "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1512 name, depth, buf, ok, X509_verify_cert_error_string(reason));
1517 ** TLS_VERIFY_CB -- verify callback for TLS certificates
1520 ** ctx -- x509 context
1523 ** accept connection?
1524 ** currently: always yes.
1528 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1530 X509_STORE_CTX *ctx;
1531 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1532 tls_verify_cb(ctx, unused)
1533 X509_STORE_CTX *ctx;
1535 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1539 ok = X509_verify_cert(ctx);
1543 return tls_verify_log(ok, ctx, "TLS");
1544 return 1; /* override it */
1549 ** TLSLOGERR -- log the errors from the TLS error stack
1552 ** who -- server/client (for logging).
1567 # define CP (const char **)
1569 es = CRYPTO_thread_id();
1570 while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags))
1573 sm_syslog(LOG_WARNING, NOQID,
1574 "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1575 ERR_error_string(l, buf),
1577 bitset(ERR_TXT_STRING, flags) ? data : "");
1581 # if OPENSSL_VERSION_NUMBER > 0x00907000L
1583 ** X509_VERIFY_CB -- verify callback
1586 ** ctx -- x509 context
1589 ** accept connection?
1590 ** currently: always yes.
1594 x509_verify_cb(ok, ctx)
1596 X509_STORE_CTX *ctx;
1601 tls_verify_log(ok, ctx, "x509");
1602 if (ctx->error == X509_V_ERR_UNABLE_TO_GET_CRL)
1605 return 1; /* override it */
1610 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1611 #endif /* STARTTLS */