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