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) || !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))
105 This is the data from which the C code has been generated:
107 -----BEGIN DH PARAMETERS-----
108 MIIBCAKCAQEArDcgcLpxEksQHPlolRKCUJ2szKRziseWV9cUSQNZGxoGw7KkROz4
109 HF9QSbg5axyNIG+QbZYtx0jp3l6/GWq1dLOj27yZkgYgaYgFrvKPiZ2jJ5xETQVH
110 UpZwbjRcyjyWkWYJVsx1aF4F/iY4kT0n/+iGEoimI3C9V3KXTJ2S6jIkyJ6M/CrN
111 EtrDynMlUMGlc7S1ouXVOTrtKeqy3S2L9eBLxVI+sChEijGIfELupdVeXihK006p
112 MgnABPDbkTx6OOtYmSZaGQX+OLW2FPmwvcrzgCz9t9cAsuUcBZv1LeHEqZZttyLU
113 oK0jjSXgFyeU4/NfyA+zuNeWzUL6bHmigwIBAg==
114 -----END DH PARAMETERS-----
120 static unsigned char dh2048_p[]={
121 0xAC,0x37,0x20,0x70,0xBA,0x71,0x12,0x4B,0x10,0x1C,0xF9,0x68,
122 0x95,0x12,0x82,0x50,0x9D,0xAC,0xCC,0xA4,0x73,0x8A,0xC7,0x96,
123 0x57,0xD7,0x14,0x49,0x03,0x59,0x1B,0x1A,0x06,0xC3,0xB2,0xA4,
124 0x44,0xEC,0xF8,0x1C,0x5F,0x50,0x49,0xB8,0x39,0x6B,0x1C,0x8D,
125 0x20,0x6F,0x90,0x6D,0x96,0x2D,0xC7,0x48,0xE9,0xDE,0x5E,0xBF,
126 0x19,0x6A,0xB5,0x74,0xB3,0xA3,0xDB,0xBC,0x99,0x92,0x06,0x20,
127 0x69,0x88,0x05,0xAE,0xF2,0x8F,0x89,0x9D,0xA3,0x27,0x9C,0x44,
128 0x4D,0x05,0x47,0x52,0x96,0x70,0x6E,0x34,0x5C,0xCA,0x3C,0x96,
129 0x91,0x66,0x09,0x56,0xCC,0x75,0x68,0x5E,0x05,0xFE,0x26,0x38,
130 0x91,0x3D,0x27,0xFF,0xE8,0x86,0x12,0x88,0xA6,0x23,0x70,0xBD,
131 0x57,0x72,0x97,0x4C,0x9D,0x92,0xEA,0x32,0x24,0xC8,0x9E,0x8C,
132 0xFC,0x2A,0xCD,0x12,0xDA,0xC3,0xCA,0x73,0x25,0x50,0xC1,0xA5,
133 0x73,0xB4,0xB5,0xA2,0xE5,0xD5,0x39,0x3A,0xED,0x29,0xEA,0xB2,
134 0xDD,0x2D,0x8B,0xF5,0xE0,0x4B,0xC5,0x52,0x3E,0xB0,0x28,0x44,
135 0x8A,0x31,0x88,0x7C,0x42,0xEE,0xA5,0xD5,0x5E,0x5E,0x28,0x4A,
136 0xD3,0x4E,0xA9,0x32,0x09,0xC0,0x04,0xF0,0xDB,0x91,0x3C,0x7A,
137 0x38,0xEB,0x58,0x99,0x26,0x5A,0x19,0x05,0xFE,0x38,0xB5,0xB6,
138 0x14,0xF9,0xB0,0xBD,0xCA,0xF3,0x80,0x2C,0xFD,0xB7,0xD7,0x00,
139 0xB2,0xE5,0x1C,0x05,0x9B,0xF5,0x2D,0xE1,0xC4,0xA9,0x96,0x6D,
140 0xB7,0x22,0xD4,0xA0,0xAD,0x23,0x8D,0x25,0xE0,0x17,0x27,0x94,
141 0xE3,0xF3,0x5F,0xC8,0x0F,0xB3,0xB8,0xD7,0x96,0xCD,0x42,0xFA,
144 static unsigned char dh2048_g[]={ 0x02, };
146 BIGNUM *dhp_bn, *dhg_bn;
148 if ((dh=DH_new()) == NULL)
150 dhp_bn = BN_bin2bn(dh2048_p,sizeof(dh2048_p),NULL);
151 dhg_bn = BN_bin2bn(dh2048_g,sizeof(dh2048_g),NULL);
152 if ((dhp_bn == NULL) || (dhg_bn == NULL) || !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))
165 ** TLS_RAND_INIT -- initialize STARTTLS random generator
168 ** randfile -- name of file with random data
175 ** initializes PRNG for tls library.
178 # define MIN_RAND_BYTES 128 /* 1024 bits */
180 # define RF_OK 0 /* randfile OK */
181 # define RF_MISS 1 /* randfile == NULL || *randfile == '\0' */
182 # define RF_UNKNOWN 2 /* unknown prefix for randfile */
184 # define RI_NONE 0 /* no init yet */
185 # define RI_SUCCESS 1 /* init was successful */
186 # define RI_FAIL 2 /* init failed */
188 static bool tls_rand_init __P((char *, int));
191 tls_rand_init(randfile, logl)
195 # ifndef HASURANDOMDEV
196 /* not required if /dev/urandom exists, OpenSSL does it internally */
200 static int done = RI_NONE;
206 /* did we try this before? if yes: return old value */
208 return done == RI_SUCCESS;
210 /* set default values */
213 randdef = (randfile == NULL || *randfile == '\0') ? RF_MISS : RF_OK;
215 if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0)
218 if (RAND_egd(randfile) < 0)
220 sm_syslog(LOG_WARNING, NOQID,
221 "STARTTLS: RAND_egd(%s) failed: random number generator not seeded",
229 if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0)
236 sff = SFF_SAFEDIRPATH | SFF_NOWLINK
237 | SFF_NOGWFILES | SFF_NOWWFILES
238 | SFF_NOGRFILES | SFF_NOWRFILES
239 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
240 if (DontLockReadFiles)
242 if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0)
244 if (fstat(fd, &st) < 0)
247 sm_syslog(LOG_ERR, NOQID,
248 "STARTTLS: can't fstat(%s)",
258 /* max. age of file: 10 minutes */
259 if (st.st_mtime + 600 < curtime())
261 use = bitnset(DBS_INSUFFICIENTENTROPY,
265 sm_syslog(LOG_ERR, NOQID,
266 "STARTTLS: RandFile %s too old: %s",
271 if (use && st.st_size < MIN_RAND_BYTES)
273 use = bitnset(DBS_INSUFFICIENTENTROPY,
277 sm_syslog(LOG_ERR, NOQID,
278 "STARTTLS: size(%s) < %d: %s",
285 ok = RAND_load_file(randfile, -1) >=
290 sm_syslog(LOG_WARNING, NOQID,
291 "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded",
297 if (ok || bitnset(DBS_INSUFFICIENTENTROPY,
300 /* add this even if fstat() failed */
301 RAND_seed((void *) &st, sizeof(st));
308 sm_syslog(LOG_WARNING, NOQID,
309 "STARTTLS: Warning: safeopen(%s) failed",
313 else if (randdef == RF_OK)
316 sm_syslog(LOG_WARNING, NOQID,
317 "STARTTLS: Error: no proper random file definition %s",
319 randdef = RF_UNKNOWN;
321 if (randdef == RF_MISS)
324 sm_syslog(LOG_WARNING, NOQID,
325 "STARTTLS: Error: missing random file definition");
327 if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail))
331 unsigned char buf[MIN_RAND_BYTES];
333 /* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */
334 for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long))
337 (void) memcpy(buf + i, (void *) &r, sizeof(long));
339 RAND_seed(buf, sizeof(buf));
341 sm_syslog(LOG_WARNING, NOQID,
342 "STARTTLS: Warning: random number generator not properly seeded");
345 done = ok ? RI_SUCCESS : RI_FAIL;
347 # else /* ! HASURANDOMDEV */
349 # endif /* ! HASURANDOMDEV */
352 ** INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
355 ** fipsmode -- use FIPS?
362 init_tls_library(fipsmode)
367 /* basic TLS initialization, ignore result for now */
369 SSL_load_error_strings();
370 OpenSSL_add_all_algorithms();
372 /* this is currently a macro for SSL_library_init */
373 SSLeay_add_ssl_algorithms();
376 bv = tls_rand_init(RandFile, 7);
380 if (!FIPS_mode_set(1))
384 err = ERR_get_error();
386 sm_syslog(LOG_ERR, NOQID,
387 "STARTTLS=init, FIPSMode=%s",
388 ERR_error_string(err, NULL));
394 sm_syslog(LOG_INFO, NOQID,
395 "STARTTLS=init, FIPSMode=ok");
398 #endif /* _FFR_FIPSMODE */
399 if (bv && CertFingerprintAlgorithm != NULL)
403 md = EVP_get_digestbyname(CertFingerprintAlgorithm);
408 sm_syslog(LOG_ERR, NOQID,
409 "STARTTLS=init, CertFingerprintAlgorithm=%s, status=invalid"
410 , CertFingerprintAlgorithm);
419 ** TLS_SET_VERIFY -- request client certificate?
422 ** ctx -- TLS context
423 ** ssl -- TLS structure
424 ** vrfy -- request certificate?
430 ** Sets verification state for TLS
432 # if TLS_VRFY_PER_CTX
434 ** This is per TLS context, not per TLS structure;
435 ** the former is global, the latter per connection.
436 ** It would be nice to do this per connection, but this
437 ** doesn't work in the current TLS libraries :-(
438 # endif * TLS_VRFY_PER_CTX *
442 tls_set_verify(ctx, ssl, vrfy)
447 # if !TLS_VRFY_PER_CTX
448 SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
449 # else /* !TLS_VRFY_PER_CTX */
450 SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
452 # endif /* !TLS_VRFY_PER_CTX */
456 ** status in initialization
457 ** these flags keep track of the status of the initialization
458 ** i.e., whether a file exists (_EX) and whether it can be used (_OK)
459 ** [due to permissions]
462 # define TLS_S_NONE 0x00000000 /* none yet */
463 # define TLS_S_CERT_EX 0x00000001 /* cert file exists */
464 # define TLS_S_CERT_OK 0x00000002 /* cert file is ok */
465 # define TLS_S_KEY_EX 0x00000004 /* key file exists */
466 # define TLS_S_KEY_OK 0x00000008 /* key file is ok */
467 # define TLS_S_CERTP_EX 0x00000010 /* CA cert path exists */
468 # define TLS_S_CERTP_OK 0x00000020 /* CA cert path is ok */
469 # define TLS_S_CERTF_EX 0x00000040 /* CA cert file exists */
470 # define TLS_S_CERTF_OK 0x00000080 /* CA cert file is ok */
471 # define TLS_S_CRLF_EX 0x00000100 /* CRL file exists */
472 # define TLS_S_CRLF_OK 0x00000200 /* CRL file is ok */
474 # define TLS_S_CERT2_EX 0x00001000 /* 2nd cert file exists */
475 # define TLS_S_CERT2_OK 0x00002000 /* 2nd cert file is ok */
476 # define TLS_S_KEY2_EX 0x00004000 /* 2nd key file exists */
477 # define TLS_S_KEY2_OK 0x00008000 /* 2nd key file is ok */
479 # define TLS_S_DH_OK 0x00200000 /* DH cert is ok */
480 # define TLS_S_DHPAR_EX 0x00400000 /* DH param file exists */
481 # define TLS_S_DHPAR_OK 0x00800000 /* DH param file is ok to use */
483 /* Type of variable */
484 # define TLS_T_OTHER 0
489 ** TLS_OK_F -- can var be an absolute filename?
493 ** fn -- what is the filename used for?
494 ** type -- type of variable
501 tls_ok_f(var, fn, type)
506 /* must be absolute pathname */
507 if (var != NULL && *var == '/')
510 sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
511 type == TLS_T_SRV ? "Server" :
512 (type == TLS_T_CLT ? "Client" : ""), fn);
516 ** TLS_SAFE_F -- is a file safe to use?
520 ** sff -- flags for safefile()
521 ** srv -- server side?
528 tls_safe_f(var, sff, srv)
535 if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
536 S_IRUSR, NULL)) == 0)
539 sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
540 srv ? "server" : "client", var, sm_errstring(ret));
545 ** TLS_OK_F -- macro to simplify calls to tls_ok_f
549 ** fn -- what is the filename used for?
550 ** req -- is the file required?
551 ** st -- status bit to set if ok
552 ** type -- type of variable
555 ** uses r, ok; may change ok and status.
559 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
561 r = tls_ok_f(var, fn, type); \
569 ** TLS_UNR -- macro to return whether a file should be unreadable
572 ** bit -- flag to test
578 # define TLS_UNR(bit, req) (bitset(bit, req) ? SFF_NORFILES : 0)
579 # define TLS_OUNR(bit, req) (bitset(bit, req) ? SFF_NOWRFILES : 0)
580 # define TLS_KEYSFF(req) \
581 (bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ? \
582 TLS_OUNR(TLS_I_KEY_OUNR, req) : \
583 TLS_UNR(TLS_I_KEY_UNR, req))
586 ** TLS_SAFE_F -- macro to simplify calls to tls_safe_f
590 ** sff -- flags for safefile()
591 ** req -- is the file required?
592 ** ex -- does the file exist?
593 ** st -- status bit to set if ok
594 ** srv -- server side?
597 ** uses r, ok, ex; may change ok and status.
601 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
603 r = tls_safe_f(var, sff, srv); \
610 # if _FFR_TLS_SE_OPTS
612 ** LOAD_CERTKEY -- load cert/key for TLS session
615 ** ssl -- TLS session context
616 ** certfile -- filename of certificate
617 ** keyfile -- filename of private key
624 load_certkey(ssl, srv, certfile, keyfile)
637 who = srv ? "server" : "client";
639 req = TLS_I_CERT_EX|TLS_I_KEY_EX;
640 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
641 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
642 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
643 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
645 /* certfile etc. must be "safe". */
646 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
647 | SFF_NOGWFILES | SFF_NOWWFILES
648 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
649 if (DontLockReadFiles)
652 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
653 bitset(TLS_I_CERT_EX, req),
654 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
655 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
656 bitset(TLS_I_KEY_EX, req),
657 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
659 # define SSL_use_cert(ssl, certfile) \
660 SSL_use_certificate_file(ssl, certfile, SSL_FILETYPE_PEM)
661 # define SSL_USE_CERT "SSL_use_certificate_file"
663 if (bitset(TLS_S_CERT_OK, status) &&
664 SSL_use_cert(ssl, certfile) <= 0)
668 sm_syslog(LOG_WARNING, NOQID,
669 "STARTTLS=%s, error: %s(%s) failed",
670 who, SSL_USE_CERT, certfile);
672 tlslogerr(LOG_WARNING, who);
674 if (bitset(TLS_I_USE_CERT, req))
677 if (bitset(TLS_S_KEY_OK, status) &&
678 SSL_use_PrivateKey_file(ssl, keyfile, SSL_FILETYPE_PEM) <= 0)
682 sm_syslog(LOG_WARNING, NOQID,
683 "STARTTLS=%s, error: SSL_use_PrivateKey_file(%s) failed",
686 tlslogerr(LOG_WARNING, who);
688 if (bitset(TLS_I_USE_KEY, req))
692 /* check the private key */
693 if (bitset(TLS_S_KEY_OK, status) &&
694 (r = SSL_check_private_key(ssl)) <= 0)
696 /* Private key does not match the certificate public key */
699 sm_syslog(LOG_WARNING, NOQID,
700 "STARTTLS=%s, error: SSL_check_private_key failed(%s): %d",
703 tlslogerr(LOG_WARNING, who);
705 if (bitset(TLS_I_USE_KEY, req))
711 # endif /* _FFR_TLS_SE_OPTS */
714 ** INITTLS -- initialize TLS
717 ** ctx -- pointer to context
718 ** req -- requirements for initialization (see sendmail.h)
719 ** options -- options
720 ** srv -- server side?
721 ** certfile -- filename of certificate
722 ** keyfile -- filename of private key
723 ** cacertpath -- path to CAs
724 ** cacertfile -- file with CA(s)
725 ** dhparam -- parameters for DH
732 ** The session_id_context identifies the service that created a session.
733 ** This information is used to distinguish between multiple TLS-based
734 ** servers running on the same server. We use the name of the mail system.
735 ** Note: the session cache is not persistent.
738 static char server_session_id_context[] = "sendmail8";
742 sm_RSA_generate_key(num, e)
749 bn_rsa_r4 = BN_new();
750 if ((bn_rsa_r4 != NULL) && BN_set_word(bn_rsa_r4, e) && (rsa = RSA_new()) != NULL)
752 if (!RSA_generate_key_ex(rsa, num, bn_rsa_r4, NULL))
761 # endif /* !TLS_NO_RSA */
763 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
764 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
765 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 1
767 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG 0
771 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
774 unsigned long options;
776 char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
779 static DH *dh = NULL;
788 # endif /* SM_CONF_SHM */
789 # if OPENSSL_VERSION_NUMBER > 0x00907000L
793 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
794 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
796 STACK_OF(SSL_COMP) *comp_methods;
800 who = srv ? "server" : "client";
803 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
805 SM_ASSERT(ctx != NULL);
808 /* already initialized? (we could re-init...) */
814 ** look for a second filename: it must be separated by a ','
815 ** no blanks allowed (they won't be skipped).
816 ** we change a global variable here! this change will be undone
817 ** before return from the function but only if it returns true.
818 ** this isn't a problem since in a failure case this function
819 ** won't be called again with the same (overwritten) values.
820 ** otherwise each return must be replaced with a goto endinittls.
825 if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
828 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
833 ** Check whether files/paths are defined
836 TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
837 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
838 TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
839 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
840 TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
841 TLS_S_CERTP_EX, TLS_T_OTHER);
842 TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
843 TLS_S_CERTF_EX, TLS_T_OTHER);
845 # if OPENSSL_VERSION_NUMBER > 0x00907000L
846 TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
847 TLS_S_CRLF_EX, TLS_T_OTHER);
848 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
851 ** if the second file is specified it must exist
852 ** XXX: it is possible here to define only one of those files
857 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
858 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
862 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
863 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
867 ** valid values for dhparam are (only the first char is checked)
868 ** none no parameters: don't use DH
869 ** i use precomputed 2048 bit parameters
870 ** 512 use precomputed 512 bit parameters
871 ** 1024 generate 1024 bit parameters
872 ** 2048 generate 2048 bit parameters
873 ** /file/name read parameters from /file/name
879 req |= TLS_I_DHFIXED; \
882 if (bitset(TLS_I_TRY_DH, req))
890 else if (c == 'I' || c == 'i')
891 req |= TLS_I_DHFIXED;
896 else if (c == 'n' || c == 'N')
897 req &= ~TLS_I_TRY_DH;
901 sm_syslog(LOG_WARNING, NOQID,
902 "STARTTLS=%s, error: illegal value '%s' for DHParameters",
909 else if (*dhparam == '/')
911 TLS_OK_F(dhparam, "DHParameters",
912 bitset(TLS_I_DHPAR_EX, req),
913 TLS_S_DHPAR_EX, TLS_T_OTHER);
919 /* certfile etc. must be "safe". */
920 sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
921 | SFF_NOGWFILES | SFF_NOWWFILES
922 | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
923 if (DontLockReadFiles)
926 TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
927 bitset(TLS_I_CERT_EX, req),
928 bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
929 TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
930 bitset(TLS_I_KEY_EX, req),
931 bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
932 TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
933 bitset(TLS_I_CERTF_EX, req),
934 bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
935 if (dhparam != NULL && *dhparam == '/')
937 TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
938 bitset(TLS_I_DHPAR_EX, req),
939 bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
940 if (!bitset(TLS_S_DHPAR_OK, status))
943 # if OPENSSL_VERSION_NUMBER > 0x00907000L
944 TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
945 bitset(TLS_I_CRLF_EX, req),
946 bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
947 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
952 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
953 bitset(TLS_I_CERT_EX, req),
954 bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
958 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
959 bitset(TLS_I_KEY_EX, req),
960 bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
963 /* create a method and a new context */
964 if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
965 SSLv23_client_method())) == NULL)
968 sm_syslog(LOG_WARNING, NOQID,
969 "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
972 tlslogerr(LOG_WARNING, who);
976 # if OPENSSL_VERSION_NUMBER > 0x00907000L
979 /* get a pointer to the current certificate validation store */
980 store = SSL_CTX_get_cert_store(*ctx); /* does not fail */
981 crl_file = BIO_new(BIO_s_file());
982 if (crl_file != NULL)
984 if (BIO_read_filename(crl_file, CRLFile) >= 0)
986 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
989 X509_STORE_add_crl(store, crl);
991 X509_STORE_set_flags(store,
992 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
993 X509_STORE_set_verify_cb_func(store,
1000 sm_syslog(LOG_WARNING, NOQID,
1001 "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
1005 /* avoid memory leaks */
1011 else if (LogLevel > 9)
1012 sm_syslog(LOG_WARNING, NOQID,
1013 "STARTTLS=%s, error: BIO_new=failed", who);
1018 if (CRLPath != NULL && store != NULL)
1020 X509_LOOKUP *lookup;
1022 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1027 sm_syslog(LOG_WARNING, NOQID,
1028 "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
1033 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
1034 X509_STORE_set_flags(store,
1035 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1037 # endif /* _FFR_CRLPATH */
1038 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1041 /* turn off backward compatibility, required for no-rsa */
1042 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
1043 # endif /* TLS_NO_RSA */
1048 ** Create a temporary RSA key
1049 ** XXX Maybe we shouldn't create this always (even though it
1050 ** is only at startup).
1051 ** It is a time-consuming operation and it is not always necessary.
1052 ** maybe we should do it only on demand...
1055 if (bitset(TLS_I_RSA_TMP, req)
1057 && ShmId != SM_SHM_NO_ID &&
1058 (rsa_tmp = sm_RSA_generate_key(RSA_KEYLENGTH, RSA_F4)) == NULL
1059 # else /* SM_CONF_SHM */
1060 && 0 /* no shared memory: no need to generate key now */
1061 # endif /* SM_CONF_SHM */
1066 sm_syslog(LOG_WARNING, NOQID,
1067 "STARTTLS=%s, error: RSA_generate_key failed",
1070 tlslogerr(LOG_WARNING, who);
1074 # endif /* !TLS_NO_RSA */
1078 ** XXX change this for DSA-only version
1081 if (bitset(TLS_S_KEY_OK, status) &&
1082 SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
1083 SSL_FILETYPE_PEM) <= 0)
1087 sm_syslog(LOG_WARNING, NOQID,
1088 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1091 tlslogerr(LOG_WARNING, who);
1093 if (bitset(TLS_I_USE_KEY, req))
1097 #if _FFR_TLS_USE_CERTIFICATE_CHAIN_FILE
1098 # define SSL_CTX_use_cert(ssl_ctx, certfile) \
1099 SSL_CTX_use_certificate_chain_file(ssl_ctx, certfile)
1100 # define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_chain_file"
1102 # define SSL_CTX_use_cert(ssl_ctx, certfile) \
1103 SSL_CTX_use_certificate_file(ssl_ctx, certfile, SSL_FILETYPE_PEM)
1104 # define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_file"
1107 /* get the certificate file */
1108 if (bitset(TLS_S_CERT_OK, status) &&
1109 SSL_CTX_use_cert(*ctx, certfile) <= 0)
1113 sm_syslog(LOG_WARNING, NOQID,
1114 "STARTTLS=%s, error: %s(%s) failed",
1115 who, SSL_CTX_USE_CERT, certfile);
1117 tlslogerr(LOG_WARNING, who);
1119 if (bitset(TLS_I_USE_CERT, req))
1123 /* check the private key */
1124 if (bitset(TLS_S_KEY_OK, status) &&
1125 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1127 /* Private key does not match the certificate public key */
1130 sm_syslog(LOG_WARNING, NOQID,
1131 "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
1134 tlslogerr(LOG_WARNING, who);
1136 if (bitset(TLS_I_USE_KEY, req))
1140 /* XXX this code is pretty much duplicated from above! */
1142 /* load private key */
1143 if (bitset(TLS_S_KEY2_OK, status) &&
1144 SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
1148 sm_syslog(LOG_WARNING, NOQID,
1149 "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1152 tlslogerr(LOG_WARNING, who);
1156 /* get the certificate file */
1157 if (bitset(TLS_S_CERT2_OK, status) &&
1158 SSL_CTX_use_cert(*ctx, cf2) <= 0)
1162 sm_syslog(LOG_WARNING, NOQID,
1163 "STARTTLS=%s, error: %s(%s) failed",
1164 who, SSL_CTX_USE_CERT, cf2);
1166 tlslogerr(LOG_WARNING, who);
1170 /* also check the private key */
1171 if (bitset(TLS_S_KEY2_OK, status) &&
1172 (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1174 /* Private key does not match the certificate public key */
1177 sm_syslog(LOG_WARNING, NOQID,
1178 "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
1181 tlslogerr(LOG_WARNING, who);
1185 /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
1187 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
1190 ** In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
1191 ** padding bug work-around, leading to false positives and
1192 ** failed connections. We may not interoperate with systems
1193 ** with the bug, but this is better than breaking on all 0.9.8[ab]
1194 ** systems that have zlib support enabled.
1195 ** Note: this checks the runtime version of the library, not
1196 ** just the compile time version.
1199 rt_version = SSLeay();
1200 if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
1202 comp_methods = SSL_COMP_get_compression_methods();
1203 if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
1204 options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
1207 SSL_CTX_set_options(*ctx, (long) options);
1210 /* Diffie-Hellman initialization */
1211 if (bitset(TLS_I_TRY_DH, req))
1215 #endif /* _FFR_TLS_EC */
1218 sm_dprintf("inittls: req=%#lx, status=%#lx\n",
1220 if (bitset(TLS_S_DHPAR_OK, status))
1224 if ((bio = BIO_new_file(dhparam, "r")) != NULL)
1226 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1228 if (dh == NULL && LogLevel > 7)
1232 err = ERR_get_error();
1233 sm_syslog(LOG_WARNING, NOQID,
1234 "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
1236 ERR_error_string(err, NULL));
1238 tlslogerr(LOG_WARNING, who);
1246 sm_syslog(LOG_WARNING, NOQID,
1247 "STARTTLS=%s, error: BIO_new_file(%s) failed",
1250 tlslogerr(LOG_WARNING, who);
1254 if (dh == NULL && bitset(TLS_I_DH1024|TLS_I_DH2048, req))
1259 bits = bitset(TLS_I_DH2048, req) ? 2048 : 1024;
1261 sm_dprintf("inittls: Generating %d bit DH parameters\n", bits);
1264 /* this takes a while! */
1265 (void)DSA_generate_parameters_ex(dsa, bits, NULL, 0,
1267 dh = DSA_dup_DH(dsa);
1270 else if (dh == NULL && bitset(TLS_I_DHFIXED, req))
1273 sm_dprintf("inittls: Using precomputed 2048 bit DH parameters\n");
1276 else if (dh == NULL && bitset(TLS_I_DH512, req))
1279 sm_dprintf("inittls: Using precomputed 512 bit DH parameters\n");
1289 err = ERR_get_error();
1290 sm_syslog(LOG_WARNING, NOQID,
1291 "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1293 ERR_error_string(err, NULL));
1295 if (bitset(TLS_I_REQ_DH, req))
1300 /* important to avoid small subgroup attacks */
1301 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
1303 SSL_CTX_set_tmp_dh(*ctx, dh);
1305 sm_syslog(LOG_INFO, NOQID,
1306 "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
1307 who, 8 * DH_size(dh), *dhparam);
1312 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1315 SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_ECDH_USE);
1316 SSL_CTX_set_tmp_ecdh(*ctx, ecdh);
1319 #endif /* _FFR_TLS_EC */
1322 # endif /* !NO_DH */
1325 /* XXX do we need this cache here? */
1326 if (bitset(TLS_I_CACHE, req))
1328 SSL_CTX_sess_set_cache_size(*ctx, 1);
1329 SSL_CTX_set_timeout(*ctx, 1);
1330 SSL_CTX_set_session_id_context(*ctx,
1331 (void *) &server_session_id_context,
1332 sizeof(server_session_id_context));
1333 (void) SSL_CTX_set_session_cache_mode(*ctx,
1334 SSL_SESS_CACHE_SERVER);
1338 (void) SSL_CTX_set_session_cache_mode(*ctx,
1339 SSL_SESS_CACHE_OFF);
1342 /* load certificate locations and default CA paths */
1343 if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1345 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1349 if (bitset(TLS_I_RSA_TMP, req))
1350 SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1351 # endif /* !TLS_NO_RSA */
1354 ** We have to install our own verify callback:
1355 ** SSL_VERIFY_PEER requests a client cert but even
1356 ** though *FAIL_IF* isn't set, the connection
1357 ** will be aborted if the client presents a cert
1358 ** that is not "liked" (can't be verified?) by
1359 ** the TLS library :-(
1363 ** XXX currently we could call tls_set_verify()
1364 ** but we hope that that function will later on
1365 ** only set the mode per connection.
1367 SSL_CTX_set_verify(*ctx,
1368 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1372 /* install verify callback */
1373 SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb,
1375 SSL_CTX_set_client_CA_list(*ctx,
1376 SSL_load_client_CA_file(cacertfile));
1381 ** can't load CA data; do we care?
1382 ** the data is necessary to authenticate the client,
1383 ** which in turn would be necessary
1384 ** if we want to allow relaying based on it.
1388 sm_syslog(LOG_WARNING, NOQID,
1389 "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1390 who, cacertpath, cacertfile, r);
1392 tlslogerr(LOG_WARNING, who);
1394 if (bitset(TLS_I_VRFY_LOC, req))
1399 /* XXX: make this dependent on an option? */
1401 SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1403 /* install our own cipher list */
1404 if (CipherList != NULL && *CipherList != '\0')
1406 if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1410 sm_syslog(LOG_WARNING, NOQID,
1411 "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1415 tlslogerr(LOG_WARNING, who);
1417 /* failure if setting to this list is required? */
1422 sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1426 ** this label is required if we want to have a "clean" exit
1427 ** see the comments above at the initialization of cf2
1433 /* undo damage to global variables */
1443 ** CERT_FP -- get cert fingerprint
1447 ** mac -- macro storage
1448 ** macro -- where to store cert fp
1451 ** <=0: cert fp calculation failed
1452 ** >0: cert fp calculation ok
1456 cert_fp(cert, evp_digest, mac, macro)
1458 const EVP_MD *evp_digest;
1464 unsigned char md[EVP_MAX_MD_SIZE];
1465 char md5h[EVP_MAX_MD_SIZE * 3];
1466 static const char hexcodes[] = "0123456789ABCDEF";
1469 if (X509_digest(cert, EVP_digest, md, &n) == 0 || n <= 0)
1471 macdefine(mac, A_TEMP, macid(macro), "");
1475 SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1476 for (r = 0; r < (int) n; r++)
1478 md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1479 md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1480 md5h[(r * 3) + 2] = ':';
1482 md5h[(n * 3) - 1] = '\0';
1483 macdefine(mac, A_TEMP, macid(macro), md5h);
1488 ** TLS_GET_INFO -- get information about TLS connection
1491 ** ssl -- TLS connection structure
1492 ** srv -- server or client
1493 ** host -- hostname of other side
1494 ** mac -- macro storage
1495 ** certreq -- did we ask for a cert?
1498 ** result of authentication.
1501 ** sets various TLS related macros.
1505 tls_get_info(ssl, srv, host, mac, certreq)
1512 const SSL_CIPHER *c;
1519 c = SSL_get_current_cipher(ssl);
1521 /* cast is just workaround for compiler warning */
1522 macdefine(mac, A_TEMP, macid("{cipher}"),
1523 (char *) SSL_CIPHER_get_name(c));
1524 b = SSL_CIPHER_get_bits(c, &r);
1525 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1526 macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1527 (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1528 macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1529 s = (char *) SSL_get_version(ssl);
1532 macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1534 who = srv ? "server" : "client";
1535 cert = SSL_get_peer_certificate(ssl);
1536 verifyok = SSL_get_verify_result(ssl);
1538 sm_syslog(LOG_INFO, NOQID,
1539 "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1540 who, verifyok, (unsigned long) cert);
1543 X509_NAME *subj, *issuer;
1546 subj = X509_get_subject_name(cert);
1547 issuer = X509_get_issuer_name(cert);
1548 X509_NAME_oneline(subj, buf, sizeof(buf));
1549 macdefine(mac, A_TEMP, macid("{cert_subject}"),
1550 xtextify(buf, "<>\")"));
1551 X509_NAME_oneline(issuer, buf, sizeof(buf));
1552 macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1553 xtextify(buf, "<>\")"));
1555 # define LL_BADCERT 8
1557 #define CERTFPMACRO (CertFingerprintAlgorithm != NULL ? "{cert_fp}" : "{cert_md5}")
1559 #define CHECK_X509_NAME(which) \
1563 sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \
1564 if (LogLevel > LL_BADCERT) \
1565 sm_syslog(LOG_INFO, NOQID, \
1566 "STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN", \
1568 host == NULL ? "local" : host, \
1571 else if ((size_t)r >= sizeof(buf) - 1) \
1573 sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \
1575 sm_syslog(LOG_INFO, NOQID, \
1576 "STARTTLS=%s, relay=%.100s, field=%s, status=CN too long", \
1578 host == NULL ? "local" : host, \
1581 else if ((size_t)r > strlen(buf)) \
1583 sm_strlcpy(buf, "BadCertificateContainsNUL", \
1586 sm_syslog(LOG_INFO, NOQID, \
1587 "STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL", \
1589 host == NULL ? "local" : host, \
1594 r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf,
1596 CHECK_X509_NAME("cn_subject");
1597 macdefine(mac, A_TEMP, macid("{cn_subject}"),
1598 xtextify(buf, "<>\")"));
1599 r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf,
1601 CHECK_X509_NAME("cn_issuer");
1602 macdefine(mac, A_TEMP, macid("{cn_issuer}"),
1603 xtextify(buf, "<>\")"));
1604 (void) cert_fp(cert, EVP_digest, mac, CERTFPMACRO);
1608 macdefine(mac, A_PERM, macid("{cert_subject}"), "");
1609 macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
1610 macdefine(mac, A_PERM, macid("{cn_subject}"), "");
1611 macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
1612 macdefine(mac, A_TEMP, macid(CERTFPMACRO), "");
1624 s = certreq ? "NO" : "NOT",
1633 macdefine(mac, A_PERM, macid("{verify}"), s);
1637 /* do some logging */
1640 char *vers, *s1, *s2, *cbits, *algbits;
1642 vers = macget(mac, macid("{tls_version}"));
1643 cbits = macget(mac, macid("{cipher_bits}"));
1644 algbits = macget(mac, macid("{alg_bits}"));
1645 s1 = macget(mac, macid("{verify}"));
1646 s2 = macget(mac, macid("{cipher}"));
1648 /* XXX: maybe cut off ident info? */
1649 sm_syslog(LOG_INFO, NOQID,
1650 "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s",
1652 host == NULL ? "local" : host,
1653 vers, s1, s2, /* sm_snprintf() can deal with NULL */
1654 algbits == NULL ? "0" : algbits,
1655 cbits == NULL ? "0" : cbits);
1659 ** Maybe run xuntextify on the strings?
1660 ** That is easier to read but makes it maybe a bit
1661 ** more complicated to figure out the right values
1662 ** for the access map...
1665 s1 = macget(mac, macid("{cert_subject}"));
1666 s2 = macget(mac, macid("{cert_issuer}"));
1667 sm_syslog(LOG_INFO, NOQID,
1668 "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
1670 X509_verify_cert_error_string(verifyok));
1676 ** ENDTLS -- shutdown secure connection
1679 ** ssl -- SSL connection information.
1680 ** side -- server/client (for logging).
1683 ** success? (EX_* code)
1697 if ((r = SSL_shutdown(ssl)) < 0)
1701 sm_syslog(LOG_WARNING, NOQID,
1702 "STARTTLS=%s, SSL_shutdown failed: %d",
1704 tlslogerr(LOG_WARNING, side);
1708 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1711 ** Bug in OpenSSL (at least up to 0.9.6b):
1712 ** From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1713 ** Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1714 ** To: openssl-users@openssl.org
1715 ** Subject: Re: SSL_shutdown() woes (fwd)
1717 ** The side sending the shutdown alert first will
1718 ** not care about the answer of the peer but will
1719 ** immediately return with a return value of "0"
1720 ** (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1721 ** the value of "0" and as the shutdown alert of the peer was
1722 ** not received (actually, the program did not even wait for
1723 ** the answer), an SSL_ERROR_SYSCALL is flagged, because this
1724 ** is the default rule in case everything else does not apply.
1726 ** For your server the problem is different, because it
1727 ** receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1728 ** then sends its response (SSL_SENT_SHUTDOWN), so for the
1729 ** server the shutdown was successfull.
1731 ** As is by know, you would have to call SSL_shutdown() once
1732 ** and ignore an SSL_ERROR_SYSCALL returned. Then call
1733 ** SSL_shutdown() again to actually get the server's response.
1735 ** In the last discussion, Bodo Moeller concluded that a
1736 ** rewrite of the shutdown code would be necessary, but
1737 ** probably with another API, as the change would not be
1738 ** compatible to the way it is now. Things do not become
1739 ** easier as other programs do not follow the shutdown
1740 ** guidelines anyway, so that a lot error conditions and
1741 ** compitibility issues would have to be caught.
1743 ** For now the recommondation is to ignore the error message.
1750 sm_syslog(LOG_WARNING, NOQID,
1751 "STARTTLS=%s, SSL_shutdown not done",
1753 tlslogerr(LOG_WARNING, side);
1757 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1766 ** TMP_RSA_KEY -- return temporary RSA key
1769 ** s -- TLS connection structure
1774 ** temporary RSA key.
1777 # ifndef MAX_RSA_TMP_CNT
1778 # define MAX_RSA_TMP_CNT 1000 /* XXX better value? */
1779 # endif /* ! MAX_RSA_TMP_CNT */
1783 tmp_rsa_key(s, export, keylength)
1790 extern int *PRSATmpCnt;
1792 if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1793 ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1795 # endif /* SM_CONF_SHM */
1797 if (rsa_tmp != NULL)
1799 rsa_tmp = sm_RSA_generate_key(RSA_KEYLENGTH, RSA_F4);
1800 if (rsa_tmp == NULL)
1803 sm_syslog(LOG_ERR, NOQID,
1804 "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1811 ** XXX we can't (yet) share the new key...
1812 ** The RSA structure contains pointers hence it can't be
1813 ** easily kept in shared memory. It must be transformed
1814 ** into a continous memory region first, then stored,
1815 ** and later read out again (each time re-transformed).
1818 if (ShmId != SM_SHM_NO_ID)
1821 # endif /* SM_CONF_SHM */
1823 sm_syslog(LOG_ERR, NOQID,
1824 "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1828 # endif /* !TLS_NO_RSA */
1830 ** APPS_SSL_INFO_CB -- info callback for TLS connections
1833 ** s -- TLS connection structure
1834 ** where -- state in handshake
1835 ** ret -- return code of last operation
1842 apps_ssl_info_cb(s, where, ret)
1849 BIO *bio_err = NULL;
1852 sm_syslog(LOG_INFO, NOQID,
1853 "STARTTLS: info_callback where=0x%x, ret=%d",
1856 w = where & ~SSL_ST_MASK;
1857 if (bio_err == NULL)
1858 bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
1860 if (bitset(SSL_ST_CONNECT, w))
1861 str = "SSL_connect";
1862 else if (bitset(SSL_ST_ACCEPT, w))
1867 if (bitset(SSL_CB_LOOP, where))
1870 sm_syslog(LOG_NOTICE, NOQID,
1872 str, SSL_state_string_long(s));
1874 else if (bitset(SSL_CB_ALERT, where))
1876 str = bitset(SSL_CB_READ, where) ? "read" : "write";
1878 sm_syslog(LOG_NOTICE, NOQID,
1879 "STARTTLS: SSL3 alert %s:%s:%s",
1880 str, SSL_alert_type_string_long(ret),
1881 SSL_alert_desc_string_long(ret));
1883 else if (bitset(SSL_CB_EXIT, where))
1888 sm_syslog(LOG_WARNING, NOQID,
1889 "STARTTLS: %s:failed in %s",
1890 str, SSL_state_string_long(s));
1895 sm_syslog(LOG_WARNING, NOQID,
1896 "STARTTLS: %s:error in %s",
1897 str, SSL_state_string_long(s));
1902 ** TLS_VERIFY_LOG -- log verify error for TLS certificates
1906 ** ctx -- x509 context
1907 ** name -- from where is this called?
1914 tls_verify_log(ok, ctx, name)
1916 X509_STORE_CTX *ctx;
1923 cert = X509_STORE_CTX_get_current_cert(ctx);
1924 reason = X509_STORE_CTX_get_error(ctx);
1925 depth = X509_STORE_CTX_get_error_depth(ctx);
1926 X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1927 sm_syslog(LOG_INFO, NOQID,
1928 "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1929 name, depth, buf, ok, X509_verify_cert_error_string(reason));
1934 ** TLS_VERIFY_CB -- verify callback for TLS certificates
1937 ** ctx -- x509 context
1940 ** accept connection?
1941 ** currently: always yes.
1945 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1947 X509_STORE_CTX *ctx;
1948 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1949 tls_verify_cb(ctx, unused)
1950 X509_STORE_CTX *ctx;
1952 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1957 ** man SSL_CTX_set_cert_verify_callback():
1958 ** callback should return 1 to indicate verification success
1959 ** and 0 to indicate verification failure.
1962 ok = X509_verify_cert(ctx);
1966 return tls_verify_log(ok, ctx, "TLS");
1971 ** TLSLOGERR -- log the errors from the TLS error stack
1974 ** level -- syslog level
1975 ** who -- server/client (for logging).
1982 tlslogerr(level, who)
1992 es = CRYPTO_thread_id();
1993 while ((l = ERR_get_error_line_data((const char **) &file, &line,
1994 (const char **) &data, &flags))
1997 sm_syslog(level, NOQID,
1998 "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1999 ERR_error_string(l, buf),
2001 bitset(ERR_TXT_STRING, flags) ? data : "");
2005 # if OPENSSL_VERSION_NUMBER > 0x00907000L
2007 ** X509_VERIFY_CB -- verify callback
2010 ** ctx -- x509 context
2013 ** accept connection?
2014 ** currently: always yes.
2018 x509_verify_cb(ok, ctx)
2020 X509_STORE_CTX *ctx;
2025 tls_verify_log(ok, ctx, "x509");
2026 if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL)
2028 X509_STORE_CTX_set_error(ctx, 0);
2029 return 1; /* override it */
2034 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
2035 #endif /* STARTTLS */