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