xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_misc.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: tls_misc.c,v 1.1.1.7 2013/09/25 19:06:33 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	tls_misc 3
6 /* SUMMARY
7 /*	miscellaneous TLS support routines
8 /* SYNOPSIS
9 /*	#define TLS_INTERNAL
10 /*	#include <tls.h>
11 /*
12 /*	char	*var_tls_high_clist;
13 /*	char	*var_tls_medium_clist;
14 /*	char	*var_tls_low_clist;
15 /*	char	*var_tls_export_clist;
16 /*	char	*var_tls_null_clist;
17 /*	char	*var_tls_eecdh_strong;
18 /*	char	*var_tls_eecdh_ultra;
19 /*	int	var_tls_daemon_rand_bytes;
20 /*	bool    var_tls_append_def_CA;
21 /*	bool	var_tls_preempt_clist;
22 /*	bool	var_tls_bc_pkey_fprint;
23 /*
24 /*	TLS_APPL_STATE *tls_alloc_app_context(ssl_ctx, log_mask)
25 /*	SSL_CTX	*ssl_ctx;
26 /*	int	log_mask;
27 /*
28 /*	void	tls_free_app_context(app_ctx)
29 /*	void	*app_ctx;
30 /*
31 /*	TLS_SESS_STATE *tls_alloc_sess_context(log_mask, namaddr)
32 /*	int	log_mask;
33 /*	const char *namaddr;
34 /*
35 /*	void	tls_free_context(TLScontext)
36 /*	TLS_SESS_STATE *TLScontext;
37 /*
38 /*	void	tls_check_version()
39 /*
40 /*	long	tls_bug_bits()
41 /*
42 /*	void	tls_param_init()
43 /*
44 /*	int	tls_protocol_mask(plist)
45 /*	const char *plist;
46 /*
47 /*	int	tls_cipher_grade(name)
48 /*	const char *name;
49 /*
50 /*	const char *str_tls_cipher_grade(grade)
51 /*	int	grade;
52 /*
53 /*	const char *tls_set_ciphers(app_ctx, context, grade, exclusions)
54 /*	TLS_APPL_STATE *app_ctx;
55 /*	const char *context;
56 /*	int	grade;
57 /*	const char *exclusions;
58 /*
59 /*	void	tls_print_errors()
60 /*
61 /*	void	tls_info_callback(ssl, where, ret)
62 /*	const SSL *ssl; /* unused */
63 /*	int	where;
64 /*	int	ret;
65 /*
66 /*	long	tls_bio_dump_cb(bio, cmd, argp, argi, argl, ret)
67 /*	BIO	*bio;
68 /*	int	cmd;
69 /*	const char *argp;
70 /*	int	argi;
71 /*	long	argl; /* unused */
72 /*	long	ret;
73 /*
74 /*	int	tls_log_mask(log_param, log_level)
75 /*	const char *log_param;
76 /*	const char *log_level;
77 /* DESCRIPTION
78 /*	This module implements routines that support the TLS client
79 /*	and server internals.
80 /*
81 /*	tls_alloc_app_context() creates an application context that
82 /*	holds the SSL context for the application and related cached state.
83 /*
84 /*	tls_free_app_context() deallocates the application context and its
85 /*	contents (the application context is stored outside the TLS library).
86 /*
87 /*	tls_alloc_sess_context() creates an initialized TLS session context
88 /*	structure with the specified log mask and peer name[addr].
89 /*
90 /*	tls_free_context() destroys a TLScontext structure
91 /*	together with OpenSSL structures that are attached to it.
92 /*
93 /*	tls_check_version() logs a warning when the run-time OpenSSL
94 /*	library differs in its major, minor or micro number from
95 /*	the compile-time OpenSSL headers.
96 /*
97 /*	tls_bug_bits() returns the bug compatibility mask appropriate
98 /*	for the run-time library. Some of the bug work-arounds are
99 /*	not appropriate for some library versions.
100 /*
101 /*	tls_param_init() loads main.cf parameters used internally in
102 /*	TLS library. Any errors are fatal.
103 /*
104 /*	tls_protocol_mask() returns a bitmask of excluded protocols, given
105 /*	a list (plist) of protocols to include or (preceded by a '!') exclude.
106 /*	If "plist" contains invalid protocol names, TLS_PROTOCOL_INVALID is
107 /*	returned and no warning is logged.
108 /*
109 /*	tls_cipher_grade() converts a case-insensitive cipher grade
110 /*	name (high, medium, low, export, null) to the corresponding
111 /*	TLS_CIPHER_ constant.  When the input specifies an unrecognized
112 /*	grade, tls_cipher_grade() logs no warning, and returns
113 /*	TLS_CIPHER_NONE.
114 /*
115 /*	str_tls_cipher_grade() converts a cipher grade to a name.
116 /*	When the input specifies an undefined grade, str_tls_cipher_grade()
117 /*	logs no warning, returns a null pointer.
118 /*
119 /*	tls_set_ciphers() generates a cipher list from the specified
120 /*	grade, minus any ciphers specified via a list of exclusions.
121 /*	The cipherlist is applied to the supplied SSL context if it
122 /*	is different from the most recently applied value. The return
123 /*	value is the cipherlist used and is overwritten upon each call.
124 /*	When the input is invalid, tls_set_ciphers() logs a warning with
125 /*	the specified context, and returns a null pointer result.
126 /*
127 /*	tls_print_errors() queries the OpenSSL error stack,
128 /*	logs the error messages, and clears the error stack.
129 /*
130 /*	tls_info_callback() is a call-back routine for the
131 /*	SSL_CTX_set_info_callback() routine. It logs SSL events
132 /*	to the Postfix logfile.
133 /*
134 /*	tls_bio_dump_cb() is a call-back routine for the
135 /*	BIO_set_callback() routine. It logs SSL content to the
136 /*	Postfix logfile.
137 /*
138 /*	tls_log_mask() converts a TLS log_level value from string
139 /*	to mask.  The main.cf parameter name is passed along for
140 /*	diagnostics.
141 /* LICENSE
142 /* .ad
143 /* .fi
144 /*	This software is free. You can do with it whatever you want.
145 /*	The original author kindly requests that you acknowledge
146 /*	the use of his software.
147 /* AUTHOR(S)
148 /*	Originally written by:
149 /*	Lutz Jaenicke
150 /*	BTU Cottbus
151 /*	Allgemeine Elektrotechnik
152 /*	Universitaetsplatz 3-4
153 /*	D-03044 Cottbus, Germany
154 /*
155 /*	Updated by:
156 /*	Wietse Venema
157 /*	IBM T.J. Watson Research
158 /*	P.O. Box 704
159 /*	Yorktown Heights, NY 10598, USA
160 /*
161 /*	Victor Duchovni
162 /*	Morgan Stanley
163 /*--*/
164 
165 /* System library. */
166 
167 #include <sys_defs.h>
168 #include <ctype.h>
169 #include <string.h>
170 
171 #ifdef USE_TLS
172 
173 /* Utility library. */
174 
175 #include <vstream.h>
176 #include <msg.h>
177 #include <mymalloc.h>
178 #include <vstring.h>
179 #include <stringops.h>
180 #include <argv.h>
181 #include <name_mask.h>
182 #include <name_code.h>
183 
184  /*
185   * Global library.
186   */
187 #include <mail_params.h>
188 #include <mail_conf.h>
189 
190  /*
191   * TLS library.
192   */
193 #define TLS_INTERNAL
194 #include <tls.h>
195 
196  /* Application-specific. */
197 
198  /*
199   * Tunable parameters.
200   */
201 char   *var_tls_high_clist;
202 char   *var_tls_medium_clist;
203 char   *var_tls_low_clist;
204 char   *var_tls_export_clist;
205 char   *var_tls_null_clist;
206 int     var_tls_daemon_rand_bytes;
207 char   *var_tls_eecdh_strong;
208 char   *var_tls_eecdh_ultra;
209 bool    var_tls_append_def_CA;
210 char   *var_tls_bug_tweaks;
211 bool    var_tls_bc_pkey_fprint;
212 
213 #ifdef VAR_TLS_PREEMPT_CLIST
214 bool    var_tls_preempt_clist;
215 
216 #endif
217 
218  /*
219   * Index to attach TLScontext pointers to SSL objects, so that they can be
220   * accessed by call-back routines.
221   */
222 int     TLScontext_index = -1;
223 
224  /*
225   * Protocol name <=> mask conversion.
226   */
227 static const NAME_CODE protocol_table[] = {
228     SSL_TXT_SSLV2, TLS_PROTOCOL_SSLv2,
229     SSL_TXT_SSLV3, TLS_PROTOCOL_SSLv3,
230     SSL_TXT_TLSV1, TLS_PROTOCOL_TLSv1,
231 #ifdef SSL_TXT_TLSV1_1
232     SSL_TXT_TLSV1_1, TLS_PROTOCOL_TLSv1_1,
233 #endif
234 #ifdef SSL_TXT_TLSV1_2
235     SSL_TXT_TLSV1_2, TLS_PROTOCOL_TLSv1_2,
236 #endif
237     0, TLS_PROTOCOL_INVALID,
238 };
239 
240  /*
241   * SSL_OP_MUMBLE bug work-around name <=> mask conversion.
242   */
243 #define NAMEBUG(x)	#x, SSL_OP_##x
244 static const LONG_NAME_MASK ssl_bug_tweaks[] = {
245 
246 #if defined(SSL_OP_MICROSOFT_SESS_ID_BUG)
247     NAMEBUG(MICROSOFT_SESS_ID_BUG),	/* 0x00000001L */
248 #endif
249 
250 #if defined(SSL_OP_NETSCAPE_CHALLENGE_BUG)
251     NAMEBUG(NETSCAPE_CHALLENGE_BUG),	/* 0x00000002L */
252 #endif
253 
254 #if defined(SSL_OP_LEGACY_SERVER_CONNECT)
255     NAMEBUG(LEGACY_SERVER_CONNECT),	/* 0x00000004L */
256 #endif
257 
258 #if defined(SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
259     NAMEBUG(NETSCAPE_REUSE_CIPHER_CHANGE_BUG),	/* 0x00000008L */
260     "CVE-2010-4180", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG,
261 #endif
262 
263 #if defined(SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG)
264     NAMEBUG(SSLREF2_REUSE_CERT_TYPE_BUG),	/* 0x00000010L */
265 #endif
266 
267 #if defined(SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
268     NAMEBUG(MICROSOFT_BIG_SSLV3_BUFFER),/* 0x00000020L	 */
269 #endif
270 
271 #if defined(SSL_OP_MSIE_SSLV2_RSA_PADDING)
272     NAMEBUG(MSIE_SSLV2_RSA_PADDING),	/* 0x00000040L */
273     "CVE-2005-2969", SSL_OP_MSIE_SSLV2_RSA_PADDING,
274 #endif
275 
276 #if defined(SSL_OP_SSLEAY_080_CLIENT_DH_BUG)
277     NAMEBUG(SSLEAY_080_CLIENT_DH_BUG),	/* 0x00000080L */
278 #endif
279 
280 #if defined(SSL_OP_TLS_D5_BUG)
281     NAMEBUG(TLS_D5_BUG),		/* 0x00000100L	 */
282 #endif
283 
284 #if defined(SSL_OP_TLS_BLOCK_PADDING_BUG)
285     NAMEBUG(TLS_BLOCK_PADDING_BUG),	/* 0x00000200L */
286 #endif
287 
288 #if defined(SSL_OP_TLS_ROLLBACK_BUG)
289     NAMEBUG(TLS_ROLLBACK_BUG),		/* 0x00000400L */
290 #endif
291 
292 #if defined(SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
293     NAMEBUG(DONT_INSERT_EMPTY_FRAGMENTS),	/* 0x00000800L */
294 #endif
295 
296 #if defined(SSL_OP_CRYPTOPRO_TLSEXT_BUG)
297     NAMEBUG(CRYPTOPRO_TLSEXT_BUG),	/* 0x80000000L */
298 #endif
299     0, 0,
300 };
301 
302  /*
303   * Ciphersuite name <=> code conversion.
304   */
305 const NAME_CODE tls_cipher_grade_table[] = {
306     "high", TLS_CIPHER_HIGH,
307     "medium", TLS_CIPHER_MEDIUM,
308     "low", TLS_CIPHER_LOW,
309     "export", TLS_CIPHER_EXPORT,
310     "null", TLS_CIPHER_NULL,
311     "invalid", TLS_CIPHER_NONE,
312     0, TLS_CIPHER_NONE,
313 };
314 
315  /*
316   * Log keyword <=> mask conversion.
317   */
318 #define TLS_LOG_0 TLS_LOG_NONE
319 #define TLS_LOG_1 TLS_LOG_SUMMARY
320 #define TLS_LOG_2 (TLS_LOG_1 | TLS_LOG_VERBOSE | TLS_LOG_CACHE | TLS_LOG_DEBUG)
321 #define TLS_LOG_3 (TLS_LOG_2 | TLS_LOG_TLSPKTS)
322 #define TLS_LOG_4 (TLS_LOG_3 | TLS_LOG_ALLPKTS)
323 
324 static const NAME_MASK tls_log_table[] = {
325     "0", TLS_LOG_0,
326     "none", TLS_LOG_NONE,
327     "1", TLS_LOG_1,
328     "routine", TLS_LOG_1,
329     "2", TLS_LOG_2,
330     "debug", TLS_LOG_2,
331     "3", TLS_LOG_3,
332     "ssl-expert", TLS_LOG_3,
333     "4", TLS_LOG_4,
334     "ssl-developer", TLS_LOG_4,
335     "5", TLS_LOG_4,			/* for good measure */
336     "6", TLS_LOG_4,			/* for good measure */
337     "7", TLS_LOG_4,			/* for good measure */
338     "8", TLS_LOG_4,			/* for good measure */
339     "9", TLS_LOG_4,			/* for good measure */
340     "summary", TLS_LOG_SUMMARY,
341     "untrusted", TLS_LOG_UNTRUSTED,
342     "peercert", TLS_LOG_PEERCERT,
343     "certmatch", TLS_LOG_CERTMATCH,
344     "verbose", TLS_LOG_VERBOSE,		/* Postfix TLS library verbose */
345     "cache", TLS_LOG_CACHE,
346     "ssl-debug", TLS_LOG_DEBUG,		/* SSL library debug/verbose */
347     "ssl-handshake-packet-dump", TLS_LOG_TLSPKTS,
348     "ssl-session-packet-dump", TLS_LOG_TLSPKTS | TLS_LOG_ALLPKTS,
349     0, 0,
350 };
351 
352  /*
353   * Parsed OpenSSL version number.
354   */
355 typedef struct {
356     int     major;
357     int     minor;
358     int     micro;
359     int     patch;
360     int     status;
361 } TLS_VINFO;
362 
363  /*
364   * OpenSSL adopted the cipher selection patch, so we don't expect any more
365   * broken ciphers other than AES and CAMELLIA.
366   */
367 typedef struct {
368     const char *ssl_name;
369     const int alg_bits;
370     const char *evp_name;
371 } cipher_probe_t;
372 
373 static const cipher_probe_t cipher_probes[] = {
374     "AES", 256, "AES-256-CBC",
375     "CAMELLIA", 256, "CAMELLIA-256-CBC",
376     0, 0, 0,
377 };
378 
379 /* tls_log_mask - Convert user TLS loglevel to internal log feature mask */
380 
381 int     tls_log_mask(const char *log_param, const char *log_level)
382 {
383     int     mask;
384 
385     mask = name_mask_opt(log_param, tls_log_table, log_level,
386 			 NAME_MASK_ANY_CASE | NAME_MASK_RETURN);
387     return (mask);
388 }
389 
390 /* tls_exclude_missing - Append exclusions for missing ciphers */
391 
392 static const char *tls_exclude_missing(SSL_CTX *ctx, VSTRING *buf)
393 {
394     const char *myname = "tls_exclude_missing";
395     static ARGV *exclude;		/* Cached */
396     SSL    *s = 0;
397 
398     STACK_OF(SSL_CIPHER) * ciphers;
399     SSL_CIPHER *c;
400     const cipher_probe_t *probe;
401     int     alg_bits;
402     int     num;
403     int     i;
404 
405     /*
406      * Process a list of probes which specify:
407      *
408      * An SSL cipher-suite name for a family of ciphers that use the same
409      * symmetric algorithm at two or more key sizes, typically 128/256 bits.
410      *
411      * The key size (typically 256) that OpenSSL fails to check, and assumes
412      * available when another key size (typically 128) is usable.
413      *
414      * The OpenSSL name of the symmetric algorithm associated with the SSL
415      * cipher-suite. Typically, this is MUMBLE-256-CBC, where "MUMBLE" is the
416      * name of the SSL cipher-suite that use the MUMBLE symmetric algorithm.
417      * On systems that support the required encryption algorithm, the name is
418      * listed in the output of "openssl list-cipher-algorithms".
419      *
420      * When an encryption algorithm is not available at the given key size but
421      * the corresponding OpenSSL cipher-suite contains ciphers that have have
422      * this key size, the problem ciphers are explicitly disabled in Postfix.
423      * The list is cached in the static "exclude" array.
424      */
425     if (exclude == 0) {
426 	exclude = argv_alloc(1);
427 
428 	/*
429 	 * Iterate over the probe list
430 	 */
431 	for (probe = cipher_probes; probe->ssl_name; ++probe) {
432 	    /* No exclusions if evp_name is a valid algorithm */
433 	    if (EVP_get_cipherbyname(probe->evp_name))
434 		continue;
435 
436 	    /*
437 	     * Sadly there is no SSL_CTX_get_ciphers() interface, so we are
438 	     * forced to allocate and free an SSL object. Fatal error if we
439 	     * can't allocate the SSL object.
440 	     */
441 	    ERR_clear_error();
442 	    if (s == 0 && (s = SSL_new(ctx)) == 0) {
443 		tls_print_errors();
444 		msg_fatal("%s: error allocating SSL object", myname);
445 	    }
446 
447 	    /*
448 	     * Cipher is not supported by libcrypto, nothing to do if also
449 	     * not supported by libssl. Flush the OpenSSL error stack.
450 	     *
451 	     * XXX: There may be additional places in pre-existing code where
452 	     * SSL errors are generated and ignored, that require a similar
453 	     * "flush". Better yet, is to always flush before calls that run
454 	     * tls_print_errors() on failure.
455 	     *
456 	     * Contrary to documentation, on SunOS 5.10 SSL_set_cipher_list()
457 	     * returns success with no ciphers selected, when this happens
458 	     * SSL_get_ciphers() produces a stack with 0 elements!
459 	     */
460 	    if (SSL_set_cipher_list(s, probe->ssl_name) == 0
461 		|| (ciphers = SSL_get_ciphers(s)) == 0
462 		|| (num = sk_SSL_CIPHER_num(ciphers)) == 0) {
463 		ERR_clear_error();		/* flush any generated errors */
464 		continue;
465 	    }
466 	    for (i = 0; i < num; ++i) {
467 		c = sk_SSL_CIPHER_value(ciphers, i);
468 		(void) SSL_CIPHER_get_bits(c, &alg_bits);
469 		if (alg_bits == probe->alg_bits)
470 		    argv_add(exclude, SSL_CIPHER_get_name(c), ARGV_END);
471 	    }
472 	}
473 	if (s != 0)
474 	    SSL_free(s);
475     }
476     for (i = 0; i < exclude->argc; ++i)
477 	vstring_sprintf_append(buf, ":!%s", exclude->argv[i]);
478     return (vstring_str(buf));
479 }
480 
481 /* tls_apply_cipher_list - update SSL_CTX cipher list */
482 
483 static const char *tls_apply_cipher_list(TLS_APPL_STATE *app_ctx,
484 				         const char *context, VSTRING *spec)
485 {
486     const char *new = tls_exclude_missing(app_ctx->ssl_ctx, spec);
487 
488     ERR_clear_error();
489     if (SSL_CTX_set_cipher_list(app_ctx->ssl_ctx, new) == 0) {
490 	tls_print_errors();
491 	vstring_sprintf(app_ctx->why, "invalid %s cipher list: \"%s\"",
492 			context, new);
493 	return (0);
494     }
495     return (new);
496 }
497 
498 /* tls_protocol_mask - Bitmask of protocols to exclude */
499 
500 int     tls_protocol_mask(const char *plist)
501 {
502     char   *save;
503     char   *tok;
504     char   *cp;
505     int     code;
506     int     exclude = 0;
507     int     include = 0;
508 
509 #define FREE_AND_RETURN(ptr, res) do { \
510 	myfree(ptr); \
511 	return (res); \
512     } while (0)
513 
514     save = cp = mystrdup(plist);
515     while ((tok = mystrtok(&cp, "\t\n\r ,:")) != 0) {
516 	if (*tok == '!')
517 	    exclude |= code =
518 		name_code(protocol_table, NAME_CODE_FLAG_NONE, ++tok);
519 	else
520 	    include |= code =
521 		name_code(protocol_table, NAME_CODE_FLAG_NONE, tok);
522 	if (code == TLS_PROTOCOL_INVALID)
523 	    FREE_AND_RETURN(save, TLS_PROTOCOL_INVALID);
524     }
525 
526     /*
527      * When the include list is empty, use only the explicit exclusions.
528      * Otherwise, also exclude the complement of the include list from the
529      * built-in list of known protocols. There is no way to exclude protocols
530      * we don't know about at compile time, and this is unavoidable because
531      * the OpenSSL API works with compile-time *exclusion* bit-masks.
532      */
533     FREE_AND_RETURN(save,
534 	(include ? (exclude | (TLS_KNOWN_PROTOCOLS & ~include)) : exclude));
535 }
536 
537 /* tls_param_init - Load TLS related config parameters */
538 
539 void    tls_param_init(void)
540 {
541     static const CONFIG_STR_TABLE str_table[] = {
542 	VAR_TLS_HIGH_CLIST, DEF_TLS_HIGH_CLIST, &var_tls_high_clist, 1, 0,
543 	VAR_TLS_MEDIUM_CLIST, DEF_TLS_MEDIUM_CLIST, &var_tls_medium_clist, 1, 0,
544 	VAR_TLS_LOW_CLIST, DEF_TLS_LOW_CLIST, &var_tls_low_clist, 1, 0,
545 	VAR_TLS_EXPORT_CLIST, DEF_TLS_EXPORT_CLIST, &var_tls_export_clist, 1, 0,
546 	VAR_TLS_NULL_CLIST, DEF_TLS_NULL_CLIST, &var_tls_null_clist, 1, 0,
547 	VAR_TLS_EECDH_STRONG, DEF_TLS_EECDH_STRONG, &var_tls_eecdh_strong, 1, 0,
548 	VAR_TLS_EECDH_ULTRA, DEF_TLS_EECDH_ULTRA, &var_tls_eecdh_ultra, 1, 0,
549 	VAR_TLS_BUG_TWEAKS, DEF_TLS_BUG_TWEAKS, &var_tls_bug_tweaks, 0, 0,
550 	0,
551     };
552     static const CONFIG_INT_TABLE int_table[] = {
553 	VAR_TLS_DAEMON_RAND_BYTES, DEF_TLS_DAEMON_RAND_BYTES, &var_tls_daemon_rand_bytes, 1, 0,
554 	0,
555     };
556     static const CONFIG_BOOL_TABLE bool_table[] = {
557 	VAR_TLS_APPEND_DEF_CA, DEF_TLS_APPEND_DEF_CA, &var_tls_append_def_CA,
558 	VAR_TLS_BC_PKEY_FPRINT, DEF_TLS_BC_PKEY_FPRINT, &var_tls_bc_pkey_fprint,
559 #if OPENSSL_VERSION_NUMBER >= 0x0090700fL	/* OpenSSL 0.9.7 and later */
560 	VAR_TLS_PREEMPT_CLIST, DEF_TLS_PREEMPT_CLIST, &var_tls_preempt_clist,
561 #endif
562 	0,
563     };
564     static int init_done;
565 
566     if (init_done)
567 	return;
568     init_done = 1;
569 
570     get_mail_conf_str_table(str_table);
571     get_mail_conf_int_table(int_table);
572     get_mail_conf_bool_table(bool_table);
573 }
574 
575 /* tls_set_ciphers - Set SSL context cipher list */
576 
577 const char *tls_set_ciphers(TLS_APPL_STATE *app_ctx, const char *context,
578 			          const char *grade, const char *exclusions)
579 {
580     const char *myname = "tls_set_ciphers";
581     static VSTRING *buf;
582     int     new_grade;
583     char   *save;
584     char   *cp;
585     char   *tok;
586     const char *new_list;
587 
588     new_grade = tls_cipher_grade(grade);
589     if (new_grade == TLS_CIPHER_NONE) {
590 	vstring_sprintf(app_ctx->why, "invalid %s cipher grade: \"%s\"",
591 			context, grade);
592 	return (0);
593     }
594     if (buf == 0)
595 	buf = vstring_alloc(10);
596     VSTRING_RESET(buf);
597 
598     /*
599      * Given cached state and identical input, we return the same result.
600      */
601     if (app_ctx->cipher_list) {
602 	if (new_grade == app_ctx->cipher_grade
603 	    && strcmp(app_ctx->cipher_exclusions, exclusions) == 0)
604 	    return (app_ctx->cipher_list);
605 
606 	/* Change required, flush cached state */
607 	app_ctx->cipher_grade = TLS_CIPHER_NONE;
608 
609 	myfree(app_ctx->cipher_exclusions);
610 	app_ctx->cipher_exclusions = 0;
611 
612 	myfree(app_ctx->cipher_list);
613 	app_ctx->cipher_list = 0;
614     }
615     switch (new_grade) {
616     case TLS_CIPHER_HIGH:
617 	vstring_strcpy(buf, var_tls_high_clist);
618 	break;
619     case TLS_CIPHER_MEDIUM:
620 	vstring_strcpy(buf, var_tls_medium_clist);
621 	break;
622     case TLS_CIPHER_LOW:
623 	vstring_strcpy(buf, var_tls_low_clist);
624 	break;
625     case TLS_CIPHER_EXPORT:
626 	vstring_strcpy(buf, var_tls_export_clist);
627 	break;
628     case TLS_CIPHER_NULL:
629 	vstring_strcpy(buf, var_tls_null_clist);
630 	break;
631     default:
632 
633 	/*
634 	 * The caller MUST provide a valid cipher grade
635 	 */
636 	msg_panic("invalid %s cipher grade: %d", context, new_grade);
637     }
638 
639     /*
640      * The base lists for each grade can't be empty.
641      */
642     if (VSTRING_LEN(buf) == 0)
643 	msg_panic("%s: empty \"%s\" cipherlist", myname, grade);
644 
645     /*
646      * Apply locally-specified exclusions.
647      */
648 #define CIPHER_SEP "\t\n\r ,:"
649     if (exclusions != 0) {
650 	cp = save = mystrdup(exclusions);
651 	while ((tok = mystrtok(&cp, CIPHER_SEP)) != 0) {
652 
653 	    /*
654 	     * Can't exclude ciphers that start with modifiers.
655 	     */
656 	    if (strchr("!+-@", *tok)) {
657 		vstring_sprintf(app_ctx->why,
658 				"invalid unary '!+-@' in %s cipher "
659 				"exclusion: \"%s\"", context, tok);
660 		return (0);
661 	    }
662 	    vstring_sprintf_append(buf, ":!%s", tok);
663 	}
664 	myfree(save);
665     }
666     if ((new_list = tls_apply_cipher_list(app_ctx, context, buf)) == 0)
667 	return (0);
668 
669     /* Cache new state */
670     app_ctx->cipher_grade = new_grade;
671     app_ctx->cipher_exclusions = mystrdup(exclusions);
672 
673     return (app_ctx->cipher_list = mystrdup(new_list));
674 }
675 
676 /* tls_alloc_app_context - allocate TLS application context */
677 
678 TLS_APPL_STATE *tls_alloc_app_context(SSL_CTX *ssl_ctx, int log_mask)
679 {
680     TLS_APPL_STATE *app_ctx;
681 
682     app_ctx = (TLS_APPL_STATE *) mymalloc(sizeof(*app_ctx));
683 
684     /* See portability note below with other memset() call. */
685     memset((char *) app_ctx, 0, sizeof(*app_ctx));
686     app_ctx->ssl_ctx = ssl_ctx;
687     app_ctx->log_mask = log_mask;
688 
689     /* See also: cache purging code in tls_set_ciphers(). */
690     app_ctx->cipher_grade = TLS_CIPHER_NONE;
691     app_ctx->cipher_exclusions = 0;
692     app_ctx->cipher_list = 0;
693     app_ctx->cache_type = 0;
694     app_ctx->why = vstring_alloc(1);
695 
696     return (app_ctx);
697 }
698 
699 /* tls_free_app_context - Free TLS application context */
700 
701 void    tls_free_app_context(TLS_APPL_STATE *app_ctx)
702 {
703     if (app_ctx->ssl_ctx)
704 	SSL_CTX_free(app_ctx->ssl_ctx);
705     if (app_ctx->cache_type)
706 	myfree(app_ctx->cache_type);
707     /* See also: cache purging code in tls_set_ciphers(). */
708     if (app_ctx->cipher_exclusions)
709 	myfree(app_ctx->cipher_exclusions);
710     if (app_ctx->cipher_list)
711 	myfree(app_ctx->cipher_list);
712     if (app_ctx->why)
713 	vstring_free(app_ctx->why);
714     myfree((char *) app_ctx);
715 }
716 
717 /* tls_alloc_sess_context - allocate TLS session context */
718 
719 TLS_SESS_STATE *tls_alloc_sess_context(int log_mask, const char *namaddr)
720 {
721     TLS_SESS_STATE *TLScontext;
722 
723     /*
724      * PORTABILITY: Do not assume that null pointers are all-zero bits. Use
725      * explicit assignments to initialize pointers.
726      *
727      * See the C language FAQ item 5.17, or if you have time to burn,
728      * http://www.google.com/search?q=zero+bit+null+pointer
729      *
730      * However, it's OK to use memset() to zero integer values.
731      */
732     TLScontext = (TLS_SESS_STATE *) mymalloc(sizeof(TLS_SESS_STATE));
733     memset((char *) TLScontext, 0, sizeof(*TLScontext));
734     TLScontext->con = 0;
735     TLScontext->cache_type = 0;
736     TLScontext->serverid = 0;
737     TLScontext->peer_CN = 0;
738     TLScontext->issuer_CN = 0;
739     TLScontext->peer_fingerprint = 0;
740     TLScontext->peer_pkey_fprint = 0;
741     TLScontext->protocol = 0;
742     TLScontext->cipher_name = 0;
743     TLScontext->log_mask = log_mask;
744     TLScontext->namaddr = lowercase(mystrdup(namaddr));
745     TLScontext->fpt_dgst = 0;
746 
747     return (TLScontext);
748 }
749 
750 /* tls_free_context - deallocate TLScontext and members */
751 
752 void    tls_free_context(TLS_SESS_STATE *TLScontext)
753 {
754 
755     /*
756      * Free the SSL structure and the BIOs. Warning: the internal_bio is
757      * connected to the SSL structure and is automatically freed with it. Do
758      * not free it again (core dump)!! Only free the network_bio.
759      */
760     if (TLScontext->con != 0)
761 	SSL_free(TLScontext->con);
762 
763     if (TLScontext->namaddr)
764 	myfree(TLScontext->namaddr);
765     if (TLScontext->serverid)
766 	myfree(TLScontext->serverid);
767 
768     if (TLScontext->peer_CN)
769 	myfree(TLScontext->peer_CN);
770     if (TLScontext->issuer_CN)
771 	myfree(TLScontext->issuer_CN);
772     if (TLScontext->peer_fingerprint)
773 	myfree(TLScontext->peer_fingerprint);
774     if (TLScontext->peer_pkey_fprint)
775 	myfree(TLScontext->peer_pkey_fprint);
776     if (TLScontext->fpt_dgst)
777 	myfree(TLScontext->fpt_dgst);
778 
779     myfree((char *) TLScontext);
780 }
781 
782 /* tls_version_split - Split OpenSSL version number into major, minor, ... */
783 
784 static void tls_version_split(long version, TLS_VINFO *info)
785 {
786 
787     /*
788      * OPENSSL_VERSION_NUMBER(3):
789      *
790      * OPENSSL_VERSION_NUMBER is a numeric release version identifier:
791      *
792      * MMNNFFPPS: major minor fix patch status
793      *
794      * The status nibble has one of the values 0 for development, 1 to e for
795      * betas 1 to 14, and f for release. Parsed OpenSSL version number. for
796      * example
797      *
798      * 0x000906000 == 0.9.6 dev 0x000906023 == 0.9.6b beta 3 0x00090605f ==
799      * 0.9.6e release
800      *
801      * Versions prior to 0.9.3 have identifiers < 0x0930.  Versions between
802      * 0.9.3 and 0.9.5 had a version identifier with this interpretation:
803      *
804      * MMNNFFRBB major minor fix final beta/patch
805      *
806      * for example
807      *
808      * 0x000904100 == 0.9.4 release 0x000905000 == 0.9.5 dev
809      *
810      * Version 0.9.5a had an interim interpretation that is like the current
811      * one, except the patch level got the highest bit set, to keep continu-
812      * ity.  The number was therefore 0x0090581f.
813      */
814 
815     if (version < 0x0930) {
816 	info->status = 0;
817 	info->patch = version & 0x0f;
818 	version >>= 4;
819 	info->micro = version & 0x0f;
820 	version >>= 4;
821 	info->minor = version & 0x0f;
822 	version >>= 4;
823 	info->major = version & 0x0f;
824     } else if (version < 0x00905800L) {
825 	info->patch = version & 0xff;
826 	version >>= 8;
827 	info->status = version & 0xf;
828 	version >>= 4;
829 	info->micro = version & 0xff;
830 	version >>= 8;
831 	info->minor = version & 0xff;
832 	version >>= 8;
833 	info->major = version & 0xff;
834     } else {
835 	info->status = version & 0xf;
836 	version >>= 4;
837 	info->patch = version & 0xff;
838 	version >>= 8;
839 	info->micro = version & 0xff;
840 	version >>= 8;
841 	info->minor = version & 0xff;
842 	version >>= 8;
843 	info->major = version & 0xff;
844 	if (version < 0x00906000L)
845 	    info->patch &= ~0x80;
846     }
847 }
848 
849 /* tls_check_version - Detect mismatch between headers and library. */
850 
851 void    tls_check_version(void)
852 {
853     TLS_VINFO hdr_info;
854     TLS_VINFO lib_info;
855 
856     tls_version_split(OPENSSL_VERSION_NUMBER, &hdr_info);
857     tls_version_split(SSLeay(), &lib_info);
858 
859     if (lib_info.major != hdr_info.major
860 	|| lib_info.minor != hdr_info.minor
861 	|| lib_info.micro != hdr_info.micro)
862 	msg_warn("run-time library vs. compile-time header version mismatch: "
863 	     "OpenSSL %d.%d.%d may not be compatible with OpenSSL %d.%d.%d",
864 		 lib_info.major, lib_info.minor, lib_info.micro,
865 		 hdr_info.major, hdr_info.minor, hdr_info.micro);
866 }
867 
868 /* tls_bug_bits - SSL bug compatibility bits for this OpenSSL version */
869 
870 long    tls_bug_bits(void)
871 {
872     long    bits = SSL_OP_ALL;		/* Work around all known bugs */
873 
874 #if OPENSSL_VERSION_NUMBER >= 0x00908000L
875     long    lib_version = SSLeay();
876 
877     /*
878      * In OpenSSL 0.9.8[ab], enabling zlib compression breaks the padding bug
879      * work-around, leading to false positives and failed connections. We may
880      * not interoperate with systems with the bug, but this is better than
881      * breaking on all 0.9.8[ab] systems that have zlib support enabled.
882      */
883     if (lib_version >= 0x00908000L && lib_version <= 0x0090802fL) {
884 	STACK_OF(SSL_COMP) * comp_methods;
885 
886 	comp_methods = SSL_COMP_get_compression_methods();
887 	if (comp_methods != 0 && sk_SSL_COMP_num(comp_methods) > 0)
888 	    bits &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
889     }
890 #endif
891 
892     /*
893      * Silently ignore any strings that don't appear in the tweaks table, or
894      * hex bits that are not in SSL_OP_ALL.
895      */
896     if (*var_tls_bug_tweaks) {
897 	bits &= ~long_name_mask_opt(VAR_TLS_BUG_TWEAKS, ssl_bug_tweaks,
898 				    var_tls_bug_tweaks, NAME_MASK_ANY_CASE |
899 				    NAME_MASK_NUMBER | NAME_MASK_WARN);
900     }
901     return (bits);
902 }
903 
904 /* tls_print_errors - print and clear the error stack */
905 
906 void    tls_print_errors(void)
907 {
908     unsigned long err;
909     char    buffer[1024];		/* XXX */
910     const char *file;
911     const char *data;
912     int     line;
913     int     flags;
914     unsigned long thread;
915 
916     thread = CRYPTO_thread_id();
917     while ((err = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
918 	ERR_error_string_n(err, buffer, sizeof(buffer));
919 	if (flags & ERR_TXT_STRING)
920 	    msg_warn("TLS library problem: %lu:%s:%s:%d:%s:",
921 		     thread, buffer, file, line, data);
922 	else
923 	    msg_warn("TLS library problem: %lu:%s:%s:%d:",
924 		     thread, buffer, file, line);
925     }
926 }
927 
928 /* tls_info_callback - callback for logging SSL events via Postfix */
929 
930 void    tls_info_callback(const SSL *s, int where, int ret)
931 {
932     char   *str;
933     int     w;
934 
935     /* Adapted from OpenSSL apps/s_cb.c. */
936 
937     w = where & ~SSL_ST_MASK;
938 
939     if (w & SSL_ST_CONNECT)
940 	str = "SSL_connect";
941     else if (w & SSL_ST_ACCEPT)
942 	str = "SSL_accept";
943     else
944 	str = "unknown";
945 
946     if (where & SSL_CB_LOOP) {
947 	msg_info("%s:%s", str, SSL_state_string_long((SSL *) s));
948     } else if (where & SSL_CB_ALERT) {
949 	str = (where & SSL_CB_READ) ? "read" : "write";
950 	if ((ret & 0xff) != SSL3_AD_CLOSE_NOTIFY)
951 	    msg_info("SSL3 alert %s:%s:%s", str,
952 		     SSL_alert_type_string_long(ret),
953 		     SSL_alert_desc_string_long(ret));
954     } else if (where & SSL_CB_EXIT) {
955 	if (ret == 0)
956 	    msg_info("%s:failed in %s",
957 		     str, SSL_state_string_long((SSL *) s));
958 	else if (ret < 0) {
959 #ifndef LOG_NON_ERROR_STATES
960 	    switch (SSL_get_error((SSL *) s, ret)) {
961 	    case SSL_ERROR_WANT_READ:
962 	    case SSL_ERROR_WANT_WRITE:
963 		/* Don't log non-error states. */
964 		break;
965 	    default:
966 #endif
967 		msg_info("%s:error in %s",
968 			 str, SSL_state_string_long((SSL *) s));
969 #ifndef LOG_NON_ERROR_STATES
970 	    }
971 #endif
972 	}
973     }
974 }
975 
976  /*
977   * taken from OpenSSL crypto/bio/b_dump.c.
978   *
979   * Modified to save a lot of strcpy and strcat by Matti Aarnio.
980   *
981   * Rewritten by Wietse to elimate fixed-size stack buffer, array index
982   * multiplication and division, sprintf() and strcpy(), and lots of strlen()
983   * calls. We could make it a little faster by using a fixed-size stack-based
984   * buffer.
985   *
986   * 200412 - use %lx to print pointers, after casting them to unsigned long.
987   */
988 
989 #define TRUNCATE_SPACE_NULL
990 #define DUMP_WIDTH	16
991 #define VERT_SPLIT	7
992 
993 static void tls_dump_buffer(const unsigned char *start, int len)
994 {
995     VSTRING *buf = vstring_alloc(100);
996     const unsigned char *last = start + len - 1;
997     const unsigned char *row;
998     const unsigned char *col;
999     int     ch;
1000 
1001 #ifdef TRUNCATE_SPACE_NULL
1002     while (last >= start && (*last == ' ' || *last == 0))
1003 	last--;
1004 #endif
1005 
1006     for (row = start; row <= last; row += DUMP_WIDTH) {
1007 	VSTRING_RESET(buf);
1008 	vstring_sprintf(buf, "%04lx ", (unsigned long) (row - start));
1009 	for (col = row; col < row + DUMP_WIDTH; col++) {
1010 	    if (col > last) {
1011 		vstring_strcat(buf, "   ");
1012 	    } else {
1013 		ch = *col;
1014 		vstring_sprintf_append(buf, "%02x%c",
1015 				   ch, col - row == VERT_SPLIT ? '|' : ' ');
1016 	    }
1017 	}
1018 	VSTRING_ADDCH(buf, ' ');
1019 	for (col = row; col < row + DUMP_WIDTH; col++) {
1020 	    if (col > last)
1021 		break;
1022 	    ch = *col;
1023 	    if (!ISPRINT(ch))
1024 		ch = '.';
1025 	    VSTRING_ADDCH(buf, ch);
1026 	    if (col - row == VERT_SPLIT)
1027 		VSTRING_ADDCH(buf, ' ');
1028 	}
1029 	VSTRING_TERMINATE(buf);
1030 	msg_info("%s", vstring_str(buf));
1031     }
1032 #ifdef TRUNCATE_SPACE_NULL
1033     if ((last + 1) - start < len)
1034 	msg_info("%04lx - <SPACES/NULLS>",
1035 		 (unsigned long) ((last + 1) - start));
1036 #endif
1037     vstring_free(buf);
1038 }
1039 
1040 /* taken from OpenSSL apps/s_cb.c */
1041 
1042 long    tls_bio_dump_cb(BIO *bio, int cmd, const char *argp, int argi,
1043 			        long unused_argl, long ret)
1044 {
1045     if (cmd == (BIO_CB_READ | BIO_CB_RETURN)) {
1046 	msg_info("read from %08lX [%08lX] (%d bytes => %ld (0x%lX))",
1047 		 (unsigned long) bio, (unsigned long) argp, argi,
1048 		 ret, (unsigned long) ret);
1049 	tls_dump_buffer((unsigned char *) argp, (int) ret);
1050     } else if (cmd == (BIO_CB_WRITE | BIO_CB_RETURN)) {
1051 	msg_info("write to %08lX [%08lX] (%d bytes => %ld (0x%lX))",
1052 		 (unsigned long) bio, (unsigned long) argp, argi,
1053 		 ret, (unsigned long) ret);
1054 	tls_dump_buffer((unsigned char *) argp, (int) ret);
1055     }
1056     return (ret);
1057 }
1058 
1059 #else
1060 
1061  /*
1062   * Broken linker workaround.
1063   */
1064 int     tls_dummy_for_broken_linkers;
1065 
1066 #endif
1067