xref: /freebsd/contrib/sendmail/src/tls.c (revision 298022457a9a016cbdda4e22d751abb5cd91c919)
1 /*
2  * Copyright (c) 2000-2006, 2008, 2009, 2011, 2013 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 /* ! HASURANDOMDEV */
22 # if !TLS_NO_RSA
23 static RSA *rsa_tmp = NULL;	/* temporary RSA key */
24 static RSA *tmp_rsa_key __P((SSL *, int, int));
25 # endif /* !TLS_NO_RSA */
26 #  if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
27 static int	tls_verify_cb __P((X509_STORE_CTX *));
28 #  else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
29 static int	tls_verify_cb __P((X509_STORE_CTX *, void *));
30 #  endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
31 
32 # if OPENSSL_VERSION_NUMBER > 0x00907000L
33 static int x509_verify_cb __P((int, X509_STORE_CTX *));
34 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
35 
36 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
37 #  define CONST097
38 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
39 #  define CONST097 const
40 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
41 static void	apps_ssl_info_cb __P((CONST097 SSL *, int , int));
42 static bool	tls_ok_f __P((char *, char *, int));
43 static bool	tls_safe_f __P((char *, long, bool));
44 static int	tls_verify_log __P((int, X509_STORE_CTX *, char *));
45 
46 # if !NO_DH
47 static DH *get_dh512 __P((void));
48 
49 static unsigned char dh512_p[] =
50 {
51 	0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
52 	0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
53 	0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
54 	0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
55 	0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
56 	0x47,0x74,0xE8,0x33
57 };
58 static unsigned char dh512_g[] =
59 {
60 	0x02
61 };
62 
63 static DH *
64 get_dh512()
65 {
66 	DH *dh = NULL;
67 
68 	if ((dh = DH_new()) == NULL)
69 		return NULL;
70 	dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
71 	dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
72 	if ((dh->p == NULL) || (dh->g == NULL))
73 		return NULL;
74 	return dh;
75 }
76 # endif /* !NO_DH */
77 
78 
79 /*
80 **  TLS_RAND_INIT -- initialize STARTTLS random generator
81 **
82 **	Parameters:
83 **		randfile -- name of file with random data
84 **		logl -- loglevel
85 **
86 **	Returns:
87 **		success/failure
88 **
89 **	Side Effects:
90 **		initializes PRNG for tls library.
91 */
92 
93 # define MIN_RAND_BYTES	128	/* 1024 bits */
94 
95 # define RF_OK		0	/* randfile OK */
96 # define RF_MISS	1	/* randfile == NULL || *randfile == '\0' */
97 # define RF_UNKNOWN	2	/* unknown prefix for randfile */
98 
99 # define RI_NONE	0	/* no init yet */
100 # define RI_SUCCESS	1	/* init was successful */
101 # define RI_FAIL	2	/* init failed */
102 
103 static bool	tls_rand_init __P((char *, int));
104 
105 static bool
106 tls_rand_init(randfile, logl)
107 	char *randfile;
108 	int logl;
109 {
110 # ifndef HASURANDOMDEV
111 	/* not required if /dev/urandom exists, OpenSSL does it internally */
112 
113 	bool ok;
114 	int randdef;
115 	static int done = RI_NONE;
116 
117 	/*
118 	**  initialize PRNG
119 	*/
120 
121 	/* did we try this before? if yes: return old value */
122 	if (done != RI_NONE)
123 		return done == RI_SUCCESS;
124 
125 	/* set default values */
126 	ok = false;
127 	done = RI_FAIL;
128 	randdef = (randfile == NULL || *randfile == '\0') ? RF_MISS : RF_OK;
129 #   if EGD
130 	if (randdef == RF_OK && sm_strncasecmp(randfile, "egd:", 4) == 0)
131 	{
132 		randfile += 4;
133 		if (RAND_egd(randfile) < 0)
134 		{
135 			sm_syslog(LOG_WARNING, NOQID,
136 				  "STARTTLS: RAND_egd(%s) failed: random number generator not seeded",
137 				   randfile);
138 		}
139 		else
140 			ok = true;
141 	}
142 	else
143 #   endif /* EGD */
144 	if (randdef == RF_OK && sm_strncasecmp(randfile, "file:", 5) == 0)
145 	{
146 		int fd;
147 		long sff;
148 		struct stat st;
149 
150 		randfile += 5;
151 		sff = SFF_SAFEDIRPATH | SFF_NOWLINK
152 		      | SFF_NOGWFILES | SFF_NOWWFILES
153 		      | SFF_NOGRFILES | SFF_NOWRFILES
154 		      | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
155 		if (DontLockReadFiles)
156 			sff |= SFF_NOLOCK;
157 		if ((fd = safeopen(randfile, O_RDONLY, 0, sff)) >= 0)
158 		{
159 			if (fstat(fd, &st) < 0)
160 			{
161 				if (LogLevel > logl)
162 					sm_syslog(LOG_ERR, NOQID,
163 						  "STARTTLS: can't fstat(%s)",
164 						  randfile);
165 			}
166 			else
167 			{
168 				bool use, problem;
169 
170 				use = true;
171 				problem = false;
172 
173 				/* max. age of file: 10 minutes */
174 				if (st.st_mtime + 600 < curtime())
175 				{
176 					use = bitnset(DBS_INSUFFICIENTENTROPY,
177 						      DontBlameSendmail);
178 					problem = true;
179 					if (LogLevel > logl)
180 						sm_syslog(LOG_ERR, NOQID,
181 							  "STARTTLS: RandFile %s too old: %s",
182 							  randfile,
183 							  use ? "unsafe" :
184 								"unusable");
185 				}
186 				if (use && st.st_size < MIN_RAND_BYTES)
187 				{
188 					use = bitnset(DBS_INSUFFICIENTENTROPY,
189 						      DontBlameSendmail);
190 					problem = true;
191 					if (LogLevel > logl)
192 						sm_syslog(LOG_ERR, NOQID,
193 							  "STARTTLS: size(%s) < %d: %s",
194 							  randfile,
195 							  MIN_RAND_BYTES,
196 							  use ? "unsafe" :
197 								"unusable");
198 				}
199 				if (use)
200 					ok = RAND_load_file(randfile, -1) >=
201 					     MIN_RAND_BYTES;
202 				if (use && !ok)
203 				{
204 					if (LogLevel > logl)
205 						sm_syslog(LOG_WARNING, NOQID,
206 							  "STARTTLS: RAND_load_file(%s) failed: random number generator not seeded",
207 							  randfile);
208 				}
209 				if (problem)
210 					ok = false;
211 			}
212 			if (ok || bitnset(DBS_INSUFFICIENTENTROPY,
213 					  DontBlameSendmail))
214 			{
215 				/* add this even if fstat() failed */
216 				RAND_seed((void *) &st, sizeof(st));
217 			}
218 			(void) close(fd);
219 		}
220 		else
221 		{
222 			if (LogLevel > logl)
223 				sm_syslog(LOG_WARNING, NOQID,
224 					  "STARTTLS: Warning: safeopen(%s) failed",
225 					  randfile);
226 		}
227 	}
228 	else if (randdef == RF_OK)
229 	{
230 		if (LogLevel > logl)
231 			sm_syslog(LOG_WARNING, NOQID,
232 				  "STARTTLS: Error: no proper random file definition %s",
233 				  randfile);
234 		randdef = RF_UNKNOWN;
235 	}
236 	if (randdef == RF_MISS)
237 	{
238 		if (LogLevel > logl)
239 			sm_syslog(LOG_WARNING, NOQID,
240 				  "STARTTLS: Error: missing random file definition");
241 	}
242 	if (!ok && bitnset(DBS_INSUFFICIENTENTROPY, DontBlameSendmail))
243 	{
244 		int i;
245 		long r;
246 		unsigned char buf[MIN_RAND_BYTES];
247 
248 		/* assert((MIN_RAND_BYTES % sizeof(long)) == 0); */
249 		for (i = 0; i <= sizeof(buf) - sizeof(long); i += sizeof(long))
250 		{
251 			r = get_random();
252 			(void) memcpy(buf + i, (void *) &r, sizeof(long));
253 		}
254 		RAND_seed(buf, sizeof(buf));
255 		if (LogLevel > logl)
256 			sm_syslog(LOG_WARNING, NOQID,
257 				  "STARTTLS: Warning: random number generator not properly seeded");
258 		ok = true;
259 	}
260 	done = ok ? RI_SUCCESS : RI_FAIL;
261 	return ok;
262 # else /* ! HASURANDOMDEV */
263 	return true;
264 # endif /* ! HASURANDOMDEV */
265 }
266 /*
267 **  INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
268 **
269 **	Parameters:
270 **		fipsmode -- use FIPS?
271 **
272 **	Returns:
273 **		succeeded?
274 */
275 
276 bool
277 init_tls_library(fipsmode)
278 	bool fipsmode;
279 {
280 	bool bv;
281 
282 	/* basic TLS initialization, ignore result for now */
283 	SSL_library_init();
284 	SSL_load_error_strings();
285 	OpenSSL_add_all_algorithms();
286 # if 0
287 	/* this is currently a macro for SSL_library_init */
288 	SSLeay_add_ssl_algorithms();
289 # endif /* 0 */
290 
291 	bv = tls_rand_init(RandFile, 7);
292 # if _FFR_FIPSMODE
293 	if (bv && fipsmode)
294 	{
295 		if (!FIPS_mode_set(1))
296 		{
297 			unsigned long err;
298 
299 			err = ERR_get_error();
300 			if (LogLevel > 0)
301 				sm_syslog(LOG_ERR, NOQID,
302 					"STARTTLS=init, FIPSMode=%s",
303 					ERR_error_string(err, NULL));
304 			return false;
305 		}
306 		else
307 		{
308 			if (LogLevel > 9)
309 				sm_syslog(LOG_INFO, NOQID,
310 					"STARTTLS=init, FIPSMode=ok");
311 		}
312 	}
313 #endif /* _FFR_FIPSMODE  */
314 	return bv;
315 }
316 /*
317 **  TLS_SET_VERIFY -- request client certificate?
318 **
319 **	Parameters:
320 **		ctx -- TLS context
321 **		ssl -- TLS structure
322 **		vrfy -- require certificate?
323 **
324 **	Returns:
325 **		none.
326 **
327 **	Side Effects:
328 **		Sets verification state for TLS
329 **
330 # if TLS_VRFY_PER_CTX
331 **	Notice:
332 **		This is per TLS context, not per TLS structure;
333 **		the former is global, the latter per connection.
334 **		It would be nice to do this per connection, but this
335 **		doesn't work in the current TLS libraries :-(
336 # endif * TLS_VRFY_PER_CTX *
337 */
338 
339 void
340 tls_set_verify(ctx, ssl, vrfy)
341 	SSL_CTX *ctx;
342 	SSL *ssl;
343 	bool vrfy;
344 {
345 # if !TLS_VRFY_PER_CTX
346 	SSL_set_verify(ssl, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
347 # else /* !TLS_VRFY_PER_CTX */
348 	SSL_CTX_set_verify(ctx, vrfy ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
349 			NULL);
350 # endif /* !TLS_VRFY_PER_CTX */
351 }
352 
353 /*
354 **  status in initialization
355 **  these flags keep track of the status of the initialization
356 **  i.e., whether a file exists (_EX) and whether it can be used (_OK)
357 **  [due to permissions]
358 */
359 
360 # define TLS_S_NONE	0x00000000	/* none yet */
361 # define TLS_S_CERT_EX	0x00000001	/* cert file exists */
362 # define TLS_S_CERT_OK	0x00000002	/* cert file is ok */
363 # define TLS_S_KEY_EX	0x00000004	/* key file exists */
364 # define TLS_S_KEY_OK	0x00000008	/* key file is ok */
365 # define TLS_S_CERTP_EX	0x00000010	/* CA cert path exists */
366 # define TLS_S_CERTP_OK	0x00000020	/* CA cert path is ok */
367 # define TLS_S_CERTF_EX	0x00000040	/* CA cert file exists */
368 # define TLS_S_CERTF_OK	0x00000080	/* CA cert file is ok */
369 # define TLS_S_CRLF_EX	0x00000100	/* CRL file exists */
370 # define TLS_S_CRLF_OK	0x00000200	/* CRL file is ok */
371 
372 # if _FFR_TLS_1
373 #  define TLS_S_CERT2_EX	0x00001000	/* 2nd cert file exists */
374 #  define TLS_S_CERT2_OK	0x00002000	/* 2nd cert file is ok */
375 #  define TLS_S_KEY2_EX	0x00004000	/* 2nd key file exists */
376 #  define TLS_S_KEY2_OK	0x00008000	/* 2nd key file is ok */
377 # endif /* _FFR_TLS_1 */
378 
379 # define TLS_S_DH_OK	0x00200000	/* DH cert is ok */
380 # define TLS_S_DHPAR_EX	0x00400000	/* DH param file exists */
381 # define TLS_S_DHPAR_OK	0x00800000	/* DH param file is ok to use */
382 
383 /* Type of variable */
384 # define TLS_T_OTHER	0
385 # define TLS_T_SRV	1
386 # define TLS_T_CLT	2
387 
388 /*
389 **  TLS_OK_F -- can var be an absolute filename?
390 **
391 **	Parameters:
392 **		var -- filename
393 **		fn -- what is the filename used for?
394 **		type -- type of variable
395 **
396 **	Returns:
397 **		ok?
398 */
399 
400 static bool
401 tls_ok_f(var, fn, type)
402 	char *var;
403 	char *fn;
404 	int type;
405 {
406 	/* must be absolute pathname */
407 	if (var != NULL && *var == '/')
408 		return true;
409 	if (LogLevel > 12)
410 		sm_syslog(LOG_WARNING, NOQID, "STARTTLS: %s%s missing",
411 			  type == TLS_T_SRV ? "Server" :
412 			  (type == TLS_T_CLT ? "Client" : ""), fn);
413 	return false;
414 }
415 /*
416 **  TLS_SAFE_F -- is a file safe to use?
417 **
418 **	Parameters:
419 **		var -- filename
420 **		sff -- flags for safefile()
421 **		srv -- server side?
422 **
423 **	Returns:
424 **		ok?
425 */
426 
427 static bool
428 tls_safe_f(var, sff, srv)
429 	char *var;
430 	long sff;
431 	bool srv;
432 {
433 	int ret;
434 
435 	if ((ret = safefile(var, RunAsUid, RunAsGid, RunAsUserName, sff,
436 			    S_IRUSR, NULL)) == 0)
437 		return true;
438 	if (LogLevel > 7)
439 		sm_syslog(LOG_WARNING, NOQID, "STARTTLS=%s: file %s unsafe: %s",
440 			  srv ? "server" : "client", var, sm_errstring(ret));
441 	return false;
442 }
443 
444 /*
445 **  TLS_OK_F -- macro to simplify calls to tls_ok_f
446 **
447 **	Parameters:
448 **		var -- filename
449 **		fn -- what is the filename used for?
450 **		req -- is the file required?
451 **		st -- status bit to set if ok
452 **		type -- type of variable
453 **
454 **	Side Effects:
455 **		uses r, ok; may change ok and status.
456 **
457 */
458 
459 # define TLS_OK_F(var, fn, req, st, type) if (ok) \
460 	{ \
461 		r = tls_ok_f(var, fn, type); \
462 		if (r) \
463 			status |= st; \
464 		else if (req) \
465 			ok = false; \
466 	}
467 
468 /*
469 **  TLS_UNR -- macro to return whether a file should be unreadable
470 **
471 **	Parameters:
472 **		bit -- flag to test
473 **		req -- flags
474 **
475 **	Returns:
476 **		0/SFF_NORFILES
477 */
478 # define TLS_UNR(bit, req)	(bitset(bit, req) ? SFF_NORFILES : 0)
479 # define TLS_OUNR(bit, req)	(bitset(bit, req) ? SFF_NOWRFILES : 0)
480 # define TLS_KEYSFF(req)	\
481 	(bitnset(DBS_GROUPREADABLEKEYFILE, DontBlameSendmail) ?	\
482 		TLS_OUNR(TLS_I_KEY_OUNR, req) :			\
483 		TLS_UNR(TLS_I_KEY_UNR, req))
484 
485 /*
486 **  TLS_SAFE_F -- macro to simplify calls to tls_safe_f
487 **
488 **	Parameters:
489 **		var -- filename
490 **		sff -- flags for safefile()
491 **		req -- is the file required?
492 **		ex -- does the file exist?
493 **		st -- status bit to set if ok
494 **		srv -- server side?
495 **
496 **	Side Effects:
497 **		uses r, ok, ex; may change ok and status.
498 **
499 */
500 
501 # define TLS_SAFE_F(var, sff, req, ex, st, srv) if (ex && ok) \
502 	{ \
503 		r = tls_safe_f(var, sff, srv); \
504 		if (r) \
505 			status |= st;	\
506 		else if (req) \
507 			ok = false;	\
508 	}
509 
510 /*
511 **  INITTLS -- initialize TLS
512 **
513 **	Parameters:
514 **		ctx -- pointer to context
515 **		req -- requirements for initialization (see sendmail.h)
516 **		options -- options
517 **		srv -- server side?
518 **		certfile -- filename of certificate
519 **		keyfile -- filename of private key
520 **		cacertpath -- path to CAs
521 **		cacertfile -- file with CA(s)
522 **		dhparam -- parameters for DH
523 **
524 **	Returns:
525 **		succeeded?
526 */
527 
528 /*
529 **  The session_id_context identifies the service that created a session.
530 **  This information is used to distinguish between multiple TLS-based
531 **  servers running on the same server. We use the name of the mail system.
532 **  Note: the session cache is not persistent.
533 */
534 
535 static char server_session_id_context[] = "sendmail8";
536 
537 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
538 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
539 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG	1
540 #else
541 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG	0
542 #endif
543 
544 bool
545 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
546 	SSL_CTX **ctx;
547 	unsigned long req;
548 	long options;
549 	bool srv;
550 	char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
551 {
552 # if !NO_DH
553 	static DH *dh = NULL;
554 # endif /* !NO_DH */
555 	int r;
556 	bool ok;
557 	long sff, status;
558 	char *who;
559 # if _FFR_TLS_1
560 	char *cf2, *kf2;
561 # endif /* _FFR_TLS_1 */
562 #  if SM_CONF_SHM
563 	extern int ShmId;
564 #  endif /* SM_CONF_SHM */
565 # if OPENSSL_VERSION_NUMBER > 0x00907000L
566 	BIO *crl_file;
567 	X509_CRL *crl;
568 	X509_STORE *store;
569 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
570 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
571 	long rt_version;
572 	STACK_OF(SSL_COMP) *comp_methods;
573 #endif
574 
575 	status = TLS_S_NONE;
576 	who = srv ? "server" : "client";
577 	if (ctx == NULL)
578 	{
579 		syserr("STARTTLS=%s, inittls: ctx == NULL", who);
580 		/* NOTREACHED */
581 		SM_ASSERT(ctx != NULL);
582 	}
583 
584 	/* already initialized? (we could re-init...) */
585 	if (*ctx != NULL)
586 		return true;
587 	ok = true;
588 
589 # if _FFR_TLS_1
590 	/*
591 	**  look for a second filename: it must be separated by a ','
592 	**  no blanks allowed (they won't be skipped).
593 	**  we change a global variable here! this change will be undone
594 	**  before return from the function but only if it returns true.
595 	**  this isn't a problem since in a failure case this function
596 	**  won't be called again with the same (overwritten) values.
597 	**  otherwise each return must be replaced with a goto endinittls.
598 	*/
599 
600 	cf2 = NULL;
601 	kf2 = NULL;
602 	if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
603 	{
604 		*cf2++ = '\0';
605 		if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
606 			*kf2++ = '\0';
607 	}
608 # endif /* _FFR_TLS_1 */
609 
610 	/*
611 	**  Check whether files/paths are defined
612 	*/
613 
614 	TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
615 		 TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
616 	TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
617 		 TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
618 	TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
619 		 TLS_S_CERTP_EX, TLS_T_OTHER);
620 	TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
621 		 TLS_S_CERTF_EX, TLS_T_OTHER);
622 
623 # if OPENSSL_VERSION_NUMBER > 0x00907000L
624 	TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
625 		 TLS_S_CRLF_EX, TLS_T_OTHER);
626 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
627 
628 # if _FFR_TLS_1
629 	/*
630 	**  if the second file is specified it must exist
631 	**  XXX: it is possible here to define only one of those files
632 	*/
633 
634 	if (cf2 != NULL)
635 	{
636 		TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
637 			 TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
638 	}
639 	if (kf2 != NULL)
640 	{
641 		TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
642 			 TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
643 	}
644 # endif /* _FFR_TLS_1 */
645 
646 	/*
647 	**  valid values for dhparam are (only the first char is checked)
648 	**  none	no parameters: don't use DH
649 	**  512		use precomputed 512 bit parameters
650 	**  1024	generate 1024 bit parameters
651 	**  2048	generate 2048 bit parameters
652 	**  /file/name	read parameters from /file/name
653 	**  default is: 1024
654 	*/
655 
656 	if (bitset(TLS_I_TRY_DH, req))
657 	{
658 		if (dhparam != NULL)
659 		{
660 			char c = *dhparam;
661 
662 			if (c == '1')
663 				req |= TLS_I_DH1024;
664 			else if (c == '2')
665 				req |= TLS_I_DH2048;
666 			else if (c == '5')
667 				req |= TLS_I_DH512;
668 			else if (c != 'n' && c != 'N' && c != '/')
669 			{
670 				if (LogLevel > 12)
671 					sm_syslog(LOG_WARNING, NOQID,
672 						  "STARTTLS=%s, error: illegal value '%s' for DHParam",
673 						  who, dhparam);
674 				dhparam = NULL;
675 			}
676 		}
677 		if (dhparam == NULL)
678 		{
679 			dhparam = "1";
680 			req |= TLS_I_DH1024;
681 		}
682 		else if (*dhparam == '/')
683 		{
684 			TLS_OK_F(dhparam, "DHParameters",
685 				 bitset(TLS_I_DHPAR_EX, req),
686 				 TLS_S_DHPAR_EX, TLS_T_OTHER);
687 		}
688 	}
689 	if (!ok)
690 		return ok;
691 
692 	/* certfile etc. must be "safe". */
693 	sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
694 	     | SFF_NOGWFILES | SFF_NOWWFILES
695 	     | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
696 	if (DontLockReadFiles)
697 		sff |= SFF_NOLOCK;
698 
699 	TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
700 		   bitset(TLS_I_CERT_EX, req),
701 		   bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
702 	TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
703 		   bitset(TLS_I_KEY_EX, req),
704 		   bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
705 	TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
706 		   bitset(TLS_I_CERTF_EX, req),
707 		   bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
708 	TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
709 		   bitset(TLS_I_DHPAR_EX, req),
710 		   bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
711 # if OPENSSL_VERSION_NUMBER > 0x00907000L
712 	TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
713 		   bitset(TLS_I_CRLF_EX, req),
714 		   bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
715 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
716 	if (!ok)
717 		return ok;
718 # if _FFR_TLS_1
719 	if (cf2 != NULL)
720 	{
721 		TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
722 			   bitset(TLS_I_CERT_EX, req),
723 			   bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
724 	}
725 	if (kf2 != NULL)
726 	{
727 		TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
728 			   bitset(TLS_I_KEY_EX, req),
729 			   bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
730 	}
731 # endif /* _FFR_TLS_1 */
732 
733 	/* create a method and a new context */
734 	if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
735 				      SSLv23_client_method())) == NULL)
736 	{
737 		if (LogLevel > 7)
738 			sm_syslog(LOG_WARNING, NOQID,
739 				  "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
740 				  who, who);
741 		if (LogLevel > 9)
742 			tlslogerr(LOG_WARNING, who);
743 		return false;
744 	}
745 
746 # if OPENSSL_VERSION_NUMBER > 0x00907000L
747 	if (CRLFile != NULL)
748 	{
749 		/* get a pointer to the current certificate validation store */
750 		store = SSL_CTX_get_cert_store(*ctx);	/* does not fail */
751 		crl_file = BIO_new(BIO_s_file_internal());
752 		if (crl_file != NULL)
753 		{
754 			if (BIO_read_filename(crl_file, CRLFile) >= 0)
755 			{
756 				crl = PEM_read_bio_X509_CRL(crl_file, NULL,
757 							NULL, NULL);
758 				BIO_free(crl_file);
759 				X509_STORE_add_crl(store, crl);
760 				X509_CRL_free(crl);
761 				X509_STORE_set_flags(store,
762 					X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
763 				X509_STORE_set_verify_cb_func(store,
764 						x509_verify_cb);
765 			}
766 			else
767 			{
768 				if (LogLevel > 9)
769 				{
770 					sm_syslog(LOG_WARNING, NOQID,
771 						  "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",
772 						  who, CRLFile);
773 				}
774 
775 				/* avoid memory leaks */
776 				BIO_free(crl_file);
777 				return false;
778 			}
779 
780 		}
781 		else if (LogLevel > 9)
782 			sm_syslog(LOG_WARNING, NOQID,
783 				  "STARTTLS=%s, error: BIO_new=failed", who);
784 	}
785 	else
786 		store = NULL;
787 #  if _FFR_CRLPATH
788 	if (CRLPath != NULL && store != NULL)
789 	{
790 		X509_LOOKUP *lookup;
791 
792 		lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
793 		if (lookup == NULL)
794 		{
795 			if (LogLevel > 9)
796 			{
797 				sm_syslog(LOG_WARNING, NOQID,
798 					  "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
799 					  who, CRLFile);
800 			}
801 			return false;
802 		}
803 		X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
804 		X509_STORE_set_flags(store,
805 			X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
806 	}
807 #  endif /* _FFR_CRLPATH */
808 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
809 
810 # if TLS_NO_RSA
811 	/* turn off backward compatibility, required for no-rsa */
812 	SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
813 # endif /* TLS_NO_RSA */
814 
815 
816 # if !TLS_NO_RSA
817 	/*
818 	**  Create a temporary RSA key
819 	**  XXX  Maybe we shouldn't create this always (even though it
820 	**  is only at startup).
821 	**  It is a time-consuming operation and it is not always necessary.
822 	**  maybe we should do it only on demand...
823 	*/
824 
825 	if (bitset(TLS_I_RSA_TMP, req)
826 #   if SM_CONF_SHM
827 	    && ShmId != SM_SHM_NO_ID &&
828 	    (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL,
829 					NULL)) == NULL
830 #   else /* SM_CONF_SHM */
831 	    && 0	/* no shared memory: no need to generate key now */
832 #   endif /* SM_CONF_SHM */
833 	   )
834 	{
835 		if (LogLevel > 7)
836 		{
837 			sm_syslog(LOG_WARNING, NOQID,
838 				  "STARTTLS=%s, error: RSA_generate_key failed",
839 				  who);
840 			if (LogLevel > 9)
841 				tlslogerr(LOG_WARNING, who);
842 		}
843 		return false;
844 	}
845 # endif /* !TLS_NO_RSA */
846 
847 	/*
848 	**  load private key
849 	**  XXX change this for DSA-only version
850 	*/
851 
852 	if (bitset(TLS_S_KEY_OK, status) &&
853 	    SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
854 					 SSL_FILETYPE_PEM) <= 0)
855 	{
856 		if (LogLevel > 7)
857 		{
858 			sm_syslog(LOG_WARNING, NOQID,
859 				  "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
860 				  who, keyfile);
861 			if (LogLevel > 9)
862 				tlslogerr(LOG_WARNING, who);
863 		}
864 		if (bitset(TLS_I_USE_KEY, req))
865 			return false;
866 	}
867 
868 	/* get the certificate file */
869 	if (bitset(TLS_S_CERT_OK, status) &&
870 	    SSL_CTX_use_certificate_file(*ctx, certfile,
871 					 SSL_FILETYPE_PEM) <= 0)
872 	{
873 		if (LogLevel > 7)
874 		{
875 			sm_syslog(LOG_WARNING, NOQID,
876 				  "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
877 				  who, certfile);
878 			if (LogLevel > 9)
879 				tlslogerr(LOG_WARNING, who);
880 		}
881 		if (bitset(TLS_I_USE_CERT, req))
882 			return false;
883 	}
884 
885 	/* check the private key */
886 	if (bitset(TLS_S_KEY_OK, status) &&
887 	    (r = SSL_CTX_check_private_key(*ctx)) <= 0)
888 	{
889 		/* Private key does not match the certificate public key */
890 		if (LogLevel > 5)
891 		{
892 			sm_syslog(LOG_WARNING, NOQID,
893 				  "STARTTLS=%s, error: SSL_CTX_check_private_key failed(%s): %d",
894 				  who, keyfile, r);
895 			if (LogLevel > 9)
896 				tlslogerr(LOG_WARNING, who);
897 		}
898 		if (bitset(TLS_I_USE_KEY, req))
899 			return false;
900 	}
901 
902 # if _FFR_TLS_1
903 	/* XXX this code is pretty much duplicated from above! */
904 
905 	/* load private key */
906 	if (bitset(TLS_S_KEY2_OK, status) &&
907 	    SSL_CTX_use_PrivateKey_file(*ctx, kf2, SSL_FILETYPE_PEM) <= 0)
908 	{
909 		if (LogLevel > 7)
910 		{
911 			sm_syslog(LOG_WARNING, NOQID,
912 				  "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
913 				  who, kf2);
914 			if (LogLevel > 9)
915 				tlslogerr(LOG_WARNING, who);
916 		}
917 	}
918 
919 	/* get the certificate file */
920 	if (bitset(TLS_S_CERT2_OK, status) &&
921 	    SSL_CTX_use_certificate_file(*ctx, cf2, SSL_FILETYPE_PEM) <= 0)
922 	{
923 		if (LogLevel > 7)
924 		{
925 			sm_syslog(LOG_WARNING, NOQID,
926 				  "STARTTLS=%s, error: SSL_CTX_use_certificate_file(%s) failed",
927 				  who, cf2);
928 			if (LogLevel > 9)
929 				tlslogerr(LOG_WARNING, who);
930 		}
931 	}
932 
933 	/* also check the private key */
934 	if (bitset(TLS_S_KEY2_OK, status) &&
935 	    (r = SSL_CTX_check_private_key(*ctx)) <= 0)
936 	{
937 		/* Private key does not match the certificate public key */
938 		if (LogLevel > 5)
939 		{
940 			sm_syslog(LOG_WARNING, NOQID,
941 				  "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
942 				  who, r);
943 			if (LogLevel > 9)
944 				tlslogerr(LOG_WARNING, who);
945 		}
946 	}
947 # endif /* _FFR_TLS_1 */
948 
949 	/* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
950 
951 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
952 
953 	/*
954 	**  In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
955 	**  padding bug work-around, leading to false positives and
956 	**  failed connections. We may not interoperate with systems
957 	**  with the bug, but this is better than breaking on all 0.9.8[ab]
958 	**  systems that have zlib support enabled.
959 	**  Note: this checks the runtime version of the library, not
960 	**  just the compile time version.
961 	*/
962 
963 	rt_version = SSLeay();
964 	if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
965 	{
966 		comp_methods = SSL_COMP_get_compression_methods();
967 		if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
968 			options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
969 	}
970 #endif
971 	SSL_CTX_set_options(*ctx, options);
972 
973 # if !NO_DH
974 	/* Diffie-Hellman initialization */
975 	if (bitset(TLS_I_TRY_DH, req))
976 	{
977 #if _FFR_TLS_EC
978 		EC_KEY *ecdh;
979 #endif /* _FFR_TLS_EC */
980 		if (bitset(TLS_S_DHPAR_OK, status))
981 		{
982 			BIO *bio;
983 
984 			if ((bio = BIO_new_file(dhparam, "r")) != NULL)
985 			{
986 				dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
987 				BIO_free(bio);
988 				if (dh == NULL && LogLevel > 7)
989 				{
990 					unsigned long err;
991 
992 					err = ERR_get_error();
993 					sm_syslog(LOG_WARNING, NOQID,
994 						  "STARTTLS=%s, error: cannot read DH parameters(%s): %s",
995 						  who, dhparam,
996 						  ERR_error_string(err, NULL));
997 					if (LogLevel > 9)
998 						tlslogerr(LOG_WARNING, who);
999 				}
1000 			}
1001 			else
1002 			{
1003 				if (LogLevel > 5)
1004 				{
1005 					sm_syslog(LOG_WARNING, NOQID,
1006 						  "STARTTLS=%s, error: BIO_new_file(%s) failed",
1007 						  who, dhparam);
1008 					if (LogLevel > 9)
1009 						tlslogerr(LOG_WARNING, who);
1010 				}
1011 			}
1012 		}
1013 		if (dh == NULL && bitset(TLS_I_DH1024|TLS_I_DH2048, req))
1014 		{
1015 			int bits;
1016 			DSA *dsa;
1017 
1018 			bits = bitset(TLS_I_DH2048, req) ? 2048 : 1024;
1019 			if (tTd(96, 2))
1020 				sm_dprintf("inittls: Generating %d bit DH parameters\n", bits);
1021 
1022 			/* this takes a while! */
1023 			dsa = DSA_generate_parameters(bits, NULL, 0, NULL,
1024 						      NULL, 0, NULL);
1025 			dh = DSA_dup_DH(dsa);
1026 			DSA_free(dsa);
1027 		}
1028 		else
1029 		if (dh == NULL && bitset(TLS_I_DH512, req))
1030 		{
1031 			if (tTd(96, 2))
1032 				sm_dprintf("inittls: Using precomputed 512 bit DH parameters\n");
1033 			dh = get_dh512();
1034 		}
1035 
1036 		if (dh == NULL)
1037 		{
1038 			if (LogLevel > 9)
1039 			{
1040 				unsigned long err;
1041 
1042 				err = ERR_get_error();
1043 				sm_syslog(LOG_WARNING, NOQID,
1044 					  "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1045 					  who, dhparam,
1046 					  ERR_error_string(err, NULL));
1047 			}
1048 			if (bitset(TLS_I_REQ_DH, req))
1049 				return false;
1050 		}
1051 		else
1052 		{
1053 			/* important to avoid small subgroup attacks */
1054 			SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
1055 
1056 			SSL_CTX_set_tmp_dh(*ctx, dh);
1057 			if (LogLevel > 13)
1058 				sm_syslog(LOG_INFO, NOQID,
1059 					  "STARTTLS=%s, Diffie-Hellman init, key=%d bit (%c)",
1060 					  who, 8 * DH_size(dh), *dhparam);
1061 			DH_free(dh);
1062 		}
1063 
1064 #if _FFR_TLS_EC
1065 		ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1066 		if (ecdh != NULL)
1067 		{
1068 			SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_ECDH_USE);
1069 			SSL_CTX_set_tmp_ecdh(*ctx, ecdh);
1070 			EC_KEY_free(ecdh);
1071 		}
1072 #endif /* _FFR_TLS_EC */
1073 
1074 	}
1075 # endif /* !NO_DH */
1076 
1077 
1078 	/* XXX do we need this cache here? */
1079 	if (bitset(TLS_I_CACHE, req))
1080 	{
1081 		SSL_CTX_sess_set_cache_size(*ctx, 1);
1082 		SSL_CTX_set_timeout(*ctx, 1);
1083 		SSL_CTX_set_session_id_context(*ctx,
1084 			(void *) &server_session_id_context,
1085 			sizeof(server_session_id_context));
1086 		(void) SSL_CTX_set_session_cache_mode(*ctx,
1087 				SSL_SESS_CACHE_SERVER);
1088 	}
1089 	else
1090 	{
1091 		(void) SSL_CTX_set_session_cache_mode(*ctx,
1092 				SSL_SESS_CACHE_OFF);
1093 	}
1094 
1095 	/* load certificate locations and default CA paths */
1096 	if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1097 	{
1098 		if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1099 						       cacertpath)) == 1)
1100 		{
1101 # if !TLS_NO_RSA
1102 			if (bitset(TLS_I_RSA_TMP, req))
1103 				SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1104 # endif /* !TLS_NO_RSA */
1105 
1106 			/*
1107 			**  We have to install our own verify callback:
1108 			**  SSL_VERIFY_PEER requests a client cert but even
1109 			**  though *FAIL_IF* isn't set, the connection
1110 			**  will be aborted if the client presents a cert
1111 			**  that is not "liked" (can't be verified?) by
1112 			**  the TLS library :-(
1113 			*/
1114 
1115 			/*
1116 			**  XXX currently we could call tls_set_verify()
1117 			**  but we hope that that function will later on
1118 			**  only set the mode per connection.
1119 			*/
1120 			SSL_CTX_set_verify(*ctx,
1121 				bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1122 							   : SSL_VERIFY_PEER,
1123 				NULL);
1124 
1125 			/* install verify callback */
1126 			SSL_CTX_set_cert_verify_callback(*ctx, tls_verify_cb,
1127 							 NULL);
1128 			SSL_CTX_set_client_CA_list(*ctx,
1129 				SSL_load_client_CA_file(cacertfile));
1130 		}
1131 		else
1132 		{
1133 			/*
1134 			**  can't load CA data; do we care?
1135 			**  the data is necessary to authenticate the client,
1136 			**  which in turn would be necessary
1137 			**  if we want to allow relaying based on it.
1138 			*/
1139 			if (LogLevel > 5)
1140 			{
1141 				sm_syslog(LOG_WARNING, NOQID,
1142 					  "STARTTLS=%s, error: load verify locs %s, %s failed: %d",
1143 					  who, cacertpath, cacertfile, r);
1144 				if (LogLevel > 9)
1145 					tlslogerr(LOG_WARNING, who);
1146 			}
1147 			if (bitset(TLS_I_VRFY_LOC, req))
1148 				return false;
1149 		}
1150 	}
1151 
1152 	/* XXX: make this dependent on an option? */
1153 	if (tTd(96, 9))
1154 		SSL_CTX_set_info_callback(*ctx, apps_ssl_info_cb);
1155 
1156 # if _FFR_TLS_1
1157 	/* install our own cipher list */
1158 	if (CipherList != NULL && *CipherList != '\0')
1159 	{
1160 		if (SSL_CTX_set_cipher_list(*ctx, CipherList) <= 0)
1161 		{
1162 			if (LogLevel > 7)
1163 			{
1164 				sm_syslog(LOG_WARNING, NOQID,
1165 					  "STARTTLS=%s, error: SSL_CTX_set_cipher_list(%s) failed, list ignored",
1166 					  who, CipherList);
1167 
1168 				if (LogLevel > 9)
1169 					tlslogerr(LOG_WARNING, who);
1170 			}
1171 			/* failure if setting to this list is required? */
1172 		}
1173 	}
1174 # endif /* _FFR_TLS_1 */
1175 	if (LogLevel > 12)
1176 		sm_syslog(LOG_INFO, NOQID, "STARTTLS=%s, init=%d", who, ok);
1177 
1178 # if _FFR_TLS_1
1179 #  if 0
1180 	/*
1181 	**  this label is required if we want to have a "clean" exit
1182 	**  see the comments above at the initialization of cf2
1183 	*/
1184 
1185     endinittls:
1186 #  endif /* 0 */
1187 
1188 	/* undo damage to global variables */
1189 	if (cf2 != NULL)
1190 		*--cf2 = ',';
1191 	if (kf2 != NULL)
1192 		*--kf2 = ',';
1193 # endif /* _FFR_TLS_1 */
1194 
1195 	return ok;
1196 }
1197 /*
1198 **  TLS_GET_INFO -- get information about TLS connection
1199 **
1200 **	Parameters:
1201 **		ssl -- TLS connection structure
1202 **		srv -- server or client
1203 **		host -- hostname of other side
1204 **		mac -- macro storage
1205 **		certreq -- did we ask for a cert?
1206 **
1207 **	Returns:
1208 **		result of authentication.
1209 **
1210 **	Side Effects:
1211 **		sets macros: {cipher}, {tls_version}, {verify},
1212 **		{cipher_bits}, {alg_bits}, {cert}, {cert_subject},
1213 **		{cert_issuer}, {cn_subject}, {cn_issuer}
1214 */
1215 
1216 int
1217 tls_get_info(ssl, srv, host, mac, certreq)
1218 	SSL *ssl;
1219 	bool srv;
1220 	char *host;
1221 	MACROS_T *mac;
1222 	bool certreq;
1223 {
1224 	const SSL_CIPHER *c;
1225 	int b, r;
1226 	long verifyok;
1227 	char *s, *who;
1228 	char bitstr[16];
1229 	X509 *cert;
1230 
1231 	c = SSL_get_current_cipher(ssl);
1232 
1233 	/* cast is just workaround for compiler warning */
1234 	macdefine(mac, A_TEMP, macid("{cipher}"),
1235 		  (char *) SSL_CIPHER_get_name(c));
1236 	b = SSL_CIPHER_get_bits(c, &r);
1237 	(void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1238 	macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1239 	(void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1240 	macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1241 	s = SSL_CIPHER_get_version(c);
1242 	if (s == NULL)
1243 		s = "UNKNOWN";
1244 	macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1245 
1246 	who = srv ? "server" : "client";
1247 	cert = SSL_get_peer_certificate(ssl);
1248 	verifyok = SSL_get_verify_result(ssl);
1249 	if (LogLevel > 14)
1250 		sm_syslog(LOG_INFO, NOQID,
1251 			  "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1252 			  who, verifyok, (unsigned long) cert);
1253 	if (cert != NULL)
1254 	{
1255 		unsigned int n;
1256 		X509_NAME *subj, *issuer;
1257 		unsigned char md[EVP_MAX_MD_SIZE];
1258 		char buf[MAXNAME];
1259 
1260 		subj = X509_get_subject_name(cert);
1261 		issuer = X509_get_issuer_name(cert);
1262 		X509_NAME_oneline(subj, buf, sizeof(buf));
1263 		macdefine(mac, A_TEMP, macid("{cert_subject}"),
1264 			 xtextify(buf, "<>\")"));
1265 		X509_NAME_oneline(issuer, buf, sizeof(buf));
1266 		macdefine(mac, A_TEMP, macid("{cert_issuer}"),
1267 			 xtextify(buf, "<>\")"));
1268 
1269 # define LL_BADCERT	8
1270 
1271 #define CHECK_X509_NAME(which)	\
1272 	do {	\
1273 		if (r == -1)	\
1274 		{		\
1275 			sm_strlcpy(buf, "BadCertificateUnknown", sizeof(buf)); \
1276 			if (LogLevel > LL_BADCERT)	\
1277 				sm_syslog(LOG_INFO, NOQID,	\
1278 					"STARTTLS=%s, relay=%.100s, field=%s, status=failed to extract CN",	\
1279 					who,	\
1280 					host == NULL ? "local" : host,	\
1281 					which);	\
1282 		}		\
1283 		else if ((size_t)r >= sizeof(buf) - 1)	\
1284 		{		\
1285 			sm_strlcpy(buf, "BadCertificateTooLong", sizeof(buf)); \
1286 			if (LogLevel > 7)	\
1287 				sm_syslog(LOG_INFO, NOQID,	\
1288 					"STARTTLS=%s, relay=%.100s, field=%s, status=CN too long",	\
1289 					who,	\
1290 					host == NULL ? "local" : host,	\
1291 					which);	\
1292 		}		\
1293 		else if ((size_t)r > strlen(buf))	\
1294 		{		\
1295 			sm_strlcpy(buf, "BadCertificateContainsNUL",	\
1296 				sizeof(buf));	\
1297 			if (LogLevel > 7)	\
1298 				sm_syslog(LOG_INFO, NOQID,	\
1299 					"STARTTLS=%s, relay=%.100s, field=%s, status=CN contains NUL",	\
1300 					who,	\
1301 					host == NULL ? "local" : host,	\
1302 					which);	\
1303 		}		\
1304 	} while (0)
1305 
1306 		r = X509_NAME_get_text_by_NID(subj, NID_commonName, buf,
1307 			sizeof buf);
1308 		CHECK_X509_NAME("cn_subject");
1309 		macdefine(mac, A_TEMP, macid("{cn_subject}"),
1310 			 xtextify(buf, "<>\")"));
1311 		r = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf,
1312 			sizeof buf);
1313 		CHECK_X509_NAME("cn_issuer");
1314 		macdefine(mac, A_TEMP, macid("{cn_issuer}"),
1315 			 xtextify(buf, "<>\")"));
1316 		n = 0;
1317 		if (X509_digest(cert, EVP_md5(), md, &n) != 0 && n > 0)
1318 		{
1319 			char md5h[EVP_MAX_MD_SIZE * 3];
1320 			static const char hexcodes[] = "0123456789ABCDEF";
1321 
1322 			SM_ASSERT((n * 3) + 2 < sizeof(md5h));
1323 			for (r = 0; r < (int) n; r++)
1324 			{
1325 				md5h[r * 3] = hexcodes[(md[r] & 0xf0) >> 4];
1326 				md5h[(r * 3) + 1] = hexcodes[(md[r] & 0x0f)];
1327 				md5h[(r * 3) + 2] = ':';
1328 			}
1329 			md5h[(n * 3) - 1] = '\0';
1330 			macdefine(mac, A_TEMP, macid("{cert_md5}"), md5h);
1331 		}
1332 		else
1333 			macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1334 	}
1335 	else
1336 	{
1337 		macdefine(mac, A_PERM, macid("{cert_subject}"), "");
1338 		macdefine(mac, A_PERM, macid("{cert_issuer}"), "");
1339 		macdefine(mac, A_PERM, macid("{cn_subject}"), "");
1340 		macdefine(mac, A_PERM, macid("{cn_issuer}"), "");
1341 		macdefine(mac, A_TEMP, macid("{cert_md5}"), "");
1342 	}
1343 	switch (verifyok)
1344 	{
1345 	  case X509_V_OK:
1346 		if (cert != NULL)
1347 		{
1348 			s = "OK";
1349 			r = TLS_AUTH_OK;
1350 		}
1351 		else
1352 		{
1353 			s = certreq ? "NO" : "NOT",
1354 			r = TLS_AUTH_NO;
1355 		}
1356 		break;
1357 	  default:
1358 		s = "FAIL";
1359 		r = TLS_AUTH_FAIL;
1360 		break;
1361 	}
1362 	macdefine(mac, A_PERM, macid("{verify}"), s);
1363 	if (cert != NULL)
1364 		X509_free(cert);
1365 
1366 	/* do some logging */
1367 	if (LogLevel > 8)
1368 	{
1369 		char *vers, *s1, *s2, *cbits, *algbits;
1370 
1371 		vers = macget(mac, macid("{tls_version}"));
1372 		cbits = macget(mac, macid("{cipher_bits}"));
1373 		algbits = macget(mac, macid("{alg_bits}"));
1374 		s1 = macget(mac, macid("{verify}"));
1375 		s2 = macget(mac, macid("{cipher}"));
1376 
1377 		/* XXX: maybe cut off ident info? */
1378 		sm_syslog(LOG_INFO, NOQID,
1379 			  "STARTTLS=%s, relay=%.100s, version=%.16s, verify=%.16s, cipher=%.64s, bits=%.6s/%.6s",
1380 			  who,
1381 			  host == NULL ? "local" : host,
1382 			  vers, s1, s2, /* sm_snprintf() can deal with NULL */
1383 			  algbits == NULL ? "0" : algbits,
1384 			  cbits == NULL ? "0" : cbits);
1385 		if (LogLevel > 11)
1386 		{
1387 			/*
1388 			**  Maybe run xuntextify on the strings?
1389 			**  That is easier to read but makes it maybe a bit
1390 			**  more complicated to figure out the right values
1391 			**  for the access map...
1392 			*/
1393 
1394 			s1 = macget(mac, macid("{cert_subject}"));
1395 			s2 = macget(mac, macid("{cert_issuer}"));
1396 			sm_syslog(LOG_INFO, NOQID,
1397 				  "STARTTLS=%s, cert-subject=%.256s, cert-issuer=%.256s, verifymsg=%s",
1398 				  who, s1, s2,
1399 				  X509_verify_cert_error_string(verifyok));
1400 		}
1401 	}
1402 	return r;
1403 }
1404 /*
1405 **  ENDTLS -- shutdown secure connection
1406 **
1407 **	Parameters:
1408 **		ssl -- SSL connection information.
1409 **		side -- server/client (for logging).
1410 **
1411 **	Returns:
1412 **		success? (EX_* code)
1413 */
1414 
1415 int
1416 endtls(ssl, side)
1417 	SSL *ssl;
1418 	char *side;
1419 {
1420 	int ret = EX_OK;
1421 
1422 	if (ssl != NULL)
1423 	{
1424 		int r;
1425 
1426 		if ((r = SSL_shutdown(ssl)) < 0)
1427 		{
1428 			if (LogLevel > 11)
1429 			{
1430 				sm_syslog(LOG_WARNING, NOQID,
1431 					  "STARTTLS=%s, SSL_shutdown failed: %d",
1432 					  side, r);
1433 				tlslogerr(LOG_WARNING, side);
1434 			}
1435 			ret = EX_SOFTWARE;
1436 		}
1437 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1438 
1439 		/*
1440 		**  Bug in OpenSSL (at least up to 0.9.6b):
1441 		**  From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1442 		**  Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1443 		**  To: openssl-users@openssl.org
1444 		**  Subject: Re: SSL_shutdown() woes (fwd)
1445 		**
1446 		**  The side sending the shutdown alert first will
1447 		**  not care about the answer of the peer but will
1448 		**  immediately return with a return value of "0"
1449 		**  (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1450 		**  the value of "0" and as the shutdown alert of the peer was
1451 		**  not received (actually, the program did not even wait for
1452 		**  the answer), an SSL_ERROR_SYSCALL is flagged, because this
1453 		**  is the default rule in case everything else does not apply.
1454 		**
1455 		**  For your server the problem is different, because it
1456 		**  receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1457 		**  then sends its response (SSL_SENT_SHUTDOWN), so for the
1458 		**  server the shutdown was successfull.
1459 		**
1460 		**  As is by know, you would have to call SSL_shutdown() once
1461 		**  and ignore an SSL_ERROR_SYSCALL returned. Then call
1462 		**  SSL_shutdown() again to actually get the server's response.
1463 		**
1464 		**  In the last discussion, Bodo Moeller concluded that a
1465 		**  rewrite of the shutdown code would be necessary, but
1466 		**  probably with another API, as the change would not be
1467 		**  compatible to the way it is now.  Things do not become
1468 		**  easier as other programs do not follow the shutdown
1469 		**  guidelines anyway, so that a lot error conditions and
1470 		**  compitibility issues would have to be caught.
1471 		**
1472 		**  For now the recommondation is to ignore the error message.
1473 		*/
1474 
1475 		else if (r == 0)
1476 		{
1477 			if (LogLevel > 15)
1478 			{
1479 				sm_syslog(LOG_WARNING, NOQID,
1480 					  "STARTTLS=%s, SSL_shutdown not done",
1481 					  side);
1482 				tlslogerr(LOG_WARNING, side);
1483 			}
1484 			ret = EX_SOFTWARE;
1485 		}
1486 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1487 		SSL_free(ssl);
1488 		ssl = NULL;
1489 	}
1490 	return ret;
1491 }
1492 
1493 # if !TLS_NO_RSA
1494 /*
1495 **  TMP_RSA_KEY -- return temporary RSA key
1496 **
1497 **	Parameters:
1498 **		s -- TLS connection structure
1499 **		export --
1500 **		keylength --
1501 **
1502 **	Returns:
1503 **		temporary RSA key.
1504 */
1505 
1506 #   ifndef MAX_RSA_TMP_CNT
1507 #    define MAX_RSA_TMP_CNT	1000	/* XXX better value? */
1508 #   endif /* ! MAX_RSA_TMP_CNT */
1509 
1510 /* ARGUSED0 */
1511 static RSA *
1512 tmp_rsa_key(s, export, keylength)
1513 	SSL *s;
1514 	int export;
1515 	int keylength;
1516 {
1517 #   if SM_CONF_SHM
1518 	extern int ShmId;
1519 	extern int *PRSATmpCnt;
1520 
1521 	if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1522 	    ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1523 		return rsa_tmp;
1524 #   endif /* SM_CONF_SHM */
1525 
1526 	if (rsa_tmp != NULL)
1527 		RSA_free(rsa_tmp);
1528 	rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL);
1529 	if (rsa_tmp == NULL)
1530 	{
1531 		if (LogLevel > 0)
1532 			sm_syslog(LOG_ERR, NOQID,
1533 				  "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1534 	}
1535 	else
1536 	{
1537 #   if SM_CONF_SHM
1538 #    if 0
1539 		/*
1540 		**  XXX we can't (yet) share the new key...
1541 		**	The RSA structure contains pointers hence it can't be
1542 		**	easily kept in shared memory.  It must be transformed
1543 		**	into a continous memory region first, then stored,
1544 		**	and later read out again (each time re-transformed).
1545 		*/
1546 
1547 		if (ShmId != SM_SHM_NO_ID)
1548 			*PRSATmpCnt = 0;
1549 #    endif /* 0 */
1550 #   endif /* SM_CONF_SHM */
1551 		if (LogLevel > 9)
1552 			sm_syslog(LOG_ERR, NOQID,
1553 				  "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1554 	}
1555 	return rsa_tmp;
1556 }
1557 # endif /* !TLS_NO_RSA */
1558 /*
1559 **  APPS_SSL_INFO_CB -- info callback for TLS connections
1560 **
1561 **	Parameters:
1562 **		s -- TLS connection structure
1563 **		where -- state in handshake
1564 **		ret -- return code of last operation
1565 **
1566 **	Returns:
1567 **		none.
1568 */
1569 
1570 static void
1571 apps_ssl_info_cb(s, where, ret)
1572 	CONST097 SSL *s;
1573 	int where;
1574 	int ret;
1575 {
1576 	int w;
1577 	char *str;
1578 	BIO *bio_err = NULL;
1579 
1580 	if (LogLevel > 14)
1581 		sm_syslog(LOG_INFO, NOQID,
1582 			  "STARTTLS: info_callback where=0x%x, ret=%d",
1583 			  where, ret);
1584 
1585 	w = where & ~SSL_ST_MASK;
1586 	if (bio_err == NULL)
1587 		bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
1588 
1589 	if (bitset(SSL_ST_CONNECT, w))
1590 		str = "SSL_connect";
1591 	else if (bitset(SSL_ST_ACCEPT, w))
1592 		str = "SSL_accept";
1593 	else
1594 		str = "undefined";
1595 
1596 	if (bitset(SSL_CB_LOOP, where))
1597 	{
1598 		if (LogLevel > 12)
1599 			sm_syslog(LOG_NOTICE, NOQID,
1600 				"STARTTLS: %s:%s",
1601 				str, SSL_state_string_long(s));
1602 	}
1603 	else if (bitset(SSL_CB_ALERT, where))
1604 	{
1605 		str = bitset(SSL_CB_READ, where) ? "read" : "write";
1606 		if (LogLevel > 12)
1607 			sm_syslog(LOG_NOTICE, NOQID,
1608 				"STARTTLS: SSL3 alert %s:%s:%s",
1609 				str, SSL_alert_type_string_long(ret),
1610 				SSL_alert_desc_string_long(ret));
1611 	}
1612 	else if (bitset(SSL_CB_EXIT, where))
1613 	{
1614 		if (ret == 0)
1615 		{
1616 			if (LogLevel > 7)
1617 				sm_syslog(LOG_WARNING, NOQID,
1618 					"STARTTLS: %s:failed in %s",
1619 					str, SSL_state_string_long(s));
1620 		}
1621 		else if (ret < 0)
1622 		{
1623 			if (LogLevel > 7)
1624 				sm_syslog(LOG_WARNING, NOQID,
1625 					"STARTTLS: %s:error in %s",
1626 					str, SSL_state_string_long(s));
1627 		}
1628 	}
1629 }
1630 /*
1631 **  TLS_VERIFY_LOG -- log verify error for TLS certificates
1632 **
1633 **	Parameters:
1634 **		ok -- verify ok?
1635 **		ctx -- x509 context
1636 **
1637 **	Returns:
1638 **		0 -- fatal error
1639 **		1 -- ok
1640 */
1641 
1642 static int
1643 tls_verify_log(ok, ctx, name)
1644 	int ok;
1645 	X509_STORE_CTX *ctx;
1646 	char *name;
1647 {
1648 	SSL *ssl;
1649 	X509 *cert;
1650 	int reason, depth;
1651 	char buf[512];
1652 
1653 	cert = X509_STORE_CTX_get_current_cert(ctx);
1654 	reason = X509_STORE_CTX_get_error(ctx);
1655 	depth = X509_STORE_CTX_get_error_depth(ctx);
1656 	ssl = (SSL *) X509_STORE_CTX_get_ex_data(ctx,
1657 			SSL_get_ex_data_X509_STORE_CTX_idx());
1658 
1659 	if (ssl == NULL)
1660 	{
1661 		/* internal error */
1662 		sm_syslog(LOG_ERR, NOQID,
1663 			  "STARTTLS: internal error: tls_verify_cb: ssl == NULL");
1664 		return 0;
1665 	}
1666 
1667 	X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1668 	sm_syslog(LOG_INFO, NOQID,
1669 		  "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1670 		  name, depth, buf, ok, X509_verify_cert_error_string(reason));
1671 	return 1;
1672 }
1673 
1674 /*
1675 **  TLS_VERIFY_CB -- verify callback for TLS certificates
1676 **
1677 **	Parameters:
1678 **		ctx -- x509 context
1679 **
1680 **	Returns:
1681 **		accept connection?
1682 **		currently: always yes.
1683 */
1684 
1685 static int
1686 #  if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1687 tls_verify_cb(ctx)
1688 	X509_STORE_CTX *ctx;
1689 #  else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1690 tls_verify_cb(ctx, unused)
1691 	X509_STORE_CTX *ctx;
1692 	void *unused;
1693 #  endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1694 {
1695 	int ok;
1696 
1697 	/*
1698 	**  man SSL_CTX_set_cert_verify_callback():
1699 	**  callback should return 1 to indicate verification success
1700 	**  and 0 to indicate verification failure.
1701 	*/
1702 
1703 	ok = X509_verify_cert(ctx);
1704 	if (ok <= 0)
1705 	{
1706 		if (LogLevel > 13)
1707 			return tls_verify_log(ok, ctx, "TLS");
1708 	}
1709 	return 1;
1710 }
1711 /*
1712 **  TLSLOGERR -- log the errors from the TLS error stack
1713 **
1714 **	Parameters:
1715 **		level -- syslog level
1716 **		who -- server/client (for logging).
1717 **
1718 **	Returns:
1719 **		none.
1720 */
1721 
1722 void
1723 tlslogerr(level, who)
1724 	int level;
1725 	const char *who;
1726 {
1727 	unsigned long l;
1728 	int line, flags;
1729 	unsigned long es;
1730 	char *file, *data;
1731 	char buf[256];
1732 #  define CP (const char **)
1733 
1734 	es = CRYPTO_thread_id();
1735 	while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags))
1736 		!= 0)
1737 	{
1738 		sm_syslog(level, NOQID,
1739 			  "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1740 			  ERR_error_string(l, buf),
1741 			  file, line,
1742 			  bitset(ERR_TXT_STRING, flags) ? data : "");
1743 	}
1744 }
1745 
1746 # if OPENSSL_VERSION_NUMBER > 0x00907000L
1747 /*
1748 **  X509_VERIFY_CB -- verify callback
1749 **
1750 **	Parameters:
1751 **		ctx -- x509 context
1752 **
1753 **	Returns:
1754 **		accept connection?
1755 **		currently: always yes.
1756 */
1757 
1758 static int
1759 x509_verify_cb(ok, ctx)
1760 	int ok;
1761 	X509_STORE_CTX *ctx;
1762 {
1763 	if (ok == 0)
1764 	{
1765 		if (LogLevel > 13)
1766 			tls_verify_log(ok, ctx, "x509");
1767 		if (ctx->error == X509_V_ERR_UNABLE_TO_GET_CRL)
1768 		{
1769 			ctx->error = 0;
1770 			return 1;	/* override it */
1771 		}
1772 	}
1773 	return ok;
1774 }
1775 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1776 #endif /* STARTTLS */
1777