xref: /freebsd/contrib/sendmail/src/tls.c (revision 783d3ff6)
1 /*
2  * Copyright (c) 2000-2006, 2008, 2009, 2011, 2013-2016 Proofpoint, Inc. and its suppliers.
3  *	All rights reserved.
4  *
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.
8  *
9  */
10 
11 #include <sendmail.h>
12 
13 SM_RCSID("@(#)$Id: tls.c,v 8.127 2013-11-27 02:51:11 gshapiro Exp $")
14 
15 #if STARTTLS
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
22 # include <openssl/engine.h>
23 # if _FFR_TLS_ALTNAMES
24 #  include <openssl/x509v3.h>
25 # endif
26 # include <tls.h>
27 
28 # if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER <= 0x00907000L
29 #  error "OpenSSL versions <= 0x00907000L are unsupported."
30 # endif
31 
32 # if DANE && OPENSSL_VERSION_NUMBER == 0x30200000L
33 #  error OpenSSL 3.2.0 has a bug related to DANE
34 #  error see https://github.com/openssl/openssl/pull/22821
35 # endif
36 
37 /*
38 **  *SSL version numbers:
39 **  OpenSSL 0.9 - 1.1 (so far), 3.[012]
40 **  LibreSSL 2.0 (0x20000000L - part of "These will never change")
41 */
42 
43 # if (OPENSSL_VERSION_NUMBER >= 0x10100000L && OPENSSL_VERSION_NUMBER < 0x20000000L) || OPENSSL_VERSION_NUMBER >= 0x30000000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
44 #  define MTA_HAVE_DH_set0_pqg 1
45 #  define MTA_HAVE_DSA_GENERATE_EX	1
46 #  define MTA_HAVE_OPENSSL_init_ssl	1
47 #  define MTA_ASN1_STRING_data ASN1_STRING_get0_data
48 #  include <openssl/bn.h>
49 #  include <openssl/dsa.h>
50 # else
51 #  define X509_STORE_CTX_get0_cert(ctx)	(ctx)->cert
52 #  define MTA_RSA_TMP_CB	1
53 #  define MTA_ASN1_STRING_data ASN1_STRING_data
54 # endif
55 
56 /* Is this ok or use HAVE_SSL_get1_peer_certificate instead? */
57 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
58 # define MTA_SSL_get_peer_certificate SSL_get1_peer_certificate
59 
60 # ifndef HAVE_ERR_get_error_all
61 #  define HAVE_ERR_get_error_all 1
62 # endif
63 
64 /* use SSL_CTX_set_dh_auto()?  which versions provide it? */
65 # define MTA_DH_AUTO	1
66 #else
67 # define MTA_SSL_get_peer_certificate SSL_get_peer_certificate
68 # define MTA_DH_AUTO	0
69 #endif
70 
71 #if HAVE_ERR_get_error_all
72 # define MTA_SSL_ERR_get(f, l, d, fl, fct) ERR_get_error_all(f, l, fct, d, fl)
73 #else /* if HAVE_ERR_get_error_line_data ? */
74 # define MTA_SSL_ERR_get(f, l, d, fl, fct) ERR_get_error_line_data(f, l, d, fl)
75 #endif
76 
77 # if !TLS_NO_RSA && MTA_RSA_TMP_CB
78 static RSA *rsa_tmp = NULL;	/* temporary RSA key */
79 static RSA *tmp_rsa_key __P((SSL *, int, int));
80 # endif
81 static int	tls_verify_cb __P((X509_STORE_CTX *, void *));
82 
83 static int x509_verify_cb __P((int, X509_STORE_CTX *));
84 
85 static void	apps_ssl_info_cb __P((const SSL *, int, int));
86 static bool	tls_ok_f __P((char *, char *, int));
87 static bool	tls_safe_f __P((char *, long, bool));
88 static int	tls_verify_log __P((int, X509_STORE_CTX *, const char *));
89 
90 int TLSsslidx = -1;
91 
92 # if !NO_DH
93 # include <openssl/dh.h>
94 static DH *get_dh512 __P((void));
95 
96 static unsigned char dh512_p[] =
97 {
98 	0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
99 	0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
100 	0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
101 	0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
102 	0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
103 	0x47,0x74,0xE8,0x33
104 };
105 static unsigned char dh512_g[] =
106 {
107 	0x02
108 };
109 
110 static DH *
111 get_dh512()
112 {
113 	DH *dh = NULL;
114 #  if MTA_HAVE_DH_set0_pqg
115 	BIGNUM *dhp_bn, *dhg_bn;
116 #  endif
117 
118 	if ((dh = DH_new()) == NULL)
119 		return NULL;
120 #  if MTA_HAVE_DH_set0_pqg
121 	dhp_bn = BN_bin2bn(dh512_p, sizeof (dh512_p), NULL);
122 	dhg_bn = BN_bin2bn(dh512_g, sizeof (dh512_g), NULL);
123 	if (dhp_bn == NULL || dhg_bn == NULL || !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))  {
124 		DH_free(dh);
125 		BN_free(dhp_bn);
126 		BN_free(dhg_bn);
127 		return NULL;
128 	}
129 #  else
130 	dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
131 	dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
132 	if ((dh->p == NULL) || (dh->g == NULL))
133 	{
134 		DH_free(dh);
135 		return NULL;
136 	}
137 #  endif
138 	return dh;
139 }
140 
141 #  if 0
142 
143 This is the data from which the C code has been generated:
144 
145 -----BEGIN DH PARAMETERS-----
146 MIIBCAKCAQEArDcgcLpxEksQHPlolRKCUJ2szKRziseWV9cUSQNZGxoGw7KkROz4
147 HF9QSbg5axyNIG+QbZYtx0jp3l6/GWq1dLOj27yZkgYgaYgFrvKPiZ2jJ5xETQVH
148 UpZwbjRcyjyWkWYJVsx1aF4F/iY4kT0n/+iGEoimI3C9V3KXTJ2S6jIkyJ6M/CrN
149 EtrDynMlUMGlc7S1ouXVOTrtKeqy3S2L9eBLxVI+sChEijGIfELupdVeXihK006p
150 MgnABPDbkTx6OOtYmSZaGQX+OLW2FPmwvcrzgCz9t9cAsuUcBZv1LeHEqZZttyLU
151 oK0jjSXgFyeU4/NfyA+zuNeWzUL6bHmigwIBAg==
152 -----END DH PARAMETERS-----
153 #  endif /* 0 */
154 
155 static DH *
156 get_dh2048()
157 {
158 	static unsigned char dh2048_p[]={
159 		0xAC,0x37,0x20,0x70,0xBA,0x71,0x12,0x4B,0x10,0x1C,0xF9,0x68,
160 		0x95,0x12,0x82,0x50,0x9D,0xAC,0xCC,0xA4,0x73,0x8A,0xC7,0x96,
161 		0x57,0xD7,0x14,0x49,0x03,0x59,0x1B,0x1A,0x06,0xC3,0xB2,0xA4,
162 		0x44,0xEC,0xF8,0x1C,0x5F,0x50,0x49,0xB8,0x39,0x6B,0x1C,0x8D,
163 		0x20,0x6F,0x90,0x6D,0x96,0x2D,0xC7,0x48,0xE9,0xDE,0x5E,0xBF,
164 		0x19,0x6A,0xB5,0x74,0xB3,0xA3,0xDB,0xBC,0x99,0x92,0x06,0x20,
165 		0x69,0x88,0x05,0xAE,0xF2,0x8F,0x89,0x9D,0xA3,0x27,0x9C,0x44,
166 		0x4D,0x05,0x47,0x52,0x96,0x70,0x6E,0x34,0x5C,0xCA,0x3C,0x96,
167 		0x91,0x66,0x09,0x56,0xCC,0x75,0x68,0x5E,0x05,0xFE,0x26,0x38,
168 		0x91,0x3D,0x27,0xFF,0xE8,0x86,0x12,0x88,0xA6,0x23,0x70,0xBD,
169 		0x57,0x72,0x97,0x4C,0x9D,0x92,0xEA,0x32,0x24,0xC8,0x9E,0x8C,
170 		0xFC,0x2A,0xCD,0x12,0xDA,0xC3,0xCA,0x73,0x25,0x50,0xC1,0xA5,
171 		0x73,0xB4,0xB5,0xA2,0xE5,0xD5,0x39,0x3A,0xED,0x29,0xEA,0xB2,
172 		0xDD,0x2D,0x8B,0xF5,0xE0,0x4B,0xC5,0x52,0x3E,0xB0,0x28,0x44,
173 		0x8A,0x31,0x88,0x7C,0x42,0xEE,0xA5,0xD5,0x5E,0x5E,0x28,0x4A,
174 		0xD3,0x4E,0xA9,0x32,0x09,0xC0,0x04,0xF0,0xDB,0x91,0x3C,0x7A,
175 		0x38,0xEB,0x58,0x99,0x26,0x5A,0x19,0x05,0xFE,0x38,0xB5,0xB6,
176 		0x14,0xF9,0xB0,0xBD,0xCA,0xF3,0x80,0x2C,0xFD,0xB7,0xD7,0x00,
177 		0xB2,0xE5,0x1C,0x05,0x9B,0xF5,0x2D,0xE1,0xC4,0xA9,0x96,0x6D,
178 		0xB7,0x22,0xD4,0xA0,0xAD,0x23,0x8D,0x25,0xE0,0x17,0x27,0x94,
179 		0xE3,0xF3,0x5F,0xC8,0x0F,0xB3,0xB8,0xD7,0x96,0xCD,0x42,0xFA,
180 		0x6C,0x79,0xA2,0x83,
181 		};
182 	static unsigned char dh2048_g[]={ 0x02, };
183 	DH *dh;
184 #  if MTA_HAVE_DH_set0_pqg
185 	BIGNUM *dhp_bn, *dhg_bn;
186 #  endif
187 
188 	if ((dh=DH_new()) == NULL)
189 		return(NULL);
190 #  if MTA_HAVE_DH_set0_pqg
191 	dhp_bn = BN_bin2bn(dh2048_p, sizeof (dh2048_p), NULL);
192 	dhg_bn = BN_bin2bn(dh2048_g, sizeof (dh2048_g), NULL);
193 	if (dhp_bn == NULL || dhg_bn == NULL || !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn))  {
194 		DH_free(dh);
195 		BN_free(dhp_bn);
196 		BN_free(dhg_bn);
197 		return NULL;
198 	}
199 #  else
200 	dh->p=BN_bin2bn(dh2048_p,sizeof(dh2048_p),NULL);
201 	dh->g=BN_bin2bn(dh2048_g,sizeof(dh2048_g),NULL);
202 	if ((dh->p == NULL) || (dh->g == NULL))
203 	{
204 		DH_free(dh);
205 		return(NULL);
206 	}
207 #  endif
208 	return(dh);
209 }
210 # endif /* !NO_DH */
211 
212 /*
213 **  TLS_RAND_INIT -- initialize STARTTLS random generator
214 **
215 **	Parameters:
216 **		randfile -- name of file with random data
217 **		logl -- loglevel
218 **
219 **	Returns:
220 **		success/failure
221 **
222 **	Side Effects:
223 **		initializes PRNG for tls library.
224 */
225 
226 # define MIN_RAND_BYTES	128	/* 1024 bits */
227 
228 # define RF_OK		0	/* randfile OK */
229 # define RF_MISS	1	/* randfile == NULL || *randfile == '\0' */
230 # define RF_UNKNOWN	2	/* unknown prefix for randfile */
231 
232 # define RI_NONE	0	/* no init yet */
233 # define RI_SUCCESS	1	/* init was successful */
234 # define RI_FAIL	2	/* init failed */
235 
236 static bool	tls_rand_init __P((char *, int));
237 
238 static bool
239 tls_rand_init(randfile, logl)
240 	char *randfile;
241 	int logl;
242 {
243 # ifndef HASURANDOMDEV
244 	/* not required if /dev/urandom exists, OpenSSL does it internally */
245 
246 	bool ok;
247 	int randdef;
248 	static int done = RI_NONE;
249 
250 	/*
251 	**  initialize PRNG
252 	*/
253 
254 	/* did we try this before? if yes: return old value */
255 	if (done != RI_NONE)
256 		return done == RI_SUCCESS;
257 
258 	/* set default values */
259 	ok = false;
260 	done = RI_FAIL;
261 	randdef = (SM_IS_EMPTY(randfile)) ? RF_MISS : RF_OK;
262 #  if EGD
263 	if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0)
264 	{
265 		randfile += 4;
266 		if (RAND_egd(randfile) < 0)
267 		{
268 			sm_syslog(LOG_WARNING, NOQID,
269 				  "STARTTLS: RAND_egd(%s) failed: random number generator not seeded",
270 				   randfile);
271 		}
272 		else
273 			ok = true;
274 	}
275 	else
276 #  endif /* EGD */
277 	/* "else" in #if code above */
278 	if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0)
279 	{
280 		int fd;
281 		long sff;
282 		struct stat st;
283 
284 		randfile += 5;
285 		sff = SFF_SAFEDIRPATH | SFF_NOWLINK
286 		      | SFF_NOGWFILES | SFF_NOWWFILES
287 		      | SFF_NOGRFILES | SFF_NOWRFILES
288 		      | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
289 		if (DontLockReadFiles)
290 			sff |= SFF_NOLOCK;
291 		if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0)
292 		{
293 			if (fstat(fd, &st) < 0)
294 			{
295 				if (LogLevel > logl)
296 					sm_syslog(LOG_ERR, NOQID,
297 						  "STARTTLS: can't fstat(%s)",
298 						  randfile);
299 			}
300 			else
301 			{
302 				bool use, problem;
303 
304 				use = true;
305 				problem = false;
306 
307 				/* max. age of file: 10 minutes */
308 				if (st.st_mtime + 600 < curtime())
309 				{
310 					use = bitnset(DBS_INSUFFICIENTENTROPY,
311 						      DontBlameSendmail);
312 					problem = true;
313 					if (LogLevel > logl)
314 						sm_syslog(LOG_ERR, NOQID,
315 							  "STARTTLS: RandFile %s too old: %s",
316 							  randfile,
317 							  use ? "unsafe" :
318 								"unusable");
319 				}
320 				if (use && st.st_size < MIN_RAND_BYTES)
321 				{
322 					use = bitnset(DBS_INSUFFICIENTENTROPY,
323 						      DontBlameSendmail);
324 					problem = true;
325 					if (LogLevel > logl)
326 						sm_syslog(LOG_ERR, NOQID,
327 							  "STARTTLS: size(%s) < %d: %s",
328 							  randfile,
329 							  MIN_RAND_BYTES,
330 							  use ? "unsafe" :
331 								"unusable");
332 				}
333 				if (use)
334 					ok = RAND_load_file(randfile, -1) >=
335 					     MIN_RAND_BYTES;
336 				if (use && !ok)
337 				{
338 					if (LogLevel > logl)
339 						sm_syslog(LOG_WARNING, NOQID,
340 							  "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded",
341 							  randfile);
342 				}
343 				if (problem)
344 					ok = false;
345 			}
346 			if (ok || bitnset(DBS_INSUFFICIENTENTROPY,
347 					  DontBlameSendmail))
348 			{
349 				/* add this even if fstat() failed */
350 				RAND_seed((void *) &st, sizeof(st));
351 			}
352 			(void) close(fd);
353 		}
354 		else
355 		{
356 			if (LogLevel > logl)
357 				sm_syslog(LOG_WARNING, NOQID,
358 					  "STARTTLS: Warning: safeopen(%s) failed",
359 					  randfile);
360 		}
361 	}
362 	else if (randdef == RF_OK)
363 	{
364 		if (LogLevel > logl)
365 			sm_syslog(LOG_WARNING, NOQID,
366 				  "STARTTLS: Error: no proper random file definition %s",
367 				  randfile);
368 		randdef = RF_UNKNOWN;
369 	}
370 	if (randdef == RF_MISS)
371 	{
372 		if (LogLevel > logl)
373 			sm_syslog(LOG_WARNING, NOQID,
374 				  "STARTTLS: Error: missing random file definition");
375 	}
376 	if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail))
377 	{
378 		int i;
379 		long r;
380 		unsigned char buf[MIN_RAND_BYTES];
381 
382 		/* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */
383 		for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long))
384 		{
385 			r = get_random();
386 			(void) memcpy(buf + i, (void *) &r, sizeof(long));
387 		}
388 		RAND_seed(buf, sizeof(buf));
389 		if (LogLevel > logl)
390 			sm_syslog(LOG_WARNING, NOQID,
391 				  "STARTTLS: Warning: random number generator not properly seeded");
392 		ok = true;
393 	}
394 	done = ok ? RI_SUCCESS : RI_FAIL;
395 	return ok;
396 # else /* ! HASURANDOMDEV */
397 	return true;
398 # endif /* ! HASURANDOMDEV */
399 }
400 
401 /*
402 **  INIT_TLS_LIBRARY -- Calls functions which set up TLS library for global use.
403 **
404 **	Parameters:
405 **		fipsmode -- use FIPS?
406 **
407 **	Returns:
408 **		0: OK
409 **		<0: perm.fail
410 **		>0: fail but can continue
411 */
412 
413 int
414 init_tls_library(fipsmode)
415 	bool fipsmode;
416 {
417 	bool bv;
418 
419 # if _FFR_FIPSMODE
420 	if (fipsmode && CertFingerprintAlgorithm == NULL)
421 		CertFingerprintAlgorithm = "sha1";
422 #  if OPENSSL_VERSION_NUMBER >= 0x30000000L
423 	if (LogLevel > 12)
424 		sm_syslog(LOG_DEBUG, NOQID,
425 			"fipsmode=%d, evp_is_FIPS=%d", fipsmode,
426 			EVP_default_properties_is_fips_enabled(NULL));
427 #  endif
428 # endif /* _FFR_FIPSMODE  */
429 
430 	/*
431 	**  OPENSSL_init_ssl(3): "As of version 1.1.0 OpenSSL will
432 	**  automatically allocate all resources that it needs
433 	**  so no explicit initialisation is required."
434 	*/
435 
436 # if !MTA_HAVE_OPENSSL_init_ssl
437 	/* basic TLS initialization, ignore result for now */
438 	SSL_library_init();
439 	SSL_load_error_strings();
440 	OpenSSL_add_all_algorithms();
441 # endif
442 
443 	bv = true;
444 	if (TLSsslidx < 0)
445 	{
446 		TLSsslidx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
447 		if (TLSsslidx < 0)
448 		{
449 			if (LogLevel > 0)
450 				sm_syslog(LOG_ERR, NOQID,
451 					"STARTTLS=init, SSL_get_ex_new_index=%d",
452 					TLSsslidx);
453 			bv = false;
454 		}
455 	}
456 
457 	if (bv)
458 		bv = tls_rand_init(RandFile, 7);
459 # if _FFR_FIPSMODE && OPENSSL_VERSION_NUMBER < 0x30000000L
460 	if (bv && fipsmode)
461 	{
462 		if (!FIPS_mode_set(1))
463 		{
464 			unsigned long err;
465 
466 			err = ERR_get_error();
467 			if (LogLevel > 0)
468 				sm_syslog(LOG_ERR, NOQID,
469 					"STARTTLS=init, FIPSMode=%s",
470 					ERR_error_string(err, NULL));
471 			return -1;
472 		}
473 		else if (LogLevel > 9)
474 		{
475 			sm_syslog(LOG_INFO, NOQID,
476 				"STARTTLS=init, FIPSMode=ok");
477 		}
478 	}
479 # endif /* _FFR_FIPSMODE && OPENSSL_VERSION_NUMBER < 0x30000000L */
480 
481 	if (!TLS_set_engine(SSLEngine, true))
482 	{
483 		if (LogLevel > 0)
484 			sm_syslog(LOG_ERR, NOQID,
485 				  "STARTTLS=init, engine=%s, TLS_set_engine=failed",
486 				  SSLEngine);
487 		return -1;
488 	}
489 
490 	if (bv && CertFingerprintAlgorithm != NULL)
491 	{
492 		const EVP_MD *md;
493 
494 		md = EVP_get_digestbyname(CertFingerprintAlgorithm);
495 		if (NULL == md)
496 		{
497 			bv = false;
498 			if (LogLevel > 0)
499 				sm_syslog(LOG_ERR, NOQID,
500 					"STARTTLS=init, CertFingerprintAlgorithm=%s, status=invalid"
501 					, CertFingerprintAlgorithm);
502 		}
503 		else
504 			EVP_digest = md;
505 	}
506 	return bv ? 0 : 1;
507 }
508 
509 /*
510 **  TLS_SET_VERIFY -- request client certificate?
511 **
512 **	Parameters:
513 **		ctx -- TLS context
514 **		ssl -- TLS session context
515 **		vrfy -- request certificate?
516 **
517 **	Returns:
518 **		none.
519 **
520 **	Side Effects:
521 **		Sets verification state for TLS
522 **
523 # if TLS_VRFY_PER_CTX
524 **	Notice:
525 **		This is per TLS context, not per TLS structure;
526 **		the former is global, the latter per connection.
527 **		It would be nice to do this per connection, but this
528 **		doesn't work in the current TLS libraries :-(
529 # endif * TLS_VRFY_PER_CTX *
530 */
531 
532 void
533 tls_set_verify(ctx, ssl, vrfy)
534 	SSL_CTX *ctx;
535 	SSL *ssl;
536 	bool vrfy;
537 {
538 # if !TLS_VRFY_PER_CTX
539 	SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
540 # else
541 	SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
542 			NULL);
543 # endif
544 }
545 
546 /*
547 **  status in initialization
548 **  these flags keep track of the status of the initialization
549 **  i.e., whether a file exists (_EX) and whether it can be used (_OK)
550 **  [due to permissions]
551 */
552 
553 # define TLS_S_NONE	0x00000000	/* none yet */
554 # define TLS_S_CERT_EX	0x00000001	/* cert file exists */
555 # define TLS_S_CERT_OK	0x00000002	/* cert file is ok */
556 # define TLS_S_KEY_EX	0x00000004	/* key file exists */
557 # define TLS_S_KEY_OK	0x00000008	/* key file is ok */
558 # define TLS_S_CERTP_EX	0x00000010	/* CA cert path exists */
559 # define TLS_S_CERTP_OK	0x00000020	/* CA cert path is ok */
560 # define TLS_S_CERTF_EX	0x00000040	/* CA cert file exists */
561 # define TLS_S_CERTF_OK	0x00000080	/* CA cert file is ok */
562 # define TLS_S_CRLF_EX	0x00000100	/* CRL file exists */
563 # define TLS_S_CRLF_OK	0x00000200	/* CRL file is ok */
564 
565 # define TLS_S_CERT2_EX	0x00001000	/* 2nd cert file exists */
566 # define TLS_S_CERT2_OK	0x00002000	/* 2nd cert file is ok */
567 # define TLS_S_KEY2_EX	0x00004000	/* 2nd key file exists */
568 # define TLS_S_KEY2_OK	0x00008000	/* 2nd key file is ok */
569 
570 # define TLS_S_DH_OK	0x00200000	/* DH cert is ok */
571 # define TLS_S_DHPAR_EX	0x00400000	/* DH param file exists */
572 # define TLS_S_DHPAR_OK	0x00800000	/* DH param file is ok to use */
573 
574 /* Type of variable */
575 # define TLS_T_OTHER	0
576 # define TLS_T_SRV	1
577 # define TLS_T_CLT	2
578 
579 /*
580 **  TLS_OK_F -- can var be an absolute filename?
581 **
582 **	Parameters:
583 **		var -- filename
584 **		fn -- what is the filename used for?
585 **		type -- type of variable
586 **
587 **	Returns:
588 **		ok?
589 */
590 
591 static bool
592 tls_ok_f(var, fn, type)
593 	char *var;
594 	char *fn;
595 	int type;
596 {
597 	/* must be absolute pathname */
598 	if (var != NULL && *var == '/')
599 		return true;
600 	if (LogLevel > 12)
601 		sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
602 			  type == TLS_T_SRV ? "Server" :
603 			  (type == TLS_T_CLT ? "Client" : ""), fn);
604 	return false;
605 }
606 /*
607 **  TLS_SAFE_F -- is a file safe to use?
608 **
609 **	Parameters:
610 **		var -- filename
611 **		sff -- flags for safefile()
612 **		srv -- server side?
613 **
614 **	Returns:
615 **		ok?
616 */
617 
618 static bool
619 tls_safe_f(var, sff, srv)
620 	char *var;
621 	long sff;
622 	bool srv;
623 {
624 	int ret;
625 
626 	if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
627 			    S_IRUSR, NULL)) == 0)
628 		return true;
629 	if (LogLevel > 7)
630 		sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
631 			  srv ? "server" : "client", var, sm_errstring(ret));
632 	return false;
633 }
634 
635 /*
636 **  TLS_OK_F -- macro to simplify calls to tls_ok_f
637 **
638 **	Parameters:
639 **		var -- filename
640 **		fn -- what is the filename used for?
641 **		req -- is the file required?
642 **		st -- status bit to set if ok
643 **		type -- type of variable
644 **
645 **	Side Effects:
646 **		uses r, ok; may change ok and status.
647 **
648 */
649 
650 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
651 	{ \
652 		r = tls_ok_f(var, fn, type); \
653 		if (r) \
654 			status |= st; \
655 		else if (req) \
656 			ok = false; \
657 	}
658 
659 /*
660 **  TLS_UNR -- macro to return whether a file should be unreadable
661 **
662 **	Parameters:
663 **		bit -- flag to test
664 **		req -- flags
665 **
666 **	Returns:
667 **		0/SFF_NORFILES
668 */
669 
670 # define TLS_UNR(bit, req)	(bitset(bit, req) ? SFF_NORFILES : 0)
671 # define TLS_OUNR(bit, req)	(bitset(bit, req) ? SFF_NOWRFILES : 0)
672 # define TLS_KEYSFF(req)	\
673 	(bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ?	\
674 		TLS_OUNR(TLS_I_KEY_OUNR, req) :			\
675 		TLS_UNR(TLS_I_KEY_UNR, req))
676 
677 /*
678 **  TLS_SAFE_F -- macro to simplify calls to tls_safe_f
679 **
680 **	Parameters:
681 **		var -- filename
682 **		sff -- flags for safefile()
683 **		req -- is the file required?
684 **		ex -- does the file exist?
685 **		st -- status bit to set if ok
686 **		srv -- server side?
687 **
688 **	Side Effects:
689 **		uses r, ok, ex; may change ok and status.
690 **
691 */
692 
693 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
694 	{ \
695 		r = tls_safe_f(var, sff, srv); \
696 		if (r) \
697 			status |= st;	\
698 		else if (req) \
699 			ok = false;	\
700 	}
701 
702 /*
703 **  LOAD_CERTKEY -- load cert/key for TLS session
704 **
705 **	Parameters:
706 **		ssl -- TLS session context
707 **		srv -- server side?
708 **		certfile -- filename of certificate
709 **		keyfile -- filename of private key
710 **
711 **	Returns:
712 **		succeeded?
713 */
714 
715 bool
716 load_certkey(ssl, srv, certfile, keyfile)
717 	SSL *ssl;
718 	bool srv;
719 	char *certfile;
720 	char *keyfile;
721 {
722 	bool ok;
723 	int r;
724 	long sff, status;
725 	unsigned long req;
726 	char *who;
727 
728 	ok = true;
729 	who = srv ? "server" : "client";
730 	status = TLS_S_NONE;
731 	req = TLS_I_CERT_EX|TLS_I_KEY_EX;
732 	TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
733 		 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
734 	TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
735 		 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
736 
737 	/* certfile etc. must be "safe". */
738 	sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
739 	     | SFF_NOGWFILES | SFF_NOWWFILES
740 	     | SFF_ROOTOK | SFF_OPENASROOT;
741 	if (!bitnset(DBS_CERTOWNER, DontBlameSendmail))
742 		sff |= SFF_MUSTOWN;
743 	if (DontLockReadFiles)
744 		sff |= SFF_NOLOCK;
745 
746 	TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
747 		   bitset(TLS_I_CERT_EX, req),
748 		   bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
749 	TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
750 		   bitset(TLS_I_KEY_EX, req),
751 		   bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
752 
753 # define SSL_use_cert(ssl, certfile) \
754 	SSL_use_certificate_file(ssl, certfile, SSL_FILETYPE_PEM)
755 # define SSL_USE_CERT "SSL_use_certificate_file"
756 
757 	if (bitset(TLS_S_CERT_OK, status) &&
758 	    SSL_use_cert(ssl, certfile) <= 0)
759 	{
760 		if (LogLevel > 7)
761 		{
762 			sm_syslog(LOG_WARNING, NOQID,
763 				  "STARTTLS=%s, error: %s(%s) failed",
764 				  who, SSL_USE_CERT, certfile);
765 			tlslogerr(LOG_WARNING, 9, who);
766 		}
767 		if (bitset(TLS_I_USE_CERT, req))
768 			return false;
769 	}
770 	if (bitset(TLS_S_KEY_OK, status) &&
771 	    SSL_use_PrivateKey_file(ssl, keyfile, SSL_FILETYPE_PEM) <= 0)
772 	{
773 		if (LogLevel > 7)
774 		{
775 			sm_syslog(LOG_WARNING, NOQID,
776 				  "STARTTLS=%s, error: SSL_use_PrivateKey_file(%s) failed",
777 				  who, keyfile);
778 			tlslogerr(LOG_WARNING, 9, who);
779 		}
780 		if (bitset(TLS_I_USE_KEY, req))
781 			return false;
782 	}
783 
784 	/* check the private key */
785 	if (bitset(TLS_S_KEY_OK, status) &&
786 	    (r = SSL_check_private_key(ssl)) <= 0)
787 	{
788 		/* Private key does not match the certificate public key */
789 		if (LogLevel > 5)
790 		{
791 			sm_syslog(LOG_WARNING, NOQID,
792 				  "STARTTLS=%s, error: SSL_check_private_key failed(%s): %d",
793 				  who, keyfile, r);
794 			tlslogerr(LOG_WARNING, 9, who);
795 		}
796 		if (bitset(TLS_I_USE_KEY, req))
797 			return false;
798 	}
799 
800 	return true;
801 }
802 
803 /*
804 **  LOAD_CRLFILE -- load a file holding a CRL into the TLS context
805 **
806 **	Parameters:
807 **		ctx -- TLS context
808 **		srv -- server side?
809 **		filename -- filename of CRL
810 **
811 **	Returns:
812 **		succeeded?
813 */
814 
815 static bool load_crlfile __P((SSL_CTX *, bool, char *));
816 
817 static bool
818 load_crlfile(ctx, srv, filename)
819 	SSL_CTX *ctx;
820 	bool srv;
821 	char *filename;
822 {
823 	char *who;
824 	BIO *crl_file;
825 	X509_CRL *crl;
826 	X509_STORE *store;
827 
828 	who = srv ? "server" : "client";
829 	crl_file = BIO_new(BIO_s_file());
830 	if (crl_file == NULL)
831 	{
832 		if (LogLevel > 9)
833 			sm_syslog(LOG_WARNING, NOQID,
834 				  "STARTTLS=%s, error: BIO_new=failed", who);
835 		return false;
836 	}
837 
838 	if (BIO_read_filename(crl_file, filename) < 0)
839 	{
840 		if (LogLevel > 9)
841 			sm_syslog(LOG_WARNING, NOQID,
842 				  "STARTTLS=%s, error: BIO_read_filename(%s)=failed",
843 				  who, filename);
844 
845 		/* avoid memory leaks */
846 		BIO_free(crl_file);
847 		return false;
848 	}
849 
850 	crl = PEM_read_bio_X509_CRL(crl_file, NULL, NULL, NULL);
851 	if (crl == NULL)
852 	{
853 		if (LogLevel > 9)
854 			sm_syslog(LOG_WARNING, NOQID,
855 				  "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
856 				  who, filename);
857 		BIO_free(crl_file);
858 		return true;	/* XXX should probably be 'false' */
859 	}
860 
861 	BIO_free(crl_file);
862 
863 	/* get a pointer to the current certificate validation store */
864 	store = SSL_CTX_get_cert_store(ctx);	/* does not fail */
865 
866 	if (X509_STORE_add_crl(store, crl) == 0)
867 	{
868 		if (LogLevel > 9)
869 			sm_syslog(LOG_WARNING, NOQID,
870 				  "STARTTLS=%s, error: X509_STORE_add_crl=failed",
871 				  who);
872 		X509_CRL_free(crl);
873 		return false;
874 	}
875 
876 	X509_CRL_free(crl);
877 
878 	X509_STORE_set_flags(store,
879 		X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
880 	X509_STORE_set_verify_cb_func(store, x509_verify_cb);
881 
882 	return true;
883 }
884 
885 /*
886 **  LOAD_CRLPATH -- configure the TLS context to lookup CRLs in a directory
887 **
888 **	Parameters:
889 **		ctx -- TLS context
890 **		srv -- server side?
891 **		path -- path of hashed directory of CRLs
892 **
893 **	Returns:
894 **		succeeded?
895 */
896 
897 static bool load_crlpath __P((SSL_CTX *, bool, char *));
898 
899 static bool
900 load_crlpath(ctx, srv, path)
901 	SSL_CTX *ctx;
902 	bool srv;
903 	char *path;
904 {
905 	char *who;
906 	X509_STORE *store;
907 	X509_LOOKUP *lookup;
908 
909 	who = srv ? "server" : "client";
910 
911 	/* get a pointer to the current certificate validation store */
912 	store = SSL_CTX_get_cert_store(ctx);	/* does not fail */
913 
914 	lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
915 	if (lookup == NULL)
916 	{
917 		if (LogLevel > 9)
918 			sm_syslog(LOG_WARNING, NOQID,
919 				  "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
920 				  who);
921 		return false;
922 	}
923 
924 	if (X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) == 0)
925 	{
926 		if (LogLevel > 9)
927 			sm_syslog(LOG_WARNING, NOQID,
928 				  "STARTTLS=%s, error: X509_LOOKUP_add_dir(%s)=failed",
929 				  who, path);
930 		return false;
931 	}
932 
933 	X509_STORE_set_flags(store,
934 		X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
935 	X509_STORE_set_verify_cb_func(store, x509_verify_cb);
936 
937 	return true;
938 }
939 
940 /*
941 **  INITTLS -- initialize TLS
942 **
943 **	Parameters:
944 **		ctx -- pointer to context
945 **		req -- requirements for initialization (see sendmail.h)
946 **		options -- options
947 **		srv -- server side?
948 **		certfile -- filename of certificate
949 **		keyfile -- filename of private key
950 **		cacertpath -- path to CAs
951 **		cacertfile -- file with CA(s)
952 **		dhparam -- parameters for DH
953 **
954 **	Returns:
955 **		succeeded?
956 */
957 
958 /*
959 **  The session_id_context identifies the service that created a session.
960 **  This information is used to distinguish between multiple TLS-based
961 **  servers running on the same server. We use the name of the mail system.
962 **  Note: the session cache is not persistent.
963 */
964 
965 static char server_session_id_context[] = "sendmail8";
966 
967 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
968 # if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
969 #  define SM_SSL_OP_TLS_BLOCK_PADDING_BUG	1
970 # else
971 #  define SM_SSL_OP_TLS_BLOCK_PADDING_BUG	0
972 # endif
973 
974 bool
975 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
976 	SSL_CTX **ctx;
977 	unsigned long req;
978 	unsigned long options;
979 	bool srv;
980 	char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
981 {
982 # if !NO_DH
983 	static DH *dh = NULL;
984 # endif
985 	int r;
986 	bool ok;
987 	long sff, status;
988 	char *who;
989 	char *cf2, *kf2;
990 # if SM_CONF_SHM && !TLS_NO_RSA && MTA_RSA_TMP_CB
991 	extern int ShmId;
992 # endif
993 # if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
994 	long rt_version;
995 	STACK_OF(SSL_COMP) *comp_methods;
996 # endif
997 
998 	status = TLS_S_NONE;
999 	who = srv ? "server" : "client";
1000 	if (ctx == NULL)
1001 	{
1002 		syserr("STARTTLS=%s, inittls: ctx == NULL", who);
1003 		/* NOTREACHED */
1004 		SM_ASSERT(ctx != NULL);
1005 	}
1006 
1007 	/* already initialized? (we could re-init...) */
1008 	if (*ctx != NULL)
1009 		return true;
1010 	ok = true;
1011 
1012 	/*
1013 	**  look for a second filename: it must be separated by a ','
1014 	**  no blanks allowed (they won't be skipped).
1015 	**  we change a global variable here! this change will be undone
1016 	**  before return from the function but only if it returns true.
1017 	**  this isn't a problem since in a failure case this function
1018 	**  won't be called again with the same (overwritten) values.
1019 	**  otherwise each return must be replaced with a goto endinittls.
1020 	*/
1021 
1022 	cf2 = NULL;
1023 	kf2 = NULL;
1024 	if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
1025 	{
1026 		*cf2++ = '\0';
1027 		if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
1028 			*kf2++ = '\0';
1029 	}
1030 
1031 	/*
1032 	**  Check whether files/paths are defined
1033 	*/
1034 
1035 	TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
1036 		 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
1037 	TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
1038 		 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
1039 	TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
1040 		 TLS_S_CERTP_EX, TLS_T_OTHER);
1041 	TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
1042 		 TLS_S_CERTF_EX, TLS_T_OTHER);
1043 
1044 	TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
1045 		 TLS_S_CRLF_EX, TLS_T_OTHER);
1046 
1047 	/*
1048 	**  if the second file is specified it must exist
1049 	**  XXX: it is possible here to define only one of those files
1050 	*/
1051 
1052 	if (cf2 != NULL)
1053 	{
1054 		TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
1055 			 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
1056 	}
1057 	if (kf2 != NULL)
1058 	{
1059 		TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
1060 			 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
1061 	}
1062 
1063 	/*
1064 	**  valid values for dhparam are (only the first char is checked)
1065 	**  none	no parameters: don't use DH
1066 	**  i		use precomputed 2048 bit parameters
1067 	**  512		use precomputed 512 bit parameters
1068 	**  1024	generate 1024 bit parameters
1069 	**  2048	generate 2048 bit parameters
1070 	**  /file/name	read parameters from /file/name
1071 	*/
1072 
1073 # if MTA_DH_AUTO
1074 #  define SET_DH_DFL	\
1075 	do {	\
1076 		dhparam = "a";	\
1077 		req |= TLS_I_DHAUTO;	\
1078 	} while (0)
1079 # else
1080 #  define SET_DH_DFL	\
1081 	do {	\
1082 		dhparam = "I";	\
1083 		req |= TLS_I_DHFIXED;	\
1084 	} while (0)
1085 # endif
1086 
1087 	if (bitset(TLS_I_TRY_DH, req))
1088 	{
1089 		if (dhparam != NULL)
1090 		{
1091 			char c = *dhparam;
1092 
1093 # if MTA_DH_AUTO
1094 			if (c == 'a')
1095 				req |= TLS_I_DHAUTO;
1096 			else
1097 # endif
1098 			if (c == '1')
1099 				req |= TLS_I_DH1024;
1100 			else if (c == 'I' || c == 'i')
1101 				req |= TLS_I_DHFIXED;
1102 			else if (c == '2')
1103 				req |= TLS_I_DH2048;
1104 			else if (c == '5')
1105 				req |= TLS_I_DH512;
1106 			else if (c == 'n' || c == 'N')
1107 				req &= ~TLS_I_TRY_DH;
1108 			else if (c != '/')
1109 			{
1110 				if (LogLevel > 12)
1111 					sm_syslog(LOG_WARNING, NOQID,
1112 						  "STARTTLS=%s, error: illegal value '%s' for DHParameters",
1113 						  who, dhparam);
1114 				dhparam = NULL;
1115 			}
1116 		}
1117 		if (dhparam == NULL)
1118 			SET_DH_DFL;
1119 		else if (*dhparam == '/')
1120 		{
1121 			TLS_OK_F(dhparam, "DHParameters",
1122 				 bitset(TLS_I_DHPAR_EX, req),
1123 				 TLS_S_DHPAR_EX, TLS_T_OTHER);
1124 		}
1125 	}
1126 	if (!ok)
1127 		return ok;
1128 
1129 	/* certfile etc. must be "safe". */
1130 	sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
1131 	     | SFF_NOGWFILES | SFF_NOWWFILES
1132 	     | SFF_ROOTOK | SFF_OPENASROOT;
1133 	if (!bitnset(DBS_CERTOWNER, DontBlameSendmail))
1134 		sff |= SFF_MUSTOWN;
1135 	if (DontLockReadFiles)
1136 		sff |= SFF_NOLOCK;
1137 
1138 	TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
1139 		   bitset(TLS_I_CERT_EX, req),
1140 		   bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
1141 	TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
1142 		   bitset(TLS_I_KEY_EX, req),
1143 		   bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
1144 	TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
1145 		   bitset(TLS_I_CERTF_EX, req),
1146 		   bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
1147 	if (dhparam != NULL && *dhparam == '/')
1148 	{
1149 		TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
1150 			   bitset(TLS_I_DHPAR_EX, req),
1151 			   bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
1152 		if (!bitset(TLS_S_DHPAR_OK, status))
1153 			SET_DH_DFL;
1154 	}
1155 	TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
1156 		   bitset(TLS_I_CRLF_EX, req),
1157 		   bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
1158 	if (!ok)
1159 		return ok;
1160 	if (cf2 != NULL)
1161 	{
1162 		TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
1163 			   bitset(TLS_I_CERT_EX, req),
1164 			   bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
1165 	}
1166 	if (kf2 != NULL)
1167 	{
1168 		TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
1169 			   bitset(TLS_I_KEY_EX, req),
1170 			   bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
1171 	}
1172 
1173 	/* create a method and a new context */
1174 	if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
1175 				      SSLv23_client_method())) == NULL)
1176 	{
1177 		if (LogLevel > 7)
1178 			sm_syslog(LOG_WARNING, NOQID,
1179 				  "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
1180 				  who, who);
1181 		tlslogerr(LOG_WARNING, 9, who);
1182 		return false;
1183 	}
1184 
1185 # if _FFR_VRFY_TRUSTED_FIRST
1186 	if (!tTd(88, 101))
1187 	{
1188 		X509_STORE *store;
1189 
1190 		/* get a pointer to the current certificate validation store */
1191 		store = SSL_CTX_get_cert_store(*ctx);	/* does not fail */
1192 		SM_ASSERT(store != NULL);
1193 		X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
1194 	}
1195 # endif
1196 
1197 	if (CRLFile != NULL && !load_crlfile(*ctx, srv, CRLFile))
1198 		return false;
1199 	if (CRLPath != NULL && !load_crlpath(*ctx, srv, CRLPath))
1200 		return false;
1201 
1202 # if defined(SSL_MODE_AUTO_RETRY) && OPENSSL_VERSION_NUMBER >= 0x10100000L && OPENSSL_VERSION_NUMBER < 0x20000000L
1203 	/*
1204 	 *  Turn off blocking I/O handling in OpenSSL: someone turned
1205 	 *  this on by default in 1.1? should we check first?
1206 	 */
1207 #  if _FFR_TESTS
1208 	if (LogLevel > 9) {
1209 		sff = SSL_CTX_get_mode(*ctx);
1210 		if (sff & SSL_MODE_AUTO_RETRY)
1211 			sm_syslog(LOG_WARNING, NOQID,
1212 				"STARTTLS=%s, SSL_MODE_AUTO_RETRY=set, mode=%#lx",
1213 				who, sff);
1214 	}
1215 
1216 	/* hack for testing! */
1217 	if (tTd(96, 101) || getenv("SSL_MODE_AUTO_RETRY") != NULL)
1218 		SSL_CTX_set_mode(*ctx, SSL_MODE_AUTO_RETRY);
1219 	else
1220 #  endif /* _FFR_TESTS */
1221 	/* "else" in #if code above */
1222 	SSL_CTX_clear_mode(*ctx, SSL_MODE_AUTO_RETRY);
1223 # endif /* defined(SSL_MODE_AUTO_RETRY) && OPENSSL_VERSION_NUMBER >= 0x10100000L && OPENSSL_VERSION_NUMBER < 0x20000000L */
1224 
1225 # if TLS_NO_RSA
1226 	/* turn off backward compatibility, required for no-rsa */
1227 	SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
1228 # endif
1229 
1230 # if !TLS_NO_RSA && MTA_RSA_TMP_CB
1231 	/*
1232 	**  Create a temporary RSA key
1233 	**  XXX  Maybe we shouldn't create this always (even though it
1234 	**  is only at startup).
1235 	**  It is a time-consuming operation and it is not always necessary.
1236 	**  maybe we should do it only on demand...
1237 	*/
1238 
1239 	if (bitset(TLS_I_RSA_TMP, req)
1240 #  if SM_CONF_SHM
1241 	    && ShmId != SM_SHM_NO_ID &&
1242 	    (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL,
1243 					NULL)) == NULL
1244 #  else /* SM_CONF_SHM */
1245 	    && 0	/* no shared memory: no need to generate key now */
1246 #  endif /* SM_CONF_SHM */
1247 	   )
1248 	{
1249 		if (LogLevel > 7)
1250 		{
1251 			sm_syslog(LOG_WARNING, NOQID,
1252 				  "STARTTLS=%s, error: RSA_generate_key failed",
1253 				  who);
1254 			tlslogerr(LOG_WARNING, 9, who);
1255 		}
1256 		return false;
1257 	}
1258 # endif /* !TLS_NO_RSA && MTA_RSA_TMP_CB */
1259 
1260 	/*
1261 	**  load private key
1262 	**  XXX change this for DSA-only version
1263 	*/
1264 
1265 	if (bitset(TLS_S_KEY_OK, status) &&
1266 	    SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
1267 					 SSL_FILETYPE_PEM) <= 0)
1268 	{
1269 		if (LogLevel > 7)
1270 		{
1271 			sm_syslog(LOG_WARNING, NOQID,
1272 				  "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1273 				  who, keyfile);
1274 			tlslogerr(LOG_WARNING, 9, who);
1275 		}
1276 		if (bitset(TLS_I_USE_KEY, req))
1277 			return false;
1278 	}
1279 
1280 # if _FFR_TLS_USE_CERTIFICATE_CHAIN_FILE
1281 #  define SSL_CTX_use_cert(ssl_ctx, certfile) \
1282 	SSL_CTX_use_certificate_chain_file(ssl_ctx, certfile)
1283 #  define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_chain_file"
1284 # else
1285 #  define SSL_CTX_use_cert(ssl_ctx, certfile) \
1286 	SSL_CTX_use_certificate_file(ssl_ctx, certfile, SSL_FILETYPE_PEM)
1287 #  define SSL_CTX_USE_CERT "SSL_CTX_use_certificate_file"
1288 # endif
1289 
1290 	/* get the certificate file */
1291 	if (bitset(TLS_S_CERT_OK, status) &&
1292 	    SSL_CTX_use_cert(*ctx, certfile) <= 0)
1293 	{
1294 		if (LogLevel > 7)
1295 		{
1296 			sm_syslog(LOG_WARNING, NOQID,
1297 				  "STARTTLS=%s, error: %s(%s) failed",
1298 				  who, SSL_CTX_USE_CERT, certfile);
1299 			tlslogerr(LOG_WARNING, 9, who);
1300 		}
1301 		if (bitset(TLS_I_USE_CERT, req))
1302 			return false;
1303 	}
1304 
1305 	/* check the private key */
1306 	if (bitset(TLS_S_KEY_OK, status) &&
1307 	    (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1308 	{
1309 		/* Private key does not match the certificate public key */
1310 		if (LogLevel > 5)
1311 		{
1312 			sm_syslog(LOG_WARNING, NOQID,
1313 				  "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
1314 				  who, keyfile, r);
1315 			tlslogerr(LOG_WARNING, 9, who);
1316 		}
1317 		if (bitset(TLS_I_USE_KEY, req))
1318 			return false;
1319 	}
1320 
1321 	/* XXX this code is pretty much duplicated from above! */
1322 
1323 	/* load private key */
1324 	if (bitset(TLS_S_KEY2_OK, status) &&
1325 	    SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
1326 	{
1327 		if (LogLevel > 7)
1328 		{
1329 			sm_syslog(LOG_WARNING, NOQID,
1330 				  "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
1331 				  who, kf2);
1332 			tlslogerr(LOG_WARNING, 9, who);
1333 		}
1334 	}
1335 
1336 	/* get the certificate file */
1337 	if (bitset(TLS_S_CERT2_OK, status) &&
1338 	    SSL_CTX_use_cert(*ctx, cf2) <= 0)
1339 	{
1340 		if (LogLevel > 7)
1341 		{
1342 			sm_syslog(LOG_WARNING, NOQID,
1343 				  "STARTTLS=%s, error: %s(%s) failed",
1344 				  who, SSL_CTX_USE_CERT, cf2);
1345 			tlslogerr(LOG_WARNING, 9, who);
1346 		}
1347 	}
1348 
1349 	/* also check the private key */
1350 	if (bitset(TLS_S_KEY2_OK, status) &&
1351 	    (r = SSL_CTX_check_private_key(*ctx)) <= 0)
1352 	{
1353 		/* Private key does not match the certificate public key */
1354 		if (LogLevel > 5)
1355 		{
1356 			sm_syslog(LOG_WARNING, NOQID,
1357 				  "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
1358 				  who, r);
1359 			tlslogerr(LOG_WARNING, 9, who);
1360 		}
1361 	}
1362 
1363 	/* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
1364 
1365 # if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
1366 
1367 	/*
1368 	**  In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
1369 	**  padding bug work-around, leading to false positives and
1370 	**  failed connections. We may not interoperate with systems
1371 	**  with the bug, but this is better than breaking on all 0.9.8[ab]
1372 	**  systems that have zlib support enabled.
1373 	**  Note: this checks the runtime version of the library, not
1374 	**  just the compile time version.
1375 	*/
1376 
1377 	rt_version = TLS_version_num();
1378 	if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
1379 	{
1380 		comp_methods = SSL_COMP_get_compression_methods();
1381 		if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
1382 			options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
1383 	}
1384 # endif
1385 	SSL_CTX_set_options(*ctx, (long) options);
1386 
1387 # if !NO_DH
1388 	/* Diffie-Hellman initialization */
1389 	if (bitset(TLS_I_TRY_DH, req))
1390 	{
1391 #  if TLS_EC == 1
1392 		EC_KEY *ecdh;
1393 #  endif
1394 
1395 		if (tTd(96, 81))
1396 			sm_dprintf("inittls: where=try_dh, req=%#lx, status=%#lx\n",
1397 				req, status);
1398 		if (bitset(TLS_S_DHPAR_OK, status))
1399 		{
1400 			BIO *bio;
1401 
1402 			if ((bio = BIO_new_file(dhparam, "r")) != NULL)
1403 			{
1404 				dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1405 				BIO_free(bio);
1406 				if (dh == NULL && LogLevel > 7)
1407 				{
1408 					unsigned long err;
1409 
1410 					err = ERR_get_error();
1411 					sm_syslog(LOG_WARNING, NOQID,
1412 						  "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
1413 						  who, dhparam,
1414 						  ERR_error_string(err, NULL));
1415 					tlslogerr(LOG_WARNING, 9, who);
1416 					SET_DH_DFL;
1417 				}
1418 			}
1419 			else
1420 			{
1421 				if (LogLevel > 5)
1422 				{
1423 					sm_syslog(LOG_WARNING, NOQID,
1424 						  "STARTTLS=%s, error: BIO_new_file(%s) failed",
1425 						  who, dhparam);
1426 					tlslogerr(LOG_WARNING, 9, who);
1427 				}
1428 			}
1429 		}
1430 # if MTA_DH_AUTO
1431 		if (dh == NULL && bitset(TLS_I_DHAUTO, req))
1432 			SSL_CTX_set_dh_auto(*ctx, 1);
1433 		else
1434 # endif
1435 		if (dh == NULL && bitset(TLS_I_DH1024|TLS_I_DH2048, req))
1436 		{
1437 			int bits;
1438 			DSA *dsa;
1439 
1440 			bits = bitset(TLS_I_DH2048, req) ? 2048 : 1024;
1441 			if (tTd(96, 2))
1442 				sm_dprintf("inittls: Generating %d bit DH parameters\n", bits);
1443 
1444 #  if MTA_HAVE_DSA_GENERATE_EX
1445 			dsa = DSA_new();
1446 			if (dsa != NULL)
1447 			{
1448 				r = DSA_generate_parameters_ex(dsa, bits, NULL,
1449 							0, NULL, NULL, NULL);
1450 				if (r != 0)
1451 					dh = DSA_dup_DH(dsa);
1452 			}
1453 #  else
1454 			/* this takes a while! */
1455 			dsa = DSA_generate_parameters(bits, NULL, 0, NULL,
1456 						      NULL, 0, NULL);
1457 			dh = DSA_dup_DH(dsa);
1458 #  endif
1459 			DSA_free(dsa);
1460 		}
1461 		else if (dh == NULL && bitset(TLS_I_DHFIXED, req))
1462 		{
1463 			if (tTd(96, 2))
1464 				sm_dprintf("inittls: Using precomputed 2048 bit DH parameters\n");
1465 			dh = get_dh2048();
1466 		}
1467 		else if (dh == NULL && bitset(TLS_I_DH512, req))
1468 		{
1469 			if (tTd(96, 2))
1470 				sm_dprintf("inittls: Using precomputed 512 bit DH parameters\n");
1471 			dh = get_dh512();
1472 		}
1473 		if (dh == NULL && !bitset(TLS_I_DHAUTO, req))
1474 		{
1475 			if (LogLevel > 9)
1476 			{
1477 				unsigned long err;
1478 
1479 				err = ERR_get_error();
1480 				sm_syslog(LOG_WARNING, NOQID,
1481 					  "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1482 					  who, dhparam,
1483 					  ERR_error_string(err, NULL));
1484 			}
1485 			if (bitset(TLS_I_REQ_DH, req))
1486 				return false;
1487 		}
1488 		else if (dh != NULL)
1489 		{
1490 			/* important to avoid small subgroup attacks */
1491 			SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
1492 
1493 			SSL_CTX_set_tmp_dh(*ctx, dh);
1494 			if (LogLevel > 13)
1495 				sm_syslog(LOG_INFO, NOQID,
1496 					  "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
1497 					  who, 8 * DH_size(dh), *dhparam);
1498 			DH_free(dh);
1499 		}
1500 
1501 #  if TLS_EC == 2
1502 		SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_ECDH_USE);
1503 		SSL_CTX_set_ecdh_auto(*ctx, 1);
1504 #  elif TLS_EC == 1
1505 		ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1506 		if (ecdh != NULL)
1507 		{
1508 			SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_ECDH_USE);
1509 			SSL_CTX_set_tmp_ecdh(*ctx, ecdh);
1510 			EC_KEY_free(ecdh);
1511 		}
1512 		else if (LogLevel > 9)
1513 		{
1514 			sm_syslog(LOG_WARNING, NOQID,
1515 				  "STARTTLS=%s, EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)=failed, error=%s",
1516 				  who, ERR_error_string(ERR_get_error(), NULL));
1517 		}
1518 #  endif /* TLS_EC */
1519 
1520 	}
1521 # endif /* !NO_DH */
1522 
1523 	/* XXX do we need this cache here? */
1524 	if (bitset(TLS_I_CACHE, req))
1525 	{
1526 		SSL_CTX_sess_set_cache_size(*ctx, 1);
1527 		SSL_CTX_set_timeout(*ctx, 1);
1528 		SSL_CTX_set_session_id_context(*ctx,
1529 			(void *) &server_session_id_context,
1530 			sizeof(server_session_id_context));
1531 		(void) SSL_CTX_set_session_cache_mode(*ctx,
1532 				SSL_SESS_CACHE_SERVER);
1533 	}
1534 	else
1535 	{
1536 		(void) SSL_CTX_set_session_cache_mode(*ctx,
1537 				SSL_SESS_CACHE_OFF);
1538 	}
1539 
1540 	/* load certificate locations and default CA paths */
1541 	if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1542 	{
1543 		if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1544 						       cacertpath)) == 1)
1545 		{
1546 # if !TLS_NO_RSA && MTA_RSA_TMP_CB
1547 			if (bitset(TLS_I_RSA_TMP, req))
1548 				SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1549 # endif
1550 
1551 			if (srv)
1552 			{
1553 				SSL_CTX_set_client_CA_list(*ctx,
1554 					SSL_load_client_CA_file(cacertfile));
1555 			}
1556 		}
1557 		else
1558 		{
1559 			/*
1560 			**  can't load CA data; do we care?
1561 			**  the data is necessary to authenticate the client,
1562 			**  which in turn would be necessary
1563 			**  if we want to allow relaying based on it.
1564 			*/
1565 
1566 			if (LogLevel > 5)
1567 			{
1568 				sm_syslog(LOG_WARNING, NOQID,
1569 					  "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1570 					  who, cacertpath, cacertfile, r);
1571 				tlslogerr(LOG_WARNING,
1572 					bitset(TLS_I_VRFY_LOC, req) ? 8 : 9,
1573 					who);
1574 			}
1575 			if (bitset(TLS_I_VRFY_LOC, req))
1576 				return false;
1577 		}
1578 	}
1579 
1580 	/*
1581 	**  XXX currently we could call tls_set_verify()
1582 	**  but we hope that that function will later on
1583 	**  only set the mode per connection.
1584 	*/
1585 
1586 	SSL_CTX_set_verify(*ctx,
1587 		bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1588 					   : SSL_VERIFY_PEER,
1589 		NULL);
1590 
1591 	/*
1592 	**  Always use our callback instead of the builtin version.
1593 	**  We have to install our own verify callback:
1594 	**  SSL_VERIFY_PEER requests a client cert but even
1595 	**  though *FAIL_IF* isn't set, the connection
1596 	**  will be aborted if the client presents a cert
1597 	**  that is not "liked" (can't be verified?) by
1598 	**  the TLS library :-(
1599 	*/
1600 
1601 	SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb, NULL);
1602 
1603 	/* XXX: make this dependent on an option? */
1604 	if (tTd(96, 9))
1605 		SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1606 
1607 	/* install our own cipher list */
1608 	if (CipherList != NULL && *CipherList != '\0')
1609 	{
1610 		if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1611 		{
1612 			if (LogLevel > 7)
1613 			{
1614 				sm_syslog(LOG_WARNING, NOQID,
1615 					  "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1616 					  who, CipherList);
1617 
1618 				tlslogerr(LOG_WARNING, 9, who);
1619 			}
1620 			/* failure if setting to this list is required? */
1621 		}
1622 	}
1623 
1624 # if MTA_HAVE_TLSv1_3
1625 	/* install our own cipher suites */
1626 	if (!SM_IS_EMPTY(CipherSuites))
1627 	{
1628 		if (SSL_CTX_set_ciphersuites(*ctx, CipherSuites) <= 0)
1629 		{
1630 			if (LogLevel > 7)
1631 			{
1632 				sm_syslog(LOG_WARNING, NOQID,
1633 					  "STARTTLS=%s, error: SSL_CTX_set_ciphersuites(%s) failed, suites ignored",
1634 					  who, CipherSuites);
1635 
1636 				tlslogerr(LOG_WARNING, 9, who);
1637 			}
1638 			/* failure if setting to this suites is required? */
1639 		}
1640 	}
1641 # endif /* MTA_HAVE_TLSv1_3 */
1642 
1643 	if (LogLevel > 12)
1644 		sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1645 
1646 # if 0
1647 	/*
1648 	**  this label is required if we want to have a "clean" exit
1649 	**  see the comments above at the initialization of cf2
1650 	*/
1651 
1652     endinittls:
1653 # endif /* 0 */
1654 
1655 	/* undo damage to global variables */
1656 	if (cf2 != NULL)
1657 		*--cf2 = ',';
1658 	if (kf2 != NULL)
1659 		*--kf2 = ',';
1660 
1661 	return ok;
1662 }
1663 
1664 /*
1665 **  CERT_FP -- get cert fingerprint
1666 **
1667 **	Parameters:
1668 **		cert -- TLS cert
1669 **		evp_digest -- digest algorithm
1670 **		mac -- macro storage
1671 **		macro -- where to store cert fp
1672 **
1673 **	Returns:
1674 **		<=0: cert fp calculation failed
1675 **		>0: cert fp calculation ok
1676 */
1677 
1678 static int
1679 cert_fp(cert, evp_digest, mac, macro)
1680 	X509 *cert;
1681 	const EVP_MD *evp_digest;
1682 	MACROS_T *mac;
1683 	char *macro;
1684 {
1685 	unsigned int n;
1686 	int r;
1687 	unsigned char md[EVP_MAX_MD_SIZE];
1688 	char md5h[EVP_MAX_MD_SIZE * 3];
1689 	static const char hexcodes[] = "0123456789ABCDEF";
1690 
1691 	n = 0;
1692 	if ((r = X509_digest(cert, evp_digest, md, &n)) == 0 || n <= 0)
1693 	{
1694 		macdefine(mac, A_TEMP, macid(macro), "");
1695 		return (0 == r) ? 0 : n;
1696 	}
1697 
1698 	SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1699 	for (r = 0; r < (int) n; r++)
1700 	{
1701 		md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1702 		md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1703 		md5h[(r * 3) + 2] = ':';
1704 	}
1705 	md5h[(n * 3) - 1] = '\0';
1706 	macdefine(mac, A_TEMP, macid(macro), md5h);
1707 	return 1;
1708 }
1709 
1710 /* host for logging */
1711 #define whichhost	host == NULL ? "local" : host
1712 
1713 # if _FFR_TLS_ALTNAMES
1714 
1715 /*
1716 **  CLEARCLASS -- clear the specified class (called from stabapply)
1717 **
1718 **	Parameters:
1719 **		s -- STAB
1720 **		id -- class id
1721 **
1722 **	Returns:
1723 **		none.
1724 */
1725 
1726 static void
1727 clearclass(s, id)
1728 	STAB *s;
1729 	int id;
1730 {
1731 	if (s->s_symtype != ST_CLASS)
1732 		return;
1733 	if (bitnset(bitidx(id), s->s_class))
1734 		clrbitn(bitidx(id), s->s_class);
1735 }
1736 
1737 /*
1738 **  GETALTNAMES -- set subject_alt_name
1739 **
1740 **	Parameters:
1741 **		cert -- cert
1742 **		srv -- server side?
1743 **		host -- hostname of other side
1744 **
1745 **	Returns:
1746 **		none.
1747 */
1748 
1749 static void
1750 getaltnames(cert, srv, host)
1751 	X509 *cert;
1752 	bool srv;
1753 	const char *host;
1754 {
1755 	STACK_OF(GENERAL_NAME) *gens;
1756 	int i, j, len, r;
1757 	const GENERAL_NAME *gn;
1758 	char *dnsname, *who;
1759 
1760 	if (!SetCertAltnames)
1761 		return;
1762 	who = srv ? "server" : "client";
1763 	gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
1764 	if (gens == NULL)
1765 		return;
1766 
1767 	r = sk_GENERAL_NAME_num(gens);
1768 	for (i = 0; i < r; i++)
1769 	{
1770 		gn = sk_GENERAL_NAME_value(gens, i);
1771 		if (gn == NULL || gn->type != GEN_DNS)
1772 			continue;
1773 
1774 		/* Ensure data is IA5 */
1775 		if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
1776 		{
1777 			if (LogLevel > 6)
1778 				sm_syslog(LOG_INFO, NOQID,
1779 					"STARTTLS=%s, relay=%.100s, field=AltName, status=value contains non IA5",
1780 					who, whichhost);
1781 			continue;
1782 		}
1783 		dnsname = (char *) MTA_ASN1_STRING_data(gn->d.ia5);
1784 		if (dnsname == NULL)
1785 			continue;
1786 		len = ASN1_STRING_length(gn->d.ia5);
1787 
1788 		/*
1789 		**  "remove" trailing NULs (except for one of course),
1790 		**  those can happen and are OK (not a sign of an attack)
1791 		*/
1792 
1793 		while (len > 0 && '\0' == dnsname[len - 1])
1794 			len--;
1795 
1796 #define ISPRINT(c)	(isascii(c) && isprint(c))
1797 
1798 		/* just check for printable char for now */
1799 		for (j = 0; j < len && ISPRINT(dnsname[j]); j++)
1800 			;
1801 		if (dnsname[j] != '\0' || len != j)
1802 			continue;
1803 
1804 		setclass(macid("{cert_altnames}"), xtextify(dnsname, "<>\")"));
1805 		if (LogLevel > 14)
1806 			sm_syslog(LOG_DEBUG, NOQID,
1807 				"STARTTLS=%s, relay=%.100s, AltName=%s",
1808 				who, whichhost, xtextify(dnsname, "<>\")"));
1809 	}
1810 }
1811 # else
1812 #  define getaltnames(cert, srv, host)
1813 # endif /* _FFR_TLS_ALTNAMES */
1814 
1815 # if DANE
1816 
1817 /*
1818 **  DANE_RES -- get DANE result if possible
1819 **
1820 **	Parameters:
1821 **		ssl -- TLS connection structure
1822 **		dane_vrfy_ctx -- dane verify context
1823 **
1824 **	Returns:
1825 **		SM_SUCCESS: DANE result dane_vrfy_res is valid
1826 **		SM_NOTDONE: DANE checking not enabled
1827 **		<0: some error
1828 */
1829 
1830 static int dane_res __P((SSL *, dane_vrfy_ctx_P));
1831 
1832 static int
1833 dane_res(ssl, dane_vrfy_ctx)
1834 	SSL *ssl;
1835 	dane_vrfy_ctx_P dane_vrfy_ctx;
1836 {
1837 #  if HAVE_SSL_CTX_dane_enable
1838 	int depth, r;
1839 	EVP_PKEY *mspki;
1840 	uint8_t usage, selector, mtype;
1841 	unsigned const char *rr;
1842 	size_t rrlen;
1843 #  endif
1844 
1845 	if (NULL == dane_vrfy_ctx)
1846 	{
1847 		/* can this happen? should it be logged? */
1848 		if (tTd(96, 20))
1849 			sm_dprintf("ERROR: dane_res: dane_vrfy_ctx=NULL\n");
1850 		return SM_NOTDONE;
1851 	}
1852 	if (tTd(96, 20))
1853 		sm_dprintf("dane_res: dane_vrfy_dane_enabled=%d, chk=%#x, res=%d\n",
1854 			dane_vrfy_ctx->dane_vrfy_dane_enabled,
1855 			dane_vrfy_ctx->dane_vrfy_chk,
1856 			dane_vrfy_ctx->dane_vrfy_res);
1857 	if (!VRFY_DANE(dane_vrfy_ctx->dane_vrfy_chk))
1858 	{
1859 		dane_vrfy_ctx->dane_vrfy_res = DANE_VRFY_NONE;
1860 		return SM_NOTDONE;
1861 	}
1862 	if (dane_vrfy_ctx->dane_vrfy_chk & TLSAFLTEMPVRFY)
1863 	{
1864 		dane_vrfy_ctx->dane_vrfy_res = DANE_VRFY_TEMP;
1865 		return SM_SUCCESS;
1866 	}
1867 	if (!dane_vrfy_ctx->dane_vrfy_dane_enabled)
1868 	{
1869 		if (DANE_VRFY_NONE == dane_vrfy_ctx->dane_vrfy_res)
1870 			return SM_NOTDONE;
1871 		return SM_SUCCESS;
1872 	}
1873 
1874 #  if HAVE_SSL_CTX_dane_enable
1875 	mspki = NULL;
1876 	depth = SSL_get0_dane_authority(ssl, NULL, &mspki);
1877 	if (tTd(96, 20))
1878 		sm_dprintf("dane_res: SSL_get0_dane_authority() depth=%d\n", depth);
1879 
1880 	if (depth < 0)
1881 	{
1882 		dane_vrfy_ctx->dane_vrfy_res = DANE_VRFY_FAIL;
1883 		return SM_SUCCESS;
1884 	}
1885 
1886 	dane_vrfy_ctx->dane_vrfy_res = DANE_VRFY_OK;
1887 	r = SSL_get0_dane_tlsa(ssl, &usage, &selector, &mtype, &rr, &rrlen);
1888 	if (tTd(96, 20))
1889 		sm_dprintf("dane_res: SSL_get0_dane_tlsa=%d, status=%s\n", r,
1890 			(mspki != NULL) ? "TA_public_key_verified_certificate"
1891 			: (depth > 0) ? "matched_TA_certificate"
1892 				: "matched_EE_certificate");
1893 
1894 	if (LogLevel > 11)
1895 	{
1896 		/* just for logging */
1897 		if (r >= 0 && rr != NULL && rrlen > 0)
1898 		{
1899 			(void) data2hex((unsigned char *)rr, rrlen,
1900 				(unsigned char *)dane_vrfy_ctx->dane_vrfy_fp,
1901 				sizeof(dane_vrfy_ctx->dane_vrfy_fp));
1902 		}
1903 
1904 		sm_syslog(LOG_DEBUG, NOQID,
1905 			"DANE_depth=%d, DANE_res=%d, SSL_get0_dane_tlsa=%d, fp=%s, status=%s",
1906 			depth, dane_vrfy_ctx->dane_vrfy_res, r,
1907 			dane_vrfy_ctx->dane_vrfy_fp,
1908 			(mspki != NULL) ? "TA_public_key_verified_certificate" :
1909 				(depth > 0) ? "matched_TA_certificate" : "matched_EE_certificate"
1910 		);
1911 	}
1912 #  else
1913 	SM_ASSERT(!dane_vrfy_ctx->dane_vrfy_dane_enabled);
1914 #  endif /* HAVE_SSL_CTX_dane_enable */
1915 	return SM_SUCCESS;
1916 }
1917 # endif /* DANE */
1918 
1919 /*
1920 **  TLS_GET_INFO -- get information about TLS connection
1921 **
1922 **	Parameters:
1923 **		ssl -- TLS session context
1924 **		srv -- server side?
1925 **		host -- hostname of other side
1926 **		mac -- macro storage
1927 **		certreq -- did we ask for a cert?
1928 **
1929 **	Returns:
1930 **		result of authentication.
1931 **
1932 **	Side Effects:
1933 **		sets various TLS related macros.
1934 */
1935 
1936 int
1937 tls_get_info(ssl, srv, host, mac, certreq)
1938 	SSL *ssl;
1939 	bool srv;
1940 	char *host;
1941 	MACROS_T *mac;
1942 	bool certreq;
1943 {
1944 	const SSL_CIPHER *c;
1945 	int b, r;
1946 	long verifyok;
1947 	char *s, *who;
1948 	char bitstr[16];
1949 	X509 *cert;
1950 # if DANE
1951 	dane_vrfy_ctx_P dane_vrfy_ctx;
1952 	dane_tlsa_P dane_tlsa;
1953 # endif
1954 
1955 	c = SSL_get_current_cipher(ssl);
1956 
1957 	/* cast is just workaround for compiler warning */
1958 	macdefine(mac, A_TEMP, macid("{cipher}"),
1959 		  (char *) SSL_CIPHER_get_name(c));
1960 	b = SSL_CIPHER_get_bits(c, &r);
1961 	(void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1962 	macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1963 	(void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1964 	macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1965 	s = (char *) SSL_get_version(ssl);
1966 	if (s == NULL)
1967 		s = "UNKNOWN";
1968 	macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1969 
1970 	who = srv ? "server" : "client";
1971 	cert = MTA_SSL_get_peer_certificate(ssl);
1972 	verifyok = SSL_get_verify_result(ssl);
1973 	if (LogLevel > 14)
1974 		sm_syslog(LOG_INFO, NOQID,
1975 			  "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1976 			  who, verifyok, (unsigned long) cert);
1977 # if _FFR_TLS_ALTNAMES
1978 	stabapply(clearclass, macid("{cert_altnames}"));
1979 # endif
1980 	if (cert != NULL)
1981 	{
1982 		X509_NAME *subj, *issuer;
1983 		char buf[MAXNAME];	/* EAI: not affected */
1984 
1985 		subj = X509_get_subject_name(cert);
1986 		issuer = X509_get_issuer_name(cert);
1987 		X509_NAME_oneline(subj, buf, sizeof(buf));
1988 		macdefine(mac, A_TEMP, macid("{cert_subject}"),
1989 			 xtextify(buf, "<>\")"));
1990 		X509_NAME_oneline(issuer, buf, sizeof(buf));
1991 		macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1992 			 xtextify(buf, "<>\")"));
1993 
1994 #  define LL_BADCERT	8
1995 
1996 #define CERTFPMACRO (CertFingerprintAlgorithm != NULL ? "{cert_fp}" : "{cert_md5}")
1997 
1998 #define CHECK_X509_NAME(which)	\
1999 	do {	\
2000 		if (r == -1)	\
2001 		{		\
2002 			sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \
2003 			if (LogLevel > LL_BADCERT)	\
2004 				sm_syslog(LOG_INFO, NOQID,	\
2005 					"STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN",	\
2006 					who, whichhost,	which);	\
2007 		}		\
2008 		else if ((size_t)r >= sizeof(buf) - 1)	\
2009 		{		\
2010 			sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \
2011 			if (LogLevel > 7)	\
2012 				sm_syslog(LOG_INFO, NOQID,	\
2013 					"STARTTLS=%s, relay=%.100s, field=%s, status=CN too long",	\
2014 					who, whichhost, which);	\
2015 		}		\
2016 		else if ((size_t)r > strlen(buf))	\
2017 		{		\
2018 			sm_strlcpy(buf, "BadCertificateContainsNUL",	\
2019 				sizeof(buf));	\
2020 			if (LogLevel > 7)	\
2021 				sm_syslog(LOG_INFO, NOQID,	\
2022 					"STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL",	\
2023 					who, whichhost, which);	\
2024 		}		\
2025 	} while (0)
2026 
2027 		r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf,
2028 			sizeof buf);
2029 		CHECK_X509_NAME("cn_subject");
2030 		macdefine(mac, A_TEMP, macid("{cn_subject}"),
2031 			 xtextify(buf, "<>\")"));
2032 		r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf,
2033 			sizeof buf);
2034 		CHECK_X509_NAME("cn_issuer");
2035 		macdefine(mac, A_TEMP, macid("{cn_issuer}"),
2036 			 xtextify(buf, "<>\")"));
2037 		r = cert_fp(cert, EVP_digest, mac, CERTFPMACRO);
2038 		if (r <= 0 && LogLevel > 8)
2039 		{
2040 			sm_syslog(LOG_WARNING, NOQID,
2041 				"STARTTLS=%s, relay=%.100s, X509_digest=%d, CertFingerprintAlgorithm=%s",
2042 				who, whichhost, r,
2043 				(NULL == CertFingerprintAlgorithm) ? "md5" :
2044 				CertFingerprintAlgorithm);
2045 			tlslogerr(LOG_WARNING, 8, who);
2046 		}
2047 		getaltnames(cert, srv, host);
2048 	}
2049 	else
2050 	{
2051 		macdefine(mac, A_PERM, macid("{cert_subject}"), "");
2052 		macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
2053 		macdefine(mac, A_PERM, macid("{cn_subject}"), "");
2054 		macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
2055 		macdefine(mac, A_TEMP, macid(CERTFPMACRO), "");
2056 	}
2057 # if DANE
2058 	dane_vrfy_ctx = NULL;
2059 	dane_tlsa = NULL;
2060 	if (TLSsslidx >= 0)
2061 	{
2062 		tlsi_ctx_T *tlsi_ctx;
2063 
2064 		tlsi_ctx = (tlsi_ctx_P) SSL_get_ex_data(ssl, TLSsslidx);
2065 		if (tlsi_ctx != NULL)
2066 		{
2067 			dane_vrfy_ctx = &(tlsi_ctx->tlsi_dvc);
2068 			dane_tlsa = dane_get_tlsa(dane_vrfy_ctx);
2069 		}
2070 	}
2071 
2072 #  define DANE_VRFY_RES_IS(r) \
2073 	((dane_vrfy_ctx != NULL) && dane_vrfy_ctx->dane_vrfy_res == (r))
2074 
2075 	if (tTd(96, 10))
2076 		sm_dprintf("tls_get_info: verifyok=%d, dane_vrfy_res=%d\n",
2077 			(int)verifyok,
2078 			(dane_vrfy_ctx != NULL) ? dane_vrfy_ctx->dane_vrfy_res : -999);
2079 	if (SM_SUCCESS == dane_res(ssl, dane_vrfy_ctx))
2080 	{
2081 		if (DANE_VRFY_RES_IS(DANE_VRFY_OK))
2082 		{
2083 			s = "TRUSTED";
2084 			r = TLS_AUTH_OK;
2085 		}
2086 		else if (DANE_VRFY_RES_IS(DANE_VRFY_TEMP))
2087 		{
2088 			s = "DANE_TEMP";
2089 			r = TLS_AUTH_TEMP;
2090 		}
2091 		else if (DANE_VRFY_RES_IS(DANE_VRFY_FAIL))
2092 		{
2093 			if (dane_tlsa != NULL &&
2094 			    TLSA_IS_FL(dane_tlsa, TLSAFL2MANY))
2095 			{
2096 				s = "DANE_TEMP";
2097 				r = TLS_AUTH_TEMP;
2098 			}
2099 			else
2100 			{
2101 				s = "DANE_FAIL";
2102 				r = TLS_AUTH_FAIL;
2103 			}
2104 		}
2105 		else {
2106 			s = "BOGUS_DANE_RES";
2107 			r = TLS_AUTH_FAIL;
2108 		}
2109 	}
2110 	else
2111 # endif /* if DANE */
2112 	/* "else" in #if code above */
2113 	switch (verifyok)
2114 	{
2115 	  case X509_V_OK:
2116 		if (cert != NULL)
2117 		{
2118 			s = "OK";
2119 			r = TLS_AUTH_OK;
2120 		}
2121 		else
2122 		{
2123 			s = certreq ? "NO" : "NOT",
2124 			r = TLS_AUTH_NO;
2125 		}
2126 		break;
2127 
2128 	  default:
2129 		s = "FAIL";
2130 		r = TLS_AUTH_FAIL;
2131 		break;
2132 	}
2133 	macdefine(mac, A_PERM, macid("{verify}"), s);
2134 	if (cert != NULL)
2135 		X509_free(cert);
2136 
2137 	/* do some logging */
2138 	if (LogLevel > 8)
2139 	{
2140 		char *vers, *s1, *s2, *cbits, *algbits;
2141 
2142 		vers = macget(mac, macid("{tls_version}"));
2143 		cbits = macget(mac, macid("{cipher_bits}"));
2144 		algbits = macget(mac, macid("{alg_bits}"));
2145 
2146 		/* XXX: use s directly? */
2147 		s1 = macget(mac, macid("{verify}"));
2148 		s2 = macget(mac, macid("{cipher}"));
2149 
2150 # if DANE
2151 #  define LOG_DANE_FP	\
2152 	('\0' != dane_vrfy_ctx->dane_vrfy_fp[0] && DANE_VRFY_RES_IS(DANE_VRFY_FAIL))
2153 # endif
2154 		/* XXX: maybe cut off ident info? */
2155 		sm_syslog(LOG_INFO, NOQID,
2156 			  "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s%s%s%s%s",
2157 			  who,
2158 			  host == NULL ? "local" : host,
2159 			  vers, s1, s2, /* sm_snprintf() can deal with NULL */
2160 			  algbits == NULL ? "0" : algbits,
2161 			  cbits == NULL ? "0" : cbits
2162 # if DANE
2163 			, LOG_DANE_FP ? ", pubkey_fp=" : ""
2164 			, LOG_DANE_FP ? dane_vrfy_ctx->dane_vrfy_fp : ""
2165 			, (dane_tlsa != NULL
2166 			    && TLSA_IS_FL(dane_tlsa, TLSAFLUNS)
2167 			    && !TLSA_IS_FL(dane_tlsa, TLSAFLSUP)
2168 			   && DANE_VRFY_RES_IS(DANE_VRFY_NONE))
2169 			  ? ONLYUNSUPTLSARR : ""
2170 			, (dane_tlsa != NULL
2171 			   && TLSA_IS_FL(dane_tlsa, TLSAFL2MANY))
2172 			  && DANE_VRFY_RES_IS(DANE_VRFY_FAIL)
2173 			  ? ", note=too many TLSA RRs" : ""
2174 # else
2175 			, "", "", "", ""
2176 # endif
2177 			);
2178 		if (LogLevel > 11)
2179 		{
2180 			/*
2181 			**  Maybe run xuntextify on the strings?
2182 			**  That is easier to read but makes it maybe a bit
2183 			**  more complicated to figure out the right values
2184 			**  for the access map...
2185 			*/
2186 
2187 			s1 = macget(mac, macid("{cert_subject}"));
2188 			s2 = macget(mac, macid("{cert_issuer}"));
2189 			sm_syslog(LOG_INFO, NOQID,
2190 				  "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
2191 				  who, s1, s2,
2192 				  X509_verify_cert_error_string(verifyok));
2193 		}
2194 	}
2195 	return r;
2196 }
2197 
2198 /*
2199 **  ENDTLS -- shut down secure connection
2200 **
2201 **	Parameters:
2202 **		pssl -- pointer to TLS session context
2203 **		who -- server/client (for logging).
2204 **
2205 **	Returns:
2206 **		success? (EX_* code)
2207 */
2208 
2209 int
2210 endtls(pssl, who)
2211 	SSL **pssl;
2212 	const char *who;
2213 {
2214 	SSL *ssl;
2215 	int ret, r;
2216 
2217 	SM_REQUIRE(pssl != NULL);
2218 	ret = EX_OK;
2219 	ssl = *pssl;
2220 	if (ssl == NULL)
2221 		return ret;
2222 
2223 	if ((r = SSL_shutdown(ssl)) < 0)
2224 	{
2225 		if (LogLevel > 11)
2226 		{
2227 			sm_syslog(LOG_WARNING, NOQID,
2228 				  "STARTTLS=%s, SSL_shutdown failed: %d",
2229 				  who, r);
2230 			tlslogerr(LOG_WARNING, 11, who);
2231 		}
2232 		ret = EX_SOFTWARE;
2233 	}
2234 
2235 	/*
2236 	**  Bug in OpenSSL (at least up to 0.9.6b):
2237 	**  From: Lutz.Jaenicke@aet.TU-Cottbus.DE
2238 	**  Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
2239 	**  To: openssl-users@openssl.org
2240 	**  Subject: Re: SSL_shutdown() woes (fwd)
2241 	**
2242 	**  The side sending the shutdown alert first will
2243 	**  not care about the answer of the peer but will
2244 	**  immediately return with a return value of "0"
2245 	**  (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
2246 	**  the value of "0" and as the shutdown alert of the peer was
2247 	**  not received (actually, the program did not even wait for
2248 	**  the answer), an SSL_ERROR_SYSCALL is flagged, because this
2249 	**  is the default rule in case everything else does not apply.
2250 	**
2251 	**  For your server the problem is different, because it
2252 	**  receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
2253 	**  then sends its response (SSL_SENT_SHUTDOWN), so for the
2254 	**  server the shutdown was successful.
2255 	**
2256 	**  As is by know, you would have to call SSL_shutdown() once
2257 	**  and ignore an SSL_ERROR_SYSCALL returned. Then call
2258 	**  SSL_shutdown() again to actually get the server's response.
2259 	**
2260 	**  In the last discussion, Bodo Moeller concluded that a
2261 	**  rewrite of the shutdown code would be necessary, but
2262 	**  probably with another API, as the change would not be
2263 	**  compatible to the way it is now.  Things do not become
2264 	**  easier as other programs do not follow the shutdown
2265 	**  guidelines anyway, so that a lot error conditions and
2266 	**  compitibility issues would have to be caught.
2267 	**
2268 	**  For now the recommondation is to ignore the error message.
2269 	*/
2270 
2271 	else if (r == 0)
2272 	{
2273 		if (LogLevel > 15)
2274 		{
2275 			sm_syslog(LOG_WARNING, NOQID,
2276 				  "STARTTLS=%s, SSL_shutdown not done",
2277 				  who);
2278 			tlslogerr(LOG_WARNING, 15, who);
2279 		}
2280 		ret = EX_SOFTWARE;
2281 	}
2282 	SM_SSL_FREE(*pssl);
2283 	return ret;
2284 }
2285 
2286 # if !TLS_NO_RSA && MTA_RSA_TMP_CB
2287 /*
2288 **  TMP_RSA_KEY -- return temporary RSA key
2289 **
2290 **	Parameters:
2291 **		ssl -- TLS session context
2292 **		export --
2293 **		keylength --
2294 **
2295 **	Returns:
2296 **		temporary RSA key.
2297 */
2298 
2299 #  ifndef MAX_RSA_TMP_CNT
2300 #   define MAX_RSA_TMP_CNT	1000	/* XXX better value? */
2301 #  endif
2302 
2303 /* ARGUSED0 */
2304 static RSA *
2305 tmp_rsa_key(s, export, keylength)
2306 	SSL *s;
2307 	int export;
2308 	int keylength;
2309 {
2310 #  if SM_CONF_SHM
2311 	extern int ShmId;
2312 	extern int *PRSATmpCnt;
2313 
2314 	if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
2315 	    ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
2316 		return rsa_tmp;
2317 #  endif /* SM_CONF_SHM */
2318 
2319 	if (rsa_tmp != NULL)
2320 		RSA_free(rsa_tmp);
2321 	rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL);
2322 	if (rsa_tmp == NULL)
2323 	{
2324 		if (LogLevel > 0)
2325 			sm_syslog(LOG_ERR, NOQID,
2326 				  "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
2327 	}
2328 	else
2329 	{
2330 #  if SM_CONF_SHM
2331 #   if 0
2332 		/*
2333 		**  XXX we can't (yet) share the new key...
2334 		**	The RSA structure contains pointers hence it can't be
2335 		**	easily kept in shared memory.  It must be transformed
2336 		**	into a continuous memory region first, then stored,
2337 		**	and later read out again (each time re-transformed).
2338 		*/
2339 
2340 		if (ShmId != SM_SHM_NO_ID)
2341 			*PRSATmpCnt = 0;
2342 #   endif /* 0 */
2343 #  endif /* SM_CONF_SHM */
2344 		if (LogLevel > 9)
2345 			sm_syslog(LOG_ERR, NOQID,
2346 				  "STARTTLS=server, tmp_rsa_key: new temp RSA key");
2347 	}
2348 	return rsa_tmp;
2349 }
2350 # endif /* !TLS_NO_RSA && MTA_RSA_TMP_CB */
2351 
2352 /*
2353 **  APPS_SSL_INFO_CB -- info callback for TLS connections
2354 **
2355 **	Parameters:
2356 **		ssl -- TLS session context
2357 **		where -- state in handshake
2358 **		ret -- return code of last operation
2359 **
2360 **	Returns:
2361 **		none.
2362 */
2363 
2364 static void
2365 apps_ssl_info_cb(ssl, where, ret)
2366 	const SSL *ssl;
2367 	int where;
2368 	int ret;
2369 {
2370 	int w;
2371 	char *str;
2372 	BIO *bio_err = NULL;
2373 
2374 	if (LogLevel > 14)
2375 		sm_syslog(LOG_INFO, NOQID,
2376 			  "STARTTLS: info_callback where=0x%x, ret=%d",
2377 			  where, ret);
2378 
2379 	w = where & ~SSL_ST_MASK;
2380 	if (bio_err == NULL)
2381 		bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
2382 
2383 	if (bitset(SSL_ST_CONNECT, w))
2384 		str = "SSL_connect";
2385 	else if (bitset(SSL_ST_ACCEPT, w))
2386 		str = "SSL_accept";
2387 	else
2388 		str = "undefined";
2389 
2390 	if (bitset(SSL_CB_LOOP, where))
2391 	{
2392 		if (LogLevel > 12)
2393 			sm_syslog(LOG_NOTICE, NOQID,
2394 				"STARTTLS: %s:%s",
2395 				str, SSL_state_string_long(ssl));
2396 	}
2397 	else if (bitset(SSL_CB_ALERT, where))
2398 	{
2399 		str = bitset(SSL_CB_READ, where) ? "read" : "write";
2400 		if (LogLevel > 12)
2401 			sm_syslog(LOG_NOTICE, NOQID,
2402 				"STARTTLS: SSL3 alert %s:%s:%s",
2403 				str, SSL_alert_type_string_long(ret),
2404 				SSL_alert_desc_string_long(ret));
2405 	}
2406 	else if (bitset(SSL_CB_EXIT, where))
2407 	{
2408 		if (ret == 0)
2409 		{
2410 			if (LogLevel > 7)
2411 				sm_syslog(LOG_WARNING, NOQID,
2412 					"STARTTLS: %s:failed in %s",
2413 					str, SSL_state_string_long(ssl));
2414 		}
2415 		else if (ret < 0)
2416 		{
2417 			if (LogLevel > 7)
2418 				sm_syslog(LOG_WARNING, NOQID,
2419 					"STARTTLS: %s:error in %s",
2420 					str, SSL_state_string_long(ssl));
2421 		}
2422 	}
2423 }
2424 
2425 /*
2426 **  TLS_VERIFY_LOG -- log verify error for TLS certificates
2427 **
2428 **	Parameters:
2429 **		ok -- verify ok?
2430 **		ctx -- X509 context
2431 **		name -- from where is this called?
2432 **
2433 **	Returns:
2434 **		1 -- ok
2435 */
2436 
2437 static int
2438 tls_verify_log(ok, ctx, name)
2439 	int ok;
2440 	X509_STORE_CTX *ctx;
2441 	const char *name;
2442 {
2443 	X509 *cert;
2444 	int reason, depth;
2445 	char buf[512];
2446 
2447 	cert = X509_STORE_CTX_get_current_cert(ctx);
2448 	reason = X509_STORE_CTX_get_error(ctx);
2449 	depth = X509_STORE_CTX_get_error_depth(ctx);
2450 	X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
2451 	sm_syslog(LOG_INFO, NOQID,
2452 		  "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
2453 		  name, depth, buf, ok, X509_verify_cert_error_string(reason));
2454 	return 1;
2455 }
2456 
2457 /*
2458 **  Declaration and access to tlsi_ctx in callbacks.
2459 */
2460 
2461 #define SM_DECTLSI	\
2462 	tlsi_ctx_T *tlsi_ctx;	\
2463 	SSL *ssl
2464 #define SM_GETTLSI	\
2465 	do {		\
2466 		tlsi_ctx = NULL;	\
2467 		if (TLSsslidx >= 0)	\
2468 		{	\
2469 			ssl = (SSL *) X509_STORE_CTX_get_ex_data(ctx,	\
2470 				SSL_get_ex_data_X509_STORE_CTX_idx());	\
2471 			if (ssl != NULL)	\
2472 				tlsi_ctx = (tlsi_ctx_P) SSL_get_ex_data(ssl, TLSsslidx);	\
2473 		}	\
2474 	}	\
2475 	while (0)
2476 
2477 # if DANE
2478 
2479 /*
2480 **  DANE_GET_TLSA -- Retrieve TLSA RR for DANE
2481 **
2482 **	Parameters:
2483 **		dane_vrfy_ctx -- dane verify context
2484 **
2485 **	Returns:
2486 **		dane_tlsa if TLSA RR is available
2487 **		NULL otherwise
2488 */
2489 
2490 dane_tlsa_P
2491 dane_get_tlsa(dane_vrfy_ctx)
2492 	dane_vrfy_ctx_P dane_vrfy_ctx;
2493 {
2494 	STAB *s;
2495 	dane_tlsa_P dane_tlsa;
2496 
2497 	dane_tlsa = NULL;
2498 	if (NULL == dane_vrfy_ctx)
2499 		return NULL;
2500 	if (!CHK_DANE(dane_vrfy_ctx->dane_vrfy_chk) ||
2501 	    dane_vrfy_ctx->dane_vrfy_host == NULL)
2502 		return NULL;
2503 
2504 	gettlsa(dane_vrfy_ctx->dane_vrfy_host, NULL, &s,
2505 		TLSAFLNOEXP, 0, dane_vrfy_ctx->dane_vrfy_port);
2506 	if (NULL == s)
2507 		goto notfound;
2508 	dane_tlsa = s->s_tlsa;
2509 	if (NULL == dane_tlsa)
2510 		goto notfound;
2511 	if (!TLSA_HAS_RRs(dane_tlsa))
2512 		goto notfound;
2513 	if (tTd(96, 4))
2514 		sm_dprintf("dane_get_tlsa: chk=%#x, host=%s, n=%d, stat=entry found\n",
2515 			dane_vrfy_ctx->dane_vrfy_chk,
2516 			dane_vrfy_ctx->dane_vrfy_host, dane_tlsa->dane_tlsa_n);
2517 	return dane_tlsa;
2518 
2519   notfound:
2520 	if (tTd(96, 4))
2521 		sm_dprintf("dane_get_tlsa: chk=%#x, host=%s, stat=no valid entry found\n",
2522 			dane_vrfy_ctx->dane_vrfy_chk,
2523 			dane_vrfy_ctx->dane_vrfy_host);
2524 	return NULL;
2525 }
2526 
2527 /*
2528 **  DANE_VERIFY -- verify callback for TLS certificates
2529 **
2530 **	Parameters:
2531 **		ctx -- X509 context
2532 **		dane_vrfy_ctx -- callback context
2533 **
2534 **	Returns:
2535 **		DANE_VRFY_{OK,NONE,FAIL}
2536 */
2537 
2538 /* NOTE: this only works because the "matching type" is 0, 1, 2 for these! */
2539 static const char *dane_mdalgs[] = { "", "sha256", "sha512" };
2540 
2541 static int
2542 dane_verify(ctx, dane_vrfy_ctx)
2543 	X509_STORE_CTX *ctx;
2544 	dane_vrfy_ctx_P dane_vrfy_ctx;
2545 {
2546 	int r, i, ok, mdalg;
2547 	X509 *cert;
2548 	dane_tlsa_P dane_tlsa;
2549 	unsigned char *fp;
2550 
2551 	dane_tlsa = dane_get_tlsa(dane_vrfy_ctx);
2552 	if (dane_tlsa == NULL)
2553 		return DANE_VRFY_NONE;
2554 
2555 	dane_vrfy_ctx->dane_vrfy_fp[0] = '\0';
2556 	cert = X509_STORE_CTX_get0_cert(ctx);
2557 	if (tTd(96, 8))
2558 		sm_dprintf("dane_verify: cert=%p, supported=%d\n",
2559 			(void *)cert, TLSA_IS_FL(dane_tlsa, TLSAFLSUP));
2560 	if (cert == NULL)
2561 		return DANE_VRFY_FAIL;
2562 
2563 	ok = DANE_VRFY_NONE;
2564 	fp = NULL;
2565 
2566 	/*
2567 	**  If the TLSA RRs would be sorted the two loops below could
2568 	**  be merged into one and simply change mdalg when it changes
2569 	**  in dane_tlsa->dane_tlsa_rr.
2570 	*/
2571 
2572 	/* use a different order? */
2573 	for (mdalg = 0; mdalg < SM_ARRAY_SIZE(dane_mdalgs); mdalg++)
2574 	{
2575 		SM_FREE(fp);
2576 		r = 0;
2577 		for (i = 0; i < dane_tlsa->dane_tlsa_n; i++)
2578 		{
2579 			unsigned char *p;
2580 			int alg;
2581 
2582 			p = dane_tlsa->dane_tlsa_rr[i];
2583 
2584 			/* ignore bogus/unsupported TLSA RRs */
2585 			alg = dane_tlsa_chk(p, dane_tlsa->dane_tlsa_len[i],
2586 					  dane_vrfy_ctx->dane_vrfy_host, false);
2587 			if (tTd(96, 8))
2588 				sm_dprintf("dane_verify: alg=%d, mdalg=%d\n",
2589 					alg, mdalg);
2590 			if (alg != mdalg)
2591 				continue;
2592 
2593 			if (NULL == fp)
2594 			{
2595 				r = pubkey_fp(cert, dane_mdalgs[mdalg], &fp);
2596 				if (NULL == fp)
2597 					return DANE_VRFY_FAIL;
2598 					/* or continue? */
2599 			}
2600 
2601 			/* just for logging */
2602 			if (r > 0 && fp != NULL)
2603 			{
2604 				(void) data2hex((unsigned char *)fp, r,
2605 					(unsigned char *)dane_vrfy_ctx->dane_vrfy_fp,
2606 					sizeof(dane_vrfy_ctx->dane_vrfy_fp));
2607 			}
2608 
2609 			if (tTd(96, 4))
2610 				sm_dprintf("dane_verify: alg=%d, r=%d, len=%d\n",
2611 					alg, r, dane_tlsa->dane_tlsa_len[i]);
2612 			if (r != dane_tlsa->dane_tlsa_len[i] - 3)
2613 				continue;
2614 			ok = DANE_VRFY_FAIL;
2615 
2616 			/*
2617 			**  Note: Type is NOT checked because only 3-1-x
2618 			**  is supported.
2619 			*/
2620 
2621 			if (memcmp(p + 3, fp, r) == 0)
2622 			{
2623 				if (tTd(96, 2))
2624 					sm_dprintf("dane_verify: status=match\n");
2625 				if (tTd(96, 8))
2626 				{
2627 					unsigned char hex[DANE_FP_DBG_LEN];
2628 
2629 					data2hex((unsigned char *)p,
2630 						dane_tlsa->dane_tlsa_len[i],
2631 						hex, sizeof(hex));
2632 					sm_dprintf("dane_verify: pubkey_fp=%s\n"
2633 						, hex);
2634 				}
2635 				dane_vrfy_ctx->dane_vrfy_res = DANE_VRFY_OK;
2636 				SM_FREE(fp);
2637 				return DANE_VRFY_OK;
2638 			}
2639 		}
2640 	}
2641 
2642 	SM_FREE(fp);
2643 	dane_vrfy_ctx->dane_vrfy_res = ok;
2644 	return ok;
2645 }
2646 
2647 /*
2648 **  SSL_DANE_ENABLE -- enable using OpenSSL DANE functions for a session
2649 **
2650 **	Parameters:
2651 **		dane_vrfy_ctx -- dane verify context
2652 **		ssl -- TLS connection structure
2653 **
2654 **	Returns:
2655 **		SM_SUCCESS: OpenSSL DANE checking enabled
2656 **		SM_NOTDONE: OpenSSL DANE checking not enabled
2657 **		<0: some error
2658 */
2659 
2660 int
2661 ssl_dane_enable(dane_vrfy_ctx, ssl)
2662 	dane_vrfy_ctx_P dane_vrfy_ctx;
2663 	SSL *ssl;
2664 {
2665 #  if HAVE_SSL_CTX_dane_enable
2666 	const char *dane_tlsa_domain;
2667 	int r, i, usable;
2668 #  endif
2669 	dane_tlsa_P dane_tlsa;
2670 
2671 	if (tTd(96, 20))
2672 		sm_dprintf("ssl_dane_enable: dane_vrfy_ctx=%p, dane_vrfy_dane_enabled=%d, dane_vrfy_chk=%#x\n",
2673 			dane_vrfy_ctx, dane_vrfy_ctx->dane_vrfy_dane_enabled,
2674 			dane_vrfy_ctx->dane_vrfy_chk);
2675 
2676 	dane_tlsa = dane_get_tlsa(dane_vrfy_ctx);
2677 	if (tTd(96, 20))
2678 		sm_dprintf("ssl_dane_enable: dane_tlsa=%p, n=%d, supported=%d\n",
2679 			dane_tlsa, dane_tlsa != NULL ? dane_tlsa->dane_tlsa_n : -999,
2680 			dane_tlsa != NULL ? TLSA_IS_FL(dane_tlsa, TLSAFLSUP) : -1);
2681 	if (NULL == dane_tlsa || !TLSA_IS_FL(dane_tlsa, TLSAFLSUP))
2682 	{
2683 		/* no DANE verification possible */
2684 		dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLNOVRFY;
2685 		return SM_SUCCESS;
2686 	}
2687 	if (0 == (dane_vrfy_ctx->dane_vrfy_chk & TLSAFLADIP))
2688 	{
2689 		/* no DANE verification possible */
2690 		dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLNOVRFY;
2691 		return SM_SUCCESS;
2692 	}
2693 
2694 	if (!dane_vrfy_ctx->dane_vrfy_dane_enabled)
2695 	{
2696 #  if HAVE_SSL_CTX_dane_enable
2697 		dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLTEMPVRFY;
2698 #  endif
2699 		return SM_NOTDONE;
2700 	}
2701 
2702 #  if HAVE_SSL_CTX_dane_enable
2703 	dane_tlsa_domain = !SM_IS_EMPTY(dane_vrfy_ctx->dane_vrfy_sni)
2704 				? dane_vrfy_ctx->dane_vrfy_sni
2705 				: dane_vrfy_ctx->dane_vrfy_host;
2706 	r = SSL_dane_enable(ssl, dane_tlsa_domain);
2707 #   if _FFR_TESTS
2708 	if (tTd(90, 102))
2709 	{
2710 		sm_dprintf("ssl_dane_enable: test=simulate SSL_dane_enable error\n");
2711 #    ifdef SSL_F_SSL_DANE_ENABLE
2712 		SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
2713 #    endif
2714 		r = -1; /* -ENOMEM; */
2715 	}
2716 #   endif /* _FFR_TESTS */
2717 	if (r <= 0)
2718 	{
2719 #  if HAVE_SSL_CTX_dane_enable
2720 		dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLTEMPVRFY;
2721 #  endif
2722 		if (LogLevel > 1)
2723 			sm_syslog(LOG_ERR, NOQID,
2724 				"STARTTLS=client, SSL_dane_enable=%d", r);
2725 		tlslogerr(LOG_ERR, 7, "client");
2726 
2727 		/* XXX need better error code */
2728 		return (r < 0) ? r : -EINVAL;
2729 	}
2730 	if (LogLevel > 13)
2731 		sm_syslog(LOG_DEBUG, NOQID,
2732 			"STARTTLS=client, SSL_dane_enable=%d, domain=%s",
2733 			r, dane_tlsa_domain);
2734 	(void) SSL_dane_set_flags(ssl, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
2735 
2736 	usable = 0;
2737 	for (i = 0; i < dane_tlsa->dane_tlsa_n; i++)
2738 	{
2739 		const unsigned char *rr;
2740 		const char *chk;
2741 
2742 		rr = (const unsigned char *)dane_tlsa->dane_tlsa_rr[i];
2743 		if (NULL == rr)
2744 			continue;
2745 
2746 		/*
2747 		**  only DANE-TA(2) or DANE-EE(3)
2748 		**  use dane_tlsa_chk() instead?
2749 		*/
2750 
2751 # if _FFR_TESTS
2752 		if (tTd(90, 101) && 3 == rr[0] && 1 == rr[1])
2753 		{
2754 			sm_dprintf("TLSA, type=%d-%d-%d:%02x, status=unsupported_due_to_test",
2755 				  (int)rr[0], (int)rr[1], (int)rr[2],
2756 				  (int)rr[3]);
2757 			r = 0;
2758 			chk = "tlsa_test";
2759 		}
2760 		else
2761 # endif /* _FFR_TESTS */
2762 		if (!(2 == rr[0] || 3 == rr[0]))
2763 		{
2764 			r = 0;
2765 			chk = "tlsa_chk";
2766 		}
2767 		else
2768 		{
2769 			r = SSL_dane_tlsa_add(ssl, rr[0], rr[1], rr[2], rr + 3,
2770 				(size_t) (dane_tlsa->dane_tlsa_len[i] - 3));
2771 			chk = "SSL_dane_tlsa_add";
2772 		}
2773 		if (r > 0)
2774 			usable++;
2775 #  if HAVE_SSL_CTX_dane_enable && 0
2776 /* should an error be ignored or cause a temporary failure? */
2777 		if (r < 0)
2778 			dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLTEMPVRFY;
2779 #  endif
2780 		else if (LogLevel > ((r < 0) ? 10 : 13))
2781 		{
2782 			unsigned char hex[DANE_FP_LOG_LEN];
2783 
2784 			(void) data2hex((unsigned char *)rr + 3,
2785 				dane_tlsa->dane_tlsa_len[i] - 3,
2786 				hex, sizeof(hex));
2787 			sm_syslog(LOG_DEBUG, NOQID,
2788 				"STARTTLS=client, %s=%d, type=%d-%d-%d, fp=%s"
2789 				, chk, r, rr[0], rr[1], rr[2], hex);
2790 			tlslogerr(LOG_DEBUG, (r < 0) ? 13 : 10, "client");
2791 		}
2792 		if (tTd(96, 20))
2793 		{
2794 			unsigned char hex[DANE_FP_DBG_LEN];
2795 
2796 			(void) data2hex((unsigned char *)rr + 3,
2797 				dane_tlsa->dane_tlsa_len[i] - 3,
2798 				hex, sizeof(hex));
2799 			sm_dprintf("ssl_dane_enable: SSL_dane_tlsa_add=%d, u=%d, s=%d, d=%d, len=%d, fp=%s\n"
2800 					, r, rr[0], rr[1], rr[2]
2801 					, dane_tlsa->dane_tlsa_len[i]-3, hex
2802 					);
2803 		}
2804 	}
2805 	if (tTd(96, 20))
2806 		sm_dprintf("ssl_dane_enable: usable=%d\n", usable);
2807 	if (0 == usable)
2808 	{
2809 		/* shouldn't happen - checked above! */
2810 		if (LogLevel > 1)
2811 			sm_syslog(LOG_CRIT, NOQID,
2812 				"ERROR: ssl_dane_enable() INCONSISTENY: %d usable TLSA RRs found but \"supported\" flag is set (%d)\n",
2813 				usable, TLSA_IS_FL(dane_tlsa, TLSAFLSUP));
2814 		dane_vrfy_ctx->dane_vrfy_chk |= TLSAFLNOVRFY;
2815 		return SM_SUCCESS;
2816 	}
2817 #  endif /* HAVE_SSL_CTX_dane_enable */
2818 	return SM_SUCCESS;
2819 }
2820 # endif /* DANE */
2821 
2822 /*
2823 **  TLS_VERIFY_CB -- verify callback for TLS certificates
2824 **
2825 **	Parameters:
2826 **		ctx -- X509 context
2827 **		cb_ctx -- callback context
2828 **
2829 **	Returns:
2830 **		accept connection?
2831 **		currently: always yes.
2832 */
2833 
2834 static int
2835 tls_verify_cb(ctx, cb_ctx)
2836 	X509_STORE_CTX *ctx;
2837 	void *cb_ctx;
2838 {
2839 	int ok;
2840 # if DANE
2841 	SM_DECTLSI;
2842 	dane_vrfy_ctx_P dane_vrfy_ctx;
2843 # endif
2844 
2845 	/*
2846 	**  SSL_CTX_set_cert_verify_callback(3):
2847 	**  callback should return 1 to indicate verification success
2848 	**  and 0 to indicate verification failure.
2849 	*/
2850 
2851 # if DANE
2852 	SM_GETTLSI;
2853 	if (tTd(96, 40))
2854 		sm_dprintf("tls_verify_cb: tlsi_ctx=%p, vrfy_chk=%#x\n", tlsi_ctx,
2855 			(tlsi_ctx != NULL && (dane_vrfy_ctx = &(tlsi_ctx->tlsi_dvc)) != NULL) ?
2856 			dane_vrfy_ctx->dane_vrfy_chk : -1);
2857 	if (tlsi_ctx != NULL && (dane_vrfy_ctx = &(tlsi_ctx->tlsi_dvc)) != NULL
2858 	    && !dane_vrfy_ctx->dane_vrfy_dane_enabled
2859 	    && (0 == (dane_vrfy_ctx->dane_vrfy_chk & TLSAFLTEMPVRFY))
2860 	    && VRFY_DANE(dane_vrfy_ctx->dane_vrfy_chk)
2861 	)
2862 	{
2863 		int depth;
2864 
2865 		depth = X509_STORE_CTX_get_error_depth(ctx);
2866 		if (tTd(96, 20))
2867 			sm_dprintf("tls_verify_cb: enabled=%d, chk=%#x, depth=%d\n",
2868 				dane_vrfy_ctx->dane_vrfy_dane_enabled,
2869 				dane_vrfy_ctx->dane_vrfy_chk, depth);
2870 
2871 		if (0 == depth)
2872 		{
2873 			ok = dane_verify(ctx, dane_vrfy_ctx);
2874 			if (tTd(96, 2))
2875 				sm_dprintf("tls_verify_cb: dane_verify=%d, res=%d\n", ok,
2876 					dane_vrfy_ctx->dane_vrfy_res);
2877 			if (ok != DANE_VRFY_NONE)
2878 				return 1;
2879 		}
2880 	}
2881 
2882 	if (tTd(96, 10))
2883 		sm_dprintf("tls_verify_cb: basic check? enabled=%d, chk=%#x\n",
2884 			(tlsi_ctx != NULL && dane_vrfy_ctx != NULL) ?
2885 				dane_vrfy_ctx->dane_vrfy_dane_enabled : -1,
2886 			(tlsi_ctx != NULL && dane_vrfy_ctx != NULL) ?
2887 				dane_vrfy_ctx->dane_vrfy_chk : -1);
2888 # endif /* DANE */
2889 
2890 	ok = X509_verify_cert(ctx);
2891 	if ((LogLevel > 13 && ok <= 0) || LogLevel > 14)
2892 		(void) tls_verify_log(ok, ctx, "TLS");
2893 	return 1;
2894 }
2895 
2896 /*
2897 **  TLSLOGERR -- log the errors from the TLS error stack
2898 **
2899 **	Parameters:
2900 **		priority -- syslog priority
2901 **		ll -- loglevel
2902 **		who -- server/client (for logging).
2903 **
2904 **	Returns:
2905 **		none.
2906 */
2907 
2908 void
2909 tlslogerr(priority, ll, who)
2910 	int priority;
2911 	int ll;
2912 	const char *who;
2913 {
2914 	unsigned long l;
2915 	int line, flags;
2916 	char *file, *data;
2917 	char buf[256];
2918 
2919 	if (LogLevel <= ll)
2920 		return;
2921 	while ((l = MTA_SSL_ERR_get((const char **) &file, &line,
2922 				    (const char **) &data, &flags, NULL))
2923 		!= 0)
2924 	{
2925 		sm_syslog(priority, NOQID,
2926 			  "STARTTLS=%s: %s:%s:%d:%s", who,
2927 			  ERR_error_string(l, buf),
2928 			  file, line,
2929 			  bitset(ERR_TXT_STRING, flags) ? data : "");
2930 	}
2931 }
2932 
2933 /*
2934 **  X509_VERIFY_CB -- verify callback
2935 **
2936 **	Parameters:
2937 **		ok -- current result
2938 **		ctx -- X509 context
2939 **
2940 **	Returns:
2941 **		accept connection?
2942 **		currently: always yes.
2943 */
2944 
2945 static int
2946 x509_verify_cb(ok, ctx)
2947 	int ok;
2948 	X509_STORE_CTX *ctx;
2949 {
2950 	SM_DECTLSI;
2951 
2952 	if (ok != 0)
2953 		return ok;
2954 
2955 	SM_GETTLSI;
2956 	if (LogLevel > 13)
2957 		tls_verify_log(ok, ctx, "X509");
2958 	if (X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL &&
2959 	    !SM_TLSI_IS(tlsi_ctx, TLSI_FL_CRLREQ))
2960 	{
2961 		X509_STORE_CTX_set_error(ctx, 0);
2962 		return 1;	/* override it */
2963 	}
2964 	return ok;
2965 }
2966 
2967 # if !USE_OPENSSL_ENGINE && !defined(OPENSSL_NO_ENGINE)
2968 /*
2969 **  TLS_SET_ENGINE -- set up ENGINE if needed
2970 **
2971 **	Parameters:
2972 **		id -- id for ENGINE
2973 **		isprefork -- called before fork()?
2974 **
2975 **	Returns: (OpenSSL "semantics", reverse it to allow returning error codes)
2976 **		0: failure
2977 **		!=0: ok
2978 */
2979 
2980 int
2981 TLS_set_engine(id, isprefork)
2982 	const char *id;
2983 	bool isprefork;
2984 {
2985 	static bool TLSEngineInitialized = false;
2986 	ENGINE *e;
2987 	char enginepath[MAXPATHLEN];
2988 
2989 	/*
2990 	**  Todo: put error for logging into a string and log it in error:
2991 	*/
2992 
2993 	if (LogLevel > 13)
2994 		sm_syslog(LOG_DEBUG, NOQID,
2995 			"engine=%s, path=%s, ispre=%d, pre=%d, initialized=%d",
2996 			id, SSLEnginePath, isprefork, SSLEngineprefork,
2997 			TLSEngineInitialized);
2998 	if (TLSEngineInitialized)
2999 		return 1;
3000 	if (SM_IS_EMPTY(id))
3001 		return 1;
3002 #  if !defined(ENGINE_METHOD_ALL)
3003 	if (LogLevel > 9)
3004 		sm_syslog(LOG_NOTICE, NOQID,
3005 			"engine=%s, status=engines_not_support", id)
3006 	goto error;
3007 #  endif
3008 
3009 	/* is this the "right time" to initialize the engine? */
3010 	if (isprefork != SSLEngineprefork)
3011 		return 1;
3012 
3013 	e = NULL;
3014 	ENGINE_load_builtin_engines();
3015 
3016 	if (SSLEnginePath != NULL && *SSLEnginePath != '\0')
3017 	{
3018 		if ((e = ENGINE_by_id("dynamic")) == NULL)
3019 		{
3020 			if (LogLevel > 1)
3021 				sm_syslog(LOG_ERR, NOQID,
3022 					"engine=%s, by_id=failed", "dynamic");
3023 			goto error;
3024 		}
3025 		(void) sm_snprintf(enginepath, sizeof(enginepath),
3026 			"%s/lib%s.so", SSLEnginePath, id);
3027 
3028 		if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", enginepath, 0))
3029 		{
3030 			if (LogLevel > 1)
3031 				sm_syslog(LOG_ERR, NOQID,
3032 					"engine=%s, SO_PATH=%s, status=failed",
3033 					id, enginepath);
3034 			goto error;
3035 		}
3036 
3037 		if (!ENGINE_ctrl_cmd_string(e, "ID", id, 0))
3038 		{
3039 			if (LogLevel > 1)
3040 				sm_syslog(LOG_ERR, NOQID,
3041 					"engine=%s, ID=failed", id);
3042 			goto error;
3043 		}
3044 
3045 		if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
3046 		{
3047 			if (LogLevel > 1)
3048 				sm_syslog(LOG_ERR, NOQID,
3049 					"engine=%s, LOAD=failed", id);
3050 			goto error;
3051 		}
3052 	}
3053 	else if ((e = ENGINE_by_id(id)) == NULL)
3054 	{
3055 		if (LogLevel > 1)
3056 			sm_syslog(LOG_ERR, NOQID, "engine=%s, by_id=failed",
3057 				id);
3058 		return 0;
3059 	}
3060 
3061 	if (!ENGINE_init(e))
3062 	{
3063 		if (LogLevel > 1)
3064 			sm_syslog(LOG_ERR, NOQID, "engine=%s, init=failed", id);
3065 		goto error;
3066 	}
3067 	if (!ENGINE_set_default(e, ENGINE_METHOD_ALL))
3068 	{
3069 		if (LogLevel > 1)
3070 			sm_syslog(LOG_ERR, NOQID,
3071 				"engine=%s, set_default=failed", id);
3072 		goto error;
3073 	}
3074 #  ifdef ENGINE_CTRL_CHIL_SET_FORKCHECK
3075 	if (strcmp(id, "chil") == 0)
3076 		ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
3077 #  endif
3078 
3079 	/* Free our "structural" reference. */
3080 	ENGINE_free(e);
3081 	if (LogLevel > 10)
3082 		sm_syslog(LOG_INFO, NOQID, "engine=%s, loaded=ok", id);
3083 	TLSEngineInitialized = true;
3084 	return 1;
3085 
3086   error:
3087 	tlslogerr(LOG_WARNING, 7, "init");
3088 	if (e != NULL)
3089 		ENGINE_free(e);
3090 	return 0;
3091 }
3092 # endif /* !USE_OPENSSL_ENGINE && !defined(OPENSSL_NO_ENGINE) */
3093 #endif /* STARTTLS */
3094