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