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