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