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