2 * Copyright (c) 2000-2006, 2008, 2009, 2011, 2013 Proofpoint, 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.127 2013-11-27 02:51:11 gshapiro Exp $")
16 # include <openssl/err.h>
17 # include <openssl/bio.h>
18 # include <openssl/pem.h>
20 # include <openssl/dh.h>
22 # ifndef HASURANDOMDEV
23 # include <openssl/rand.h>
24 # endif /* ! HASURANDOMDEV */
26 static RSA *rsa_tmp = NULL; /* temporary RSA key */
27 static RSA *tmp_rsa_key __P((SSL *, int, int));
28 # endif /* !TLS_NO_RSA */
29 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
30 static int tls_verify_cb __P((X509_STORE_CTX *));
31 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
32 static int tls_verify_cb __P((X509_STORE_CTX *, void *));
33 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
35 # if OPENSSL_VERSION_NUMBER > 0x00907000L
36 static int x509_verify_cb __P((int, X509_STORE_CTX *));
37 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
39 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
41 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
42 # define CONST097 const
43 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
44 static void apps_ssl_info_cb __P((CONST097 SSL *, int , int));
45 static bool tls_ok_f __P((char *, char *, int));
46 static bool tls_safe_f __P((char *, long, bool));
47 static int tls_verify_log __P((int, X509_STORE_CTX *, const char *));
50 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x10100001L || \
51 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
53 DH_set0_pqg(dh, p, q, g)
63 return 1; /* success */
65 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
67 static DH *get_dh512 __P((void));
69 static unsigned char dh512_p[] =
71 0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
72 0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
73 0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
74 0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
75 0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
78 static unsigned char dh512_g[] =
87 BIGNUM *dhp_bn, *dhg_bn;
89 if ((dh = DH_new()) == NULL)
91 dhp_bn = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
92 dhg_bn = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
93 if ((dhp_bn == NULL) || (dhg_bn == NULL))
100 if (!DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))
110 This is the data from which the C code has been generated:
112 -----BEGIN DH PARAMETERS-----
113 MIIBCAKCAQEArDcgcLpxEksQHPlolRKCUJ2szKRziseWV9cUSQNZGxoGw7KkROz4
114 HF9QSbg5axyNIG+QbZYtx0jp3l6/GWq1dLOj27yZkgYgaYgFrvKPiZ2jJ5xETQVH
115 UpZwbjRcyjyWkWYJVsx1aF4F/iY4kT0n/+iGEoimI3C9V3KXTJ2S6jIkyJ6M/CrN
116 EtrDynMlUMGlc7S1ouXVOTrtKeqy3S2L9eBLxVI+sChEijGIfELupdVeXihK006p
117 MgnABPDbkTx6OOtYmSZaGQX+OLW2FPmwvcrzgCz9t9cAsuUcBZv1LeHEqZZttyLU
118 oK0jjSXgFyeU4/NfyA+zuNeWzUL6bHmigwIBAg==
119 -----END DH PARAMETERS-----
125 static unsigned char dh2048_p[] = {
126 0xAC,0x37,0x20,0x70,0xBA,0x71,0x12,0x4B,0x10,0x1C,0xF9,0x68,
127 0x95,0x12,0x82,0x50,0x9D,0xAC,0xCC,0xA4,0x73,0x8A,0xC7,0x96,
128 0x57,0xD7,0x14,0x49,0x03,0x59,0x1B,0x1A,0x06,0xC3,0xB2,0xA4,
129 0x44,0xEC,0xF8,0x1C,0x5F,0x50,0x49,0xB8,0x39,0x6B,0x1C,0x8D,
130 0x20,0x6F,0x90,0x6D,0x96,0x2D,0xC7,0x48,0xE9,0xDE,0x5E,0xBF,
131 0x19,0x6A,0xB5,0x74,0xB3,0xA3,0xDB,0xBC,0x99,0x92,0x06,0x20,
132 0x69,0x88,0x05,0xAE,0xF2,0x8F,0x89,0x9D,0xA3,0x27,0x9C,0x44,
133 0x4D,0x05,0x47,0x52,0x96,0x70,0x6E,0x34,0x5C,0xCA,0x3C,0x96,
134 0x91,0x66,0x09,0x56,0xCC,0x75,0x68,0x5E,0x05,0xFE,0x26,0x38,
135 0x91,0x3D,0x27,0xFF,0xE8,0x86,0x12,0x88,0xA6,0x23,0x70,0xBD,
136 0x57,0x72,0x97,0x4C,0x9D,0x92,0xEA,0x32,0x24,0xC8,0x9E,0x8C,
137 0xFC,0x2A,0xCD,0x12,0xDA,0xC3,0xCA,0x73,0x25,0x50,0xC1,0xA5,
138 0x73,0xB4,0xB5,0xA2,0xE5,0xD5,0x39,0x3A,0xED,0x29,0xEA,0xB2,
139 0xDD,0x2D,0x8B,0xF5,0xE0,0x4B,0xC5,0x52,0x3E,0xB0,0x28,0x44,
140 0x8A,0x31,0x88,0x7C,0x42,0xEE,0xA5,0xD5,0x5E,0x5E,0x28,0x4A,
141 0xD3,0x4E,0xA9,0x32,0x09,0xC0,0x04,0xF0,0xDB,0x91,0x3C,0x7A,
142 0x38,0xEB,0x58,0x99,0x26,0x5A,0x19,0x05,0xFE,0x38,0xB5,0xB6,
143 0x14,0xF9,0xB0,0xBD,0xCA,0xF3,0x80,0x2C,0xFD,0xB7,0xD7,0x00,
144 0xB2,0xE5,0x1C,0x05,0x9B,0xF5,0x2D,0xE1,0xC4,0xA9,0x96,0x6D,
145 0xB7,0x22,0xD4,0xA0,0xAD,0x23,0x8D,0x25,0xE0,0x17,0x27,0x94,
146 0xE3,0xF3,0x5F,0xC8,0x0F,0xB3,0xB8,0xD7,0x96,0xCD,0x42,0xFA,
149 static unsigned char dh2048_g[] = { 0x02, };
151 BIGNUM *dhp_bn, *dhg_bn;
153 if ((dh = DH_new()) == NULL)
155 dhp_bn = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
156 dhg_bn = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
157 if ((dhp_bn == NULL) || (dhg_bn == NULL))
164 if (!DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))
175 ** TLS_RAND_INIT -- initialize STARTTLS random generator
178 ** randfile -- name of file with random data
185 ** initializes PRNG for tls library.
188 # define MIN_RAND_BYTES 128 /* 1024 bits */
190 # define RF_OK 0 /* randfile OK */
191 # define RF_MISS 1 /* randfile == NULL || *randfile == '\0' */
192 # define RF_UNKNOWN 2 /* unknown prefix for randfile */
194 # define RI_NONE 0 /* no init yet */
195 # define RI_SUCCESS 1 /* init was successful */
196 # define RI_FAIL 2 /* init failed */
198 static bool tls_rand_init __P((char *, int));
201 tls_rand_init(randfile, logl)
205 # ifndef HASURANDOMDEV
206 /* not required if /dev/urandom exists, OpenSSL does it internally */
210 static int done = RI_NONE;
216 /* did we try this before? if yes: return old value */
218 return done == RI_SUCCESS;
220 /* set default values */
223 randdef = (randfile == NULL || *randfile == '\0') ? RF_MISS : RF_OK;
225 if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0)
228 if (RAND_egd(randfile) < 0)
230 sm_syslog(LOG_WARNING, NOQID,
231 "STARTTLS: RAND_egd(%s) failed: random number generator not seeded",
239 if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0)
246 sff = SFF_SAFEDIRPATH | SFF_NOWLINK
247 | SFF_NOGWFILES | SFF_NOWWFILES
248 | SFF_NOGRFILES | SFF_NOWRFILES
249 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
250 if (DontLockReadFiles)
252 if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0)
254 if (fstat(fd, &st) < 0)
257 sm_syslog(LOG_ERR, NOQID,
258 "STARTTLS: can't fstat(%s)",
268 /* max. age of file: 10 minutes */
269 if (st.st_mtime + 600 < curtime())
271 use = bitnset(DBS_INSUFFICIENTENTROPY,
275 sm_syslog(LOG_ERR, NOQID,
276 "STARTTLS: RandFile %s too old: %s",
281 if (use && st.st_size < MIN_RAND_BYTES)
283 use = bitnset(DBS_INSUFFICIENTENTROPY,
287 sm_syslog(LOG_ERR, NOQID,
288 "STARTTLS: size(%s) < %d: %s",
295 ok = RAND_load_file(randfile, -1) >=
300 sm_syslog(LOG_WARNING, NOQID,
301 "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded",
307 if (ok || bitnset(DBS_INSUFFICIENTENTROPY,
310 /* add this even if fstat() failed */
311 RAND_seed((void *) &st, sizeof(st));
318 sm_syslog(LOG_WARNING, NOQID,
319 "STARTTLS: Warning: safeopen(%s) failed",
323 else if (randdef == RF_OK)
326 sm_syslog(LOG_WARNING, NOQID,
327 "STARTTLS: Error: no proper random file definition %s",
329 randdef = RF_UNKNOWN;
331 if (randdef == RF_MISS)
334 sm_syslog(LOG_WARNING, NOQID,
335 "STARTTLS: Error: missing random file definition");
337 if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail))
341 unsigned char buf[MIN_RAND_BYTES];
343 /* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */
344 for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long))
347 (void) memcpy(buf + i, (void *) &r, sizeof(long));
349 RAND_seed(buf, sizeof(buf));
351 sm_syslog(LOG_WARNING, NOQID,
352 "STARTTLS: Warning: random number generator not properly seeded");
355 done = ok ? RI_SUCCESS : RI_FAIL;
357 # else /* ! HASURANDOMDEV */
359 # endif /* ! HASURANDOMDEV */
362 ** INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
365 ** fipsmode -- use FIPS?
372 init_tls_library(fipsmode)
377 /* basic TLS initialization, ignore result for now */
379 SSL_load_error_strings();
380 OpenSSL_add_all_algorithms();
382 /* this is currently a macro for SSL_library_init */
383 SSLeay_add_ssl_algorithms();
386 bv = tls_rand_init(RandFile, 7);
390 if (!FIPS_mode_set(1))
394 err = ERR_get_error();
396 sm_syslog(LOG_ERR, NOQID,
397 "STARTTLS=init, FIPSMode=%s",
398 ERR_error_string(err, NULL));
404 sm_syslog(LOG_INFO, NOQID,
405 "STARTTLS=init, FIPSMode=ok");
408 #endif /* _FFR_FIPSMODE */
409 if (bv && CertFingerprintAlgorithm != NULL)
413 md = EVP_get_digestbyname(CertFingerprintAlgorithm);
418 sm_syslog(LOG_ERR, NOQID,
419 "STARTTLS=init, CertFingerprintAlgorithm=%s, status=invalid"
420 , CertFingerprintAlgorithm);
429 ** TLS_SET_VERIFY -- request client certificate?
432 ** ctx -- TLS context
433 ** ssl -- TLS structure
434 ** vrfy -- request certificate?
440 ** Sets verification state for TLS
442 # if TLS_VRFY_PER_CTX
444 ** This is per TLS context, not per TLS structure;
445 ** the former is global, the latter per connection.
446 ** It would be nice to do this per connection, but this
447 ** doesn't work in the current TLS libraries :-(
448 # endif * TLS_VRFY_PER_CTX *
452 tls_set_verify(ctx, ssl, vrfy)
457 # if !TLS_VRFY_PER_CTX
458 SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
459 # else /* !TLS_VRFY_PER_CTX */
460 SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
462 # endif /* !TLS_VRFY_PER_CTX */
466 ** status in initialization
467 ** these flags keep track of the status of the initialization
468 ** i.e., whether a file exists (_EX) and whether it can be used (_OK)
469 ** [due to permissions]
472 # define TLS_S_NONE 0x00000000 /* none yet */
473 # define TLS_S_CERT_EX 0x00000001 /* cert file exists */
474 # define TLS_S_CERT_OK 0x00000002 /* cert file is ok */
475 # define TLS_S_KEY_EX 0x00000004 /* key file exists */
476 # define TLS_S_KEY_OK 0x00000008 /* key file is ok */
477 # define TLS_S_CERTP_EX 0x00000010 /* CA cert path exists */
478 # define TLS_S_CERTP_OK 0x00000020 /* CA cert path is ok */
479 # define TLS_S_CERTF_EX 0x00000040 /* CA cert file exists */
480 # define TLS_S_CERTF_OK 0x00000080 /* CA cert file is ok */
481 # define TLS_S_CRLF_EX 0x00000100 /* CRL file exists */
482 # define TLS_S_CRLF_OK 0x00000200 /* CRL file is ok */
484 # define TLS_S_CERT2_EX 0x00001000 /* 2nd cert file exists */
485 # define TLS_S_CERT2_OK 0x00002000 /* 2nd cert file is ok */
486 # define TLS_S_KEY2_EX 0x00004000 /* 2nd key file exists */
487 # define TLS_S_KEY2_OK 0x00008000 /* 2nd key file is ok */
489 # define TLS_S_DH_OK 0x00200000 /* DH cert is ok */
490 # define TLS_S_DHPAR_EX 0x00400000 /* DH param file exists */
491 # define TLS_S_DHPAR_OK 0x00800000 /* DH param file is ok to use */
493 /* Type of variable */
494 # define TLS_T_OTHER 0
499 ** TLS_OK_F -- can var be an absolute filename?
503 ** fn -- what is the filename used for?
504 ** type -- type of variable
511 tls_ok_f(var, fn, type)
516 /* must be absolute pathname */
517 if (var != NULL && *var == '/')
520 sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
521 type == TLS_T_SRV ? "Server" :
522 (type == TLS_T_CLT ? "Client" : ""), fn);
526 ** TLS_SAFE_F -- is a file safe to use?
530 ** sff -- flags for safefile()
531 ** srv -- server side?
538 tls_safe_f(var, sff, srv)
545 if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
546 S_IRUSR, NULL)) == 0)
549 sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
550 srv ? "server" : "client", var, sm_errstring(ret));
555 ** TLS_OK_F -- macro to simplify calls to tls_ok_f
559 ** fn -- what is the filename used for?
560 ** req -- is the file required?
561 ** st -- status bit to set if ok
562 ** type -- type of variable
565 ** uses r, ok; may change ok and status.
569 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
571 r = tls_ok_f(var, fn, type); \
579 ** TLS_UNR -- macro to return whether a file should be unreadable
582 ** bit -- flag to test
588 # define TLS_UNR(bit, req) (bitset(bit, req) ? SFF_NORFILES : 0)
589 # define TLS_OUNR(bit, req) (bitset(bit, req) ? SFF_NOWRFILES : 0)
590 # define TLS_KEYSFF(req) \
591 (bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ? \
592 TLS_OUNR(TLS_I_KEY_OUNR, req) : \
593 TLS_UNR(TLS_I_KEY_UNR, req))
596 ** TLS_SAFE_F -- macro to simplify calls to tls_safe_f
600 ** sff -- flags for safefile()
601 ** req -- is the file required?
602 ** ex -- does the file exist?
603 ** st -- status bit to set if ok
604 ** srv -- server side?
607 ** uses r, ok, ex; may change ok and status.
611 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
613 r = tls_safe_f(var, sff, srv); \
620 # if _FFR_TLS_SE_OPTS
622 ** LOAD_CERTKEY -- load cert/key for TLS session
625 ** ssl -- TLS session context
626 ** certfile -- filename of certificate
627 ** keyfile -- filename of private key
634 load_certkey(ssl, srv, certfile, keyfile)
647 who = srv ? "server" : "client";
649 req = TLS_I_CERT_EX|TLS_I_KEY_EX;
650 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
651 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
652 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
653 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
655 /* certfile etc. must be "safe". */
656 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
657 | SFF_NOGWFILES | SFF_NOWWFILES
658 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
659 if (DontLockReadFiles)
662 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
663 bitset(TLS_I_CERT_EX, req),
664 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
665 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
666 bitset(TLS_I_KEY_EX, req),
667 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
669 # define SSL_use_cert(ssl, certfile) \
670 SSL_use_certificate_file(ssl, certfile, SSL_FILETYPE_PEM)
671 # define SSL_USE_CERT "SSL_use_certificate_file"
673 if (bitset(TLS_S_CERT_OK, status) &&
674 SSL_use_cert(ssl, certfile) <= 0)
678 sm_syslog(LOG_WARNING, NOQID,
679 "STARTTLS=%s, error: %s(%s) failed",
680 who, SSL_USE_CERT, certfile);
682 tlslogerr(LOG_WARNING, who);
684 if (bitset(TLS_I_USE_CERT, req))
687 if (bitset(TLS_S_KEY_OK, status) &&
688 SSL_use_PrivateKey_file(ssl, keyfile, SSL_FILETYPE_PEM) <= 0)
692 sm_syslog(LOG_WARNING, NOQID,
693 "STARTTLS=%s, error: SSL_use_PrivateKey_file(%s) failed",
696 tlslogerr(LOG_WARNING, who);
698 if (bitset(TLS_I_USE_KEY, req))
702 /* check the private key */
703 if (bitset(TLS_S_KEY_OK, status) &&
704 (r = SSL_check_private_key(ssl)) <= 0)
706 /* Private key does not match the certificate public key */
709 sm_syslog(LOG_WARNING, NOQID,
710 "STARTTLS=%s, error: SSL_check_private_key failed(%s): %d",
713 tlslogerr(LOG_WARNING, who);
715 if (bitset(TLS_I_USE_KEY, req))
721 # endif /* _FFR_TLS_SE_OPTS */
724 ** INITTLS -- initialize TLS
727 ** ctx -- pointer to context
728 ** req -- requirements for initialization (see sendmail.h)
729 ** options -- options
730 ** srv -- server side?
731 ** certfile -- filename of certificate
732 ** keyfile -- filename of private key
733 ** cacertpath -- path to CAs
734 ** cacertfile -- file with CA(s)
735 ** dhparam -- parameters for DH
742 ** The session_id_context identifies the service that created a session.
743 ** This information is used to distinguish between multiple TLS-based
744 ** servers running on the same server. We use the name of the mail system.
745 ** Note: the session cache is not persistent.
748 static char server_session_id_context[] = "sendmail8";
752 sm_RSA_generate_key(num, e)
759 bn_rsa_r4 = BN_new();
760 if ((bn_rsa_r4 != NULL) && BN_set_word(bn_rsa_r4, e) && (rsa = RSA_new()) != NULL)
762 if (!RSA_generate_key_ex(rsa, num, bn_rsa_r4, NULL))
771 # endif /* !TLS_NO_RSA */
773 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
774 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
775 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 1
777 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 0
781 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
784 unsigned long options;
786 char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
789 static DH *dh = NULL;
798 # endif /* SM_CONF_SHM */
799 # if OPENSSL_VERSION_NUMBER > 0x00907000L
803 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
804 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
806 STACK_OF(SSL_COMP) *comp_methods;
810 who = srv ? "server" : "client";
813 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
815 SM_ASSERT(ctx != NULL);
818 /* already initialized? (we could re-init...) */
824 ** look for a second filename: it must be separated by a ','
825 ** no blanks allowed (they won't be skipped).
826 ** we change a global variable here! this change will be undone
827 ** before return from the function but only if it returns true.
828 ** this isn't a problem since in a failure case this function
829 ** won't be called again with the same (overwritten) values.
830 ** otherwise each return must be replaced with a goto endinittls.
835 if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
838 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
843 ** Check whether files/paths are defined
846 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
847 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
848 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
849 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
850 TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
851 TLS_S_CERTP_EX, TLS_T_OTHER);
852 TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
853 TLS_S_CERTF_EX, TLS_T_OTHER);
855 # if OPENSSL_VERSION_NUMBER > 0x00907000L
856 TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
857 TLS_S_CRLF_EX, TLS_T_OTHER);
858 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
861 ** if the second file is specified it must exist
862 ** XXX: it is possible here to define only one of those files
867 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
868 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
872 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
873 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
877 ** valid values for dhparam are (only the first char is checked)
878 ** none no parameters: don't use DH
879 ** i use precomputed 2048 bit parameters
880 ** 512 use precomputed 512 bit parameters
881 ** 1024 generate 1024 bit parameters
882 ** 2048 generate 2048 bit parameters
883 ** /file/name read parameters from /file/name
889 req |= TLS_I_DHFIXED; \
892 if (bitset(TLS_I_TRY_DH, req))
900 else if (c == 'I' || c == 'i')
901 req |= TLS_I_DHFIXED;
906 else if (c == 'n' || c == 'N')
907 req &= ~TLS_I_TRY_DH;
911 sm_syslog(LOG_WARNING, NOQID,
912 "STARTTLS=%s, error: illegal value '%s' for DHParameters",
919 else if (*dhparam == '/')
921 TLS_OK_F(dhparam, "DHParameters",
922 bitset(TLS_I_DHPAR_EX, req),
923 TLS_S_DHPAR_EX, TLS_T_OTHER);
929 /* certfile etc. must be "safe". */
930 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
931 | SFF_NOGWFILES | SFF_NOWWFILES
932 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
933 if (DontLockReadFiles)
936 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
937 bitset(TLS_I_CERT_EX, req),
938 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
939 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
940 bitset(TLS_I_KEY_EX, req),
941 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
942 TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
943 bitset(TLS_I_CERTF_EX, req),
944 bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
945 if (dhparam != NULL && *dhparam == '/')
947 TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
948 bitset(TLS_I_DHPAR_EX, req),
949 bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
950 if (!bitset(TLS_S_DHPAR_OK, status))
953 # if OPENSSL_VERSION_NUMBER > 0x00907000L
954 TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
955 bitset(TLS_I_CRLF_EX, req),
956 bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
957 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
962 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
963 bitset(TLS_I_CERT_EX, req),
964 bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
968 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
969 bitset(TLS_I_KEY_EX, req),
970 bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
973 /* create a method and a new context */
974 if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
975 SSLv23_client_method())) == NULL)
978 sm_syslog(LOG_WARNING, NOQID,
979 "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
982 tlslogerr(LOG_WARNING, who);
986 # if OPENSSL_VERSION_NUMBER > 0x00907000L
989 /* get a pointer to the current certificate validation store */
990 store = SSL_CTX_get_cert_store(*ctx); /* does not fail */
991 crl_file = BIO_new(BIO_s_file());
992 if (crl_file != NULL)
994 if (BIO_read_filename(crl_file, CRLFile) >= 0)
996 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
999 X509_STORE_add_crl(store, crl);
1001 X509_STORE_set_flags(store,
1002 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1003 X509_STORE_set_verify_cb_func(store,
1010 sm_syslog(LOG_WARNING, NOQID,
1011 "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
1015 /* avoid memory leaks */
1021 else if (LogLevel > 9)
1022 sm_syslog(LOG_WARNING, NOQID,
1023 "STARTTLS=%s, error: BIO_new=failed", who);
1028 if (CRLPath != NULL && store != NULL)
1030 X509_LOOKUP *lookup;
1032 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1037 sm_syslog(LOG_WARNING, NOQID,
1038 "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
1043 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
1044 X509_STORE_set_flags(store,
1045 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1047 # endif /* _FFR_CRLPATH */
1048 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1051 /* turn off backward compatibility, required for no-rsa */
1052 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
1053 # endif /* TLS_NO_RSA */
1058 ** Create a temporary RSA key
1059 ** XXX Maybe we shouldn't create this always (even though it
1060 ** is only at startup).
1061 ** It is a time-consuming operation and it is not always necessary.
1062 ** maybe we should do it only on demand...
1065 if (bitset(TLS_I_RSA_TMP, req)
1067 && ShmId != SM_SHM_NO_ID &&
1068 (rsa_tmp = sm_RSA_generate_key(RSA_KEYLENGTH, RSA_F4)) == NULL
1069 # else /* SM_CONF_SHM */
1070 && 0 /* no shared memory: no need to generate key now */
1071 # endif /* SM_CONF_SHM */
1076 sm_syslog(LOG_WARNING, NOQID,
1077 "STARTTLS=%s, error: RSA_generate_key failed",
1080 tlslogerr(LOG_WARNING, who);
1084 # endif /* !TLS_NO_RSA */
1088 ** XXX change this for DSA-only version
1091 if (bitset(TLS_S_KEY_OK, status) &&
1092 SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
1093 SSL_FILETYPE_PEM) <= 0)
1097 sm_syslog(LOG_WARNING, NOQID,
1098 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1101 tlslogerr(LOG_WARNING, who);
1103 if (bitset(TLS_I_USE_KEY, req))
1107 #if _FFR_TLS_USE_CERTIFICATE_CHAIN_FILE
1108 # define SSL_CTX_use_cert(ssl_ctx, certfile) \
1109 SSL_CTX_use_certificate_chain_file(ssl_ctx, certfile)
1110 # define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_chain_file"
1112 # define SSL_CTX_use_cert(ssl_ctx, certfile) \
1113 SSL_CTX_use_certificate_file(ssl_ctx, certfile, SSL_FILETYPE_PEM)
1114 # define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_file"
1117 /* get the certificate file */
1118 if (bitset(TLS_S_CERT_OK, status) &&
1119 SSL_CTX_use_cert(*ctx, certfile) <= 0)
1123 sm_syslog(LOG_WARNING, NOQID,
1124 "STARTTLS=%s, error: %s(%s) failed",
1125 who, SSL_CTX_USE_CERT, certfile);
1127 tlslogerr(LOG_WARNING, who);
1129 if (bitset(TLS_I_USE_CERT, req))
1133 /* check the private key */
1134 if (bitset(TLS_S_KEY_OK, status) &&
1135 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1137 /* Private key does not match the certificate public key */
1140 sm_syslog(LOG_WARNING, NOQID,
1141 "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
1144 tlslogerr(LOG_WARNING, who);
1146 if (bitset(TLS_I_USE_KEY, req))
1150 /* XXX this code is pretty much duplicated from above! */
1152 /* load private key */
1153 if (bitset(TLS_S_KEY2_OK, status) &&
1154 SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
1158 sm_syslog(LOG_WARNING, NOQID,
1159 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1162 tlslogerr(LOG_WARNING, who);
1166 /* get the certificate file */
1167 if (bitset(TLS_S_CERT2_OK, status) &&
1168 SSL_CTX_use_cert(*ctx, cf2) <= 0)
1172 sm_syslog(LOG_WARNING, NOQID,
1173 "STARTTLS=%s, error: %s(%s) failed",
1174 who, SSL_CTX_USE_CERT, cf2);
1176 tlslogerr(LOG_WARNING, who);
1180 /* also check the private key */
1181 if (bitset(TLS_S_KEY2_OK, status) &&
1182 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1184 /* Private key does not match the certificate public key */
1187 sm_syslog(LOG_WARNING, NOQID,
1188 "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
1191 tlslogerr(LOG_WARNING, who);
1195 /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
1197 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
1200 ** In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
1201 ** padding bug work-around, leading to false positives and
1202 ** failed connections. We may not interoperate with systems
1203 ** with the bug, but this is better than breaking on all 0.9.8[ab]
1204 ** systems that have zlib support enabled.
1205 ** Note: this checks the runtime version of the library, not
1206 ** just the compile time version.
1209 rt_version = SSLeay();
1210 if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
1212 comp_methods = SSL_COMP_get_compression_methods();
1213 if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
1214 options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
1217 SSL_CTX_set_options(*ctx, (long) options);
1220 /* Diffie-Hellman initialization */
1221 if (bitset(TLS_I_TRY_DH, req))
1225 #endif /* _FFR_TLS_EC */
1228 sm_dprintf("inittls: req=%#lx, status=%#lx\n",
1230 if (bitset(TLS_S_DHPAR_OK, status))
1234 if ((bio = BIO_new_file(dhparam, "r")) != NULL)
1236 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1238 if (dh == NULL && LogLevel > 7)
1242 err = ERR_get_error();
1243 sm_syslog(LOG_WARNING, NOQID,
1244 "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
1246 ERR_error_string(err, NULL));
1248 tlslogerr(LOG_WARNING, who);
1256 sm_syslog(LOG_WARNING, NOQID,
1257 "STARTTLS=%s, error: BIO_new_file(%s) failed",
1260 tlslogerr(LOG_WARNING, who);
1264 if (dh == NULL && bitset(TLS_I_DH1024|TLS_I_DH2048, req))
1269 bits = bitset(TLS_I_DH2048, req) ? 2048 : 1024;
1271 sm_dprintf("inittls: Generating %d bit DH parameters\n", bits);
1274 /* this takes a while! */
1275 (void)DSA_generate_parameters_ex(dsa, bits, NULL, 0,
1277 dh = DSA_dup_DH(dsa);
1280 else if (dh == NULL && bitset(TLS_I_DHFIXED, req))
1283 sm_dprintf("inittls: Using precomputed 2048 bit DH parameters\n");
1286 else if (dh == NULL && bitset(TLS_I_DH512, req))
1289 sm_dprintf("inittls: Using precomputed 512 bit DH parameters\n");
1299 err = ERR_get_error();
1300 sm_syslog(LOG_WARNING, NOQID,
1301 "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1303 ERR_error_string(err, NULL));
1305 if (bitset(TLS_I_REQ_DH, req))
1310 /* important to avoid small subgroup attacks */
1311 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
1313 SSL_CTX_set_tmp_dh(*ctx, dh);
1315 sm_syslog(LOG_INFO, NOQID,
1316 "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
1317 who, 8 * DH_size(dh), *dhparam);
1322 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1325 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_ECDH_USE);
1326 SSL_CTX_set_tmp_ecdh(*ctx, ecdh);
1329 #endif /* _FFR_TLS_EC */
1332 # endif /* !NO_DH */
1335 /* XXX do we need this cache here? */
1336 if (bitset(TLS_I_CACHE, req))
1338 SSL_CTX_sess_set_cache_size(*ctx, 1);
1339 SSL_CTX_set_timeout(*ctx, 1);
1340 SSL_CTX_set_session_id_context(*ctx,
1341 (void *) &server_session_id_context,
1342 sizeof(server_session_id_context));
1343 (void) SSL_CTX_set_session_cache_mode(*ctx,
1344 SSL_SESS_CACHE_SERVER);
1348 (void) SSL_CTX_set_session_cache_mode(*ctx,
1349 SSL_SESS_CACHE_OFF);
1352 /* load certificate locations and default CA paths */
1353 if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1355 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1359 if (bitset(TLS_I_RSA_TMP, req))
1360 SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1361 # endif /* !TLS_NO_RSA */
1364 ** We have to install our own verify callback:
1365 ** SSL_VERIFY_PEER requests a client cert but even
1366 ** though *FAIL_IF* isn't set, the connection
1367 ** will be aborted if the client presents a cert
1368 ** that is not "liked" (can't be verified?) by
1369 ** the TLS library :-(
1373 ** XXX currently we could call tls_set_verify()
1374 ** but we hope that that function will later on
1375 ** only set the mode per connection.
1377 SSL_CTX_set_verify(*ctx,
1378 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1382 /* install verify callback */
1383 SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb,
1385 SSL_CTX_set_client_CA_list(*ctx,
1386 SSL_load_client_CA_file(cacertfile));
1391 ** can't load CA data; do we care?
1392 ** the data is necessary to authenticate the client,
1393 ** which in turn would be necessary
1394 ** if we want to allow relaying based on it.
1398 sm_syslog(LOG_WARNING, NOQID,
1399 "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1400 who, cacertpath, cacertfile, r);
1402 tlslogerr(LOG_WARNING, who);
1404 if (bitset(TLS_I_VRFY_LOC, req))
1409 /* XXX: make this dependent on an option? */
1411 SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1413 /* install our own cipher list */
1414 if (CipherList != NULL && *CipherList != '\0')
1416 if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1420 sm_syslog(LOG_WARNING, NOQID,
1421 "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1425 tlslogerr(LOG_WARNING, who);
1427 /* failure if setting to this list is required? */
1432 sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1436 ** this label is required if we want to have a "clean" exit
1437 ** see the comments above at the initialization of cf2
1443 /* undo damage to global variables */
1453 ** CERT_FP -- get cert fingerprint
1457 ** mac -- macro storage
1458 ** macro -- where to store cert fp
1461 ** <=0: cert fp calculation failed
1462 ** >0: cert fp calculation ok
1466 cert_fp(cert, evp_digest, mac, macro)
1468 const EVP_MD *evp_digest;
1474 unsigned char md[EVP_MAX_MD_SIZE];
1475 char md5h[EVP_MAX_MD_SIZE * 3];
1476 static const char hexcodes[] = "0123456789ABCDEF";
1479 if (X509_digest(cert, EVP_digest, md, &n) == 0 || n <= 0)
1481 macdefine(mac, A_TEMP, macid(macro), "");
1485 SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1486 for (r = 0; r < (int) n; r++)
1488 md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1489 md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1490 md5h[(r * 3) + 2] = ':';
1492 md5h[(n * 3) - 1] = '\0';
1493 macdefine(mac, A_TEMP, macid(macro), md5h);
1498 ** TLS_GET_INFO -- get information about TLS connection
1501 ** ssl -- TLS connection structure
1502 ** srv -- server or client
1503 ** host -- hostname of other side
1504 ** mac -- macro storage
1505 ** certreq -- did we ask for a cert?
1508 ** result of authentication.
1511 ** sets various TLS related macros.
1515 tls_get_info(ssl, srv, host, mac, certreq)
1522 const SSL_CIPHER *c;
1529 c = SSL_get_current_cipher(ssl);
1531 /* cast is just workaround for compiler warning */
1532 macdefine(mac, A_TEMP, macid("{cipher}"),
1533 (char *) SSL_CIPHER_get_name(c));
1534 b = SSL_CIPHER_get_bits(c, &r);
1535 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1536 macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1537 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1538 macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1539 s = (char *) SSL_get_version(ssl);
1542 macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1544 who = srv ? "server" : "client";
1545 cert = SSL_get_peer_certificate(ssl);
1546 verifyok = SSL_get_verify_result(ssl);
1548 sm_syslog(LOG_INFO, NOQID,
1549 "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1550 who, verifyok, (unsigned long) cert);
1553 X509_NAME *subj, *issuer;
1556 subj = X509_get_subject_name(cert);
1557 issuer = X509_get_issuer_name(cert);
1558 X509_NAME_oneline(subj, buf, sizeof(buf));
1559 macdefine(mac, A_TEMP, macid("{cert_subject}"),
1560 xtextify(buf, "<>\")"));
1561 X509_NAME_oneline(issuer, buf, sizeof(buf));
1562 macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1563 xtextify(buf, "<>\")"));
1565 # define LL_BADCERT 8
1567 #define CERTFPMACRO (CertFingerprintAlgorithm != NULL ? "{cert_fp}" : "{cert_md5}")
1569 #define CHECK_X509_NAME(which) \
1573 sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \
1574 if (LogLevel > LL_BADCERT) \
1575 sm_syslog(LOG_INFO, NOQID, \
1576 "STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN", \
1578 host == NULL ? "local" : host, \
1581 else if ((size_t)r >= sizeof(buf) - 1) \
1583 sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \
1585 sm_syslog(LOG_INFO, NOQID, \
1586 "STARTTLS=%s, relay=%.100s, field=%s, status=CN too long", \
1588 host == NULL ? "local" : host, \
1591 else if ((size_t)r > strlen(buf)) \
1593 sm_strlcpy(buf, "BadCertificateContainsNUL", \
1596 sm_syslog(LOG_INFO, NOQID, \
1597 "STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL", \
1599 host == NULL ? "local" : host, \
1604 r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf,
1606 CHECK_X509_NAME("cn_subject");
1607 macdefine(mac, A_TEMP, macid("{cn_subject}"),
1608 xtextify(buf, "<>\")"));
1609 r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf,
1611 CHECK_X509_NAME("cn_issuer");
1612 macdefine(mac, A_TEMP, macid("{cn_issuer}"),
1613 xtextify(buf, "<>\")"));
1614 (void) cert_fp(cert, EVP_digest, mac, CERTFPMACRO);
1618 macdefine(mac, A_PERM, macid("{cert_subject}"), "");
1619 macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
1620 macdefine(mac, A_PERM, macid("{cn_subject}"), "");
1621 macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
1622 macdefine(mac, A_TEMP, macid(CERTFPMACRO), "");
1634 s = certreq ? "NO" : "NOT",
1643 macdefine(mac, A_PERM, macid("{verify}"), s);
1647 /* do some logging */
1650 char *vers, *s1, *s2, *cbits, *algbits;
1652 vers = macget(mac, macid("{tls_version}"));
1653 cbits = macget(mac, macid("{cipher_bits}"));
1654 algbits = macget(mac, macid("{alg_bits}"));
1655 s1 = macget(mac, macid("{verify}"));
1656 s2 = macget(mac, macid("{cipher}"));
1658 /* XXX: maybe cut off ident info? */
1659 sm_syslog(LOG_INFO, NOQID,
1660 "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s",
1662 host == NULL ? "local" : host,
1663 vers, s1, s2, /* sm_snprintf() can deal with NULL */
1664 algbits == NULL ? "0" : algbits,
1665 cbits == NULL ? "0" : cbits);
1669 ** Maybe run xuntextify on the strings?
1670 ** That is easier to read but makes it maybe a bit
1671 ** more complicated to figure out the right values
1672 ** for the access map...
1675 s1 = macget(mac, macid("{cert_subject}"));
1676 s2 = macget(mac, macid("{cert_issuer}"));
1677 sm_syslog(LOG_INFO, NOQID,
1678 "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
1680 X509_verify_cert_error_string(verifyok));
1686 ** ENDTLS -- shutdown secure connection
1689 ** ssl -- SSL connection information.
1690 ** side -- server/client (for logging).
1693 ** success? (EX_* code)
1707 if ((r = SSL_shutdown(ssl)) < 0)
1711 sm_syslog(LOG_WARNING, NOQID,
1712 "STARTTLS=%s, SSL_shutdown failed: %d",
1714 tlslogerr(LOG_WARNING, side);
1718 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1721 ** Bug in OpenSSL (at least up to 0.9.6b):
1722 ** From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1723 ** Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1724 ** To: openssl-users@openssl.org
1725 ** Subject: Re: SSL_shutdown() woes (fwd)
1727 ** The side sending the shutdown alert first will
1728 ** not care about the answer of the peer but will
1729 ** immediately return with a return value of "0"
1730 ** (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1731 ** the value of "0" and as the shutdown alert of the peer was
1732 ** not received (actually, the program did not even wait for
1733 ** the answer), an SSL_ERROR_SYSCALL is flagged, because this
1734 ** is the default rule in case everything else does not apply.
1736 ** For your server the problem is different, because it
1737 ** receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1738 ** then sends its response (SSL_SENT_SHUTDOWN), so for the
1739 ** server the shutdown was successfull.
1741 ** As is by know, you would have to call SSL_shutdown() once
1742 ** and ignore an SSL_ERROR_SYSCALL returned. Then call
1743 ** SSL_shutdown() again to actually get the server's response.
1745 ** In the last discussion, Bodo Moeller concluded that a
1746 ** rewrite of the shutdown code would be necessary, but
1747 ** probably with another API, as the change would not be
1748 ** compatible to the way it is now. Things do not become
1749 ** easier as other programs do not follow the shutdown
1750 ** guidelines anyway, so that a lot error conditions and
1751 ** compitibility issues would have to be caught.
1753 ** For now the recommondation is to ignore the error message.
1760 sm_syslog(LOG_WARNING, NOQID,
1761 "STARTTLS=%s, SSL_shutdown not done",
1763 tlslogerr(LOG_WARNING, side);
1767 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1776 ** TMP_RSA_KEY -- return temporary RSA key
1779 ** s -- TLS connection structure
1784 ** temporary RSA key.
1787 # ifndef MAX_RSA_TMP_CNT
1788 # define MAX_RSA_TMP_CNT 1000 /* XXX better value? */
1789 # endif /* ! MAX_RSA_TMP_CNT */
1793 tmp_rsa_key(s, export, keylength)
1800 extern int *PRSATmpCnt;
1802 if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1803 ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1805 # endif /* SM_CONF_SHM */
1807 if (rsa_tmp != NULL)
1809 rsa_tmp = sm_RSA_generate_key(RSA_KEYLENGTH, RSA_F4);
1810 if (rsa_tmp == NULL)
1813 sm_syslog(LOG_ERR, NOQID,
1814 "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1821 ** XXX we can't (yet) share the new key...
1822 ** The RSA structure contains pointers hence it can't be
1823 ** easily kept in shared memory. It must be transformed
1824 ** into a continous memory region first, then stored,
1825 ** and later read out again (each time re-transformed).
1828 if (ShmId != SM_SHM_NO_ID)
1831 # endif /* SM_CONF_SHM */
1833 sm_syslog(LOG_ERR, NOQID,
1834 "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1838 # endif /* !TLS_NO_RSA */
1840 ** APPS_SSL_INFO_CB -- info callback for TLS connections
1843 ** s -- TLS connection structure
1844 ** where -- state in handshake
1845 ** ret -- return code of last operation
1852 apps_ssl_info_cb(s, where, ret)
1859 BIO *bio_err = NULL;
1862 sm_syslog(LOG_INFO, NOQID,
1863 "STARTTLS: info_callback where=0x%x, ret=%d",
1866 w = where & ~SSL_ST_MASK;
1867 if (bio_err == NULL)
1868 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
1870 if (bitset(SSL_ST_CONNECT, w))
1871 str = "SSL_connect";
1872 else if (bitset(SSL_ST_ACCEPT, w))
1877 if (bitset(SSL_CB_LOOP, where))
1880 sm_syslog(LOG_NOTICE, NOQID,
1882 str, SSL_state_string_long(s));
1884 else if (bitset(SSL_CB_ALERT, where))
1886 str = bitset(SSL_CB_READ, where) ? "read" : "write";
1888 sm_syslog(LOG_NOTICE, NOQID,
1889 "STARTTLS: SSL3 alert %s:%s:%s",
1890 str, SSL_alert_type_string_long(ret),
1891 SSL_alert_desc_string_long(ret));
1893 else if (bitset(SSL_CB_EXIT, where))
1898 sm_syslog(LOG_WARNING, NOQID,
1899 "STARTTLS: %s:failed in %s",
1900 str, SSL_state_string_long(s));
1905 sm_syslog(LOG_WARNING, NOQID,
1906 "STARTTLS: %s:error in %s",
1907 str, SSL_state_string_long(s));
1912 ** TLS_VERIFY_LOG -- log verify error for TLS certificates
1916 ** ctx -- x509 context
1917 ** name -- from where is this called?
1924 tls_verify_log(ok, ctx, name)
1926 X509_STORE_CTX *ctx;
1933 cert = X509_STORE_CTX_get_current_cert(ctx);
1934 reason = X509_STORE_CTX_get_error(ctx);
1935 depth = X509_STORE_CTX_get_error_depth(ctx);
1936 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1937 sm_syslog(LOG_INFO, NOQID,
1938 "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1939 name, depth, buf, ok, X509_verify_cert_error_string(reason));
1944 ** TLS_VERIFY_CB -- verify callback for TLS certificates
1947 ** ctx -- x509 context
1950 ** accept connection?
1951 ** currently: always yes.
1955 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1957 X509_STORE_CTX *ctx;
1958 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1959 tls_verify_cb(ctx, unused)
1960 X509_STORE_CTX *ctx;
1962 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1967 ** man SSL_CTX_set_cert_verify_callback():
1968 ** callback should return 1 to indicate verification success
1969 ** and 0 to indicate verification failure.
1972 ok = X509_verify_cert(ctx);
1976 return tls_verify_log(ok, ctx, "TLS");
1981 ** TLSLOGERR -- log the errors from the TLS error stack
1984 ** level -- syslog level
1985 ** who -- server/client (for logging).
1992 tlslogerr(level, who)
2002 es = CRYPTO_thread_id();
2003 while ((l = ERR_get_error_line_data((const char **) &file, &line,
2004 (const char **) &data, &flags))
2007 sm_syslog(level, NOQID,
2008 "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
2009 ERR_error_string(l, buf),
2011 bitset(ERR_TXT_STRING, flags) ? data : "");
2015 # if OPENSSL_VERSION_NUMBER > 0x00907000L
2017 ** X509_VERIFY_CB -- verify callback
2020 ** ctx -- x509 context
2023 ** accept connection?
2024 ** currently: always yes.
2028 x509_verify_cb(ok, ctx)
2030 X509_STORE_CTX *ctx;
2035 tls_verify_log(ok, ctx, "x509");
2036 if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL)
2038 X509_STORE_CTX_set_error(ctx, 0);
2039 return 1; /* override it */
2044 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2045 #endif /* STARTTLS */