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