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