Home | History | Annotate | Line # | Download | only in syslogd
tls.c revision 1.3
      1  1.3   minskim /*	$NetBSD: tls.c,v 1.3 2008/11/07 07:36:38 minskim Exp $	*/
      2  1.1  christos 
      3  1.1  christos /*-
      4  1.1  christos  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  1.1  christos  * All rights reserved.
      6  1.1  christos  *
      7  1.1  christos  * This code is derived from software contributed to The NetBSD Foundation
      8  1.1  christos  * by Martin Schtte.
      9  1.1  christos  *
     10  1.1  christos  * Redistribution and use in source and binary forms, with or without
     11  1.1  christos  * modification, are permitted provided that the following conditions
     12  1.1  christos  * are met:
     13  1.1  christos  * 1. Redistributions of source code must retain the above copyright
     14  1.1  christos  *    notice, this list of conditions and the following disclaimer.
     15  1.1  christos  * 2. Redistributions in binary form must reproduce the above copyright
     16  1.1  christos  *    notice, this list of conditions and the following disclaimer in the
     17  1.1  christos  *    documentation and/or other materials provided with the distribution.
     18  1.1  christos  * 3. All advertising materials mentioning features or use of this software
     19  1.1  christos  *    must display the following acknowledgement:
     20  1.1  christos  *        This product includes software developed by the NetBSD
     21  1.1  christos  *        Foundation, Inc. and its contributors.
     22  1.1  christos  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  1.1  christos  *    contributors may be used to endorse or promote products derived
     24  1.1  christos  *    from this software without specific prior written permission.
     25  1.1  christos  *
     26  1.1  christos  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  1.1  christos  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  1.1  christos  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  1.1  christos  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  1.1  christos  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  1.1  christos  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  1.1  christos  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  1.1  christos  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  1.1  christos  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  1.1  christos  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  1.1  christos  * POSSIBILITY OF SUCH DAMAGE.
     37  1.1  christos  */
     38  1.1  christos /*
     39  1.1  christos  * tls.c TLS related code for syslogd
     40  1.1  christos  *
     41  1.1  christos  * implements the TLS init and handshake callbacks with all required
     42  1.1  christos  * checks from http://tools.ietf.org/html/draft-ietf-syslog-transport-tls-13
     43  1.1  christos  *
     44  1.1  christos  * Martin Schtte
     45  1.1  christos  */
     46  1.1  christos 
     47  1.1  christos #include <sys/cdefs.h>
     48  1.3   minskim __RCSID("$NetBSD: tls.c,v 1.3 2008/11/07 07:36:38 minskim Exp $");
     49  1.1  christos 
     50  1.1  christos #ifndef DISABLE_TLS
     51  1.1  christos #include "syslogd.h"
     52  1.1  christos #include "tls.h"
     53  1.1  christos #include <netinet/in.h>
     54  1.1  christos #include <ifaddrs.h>
     55  1.1  christos #include "extern.h"
     56  1.1  christos 
     57  1.1  christos static unsigned getVerifySetting(const char *x509verifystring);
     58  1.1  christos 
     59  1.1  christos /* to output SSL error codes */
     60  1.1  christos static const char *SSL_ERRCODE[] = {
     61  1.1  christos 	"SSL_ERROR_NONE",
     62  1.1  christos 	"SSL_ERROR_SSL",
     63  1.1  christos 	"SSL_ERROR_WANT_READ",
     64  1.1  christos 	"SSL_ERROR_WANT_WRITE",
     65  1.1  christos 	"SSL_ERROR_WANT_X509_LOOKUP",
     66  1.1  christos 	"SSL_ERROR_SYSCALL",
     67  1.1  christos 	"SSL_ERROR_ZERO_RETURN",
     68  1.1  christos 	"SSL_ERROR_WANT_CONNECT",
     69  1.1  christos 	"SSL_ERROR_WANT_ACCEPT"};
     70  1.1  christos /* TLS connection states -- keep in sync with symbols in .h */
     71  1.1  christos static const char *TLS_CONN_STATES[] = {
     72  1.1  christos 	"ST_NONE",
     73  1.1  christos 	"ST_TLS_EST",
     74  1.1  christos 	"ST_TCP_EST",
     75  1.1  christos 	"ST_CONNECTING",
     76  1.1  christos 	"ST_ACCEPTING",
     77  1.1  christos 	"ST_READING",
     78  1.1  christos 	"ST_WRITING",
     79  1.1  christos 	"ST_EOF",
     80  1.1  christos 	"ST_CLOSING0",
     81  1.1  christos 	"ST_CLOSING1",
     82  1.1  christos 	"ST_CLOSING2"};
     83  1.1  christos 
     84  1.1  christos DH *get_dh1024(void);
     85  1.1  christos /* DH parameter precomputed with "openssl dhparam -C -2 1024" */
     86  1.1  christos #ifndef HEADER_DH_H
     87  1.1  christos #include <openssl/dh.h>
     88  1.1  christos #endif
     89  1.1  christos DH *
     90  1.1  christos get_dh1024(void)
     91  1.1  christos {
     92  1.1  christos 	static const unsigned char dh1024_p[]={
     93  1.1  christos 		0x94,0xBC,0xC4,0x71,0xD4,0xD3,0x2B,0x17,0x69,0xEA,0x82,0x1B,
     94  1.1  christos 		0x0F,0x86,0x45,0x57,0xF8,0x86,0x2C,0xC8,0xF5,0x37,0x1F,0x1F,
     95  1.1  christos 		0x12,0xDA,0x2C,0x62,0x4C,0xF6,0x95,0xF0,0xE4,0x6A,0x63,0x00,
     96  1.1  christos 		0x32,0x54,0x5F,0xA9,0xAA,0x2E,0xD2,0xD3,0xA5,0x7A,0x4E,0xCF,
     97  1.1  christos 		0xE8,0x2A,0xF6,0xAB,0xAF,0xD3,0x71,0x3E,0x75,0x9E,0x6B,0xF3,
     98  1.1  christos 		0x2E,0x6D,0x97,0x42,0xC2,0x45,0xC0,0x03,0xE1,0x17,0xA4,0x39,
     99  1.1  christos 		0xF6,0x36,0xA7,0x11,0xBD,0x30,0xF6,0x6F,0x21,0xBF,0x28,0xE4,
    100  1.1  christos 		0xF9,0xE1,0x1E,0x48,0x72,0x58,0xA9,0xC8,0x61,0x65,0xDB,0x66,
    101  1.1  christos 		0x36,0xA3,0x77,0x0A,0x81,0x79,0x2C,0x45,0x1E,0x97,0xA6,0xB1,
    102  1.1  christos 		0xD9,0x25,0x9C,0x28,0x96,0x91,0x40,0xF8,0xF6,0x86,0x11,0x9C,
    103  1.1  christos 		0x88,0xEC,0xA6,0xBA,0x9F,0x4F,0x85,0x43 };
    104  1.1  christos 	static const unsigned char dh1024_g[]={ 0x02 };
    105  1.1  christos 	DH *dh;
    106  1.1  christos 
    107  1.1  christos 	if ((dh=DH_new()) == NULL)
    108  1.1  christos 		return NULL;
    109  1.1  christos 	dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
    110  1.1  christos 	dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
    111  1.1  christos 	if ((dh->p == NULL) || (dh->g == NULL)) {
    112  1.1  christos 		DH_free(dh);
    113  1.1  christos 		return NULL;
    114  1.1  christos 	}
    115  1.1  christos 	return dh;
    116  1.1  christos }
    117  1.1  christos 
    118  1.1  christos #define ST_CHANGE(x, y) do {					\
    119  1.1  christos 	if ((x) != (y)) { 					\
    120  1.1  christos 		DPRINTF(D_TLS, "Change state: %s --> %s\n",	\
    121  1.1  christos 		    TLS_CONN_STATES[x], TLS_CONN_STATES[y]);	\
    122  1.1  christos 		(x) = (y);					\
    123  1.1  christos 	}							\
    124  1.1  christos } while (/*CONSTCOND*/0)
    125  1.1  christos 
    126  1.1  christos static unsigned
    127  1.1  christos getVerifySetting(const char *x509verifystring)
    128  1.1  christos {
    129  1.1  christos 	if (!x509verifystring)
    130  1.1  christos 		return X509VERIFY_ALWAYS;
    131  1.1  christos 
    132  1.1  christos 	if (!strcasecmp(x509verifystring, "off"))
    133  1.1  christos 		return X509VERIFY_NONE;
    134  1.1  christos 	else if (!strcasecmp(x509verifystring, "opt"))
    135  1.1  christos 		return X509VERIFY_IFPRESENT;
    136  1.1  christos 	else
    137  1.1  christos 		return X509VERIFY_ALWAYS;
    138  1.1  christos }
    139  1.1  christos /*
    140  1.1  christos  * init OpenSSL lib and one context.
    141  1.1  christos  * returns NULL if global context already exists.
    142  1.1  christos  * returns a status message on successfull init (to be free()d by caller).
    143  1.1  christos  * calls die() on serious error.
    144  1.1  christos  */
    145  1.1  christos char*
    146  1.1  christos init_global_TLS_CTX()
    147  1.1  christos {
    148  1.1  christos 	const char *keyfilename	  = tls_opt.keyfile;
    149  1.1  christos 	const char *certfilename  = tls_opt.certfile;
    150  1.1  christos 	const char *CAfile	  = tls_opt.CAfile;
    151  1.1  christos 	const char *CApath	  = tls_opt.CAdir;
    152  1.1  christos 
    153  1.1  christos 	SSL_CTX *ctx;
    154  1.1  christos 	unsigned x509verify = X509VERIFY_ALWAYS;
    155  1.1  christos 	EVP_PKEY *pkey = NULL;
    156  1.1  christos 	X509	 *cert = NULL;
    157  1.1  christos 	FILE *certfile = NULL;
    158  1.1  christos 	FILE  *keyfile = NULL;
    159  1.1  christos 	unsigned long err;
    160  1.1  christos 	char *fp = NULL, *cn = NULL;
    161  1.3   minskim 
    162  1.1  christos 	char statusmsg[1024];
    163  1.3   minskim 
    164  1.1  christos 	if (tls_opt.global_TLS_CTX) /* already initialized */
    165  1.1  christos 		return NULL;
    166  1.1  christos 
    167  1.1  christos 	x509verify = getVerifySetting(tls_opt.x509verify);
    168  1.1  christos 	if (x509verify != X509VERIFY_ALWAYS)
    169  1.1  christos 		loginfo("insecure configuration, peer authentication disabled");
    170  1.1  christos 
    171  1.1  christos 	if (!(ctx = SSL_CTX_new(SSLv23_method()))) {
    172  1.1  christos 		logerror("Unable to initialize OpenSSL: %s",
    173  1.1  christos 		    ERR_error_string(ERR_get_error(), NULL));
    174  1.1  christos 		die(0,0,NULL);
    175  1.1  christos 	}
    176  1.1  christos 
    177  1.1  christos 	if (!keyfilename)
    178  1.1  christos 		keyfilename = DEFAULT_X509_KEYFILE;
    179  1.1  christos 	if (!certfilename)
    180  1.1  christos 		certfilename = DEFAULT_X509_CERTFILE;
    181  1.3   minskim 
    182  1.1  christos 	/* TODO: would it be better to use stat() for access checking? */
    183  1.1  christos 	if (!(keyfile  = fopen(keyfilename,  "r"))
    184  1.1  christos 	 && !(certfile = fopen(certfilename, "r"))) {
    185  1.1  christos 		errno = 0;
    186  1.1  christos 		if (!tls_opt.gen_cert) {
    187  1.1  christos 			logerror("TLS certificate files \"%s\" and \"%s\""
    188  1.1  christos 			    "not readable. Please configure them with "
    189  1.1  christos 			    "\"tls_cert\" and \"tls_key\" or set "
    190  1.1  christos 			    "\"tls_gen_cert=1\" to generate a new "
    191  1.1  christos 			    "certificate", keyfilename, certfilename);
    192  1.1  christos 			die(0,0,NULL);
    193  1.1  christos 		}
    194  1.1  christos 
    195  1.1  christos 		loginfo("Generating a self-signed certificate and writing "
    196  1.1  christos 		    "files \"%s\" and \"%s\"", keyfilename, certfilename);
    197  1.1  christos 		if (!mk_x509_cert(&cert, &pkey, TLS_GENCERT_BITS,
    198  1.1  christos 		    TLS_GENCERT_SERIAL, TLS_GENCERT_DAYS)) {
    199  1.1  christos 			logerror("Unable to generate new certificate.");
    200  1.1  christos 			die(0,0,NULL);
    201  1.1  christos 		}
    202  1.1  christos 		if (!write_x509files(pkey, cert,
    203  1.1  christos 		    keyfilename, certfilename)) {
    204  1.1  christos 			logerror("Unable to write certificate to files \"%s\""
    205  1.1  christos 			    " and \"%s\"", keyfilename, certfilename);
    206  1.1  christos 			/* not fatal */
    207  1.1  christos 		}
    208  1.1  christos 	}
    209  1.1  christos 	if (keyfile)
    210  1.1  christos 		(void)fclose(keyfile);
    211  1.1  christos 	if (certfile)
    212  1.1  christos 		(void)fclose(certfile);
    213  1.1  christos 	errno = 0;
    214  1.1  christos 
    215  1.1  christos 	/* if generated, then use directly */
    216  1.1  christos 	if (cert && pkey) {
    217  1.1  christos 		if (!SSL_CTX_use_PrivateKey(ctx, pkey)
    218  1.1  christos 		    || !SSL_CTX_use_certificate(ctx, cert)) {
    219  1.1  christos 			logerror("Unable to use generated private "
    220  1.1  christos 			    "key and certificate: %s",
    221  1.1  christos 			    ERR_error_string(ERR_get_error(), NULL));
    222  1.1  christos 			die(0,0,NULL);	/* any better reaction? */
    223  1.1  christos 		 }
    224  1.1  christos 	} else {
    225  1.1  christos 		/* load keys and certs from files */
    226  1.1  christos 		if (!SSL_CTX_use_PrivateKey_file(ctx, keyfilename,
    227  1.1  christos 							SSL_FILETYPE_PEM)
    228  1.1  christos 		    || !SSL_CTX_use_certificate_chain_file(ctx, certfilename)) {
    229  1.1  christos 			logerror("Unable to load private key and "
    230  1.1  christos 			    "certificate from files \"%s\" and \"%s\": %s",
    231  1.1  christos 			    keyfilename, certfilename,
    232  1.1  christos 			    ERR_error_string(ERR_get_error(), NULL));
    233  1.1  christos 			die(0,0,NULL);	/* any better reaction? */
    234  1.1  christos 		}
    235  1.1  christos 	}
    236  1.1  christos 	if (!SSL_CTX_check_private_key(ctx)) {
    237  1.1  christos 		logerror("Private key \"%s\" does not match "
    238  1.1  christos 		    "certificate \"%s\": %s",
    239  1.1  christos 		    keyfilename, certfilename,
    240  1.1  christos 		    ERR_error_string(ERR_get_error(), NULL));
    241  1.1  christos 		die(0,0,NULL);
    242  1.1  christos 	}
    243  1.1  christos 
    244  1.1  christos 	if (CAfile || CApath) {
    245  1.1  christos 		if (SSL_CTX_load_verify_locations(ctx, CAfile, CApath) != 1) {
    246  1.1  christos 			if (CAfile && CApath)
    247  1.1  christos 				logerror("unable to load trust anchors from "
    248  1.1  christos 				    "\"%s\" and \"%s\": %s\n",
    249  1.1  christos 				    CAfile, CApath, ERR_error_string(
    250  1.1  christos 				    ERR_get_error(), NULL));
    251  1.1  christos 			else
    252  1.1  christos 				logerror("unable to load trust anchors from "
    253  1.1  christos 				    "\"%s\": %s\n", (CAfile?CAfile:CApath),
    254  1.1  christos 				    ERR_error_string(
    255  1.1  christos 				    ERR_get_error(), NULL));
    256  1.1  christos 		} else {
    257  1.1  christos 			DPRINTF(D_TLS, "loaded trust anchors\n");
    258  1.1  christos 		}
    259  1.1  christos 	}
    260  1.1  christos 
    261  1.1  christos 	/* options */
    262  1.1  christos 	(void)SSL_CTX_set_options(ctx,
    263  1.1  christos 	    SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_SINGLE_DH_USE);
    264  1.1  christos 	(void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
    265  1.1  christos 
    266  1.1  christos 	/* peer verification */
    267  1.1  christos 	if ((x509verify == X509VERIFY_NONE)
    268  1.1  christos 	    || (x509verify == X509VERIFY_IFPRESENT))
    269  1.1  christos 		/* ask for cert, but a client does not have to send one */
    270  1.1  christos 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, check_peer_cert);
    271  1.1  christos 	else
    272  1.1  christos 		/* default: ask for cert and check it */
    273  1.1  christos 		SSL_CTX_set_verify(ctx,
    274  1.1  christos 			SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
    275  1.1  christos 			check_peer_cert);
    276  1.1  christos 
    277  1.1  christos 	if (SSL_CTX_set_tmp_dh(ctx, get_dh1024()) != 1)
    278  1.1  christos 		logerror("SSL_CTX_set_tmp_dh() failed: %s",
    279  1.1  christos 		    ERR_error_string(ERR_get_error(), NULL));
    280  1.1  christos 
    281  1.3   minskim 	/* make sure the OpenSSL error queue is empty */
    282  1.1  christos 	while ((err = ERR_get_error()) != 0)
    283  1.1  christos 		logerror("Unexpected OpenSSL error: %s",
    284  1.1  christos 		    ERR_error_string(err, NULL));
    285  1.1  christos 
    286  1.1  christos 
    287  1.1  christos 	/* On successful init the status message is not logged immediately
    288  1.1  christos 	 * but passed to the caller. The reason is that init() can continue
    289  1.1  christos 	 * to initialize syslog-sign. When the status message is logged
    290  1.1  christos 	 * after that it will get a valid signature and not cause errors
    291  1.3   minskim 	 * with signature verification.
    292  1.1  christos 	 */
    293  1.1  christos 	if (cert || read_certfile(&cert, certfilename)) {
    294  1.1  christos 		get_fingerprint(cert, &fp, NULL);
    295  1.1  christos 		get_commonname(cert, &cn);
    296  1.1  christos 	}
    297  1.1  christos 	DPRINTF(D_TLS, "loaded and checked own certificate\n");
    298  1.1  christos 	snprintf(statusmsg, sizeof(statusmsg),
    299  1.1  christos 	    "Initialized TLS settings using library \"%s\". "
    300  1.1  christos 	    "Use certificate from file \"%s\" with CN \"%s\" "
    301  1.1  christos 	    "and fingerprint \"%s\"", SSLeay_version(SSLEAY_VERSION),
    302  1.1  christos 	    certfilename, cn, fp);
    303  1.1  christos 	free(cn);
    304  1.1  christos 	free(fp);
    305  1.1  christos 
    306  1.1  christos 	tls_opt.global_TLS_CTX = ctx;
    307  1.1  christos 	return strdup(statusmsg);
    308  1.1  christos }
    309  1.1  christos 
    310  1.1  christos 
    311  1.1  christos /*
    312  1.1  christos  * get fingerprint of cert
    313  1.1  christos  * returnstring will be allocated and should be free()d by the caller
    314  1.1  christos  * alg_name selects an algorithm, if it is NULL then DEFAULT_FINGERPRINT_ALG
    315  1.1  christos  * (should be "sha-1") will be used
    316  1.1  christos  * return value and non-NULL *returnstring indicate success
    317  1.1  christos  */
    318  1.1  christos bool
    319  1.1  christos get_fingerprint(const X509 *cert, char **returnstring, const char *alg_name)
    320  1.1  christos {
    321  1.1  christos #define MAX_ALG_NAME_LENGTH 8
    322  1.1  christos 	unsigned char md[EVP_MAX_MD_SIZE];
    323  1.1  christos 	char fp_val[4];
    324  1.1  christos 	size_t memsize, i;
    325  1.1  christos 	unsigned len;
    326  1.1  christos 	const EVP_MD *digest;
    327  1.1  christos 	const char *openssl_algname;
    328  1.3   minskim 	/* RFC nnnn uses hash function names from
    329  1.1  christos 	 * http://www.iana.org/assignments/hash-function-text-names/
    330  1.1  christos 	 * in certificate fingerprints.
    331  1.1  christos 	 * We have to map them to the hash function names used by OpenSSL.
    332  1.1  christos 	 * Actually we use the union of both namespaces to be RFC compliant
    333  1.1  christos 	 * and to let the user use "openssl -fingerprint ..."
    334  1.3   minskim 	 *
    335  1.1  christos 	 * Intended behaviour is to prefer the IANA names,
    336  1.1  christos 	 * but allow the user to use OpenSSL names as well
    337  1.1  christos 	 * (e.g. for "RIPEMD160" wich has no IANA name)
    338  1.1  christos 	 */
    339  1.1  christos 	static const struct hash_alg_namemap {
    340  1.1  christos 		const char *iana;
    341  1.1  christos 		const char *openssl;
    342  1.1  christos 	} hash_alg_namemap[] = {
    343  1.1  christos 		{"md2",	    "MD2"   },
    344  1.1  christos 		{"md5",	    "MD5"   },
    345  1.1  christos 		{"sha-1",   "SHA1"  },
    346  1.1  christos 		{"sha-224", "SHA224"},
    347  1.1  christos 		{"sha-256", "SHA256"},
    348  1.1  christos 		{"sha-384", "SHA384"},
    349  1.1  christos 		{"sha-512", "SHA512"}
    350  1.1  christos 	};
    351  1.1  christos 
    352  1.1  christos 	DPRINTF(D_TLS, "get_fingerprint(cert@%p, return@%p, alg \"%s\")\n",
    353  1.1  christos 	    cert, returnstring, alg_name);
    354  1.1  christos 	*returnstring = NULL;
    355  1.1  christos 
    356  1.1  christos 	if (!alg_name)
    357  1.1  christos 		alg_name = DEFAULT_FINGERPRINT_ALG;
    358  1.1  christos 	openssl_algname = alg_name;
    359  1.1  christos 	for (i = 0; i < A_CNT(hash_alg_namemap); i++)
    360  1.1  christos 		if (!strcasecmp(alg_name, hash_alg_namemap[i].iana))
    361  1.1  christos 			openssl_algname = hash_alg_namemap[i].openssl;
    362  1.1  christos 
    363  1.1  christos 	if (!(digest = (const EVP_MD *) EVP_get_digestbyname(
    364  1.1  christos 	    __UNCONST(openssl_algname)))) {
    365  1.1  christos 		DPRINTF(D_TLS, "unknown digest algorithm %s\n",
    366  1.1  christos 		    openssl_algname);
    367  1.1  christos 		return false;
    368  1.1  christos 	}
    369  1.1  christos 	if (!X509_digest(cert, digest, md, &len)) {
    370  1.1  christos 		DPRINTF(D_TLS, "cannot get %s digest\n", openssl_algname);
    371  1.1  christos 		return false;
    372  1.1  christos 	}
    373  1.1  christos 
    374  1.1  christos 	/* 'normalise' and translate back to IANA name */
    375  1.1  christos 	alg_name = openssl_algname = OBJ_nid2sn(EVP_MD_type(digest));
    376  1.1  christos 	for (i = 0; i < A_CNT(hash_alg_namemap); i++)
    377  1.1  christos 		if (!strcasecmp(openssl_algname, hash_alg_namemap[i].openssl))
    378  1.1  christos 			alg_name = hash_alg_namemap[i].iana;
    379  1.1  christos 
    380  1.1  christos 	/* needed memory: 3 string bytes for every binary byte with delimiter
    381  1.1  christos 	 *		  + max_iana_strlen with delimiter  */
    382  1.1  christos 	memsize = (len * 3) + strlen(alg_name) + 1;
    383  1.1  christos 	MALLOC(*returnstring, memsize);
    384  1.1  christos 	(void)strlcpy(*returnstring, alg_name, memsize);
    385  1.1  christos 	(void)strlcat(*returnstring, ":", memsize);
    386  1.1  christos 	/* append the fingeprint data */
    387  1.1  christos 	for (i = 0; i < len; i++) {
    388  1.1  christos 		(void)snprintf(fp_val, sizeof(fp_val),
    389  1.1  christos 			"%02X:", (unsigned) md[i]);
    390  1.1  christos 		(void)strlcat(*returnstring, fp_val, memsize);
    391  1.1  christos 	}
    392  1.1  christos 	return true;
    393  1.1  christos }
    394  1.1  christos 
    395  1.3   minskim /*
    396  1.1  christos  * gets first CN from cert in returnstring (has to be freed by caller)
    397  1.1  christos  * on failure it returns false and *returnstring is NULL
    398  1.1  christos  */
    399  1.1  christos bool
    400  1.1  christos get_commonname(X509 *cert, char **returnstring)
    401  1.1  christos {
    402  1.1  christos 	X509_NAME *x509name;
    403  1.1  christos 	X509_NAME_ENTRY *entry;
    404  1.1  christos 	unsigned char *ubuf;
    405  1.1  christos 	int len, i;
    406  1.3   minskim 
    407  1.1  christos 	x509name = X509_get_subject_name(cert);
    408  1.1  christos 	i = X509_NAME_get_index_by_NID(x509name, NID_commonName, -1);
    409  1.1  christos 	if (i != -1) {
    410  1.1  christos 		entry = X509_NAME_get_entry(x509name, i);
    411  1.1  christos 		len = ASN1_STRING_to_UTF8(&ubuf,
    412  1.1  christos 		    X509_NAME_ENTRY_get_data(entry));
    413  1.1  christos 		if (len > 0) {
    414  1.1  christos 			MALLOC(*returnstring, (size_t)len+1);
    415  1.1  christos 			strlcpy(*returnstring, (const char*)ubuf, len+1);
    416  1.1  christos 			OPENSSL_free(ubuf);
    417  1.1  christos 			return true;
    418  1.1  christos 		}
    419  1.1  christos 		OPENSSL_free(ubuf);
    420  1.1  christos 	}
    421  1.1  christos 	*returnstring = NULL;
    422  1.1  christos 	return false;
    423  1.1  christos }
    424  1.1  christos /*
    425  1.1  christos  * test if cert matches as configured hostname or IP
    426  1.1  christos  * checks a 'really used' hostname and optionally a second expected subject
    427  1.1  christos  * against iPAddresses, dnsNames and commonNames
    428  1.1  christos  *
    429  1.1  christos  * TODO: wildcard matching for dnsNames is not implemented.
    430  1.1  christos  *	 in transport-tls that is a MAY, and I do not trust them anyway.
    431  1.1  christos  *	 but there might be demand for, so it's a todo item.
    432  1.1  christos  */
    433  1.1  christos bool
    434  1.1  christos match_hostnames(X509 *cert, const char *hostname, const char *subject)
    435  1.1  christos {
    436  1.1  christos 	int i, len, num;
    437  1.1  christos 	char *buf;
    438  1.1  christos 	unsigned char *ubuf;
    439  1.1  christos 	GENERAL_NAMES *gennames;
    440  1.1  christos 	GENERAL_NAME *gn;
    441  1.1  christos 	X509_NAME *x509name;
    442  1.1  christos 	X509_NAME_ENTRY *entry;
    443  1.1  christos 	ASN1_OCTET_STRING *asn1_ip, *asn1_cn_ip;
    444  1.1  christos 	int crit, idx;
    445  1.1  christos 
    446  1.1  christos 	DPRINTF((D_TLS|D_CALL), "match_hostnames(%p, \"%s\", \"%s\")\n",
    447  1.1  christos 	    cert, hostname, subject);
    448  1.1  christos 
    449  1.1  christos 	/* see if hostname is an IP */
    450  1.1  christos 	if ((subject  && (asn1_ip = a2i_IPADDRESS(subject )))
    451  1.1  christos 	 || (hostname && (asn1_ip = a2i_IPADDRESS(hostname))))
    452  1.1  christos 		/* nothing */;
    453  1.1  christos 	else
    454  1.1  christos 		asn1_ip = NULL;
    455  1.1  christos 
    456  1.1  christos 	if (!(gennames = X509_get_ext_d2i(cert, NID_subject_alt_name,
    457  1.1  christos 	    &crit, &idx))) {
    458  1.1  christos 		DPRINTF(D_TLS, "X509_get_ext_d2i() returned (%p,%d,%d) "
    459  1.1  christos 		    "--> no subjectAltName\n", gennames, crit, idx);
    460  1.1  christos 	} else {
    461  1.1  christos 		num = sk_GENERAL_NAME_num(gennames);
    462  1.1  christos 		if (asn1_ip) {
    463  1.1  christos 			/* first loop: check IPs */
    464  1.1  christos 			for (i = 0; i < num; ++i) {
    465  1.1  christos 				gn = sk_GENERAL_NAME_value(gennames, i);
    466  1.1  christos 				if (gn->type == GEN_IPADD
    467  1.1  christos 				    && !ASN1_OCTET_STRING_cmp(asn1_ip,
    468  1.1  christos 					gn->d.iPAddress))
    469  1.1  christos 					return true;
    470  1.1  christos 			}
    471  1.1  christos 		}
    472  1.1  christos 		/* second loop: check DNS names */
    473  1.1  christos 		for (i = 0; i < num; ++i) {
    474  1.1  christos 			gn = sk_GENERAL_NAME_value(gennames, i);
    475  1.1  christos 			if (gn->type == GEN_DNS) {
    476  1.1  christos 				buf = (char *)ASN1_STRING_data(gn->d.ia5);
    477  1.1  christos 				len = ASN1_STRING_length(gn->d.ia5);
    478  1.1  christos 				if (!strncasecmp(subject, buf, len)
    479  1.1  christos 				    || !strncasecmp(hostname, buf, len))
    480  1.1  christos 					return true;
    481  1.1  christos 			}
    482  1.1  christos 		}
    483  1.1  christos 	}
    484  1.1  christos 
    485  1.1  christos 	/* check commonName; not sure if more than one CNs possible, but we
    486  1.1  christos 	 * will look at all of them */
    487  1.1  christos 	x509name = X509_get_subject_name(cert);
    488  1.1  christos 	i = X509_NAME_get_index_by_NID(x509name, NID_commonName, -1);
    489  1.1  christos 	while (i != -1) {
    490  1.1  christos 		entry = X509_NAME_get_entry(x509name, i);
    491  1.1  christos 		len = ASN1_STRING_to_UTF8(&ubuf,
    492  1.1  christos 		    X509_NAME_ENTRY_get_data(entry));
    493  1.1  christos 		if (len > 0) {
    494  1.1  christos 			DPRINTF(D_TLS, "found CN: %.*s\n", len, ubuf);
    495  1.1  christos 			/* hostname */
    496  1.1  christos 			if ((subject && !strncasecmp(subject,
    497  1.1  christos 			    (const char*)ubuf, len))
    498  1.1  christos 			    || (hostname && !strncasecmp(hostname,
    499  1.1  christos 			    (const char*)ubuf, len))) {
    500  1.1  christos 				OPENSSL_free(ubuf);
    501  1.1  christos 				return true;
    502  1.1  christos 			}
    503  1.1  christos 			OPENSSL_free(ubuf);
    504  1.1  christos 			/* IP -- convert to ASN1_OCTET_STRING and compare then
    505  1.1  christos 			 * so that "10.1.2.3" and "10.01.02.03" are equal */
    506  1.1  christos 			if ((asn1_ip)
    507  1.1  christos 			    && subject
    508  1.1  christos 			    && (asn1_cn_ip = a2i_IPADDRESS(subject))
    509  1.1  christos 			    && !ASN1_OCTET_STRING_cmp(asn1_ip, asn1_cn_ip)) {
    510  1.1  christos 				return true;
    511  1.1  christos 			}
    512  1.1  christos 		}
    513  1.1  christos 		i = X509_NAME_get_index_by_NID(x509name, NID_commonName, i);
    514  1.1  christos 	}
    515  1.1  christos 	return false;
    516  1.1  christos }
    517  1.1  christos 
    518  1.1  christos /*
    519  1.1  christos  * check if certificate matches given fingerprint
    520  1.1  christos  */
    521  1.1  christos bool
    522  1.1  christos match_fingerprint(const X509 *cert, const char *fingerprint)
    523  1.1  christos {
    524  1.1  christos #define MAX_ALG_NAME_LENGTH 8
    525  1.1  christos 	char alg[MAX_ALG_NAME_LENGTH];
    526  1.1  christos 	char *certfingerprint;
    527  1.1  christos 	char *p;
    528  1.1  christos 	const char *q;
    529  1.1  christos 
    530  1.1  christos 	DPRINTF((D_TLS|D_CALL), "match_fingerprint(cert@%p, fp \"%s\")\n",
    531  1.1  christos 		cert, fingerprint);
    532  1.1  christos 	if (!fingerprint)
    533  1.1  christos 		return false;
    534  1.1  christos 
    535  1.1  christos 	/* get algorithm */
    536  1.1  christos 	p = alg;
    537  1.1  christos 	q = fingerprint;
    538  1.1  christos 	while (*q != ':' && *q != '\0' && p < alg + MAX_ALG_NAME_LENGTH)
    539  1.1  christos 		*p++ = *q++;
    540  1.1  christos 	*p = '\0';
    541  1.1  christos 
    542  1.1  christos 	if (!get_fingerprint(cert, &certfingerprint, alg)) {
    543  1.1  christos 		DPRINTF(D_TLS, "cannot get %s digest\n", alg);
    544  1.1  christos 		return false;
    545  1.1  christos 	}
    546  1.1  christos 	if (strncmp(certfingerprint, fingerprint, strlen(certfingerprint))) {
    547  1.1  christos 		DPRINTF(D_TLS, "fail: fingerprints do not match\n");
    548  1.1  christos 		free(certfingerprint);
    549  1.1  christos 		return false;
    550  1.1  christos 	}
    551  1.1  christos 	DPRINTF(D_TLS, "accepted: fingerprints match\n");
    552  1.1  christos 	free(certfingerprint);
    553  1.1  christos 	return true;
    554  1.1  christos }
    555  1.1  christos 
    556  1.1  christos /*
    557  1.1  christos  * check if certificate matches given certificate file
    558  1.1  christos  */
    559  1.1  christos bool
    560  1.1  christos match_certfile(const X509 *cert1, const char *certfilename)
    561  1.1  christos {
    562  1.1  christos 	X509 *cert2;
    563  1.1  christos 	char *fp1, *fp2;
    564  1.1  christos 	bool rc = false;
    565  1.1  christos 	errno = 0;
    566  1.1  christos 
    567  1.1  christos 	if (read_certfile(&cert2, certfilename)
    568  1.1  christos 	    && get_fingerprint(cert1, &fp1, NULL)
    569  1.1  christos 	    && get_fingerprint(cert2, &fp2, NULL)) {
    570  1.1  christos 		if (!strcmp(fp1, fp2))
    571  1.1  christos 			rc = true;
    572  1.1  christos 		FREEPTR(fp1);
    573  1.1  christos 		FREEPTR(fp2);
    574  1.1  christos 	 }
    575  1.1  christos 	DPRINTF((D_TLS|D_CALL), "match_certfile(cert@%p, file \"%s\") "
    576  1.1  christos 	    "returns %d\n", cert1, certfilename, rc);
    577  1.1  christos 	return rc;
    578  1.1  christos }
    579  1.1  christos 
    580  1.1  christos /*
    581  1.1  christos  * reads X.509 certificate from file
    582  1.1  christos  * caller has to free it later with 'OPENSSL_free(cert);'
    583  1.1  christos  */
    584  1.1  christos bool
    585  1.1  christos read_certfile(X509 **cert, const char *certfilename)
    586  1.1  christos {
    587  1.1  christos 	FILE *certfile;
    588  1.1  christos 	errno = 0;
    589  1.3   minskim 
    590  1.1  christos 	DPRINTF((D_TLS|D_CALL), "read_certfile(%p, \"%s\")\n",
    591  1.1  christos 		cert, certfilename);
    592  1.1  christos 	if (!cert || !certfilename)
    593  1.1  christos 		return false;
    594  1.1  christos 
    595  1.1  christos 	if (!(certfile = fopen(certfilename, "rb"))) {
    596  1.1  christos 		logerror("Unable to open certificate file: %s", certfilename);
    597  1.1  christos 		return false;
    598  1.1  christos 	}
    599  1.1  christos 
    600  1.1  christos 	/* either PEM or DER */
    601  1.1  christos 	if (!(*cert = PEM_read_X509(certfile, NULL, NULL, NULL))
    602  1.1  christos 	    && !(*cert = d2i_X509_fp(certfile, NULL))) {
    603  1.1  christos 		DPRINTF((D_TLS), "Unable to read certificate from %s\n",
    604  1.1  christos 			certfilename);
    605  1.1  christos 		(void)fclose(certfile);
    606  1.1  christos 		return false;
    607  1.1  christos 	}
    608  1.1  christos 	else {
    609  1.1  christos 		DPRINTF((D_TLS), "Read certificate from %s\n", certfilename);
    610  1.1  christos 		(void)fclose(certfile);
    611  1.1  christos 		return true;
    612  1.1  christos 	}
    613  1.1  christos }
    614  1.1  christos 
    615  1.1  christos /* used for incoming connections in check_peer_cert() */
    616  1.1  christos int
    617  1.1  christos accept_cert(const char* reason, struct tls_conn_settings *conn_info,
    618  1.1  christos 	char *cur_fingerprint, char *cur_subjectline)
    619  1.1  christos {
    620  1.1  christos 	/* When using DSA keys the callback gets called twice.
    621  1.1  christos 	 * This flag avoids multiple log messages for the same connection.
    622  1.1  christos 	 */
    623  1.1  christos 	if (!conn_info->accepted)
    624  1.1  christos 		loginfo("Established connection and accepted %s certificate "
    625  1.1  christos 		    "from %s due to %s. Subject is \"%s\", fingerprint is"
    626  1.3   minskim 		    " \"%s\"", conn_info->incoming ? "server" : "client",
    627  1.1  christos 		    conn_info->hostname, reason, cur_subjectline,
    628  1.1  christos 		    cur_fingerprint);
    629  1.1  christos 
    630  1.1  christos 	if (cur_fingerprint && !conn_info->fingerprint)
    631  1.1  christos 		conn_info->fingerprint = cur_fingerprint;
    632  1.1  christos 	else
    633  1.1  christos 		FREEPTR(cur_fingerprint);
    634  1.1  christos 
    635  1.1  christos 	if (cur_subjectline && !conn_info->subject)
    636  1.1  christos 		conn_info->subject = cur_subjectline;
    637  1.1  christos 	else
    638  1.1  christos 		FREEPTR(cur_subjectline);
    639  1.1  christos 
    640  1.1  christos 	conn_info->accepted = true;
    641  1.1  christos 	return 1;
    642  1.1  christos }
    643  1.1  christos int
    644  1.1  christos deny_cert(struct tls_conn_settings *conn_info,
    645  1.1  christos 	char *cur_fingerprint, char *cur_subjectline)
    646  1.1  christos {
    647  1.1  christos 	if (!conn_info->accepted)
    648  1.1  christos 		loginfo("Deny %s certificate from %s. "
    649  1.1  christos 		    "Subject is \"%s\", fingerprint is \"%s\"",
    650  1.3   minskim 		    conn_info->incoming ? "client" : "server",
    651  1.1  christos 		    conn_info->hostname,
    652  1.1  christos 		    cur_subjectline, cur_fingerprint);
    653  1.1  christos 	else
    654  1.1  christos 		logerror("Error with TLS %s certificate authentication, "
    655  1.1  christos 		    "already approved certificate became invalid. "
    656  1.1  christos 		    "Subject is \"%s\", fingerprint is \"%s\"",
    657  1.3   minskim 		    conn_info->incoming ? "client" : "server",
    658  1.1  christos 		    cur_subjectline, cur_fingerprint);
    659  1.1  christos 	FREEPTR(cur_fingerprint);
    660  1.1  christos 	FREEPTR(cur_subjectline);
    661  1.1  christos 	return 0;
    662  1.1  christos }
    663  1.1  christos 
    664  1.1  christos /*
    665  1.1  christos  * Callback after OpenSSL has verified a peer certificate,
    666  1.1  christos  * gets called for every certificate in a chain (starting with root CA).
    667  1.1  christos  * preverify_ok indicates a valid trust path (necessary),
    668  1.1  christos  * then we check wether the hostname or configured subject matches the cert.
    669  1.1  christos  */
    670  1.1  christos int
    671  1.1  christos check_peer_cert(int preverify_ok, X509_STORE_CTX *ctx)
    672  1.1  christos {
    673  1.1  christos 	char *cur_subjectline = NULL;
    674  1.1  christos 	char *cur_fingerprint = NULL;
    675  1.1  christos 	char cur_issuerline[256];
    676  1.1  christos 	SSL *ssl;
    677  1.1  christos 	X509 *cur_cert;
    678  1.1  christos 	int cur_err, cur_depth;
    679  1.1  christos 	struct tls_conn_settings *conn_info;
    680  1.1  christos 	struct peer_cred *cred, *tmp_cred;
    681  1.3   minskim 
    682  1.1  christos 	/* read context info */
    683  1.1  christos 	cur_cert = X509_STORE_CTX_get_current_cert(ctx);
    684  1.1  christos 	cur_err = X509_STORE_CTX_get_error(ctx);
    685  1.1  christos 	cur_depth = X509_STORE_CTX_get_error_depth(ctx);
    686  1.1  christos 	ssl = X509_STORE_CTX_get_ex_data(ctx,
    687  1.1  christos 	    SSL_get_ex_data_X509_STORE_CTX_idx());
    688  1.1  christos 	conn_info = SSL_get_app_data(ssl);
    689  1.1  christos 
    690  1.1  christos 	/* some info */
    691  1.1  christos 	(void)get_commonname(cur_cert, &cur_subjectline);
    692  1.1  christos 	(void)get_fingerprint(cur_cert, &cur_fingerprint, NULL);
    693  1.1  christos 	DPRINTF((D_TLS|D_CALL), "check cert for connection with %s. "
    694  1.1  christos 	    "depth is %d, preverify is %d, subject is %s, fingerprint "
    695  1.3   minskim 	    "is %s, conn_info@%p%s\n", conn_info->hostname, cur_depth,
    696  1.1  christos 	    preverify_ok, cur_subjectline, cur_fingerprint, conn_info,
    697  1.1  christos 	    (conn_info->accepted ? ", cb was already called" : ""));
    698  1.1  christos 
    699  1.1  christos 	if (Debug && !preverify_ok) {
    700  1.1  christos 		DPRINTF(D_TLS, "openssl verify error:"
    701  1.1  christos 		    "num=%d:%s:depth=%d:%s\t\n", cur_err,
    702  1.1  christos 		    X509_verify_cert_error_string(cur_err),
    703  1.1  christos 		    cur_depth, cur_subjectline);
    704  1.1  christos 		if (cur_err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT) {
    705  1.1  christos 			X509_NAME_oneline(
    706  1.1  christos 			    X509_get_issuer_name(ctx->current_cert),
    707  1.1  christos 			    cur_issuerline, sizeof(cur_issuerline));
    708  1.1  christos 			DPRINTF(D_TLS, "openssl verify error:missing "
    709  1.1  christos 			    "cert for issuer=%s\n", cur_issuerline);
    710  1.1  christos 		}
    711  1.1  christos 	}
    712  1.1  christos 
    713  1.3   minskim 	/*
    714  1.1  christos 	 * quite a lot of variables here,
    715  1.3   minskim 	 * the big if/elseif covers all possible combinations.
    716  1.1  christos 	 *
    717  1.1  christos 	 * here is a list, ordered like the conditions below:
    718  1.1  christos 	 * - conn_info->x509verify
    719  1.1  christos 	 *   X509VERIFY_NONE:	   do not verify certificates,
    720  1.1  christos 	 *			   only log its subject and fingerprint
    721  1.1  christos 	 *   X509VERIFY_IFPRESENT: if we got her, then a cert is present,
    722  1.1  christos 	 *			   so check it normally
    723  1.1  christos 	 *   X509VERIFY_ALWAYS:	   normal certificate check
    724  1.1  christos 	 * - cur_depth:
    725  1.1  christos 	 *   > 0:  peer provided CA cert. remember if its valid,
    726  1.1  christos 	 *	   but always accept, because most checks work on depth 0
    727  1.1  christos 	 *   == 0: the peer's own cert. check this for final decision
    728  1.1  christos 	 * - preverify_ok:
    729  1.3   minskim 	 *   true:  valid certificate chain from a trust anchor to this cert
    730  1.1  christos 	 *   false: no valid and trusted certificate chain
    731  1.1  christos 	 * - conn_info->incoming:
    732  1.1  christos 	 *   true:  we are the server, means we authenticate against all
    733  1.1  christos 	 *	    allowed attributes in tls_opt
    734  1.1  christos 	 *   false: otherwise we are client and conn_info has all attributes
    735  1.1  christos 	 *	    to check
    736  1.1  christos 	 * - conn_info->fingerprint (only if !conn_info->incoming)
    737  1.1  christos 	 *   NULL:  no fingerprint configured, only check certificate chain
    738  1.1  christos 	 *   !NULL: a peer cert with this fingerprint is trusted
    739  1.3   minskim 	 *
    740  1.1  christos 	 */
    741  1.1  christos 	/* shortcut */
    742  1.1  christos 	if (cur_depth != 0) {
    743  1.1  christos 		FREEPTR(cur_fingerprint);
    744  1.1  christos 		FREEPTR(cur_subjectline);
    745  1.1  christos 		return 1;
    746  1.1  christos 	}
    747  1.1  christos 
    748  1.1  christos 	if (conn_info->x509verify == X509VERIFY_NONE)
    749  1.1  christos 		return accept_cert("disabled verification", conn_info,
    750  1.1  christos 		    cur_fingerprint, cur_subjectline);
    751  1.1  christos 
    752  1.1  christos 	/* implicit: (cur_depth == 0)
    753  1.1  christos 	 *	  && (conn_info->x509verify != X509VERIFY_NONE) */
    754  1.1  christos 	if (conn_info->incoming) {
    755  1.1  christos 		if (preverify_ok)
    756  1.1  christos 			return accept_cert("valid certificate chain",
    757  1.1  christos 			    conn_info, cur_fingerprint, cur_subjectline);
    758  1.1  christos 
    759  1.1  christos 		/* else: now check allowed client fingerprints/certs */
    760  1.1  christos 		SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
    761  1.1  christos 			if (match_fingerprint(cur_cert, cred->data)) {
    762  1.1  christos 				return accept_cert("matching fingerprint",
    763  1.1  christos 				    conn_info, cur_fingerprint,
    764  1.1  christos 				    cur_subjectline);
    765  1.1  christos 			}
    766  1.1  christos 		}
    767  1.1  christos 		SLIST_FOREACH_SAFE(cred, &tls_opt.cert_head,
    768  1.1  christos 			entries, tmp_cred) {
    769  1.1  christos 			if (match_certfile(cur_cert, cred->data))
    770  1.1  christos 				return accept_cert("matching certfile",
    771  1.1  christos 				    conn_info, cur_fingerprint,
    772  1.1  christos 				    cur_subjectline);
    773  1.1  christos 		}
    774  1.1  christos 		return deny_cert(conn_info, cur_fingerprint, cur_subjectline);
    775  1.1  christos 	}
    776  1.1  christos 
    777  1.1  christos 	/* implicit: (cur_depth == 0)
    778  1.1  christos 	 *	  && (conn_info->x509verify != X509VERIFY_NONE)
    779  1.1  christos 	 *	  && !conn_info->incoming */
    780  1.1  christos 	if (!conn_info->incoming && preverify_ok) {
    781  1.1  christos 		/* certificate chain OK. check subject/hostname */
    782  1.1  christos 		if (match_hostnames(cur_cert, conn_info->hostname,
    783  1.1  christos 		    conn_info->subject))
    784  1.1  christos 			return accept_cert("matching hostname/subject",
    785  1.1  christos 			    conn_info, cur_fingerprint, cur_subjectline);
    786  1.1  christos 		else
    787  1.1  christos 			return deny_cert(conn_info, cur_fingerprint,
    788  1.1  christos 			    cur_subjectline);
    789  1.1  christos 	} else if (!conn_info->incoming && !preverify_ok) {
    790  1.1  christos 		/* chain not OK. check fingerprint/subject/hostname */
    791  1.1  christos 		if (match_fingerprint(cur_cert, conn_info->fingerprint))
    792  1.1  christos 			return accept_cert("matching fingerprint", conn_info,
    793  1.1  christos 			    cur_fingerprint, cur_subjectline);
    794  1.1  christos 		else if (match_certfile(cur_cert, conn_info->certfile))
    795  1.1  christos 			return accept_cert("matching certfile", conn_info,
    796  1.1  christos 			    cur_fingerprint, cur_subjectline);
    797  1.1  christos 		else
    798  1.1  christos 			return deny_cert(conn_info, cur_fingerprint,
    799  1.1  christos 			    cur_subjectline);
    800  1.1  christos 	}
    801  1.1  christos 
    802  1.1  christos 	FREEPTR(cur_fingerprint);
    803  1.1  christos 	FREEPTR(cur_subjectline);
    804  1.1  christos 	return 0;
    805  1.1  christos }
    806  1.1  christos 
    807  1.1  christos /*
    808  1.1  christos  * Create TCP sockets for incoming TLS connections.
    809  1.1  christos  * To be used like socksetup(), hostname and port are optional,
    810  1.3   minskim  * returns bound stream sockets.
    811  1.1  christos  */
    812  1.1  christos struct socketEvent *
    813  1.1  christos socksetup_tls(const int af, const char *bindhostname, const char *port)
    814  1.1  christos {
    815  1.1  christos 	struct addrinfo hints, *res, *r;
    816  1.1  christos 	int error, maxs;
    817  1.1  christos 	const int on = 1;
    818  1.1  christos 	struct socketEvent *s, *socks;
    819  1.1  christos 
    820  1.1  christos 	if(!tls_opt.server
    821  1.1  christos 	|| !tls_opt.global_TLS_CTX)
    822  1.1  christos 		return NULL;
    823  1.1  christos 
    824  1.1  christos 	memset(&hints, 0, sizeof(hints));
    825  1.1  christos 	hints.ai_flags = AI_PASSIVE;
    826  1.1  christos 	hints.ai_family = af;
    827  1.1  christos 	hints.ai_socktype = SOCK_STREAM;
    828  1.3   minskim 
    829  1.1  christos 	error = getaddrinfo(bindhostname, (port ? port : "syslog-tls"),
    830  1.1  christos 	    &hints, &res);
    831  1.1  christos 	if (error) {
    832  1.1  christos 		logerror(gai_strerror(error));
    833  1.1  christos 		errno = 0;
    834  1.1  christos 		die(0, 0, NULL);
    835  1.1  christos 	}
    836  1.1  christos 
    837  1.1  christos 	/* Count max number of sockets we may open */
    838  1.1  christos 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
    839  1.1  christos 		continue;
    840  1.1  christos 	socks = malloc((maxs+1) * sizeof(*socks));
    841  1.1  christos 	if (!socks) {
    842  1.1  christos 		logerror("Unable to allocate memory for sockets");
    843  1.1  christos 		die(0, 0, NULL);
    844  1.1  christos 	}
    845  1.1  christos 
    846  1.1  christos 	socks->fd = 0;	 /* num of sockets counter at start of array */
    847  1.1  christos 	s = socks + 1;
    848  1.1  christos 	for (r = res; r; r = r->ai_next) {
    849  1.1  christos 		if ((s->fd = socket(r->ai_family, r->ai_socktype,
    850  1.1  christos 			r->ai_protocol)) == -1) {
    851  1.1  christos 			logerror("socket() failed: %s", strerror(errno));
    852  1.1  christos 			continue;
    853  1.1  christos 		}
    854  1.1  christos 		if (r->ai_family == AF_INET6
    855  1.1  christos 		 && setsockopt(s->fd, IPPROTO_IPV6, IPV6_V6ONLY,
    856  1.1  christos 			&on, sizeof(on)) == -1) {
    857  1.1  christos 			logerror("setsockopt(IPV6_V6ONLY) failed: %s",
    858  1.1  christos 			    strerror(errno));
    859  1.1  christos 			close(s->fd);
    860  1.1  christos 			continue;
    861  1.1  christos 		}
    862  1.1  christos 		if (setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR,
    863  1.1  christos 			&on, sizeof(on)) == -1) {
    864  1.1  christos 			DPRINTF(D_NET, "Unable to setsockopt(): %s\n",
    865  1.1  christos 			    strerror(errno));
    866  1.1  christos 		}
    867  1.1  christos 		if ((error = bind(s->fd, r->ai_addr, r->ai_addrlen)) == -1) {
    868  1.1  christos 			logerror("bind() failed: %s", strerror(errno));
    869  1.1  christos 			/* is there a better way to handle a EADDRINUSE? */
    870  1.1  christos 			close(s->fd);
    871  1.1  christos 			continue;
    872  1.1  christos 		}
    873  1.1  christos 		if (listen(s->fd, TLSBACKLOG) == -1) {
    874  1.1  christos 			logerror("listen() failed: %s", strerror(errno));
    875  1.1  christos 			close(s->fd);
    876  1.1  christos 			continue;
    877  1.1  christos 		}
    878  1.1  christos 		s->ev = allocev();
    879  1.1  christos 		event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
    880  1.1  christos 		    dispatch_socket_accept, s->ev);
    881  1.1  christos 		EVENT_ADD(s->ev);
    882  1.1  christos 
    883  1.1  christos 		socks->fd = socks->fd + 1;  /* num counter */
    884  1.1  christos 		s++;
    885  1.1  christos 	}
    886  1.1  christos 
    887  1.1  christos 	if (socks->fd == 0) {
    888  1.1  christos 		free (socks);
    889  1.1  christos 		if(Debug)
    890  1.1  christos 			return NULL;
    891  1.1  christos 		else
    892  1.1  christos 			die(0, 0, NULL);
    893  1.1  christos 	}
    894  1.1  christos 	if (res)
    895  1.1  christos 		freeaddrinfo(res);
    896  1.1  christos 
    897  1.1  christos 	return socks;
    898  1.1  christos }
    899  1.1  christos 
    900  1.1  christos /*
    901  1.1  christos  * Dispatch routine for non-blocking SSL_connect()
    902  1.1  christos  * Has to be idempotent in case of TLS_RETRY (~ EAGAIN),
    903  1.1  christos  * so we can continue a slow handshake.
    904  1.1  christos  */
    905  1.1  christos /*ARGSUSED*/
    906  1.1  christos void
    907  1.1  christos dispatch_SSL_connect(int fd, short event, void *arg)
    908  1.1  christos {
    909  1.1  christos 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
    910  1.1  christos 	SSL *ssl = conn_info->sslptr;
    911  1.1  christos 	int rc, error;
    912  1.1  christos 	sigset_t newmask, omask;
    913  1.1  christos 	struct timeval tv;
    914  1.1  christos 
    915  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
    916  1.1  christos 	DPRINTF((D_TLS|D_CALL), "dispatch_SSL_connect(conn_info@%p, fd %d)\n",
    917  1.1  christos 	    conn_info, fd);
    918  1.1  christos 	assert(conn_info->state == ST_TCP_EST
    919  1.1  christos 	    || conn_info->state == ST_CONNECTING);
    920  1.1  christos 
    921  1.1  christos 	ST_CHANGE(conn_info->state, ST_CONNECTING);
    922  1.1  christos 	rc = SSL_connect(ssl);
    923  1.1  christos 	if (0 >= rc) {
    924  1.1  christos 		error = tls_examine_error("SSL_connect()",
    925  1.1  christos 		    conn_info->sslptr, NULL, rc);
    926  1.1  christos 		switch (error) {
    927  1.1  christos 		case TLS_RETRY_READ:
    928  1.1  christos 			event_set(conn_info->retryevent, fd, EV_READ,
    929  1.1  christos 			    dispatch_SSL_connect, conn_info);
    930  1.1  christos 			EVENT_ADD(conn_info->retryevent);
    931  1.1  christos 			break;
    932  1.1  christos 		case TLS_RETRY_WRITE:
    933  1.1  christos 			event_set(conn_info->retryevent, fd, EV_WRITE,
    934  1.1  christos 			    dispatch_SSL_connect, conn_info);
    935  1.1  christos 			EVENT_ADD(conn_info->retryevent);
    936  1.1  christos 			break;
    937  1.1  christos 		default: /* should not happen,
    938  1.1  christos 			  * ... but does if the cert is not accepted */
    939  1.1  christos 			logerror("Cannot establish TLS connection "
    940  1.1  christos 			    "to \"%s\" -- TLS handshake aborted "
    941  1.1  christos 			    "before certificate authentication.",
    942  1.1  christos 			    conn_info->hostname);
    943  1.1  christos 			ST_CHANGE(conn_info->state, ST_NONE);
    944  1.1  christos 			conn_info->reconnect = 5 * TLS_RECONNECT_SEC;
    945  1.1  christos 			tv.tv_sec = conn_info->reconnect;
    946  1.1  christos 			tv.tv_usec = 0;
    947  1.1  christos 			schedule_event(&conn_info->event, &tv,
    948  1.1  christos 			    tls_reconnect, conn_info);
    949  1.1  christos 			break;
    950  1.1  christos 		}
    951  1.1  christos 		RESTORE_SIGNALS(omask);
    952  1.1  christos 		return;
    953  1.1  christos 	}
    954  1.1  christos 	/* else */
    955  1.1  christos 	conn_info->reconnect = TLS_RECONNECT_SEC;
    956  1.1  christos 	event_set(conn_info->event, fd, EV_READ, dispatch_tls_eof, conn_info);
    957  1.1  christos 	EVENT_ADD(conn_info->event);
    958  1.1  christos 
    959  1.1  christos 	DPRINTF(D_TLS, "TLS connection established.\n");
    960  1.1  christos 	ST_CHANGE(conn_info->state, ST_TLS_EST);
    961  1.1  christos 
    962  1.1  christos 	send_queue(0, 0, get_f_by_conninfo(conn_info));
    963  1.1  christos 	RESTORE_SIGNALS(omask);
    964  1.1  christos }
    965  1.1  christos 
    966  1.1  christos /*
    967  1.3   minskim  * establish TLS connection
    968  1.1  christos  */
    969  1.1  christos bool
    970  1.1  christos tls_connect(struct tls_conn_settings *conn_info)
    971  1.1  christos {
    972  1.1  christos 	struct addrinfo hints, *res, *res1;
    973  1.1  christos 	int    error, rc, sock;
    974  1.1  christos 	const int one = 1;
    975  1.1  christos 	char   buf[MAXLINE];
    976  1.1  christos 	SSL    *ssl = NULL;
    977  1.3   minskim 
    978  1.1  christos 	DPRINTF((D_TLS|D_CALL), "tls_connect(conn_info@%p)\n", conn_info);
    979  1.1  christos 	assert(conn_info->state == ST_NONE);
    980  1.3   minskim 
    981  1.1  christos 	if(!tls_opt.global_TLS_CTX)
    982  1.1  christos 		return false;
    983  1.3   minskim 
    984  1.1  christos 	memset(&hints, 0, sizeof(hints));
    985  1.1  christos 	hints.ai_family = AF_UNSPEC;
    986  1.1  christos 	hints.ai_socktype = SOCK_STREAM;
    987  1.1  christos 	hints.ai_protocol = 0;
    988  1.1  christos 	hints.ai_flags = AI_CANONNAME;
    989  1.1  christos 	error = getaddrinfo(conn_info->hostname,
    990  1.1  christos 	    (conn_info->port ? conn_info->port : "syslog-tls"), &hints, &res);
    991  1.1  christos 	if (error) {
    992  1.1  christos 		logerror(gai_strerror(error));
    993  1.1  christos 		return false;
    994  1.1  christos 	}
    995  1.3   minskim 
    996  1.1  christos 	sock = -1;
    997  1.1  christos 	for (res1 = res; res1; res1 = res1->ai_next) {
    998  1.1  christos 		if ((sock = socket(res1->ai_family, res1->ai_socktype,
    999  1.1  christos 		    res1->ai_protocol)) == -1) {
   1000  1.1  christos 			DPRINTF(D_NET, "Unable to open socket.\n");
   1001  1.1  christos 			continue;
   1002  1.1  christos 		}
   1003  1.1  christos 		if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
   1004  1.1  christos 			&one, sizeof(one)) == -1) {
   1005  1.1  christos 			DPRINTF(D_NET, "Unable to setsockopt(): %s\n",
   1006  1.1  christos 			    strerror(errno));
   1007  1.1  christos 		}
   1008  1.1  christos 		if (connect(sock, res1->ai_addr, res1->ai_addrlen) == -1) {
   1009  1.1  christos 			DPRINTF(D_NET, "Unable to connect() to %s: %s\n",
   1010  1.1  christos 			    res1->ai_canonname, strerror(errno));
   1011  1.1  christos 			close(sock);
   1012  1.1  christos 			sock = -1;
   1013  1.1  christos 			continue;
   1014  1.1  christos 		}
   1015  1.1  christos 		ST_CHANGE(conn_info->state, ST_TCP_EST);
   1016  1.1  christos 
   1017  1.1  christos 		if (!(ssl = SSL_new(tls_opt.global_TLS_CTX))) {
   1018  1.1  christos 			ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
   1019  1.1  christos 			DPRINTF(D_TLS, "Unable to establish TLS: %s\n", buf);
   1020  1.1  christos 			close(sock);
   1021  1.1  christos 			sock = -1;
   1022  1.1  christos 			ST_CHANGE(conn_info->state, ST_NONE);
   1023  1.3   minskim 			continue;
   1024  1.1  christos 		}
   1025  1.1  christos 		if (!SSL_set_fd(ssl, sock)) {
   1026  1.1  christos 			ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
   1027  1.1  christos 			DPRINTF(D_TLS, "Unable to connect TLS to socket: %s\n",
   1028  1.1  christos 			    buf);
   1029  1.1  christos 			FREE_SSL(ssl);
   1030  1.1  christos 			close(sock);
   1031  1.1  christos 			sock = -1;
   1032  1.1  christos 			ST_CHANGE(conn_info->state, ST_NONE);
   1033  1.1  christos 			continue;
   1034  1.1  christos 		}
   1035  1.3   minskim 
   1036  1.1  christos 		SSL_set_app_data(ssl, conn_info);
   1037  1.1  christos 		SSL_set_connect_state(ssl);
   1038  1.1  christos 		while ((rc = ERR_get_error()) != 0) {
   1039  1.1  christos 			ERR_error_string_n(rc, buf, sizeof(buf));
   1040  1.1  christos 			DPRINTF(D_TLS, "Found SSL error in queue: %s\n", buf);
   1041  1.1  christos 		}
   1042  1.1  christos 		errno = 0;  /* reset to be sure we get the right one later on */
   1043  1.3   minskim 
   1044  1.1  christos 		if ((fcntl(sock, F_SETFL, O_NONBLOCK)) == -1) {
   1045  1.1  christos 			DPRINTF(D_NET, "Unable to fcntl(sock, O_NONBLOCK): "
   1046  1.1  christos 			    "%s\n", strerror(errno));
   1047  1.1  christos 		}
   1048  1.1  christos 
   1049  1.1  christos 		/* now we have a TCP connection, so assume we can
   1050  1.1  christos 		 * use that and do not have to try another res */
   1051  1.1  christos 		conn_info->sslptr = ssl;
   1052  1.1  christos 
   1053  1.1  christos 		assert(conn_info->state == ST_TCP_EST);
   1054  1.1  christos 		assert(conn_info->event);
   1055  1.1  christos 		assert(conn_info->retryevent);
   1056  1.1  christos 
   1057  1.1  christos 		freeaddrinfo(res);
   1058  1.1  christos 		dispatch_SSL_connect(sock, 0, conn_info);
   1059  1.1  christos 		return true;
   1060  1.1  christos 	}
   1061  1.1  christos 	/* still no connection after for loop */
   1062  1.1  christos 	DPRINTF((D_TLS|D_NET), "Unable to establish a TCP connection to %s\n",
   1063  1.1  christos 	    conn_info->hostname);
   1064  1.1  christos 	freeaddrinfo(res);
   1065  1.1  christos 
   1066  1.1  christos 	assert(conn_info->state == ST_NONE);
   1067  1.1  christos 	if (sock != -1)
   1068  1.1  christos 		close(sock);
   1069  1.1  christos 	if (ssl) {
   1070  1.1  christos 		SSL_shutdown(ssl);
   1071  1.1  christos 		SSL_free(ssl);
   1072  1.1  christos 	}
   1073  1.1  christos 	return false;
   1074  1.1  christos }
   1075  1.1  christos 
   1076  1.1  christos int
   1077  1.1  christos tls_examine_error(const char *functionname, const SSL *ssl,
   1078  1.1  christos 	struct tls_conn_settings *tls_conn, const int rc)
   1079  1.1  christos {
   1080  1.1  christos 	int ssl_error, err_error;
   1081  1.3   minskim 
   1082  1.1  christos 	ssl_error = SSL_get_error(ssl, rc);
   1083  1.1  christos 	DPRINTF(D_TLS, "%s returned rc %d and error %s: %s\n", functionname,
   1084  1.1  christos 		rc, SSL_ERRCODE[ssl_error], ERR_error_string(ssl_error, NULL));
   1085  1.1  christos 	switch (ssl_error) {
   1086  1.1  christos 	case SSL_ERROR_WANT_READ:
   1087  1.1  christos 		return TLS_RETRY_READ;
   1088  1.1  christos 	case SSL_ERROR_WANT_WRITE:
   1089  1.1  christos 		return TLS_RETRY_WRITE;
   1090  1.1  christos 	case SSL_ERROR_SYSCALL:
   1091  1.1  christos 		DPRINTF(D_TLS, "SSL_ERROR_SYSCALL: ");
   1092  1.1  christos 		err_error = ERR_get_error();
   1093  1.1  christos 		if ((rc == -1) && (err_error == 0)) {
   1094  1.1  christos 			DPRINTF(D_TLS, "socket I/O error: %s\n",
   1095  1.1  christos 			    strerror(errno));
   1096  1.1  christos 		} else if ((rc == 0) && (err_error == 0)) {
   1097  1.1  christos 			DPRINTF(D_TLS, "unexpected EOF from %s\n",
   1098  1.1  christos 			    tls_conn ? tls_conn->hostname : NULL);
   1099  1.1  christos 		} else {
   1100  1.1  christos 			DPRINTF(D_TLS, "no further info\n");
   1101  1.1  christos 		}
   1102  1.1  christos 		return TLS_PERM_ERROR;
   1103  1.1  christos 	case SSL_ERROR_ZERO_RETURN:
   1104  1.1  christos 		logerror("TLS connection closed by %s",
   1105  1.1  christos 		    tls_conn ? tls_conn->hostname : NULL);
   1106  1.1  christos 		return TLS_PERM_ERROR;
   1107  1.1  christos 	case SSL_ERROR_SSL:
   1108  1.1  christos 		logerror("internal SSL error, error queue gives %s",
   1109  1.1  christos 		    ERR_error_string(ERR_get_error(), NULL));
   1110  1.1  christos 		return TLS_PERM_ERROR;
   1111  1.1  christos 	default:
   1112  1.3   minskim 		break;
   1113  1.1  christos 	}
   1114  1.1  christos 	if (tls_conn)
   1115  1.1  christos 		tls_conn->errorcount++;
   1116  1.1  christos 	/* TODO: is this ever reached? */
   1117  1.1  christos 	return TLS_TEMP_ERROR;
   1118  1.1  christos }
   1119  1.1  christos 
   1120  1.1  christos 
   1121  1.1  christos bool
   1122  1.1  christos parse_tls_destination(const char *p, struct filed *f, size_t linenum)
   1123  1.1  christos {
   1124  1.1  christos 	const char *q;
   1125  1.1  christos 
   1126  1.1  christos 	if ((*p++ != '@') || *p++ != '[') {
   1127  1.1  christos 		logerror("parse_tls_destination() on non-TLS action "
   1128  1.1  christos 		    "in config line %zu", linenum);
   1129  1.3   minskim 		return false;
   1130  1.1  christos 	}
   1131  1.3   minskim 
   1132  1.1  christos 	if (!(q = strchr(p, ']'))) {
   1133  1.1  christos 		logerror("Unterminated [ "
   1134  1.1  christos 		    "in config line %zu", linenum);
   1135  1.1  christos 		return false;
   1136  1.1  christos 	}
   1137  1.1  christos 
   1138  1.1  christos 	if (!(f->f_un.f_tls.tls_conn =
   1139  1.1  christos 		calloc(1, sizeof(*f->f_un.f_tls.tls_conn)))
   1140  1.1  christos 	 || !(f->f_un.f_tls.tls_conn->event = allocev())
   1141  1.1  christos 	 || !(f->f_un.f_tls.tls_conn->retryevent = allocev())) {
   1142  1.1  christos 		free(f->f_un.f_tls.tls_conn->event);
   1143  1.1  christos 		free(f->f_un.f_tls.tls_conn);
   1144  1.1  christos 		logerror("Couldn't allocate memory for TLS config");
   1145  1.1  christos 		return false;
   1146  1.1  christos 	}
   1147  1.1  christos 	/* default values */
   1148  1.1  christos 	f->f_un.f_tls.tls_conn->x509verify = X509VERIFY_ALWAYS;
   1149  1.1  christos 	f->f_un.f_tls.tls_conn->reconnect = TLS_RECONNECT_SEC;
   1150  1.1  christos 
   1151  1.1  christos 	if (!(copy_string(&(f->f_un.f_tls.tls_conn->hostname), p, q))) {
   1152  1.1  christos 		logerror("Unable to read TLS server name"
   1153  1.1  christos 		    "in config line %zu", linenum);
   1154  1.1  christos 		free_tls_conn(f->f_un.f_tls.tls_conn);
   1155  1.1  christos 		return false;
   1156  1.1  christos 	}
   1157  1.1  christos 	p = ++q;
   1158  1.3   minskim 
   1159  1.1  christos 	if (*p == ':') {
   1160  1.1  christos 		p++; q++;
   1161  1.1  christos 		while (isalnum((unsigned char)*q))
   1162  1.1  christos 			q++;
   1163  1.1  christos 		if (!(copy_string(&(f->f_un.f_tls.tls_conn->port), p, q))) {
   1164  1.1  christos 			logerror("Unable to read TLS port or service name"
   1165  1.1  christos 				" after ':' in config line %zu", linenum);
   1166  1.1  christos 			free_tls_conn(f->f_un.f_tls.tls_conn);
   1167  1.1  christos 			return false;
   1168  1.1  christos 		}
   1169  1.1  christos 		p = q;
   1170  1.1  christos 	}
   1171  1.1  christos 	/* allow whitespace for readability? */
   1172  1.1  christos 	while (isblank((unsigned char)*p))
   1173  1.1  christos 		p++;
   1174  1.1  christos 	if (*p == '(') {
   1175  1.1  christos 		p++;
   1176  1.1  christos 		while (*p != ')') {
   1177  1.1  christos 			if (copy_config_value_quoted("subject=\"",
   1178  1.1  christos 			    &(f->f_un.f_tls.tls_conn->subject), &p)
   1179  1.1  christos 			    || copy_config_value_quoted("fingerprint=\"",
   1180  1.1  christos 			    &(f->f_un.f_tls.tls_conn->fingerprint), &p)
   1181  1.1  christos 			    || copy_config_value_quoted("cert=\"",
   1182  1.1  christos 			    &(f->f_un.f_tls.tls_conn->certfile), &p)) {
   1183  1.1  christos 			/* nothing */
   1184  1.1  christos 			} else if (!strcmp(p, "verify=")) {
   1185  1.1  christos 				q = p += sizeof("verify=")-1;
   1186  1.1  christos 				/* "" are optional */
   1187  1.1  christos 				if (*p == '\"') { p++; q++; }
   1188  1.1  christos 				while (isalpha((unsigned char)*q)) q++;
   1189  1.1  christos 				f->f_un.f_tls.tls_conn->x509verify =
   1190  1.1  christos 				    getVerifySetting(p);
   1191  1.1  christos 				if (*q == '\"') q++;  /* "" are optional */
   1192  1.1  christos 				p = q;
   1193  1.1  christos 			} else {
   1194  1.1  christos 				logerror("unknown keyword %s "
   1195  1.1  christos 				    "in config line %zu", p, linenum);
   1196  1.1  christos 			}
   1197  1.1  christos 			while (*p == ',' || isblank(*p))
   1198  1.1  christos 				p++;
   1199  1.1  christos 			if (*p == '\0') {
   1200  1.1  christos 				logerror("unterminated ("
   1201  1.1  christos 				    "in config line %zu", linenum);
   1202  1.1  christos 			}
   1203  1.1  christos 		}
   1204  1.1  christos 	}
   1205  1.3   minskim 
   1206  1.1  christos 	DPRINTF((D_TLS|D_PARSE),
   1207  1.1  christos 	    "got TLS config: host %s, port %s, "
   1208  1.1  christos 	    "subject: %s, certfile: %s, fingerprint: %s\n",
   1209  1.1  christos 	    f->f_un.f_tls.tls_conn->hostname,
   1210  1.1  christos 	    f->f_un.f_tls.tls_conn->port,
   1211  1.1  christos 	    f->f_un.f_tls.tls_conn->subject,
   1212  1.1  christos 	    f->f_un.f_tls.tls_conn->certfile,
   1213  1.1  christos 	    f->f_un.f_tls.tls_conn->fingerprint);
   1214  1.1  christos 	return true;
   1215  1.1  christos }
   1216  1.1  christos 
   1217  1.1  christos /*
   1218  1.1  christos  * Dispatch routine (triggered by timer) to reconnect to a lost TLS server
   1219  1.1  christos  */
   1220  1.1  christos /*ARGSUSED*/
   1221  1.1  christos void
   1222  1.1  christos tls_reconnect(int fd, short event, void *arg)
   1223  1.1  christos {
   1224  1.1  christos 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
   1225  1.1  christos 
   1226  1.1  christos 	DPRINTF((D_TLS|D_CALL|D_EVENT), "tls_reconnect(conn_info@%p, "
   1227  1.1  christos 	    "server %s)\n", conn_info, conn_info->hostname);
   1228  1.1  christos 	if (conn_info->sslptr) {
   1229  1.1  christos 		conn_info->shutdown = true;
   1230  1.1  christos 		free_tls_sslptr(conn_info);
   1231  1.1  christos 	}
   1232  1.1  christos 	assert(conn_info->state == ST_NONE);
   1233  1.1  christos 
   1234  1.1  christos 	if (!tls_connect(conn_info)) {
   1235  1.1  christos 		if (conn_info->reconnect > TLS_RECONNECT_GIVEUP) {
   1236  1.1  christos 			logerror("Unable to connect to TLS server %s, "
   1237  1.1  christos 			    "giving up now", conn_info->hostname);
   1238  1.1  christos 			message_queue_freeall(get_f_by_conninfo(conn_info));
   1239  1.1  christos 			/* free the message queue; but do not free the
   1240  1.1  christos 			 * tls_conn_settings nor change the f_type to F_UNUSED.
   1241  1.1  christos 			 * that way one can still trigger a reconnect
   1242  1.1  christos 			 * with a SIGUSR1
   1243  1.1  christos 			 */
   1244  1.1  christos 		} else {
   1245  1.1  christos 			struct timeval tv;
   1246  1.1  christos 			logerror("Unable to connect to TLS server %s, "
   1247  1.1  christos 			    "try again in %d sec", conn_info->hostname,
   1248  1.1  christos 			    conn_info->reconnect);
   1249  1.1  christos 			tv.tv_sec = conn_info->reconnect;
   1250  1.1  christos 			tv.tv_usec = 0;
   1251  1.1  christos 			schedule_event(&conn_info->event, &tv,
   1252  1.1  christos 			    tls_reconnect, conn_info);
   1253  1.1  christos 			TLS_RECONNECT_BACKOFF(conn_info->reconnect);
   1254  1.1  christos 		}
   1255  1.1  christos 	} else {
   1256  1.1  christos 		assert(conn_info->state == ST_TLS_EST
   1257  1.1  christos 		    || conn_info->state == ST_CONNECTING
   1258  1.1  christos 		    || conn_info->state == ST_NONE);
   1259  1.3   minskim 	}
   1260  1.1  christos }
   1261  1.1  christos /*
   1262  1.1  christos  * Dispatch routine for accepting TLS connections.
   1263  1.1  christos  * Has to be idempotent in case of TLS_RETRY (~ EAGAIN),
   1264  1.1  christos  * so we can continue a slow handshake.
   1265  1.1  christos  */
   1266  1.1  christos /*ARGSUSED*/
   1267  1.1  christos void
   1268  1.1  christos dispatch_tls_accept(int fd, short event, void *arg)
   1269  1.1  christos {
   1270  1.1  christos 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
   1271  1.1  christos 	int rc, error;
   1272  1.1  christos 	struct TLS_Incoming_Conn *tls_in;
   1273  1.1  christos 	sigset_t newmask, omask;
   1274  1.1  christos 
   1275  1.1  christos 	DPRINTF((D_TLS|D_CALL),
   1276  1.1  christos 		"dispatch_tls_accept(conn_info@%p, fd %d)\n", conn_info, fd);
   1277  1.1  christos 	assert(conn_info->event);
   1278  1.1  christos 	assert(conn_info->retryevent);
   1279  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1280  1.1  christos 
   1281  1.1  christos 	ST_CHANGE(conn_info->state, ST_ACCEPTING);
   1282  1.1  christos 	rc = SSL_accept(conn_info->sslptr);
   1283  1.1  christos 	if (0 >= rc) {
   1284  1.1  christos 		error = tls_examine_error("SSL_accept()",
   1285  1.1  christos 		    conn_info->sslptr, NULL, rc);
   1286  1.1  christos 		switch (error) {
   1287  1.1  christos 		case TLS_RETRY_READ:
   1288  1.1  christos 			event_set(conn_info->retryevent, fd, EV_READ,
   1289  1.1  christos 			    dispatch_tls_accept, conn_info);
   1290  1.1  christos 			EVENT_ADD(conn_info->retryevent);
   1291  1.1  christos 			break;
   1292  1.1  christos 		case TLS_RETRY_WRITE:
   1293  1.1  christos 			event_set(conn_info->retryevent, fd, EV_WRITE,
   1294  1.1  christos 			    dispatch_tls_accept, conn_info);
   1295  1.1  christos 			EVENT_ADD(conn_info->retryevent);
   1296  1.1  christos 			break;
   1297  1.1  christos 		default: /* should not happen */
   1298  1.1  christos 			free_tls_conn(conn_info);
   1299  1.1  christos 			break;
   1300  1.1  christos 		}
   1301  1.1  christos 		RESTORE_SIGNALS(omask);
   1302  1.1  christos 		return;
   1303  1.1  christos 	}
   1304  1.1  christos 	/* else */
   1305  1.1  christos 	CALLOC(tls_in, sizeof(*tls_in));
   1306  1.1  christos 	CALLOC(tls_in->inbuf, (size_t)TLS_MIN_LINELENGTH);
   1307  1.1  christos 
   1308  1.1  christos 	tls_in->tls_conn = conn_info;
   1309  1.1  christos 	tls_in->socket = SSL_get_fd(conn_info->sslptr);
   1310  1.1  christos 	tls_in->inbuf[0] = '\0';
   1311  1.1  christos 	tls_in->inbuflen = TLS_MIN_LINELENGTH;
   1312  1.1  christos 	SLIST_INSERT_HEAD(&TLS_Incoming_Head, tls_in, entries);
   1313  1.1  christos 
   1314  1.1  christos 	event_set(conn_info->event, tls_in->socket, EV_READ | EV_PERSIST,
   1315  1.1  christos 	    dispatch_tls_read, tls_in);
   1316  1.1  christos 	EVENT_ADD(conn_info->event);
   1317  1.1  christos 	ST_CHANGE(conn_info->state, ST_TLS_EST);
   1318  1.1  christos 
   1319  1.1  christos 	loginfo("established TLS connection from %s with certificate "
   1320  1.1  christos 	    "%s (%s)", conn_info->hostname, conn_info->subject,
   1321  1.1  christos 	    conn_info->fingerprint);
   1322  1.1  christos 	RESTORE_SIGNALS(omask);
   1323  1.1  christos 	/*
   1324  1.1  christos 	 * We could also listen to EOF kevents -- but I do not think
   1325  1.1  christos 	 * that would be useful, because we still had to read() the buffer
   1326  1.1  christos 	 * before closing the socket.
   1327  1.1  christos 	 */
   1328  1.1  christos }
   1329  1.1  christos 
   1330  1.1  christos /*
   1331  1.1  christos  * Dispatch routine for accepting TCP connections and preparing
   1332  1.1  christos  * the tls_conn_settings object for a following SSL_accept().
   1333  1.1  christos  */
   1334  1.1  christos /*ARGSUSED*/
   1335  1.1  christos void
   1336  1.1  christos dispatch_socket_accept(int fd, short event, void *ev)
   1337  1.1  christos {
   1338  1.1  christos #ifdef LIBWRAP
   1339  1.1  christos 	struct request_info req;
   1340  1.1  christos #endif
   1341  1.1  christos 	struct sockaddr_storage frominet;
   1342  1.1  christos 	socklen_t addrlen;
   1343  1.1  christos 	int newsock, rc;
   1344  1.1  christos 	sigset_t newmask, omask;
   1345  1.1  christos 	SSL *ssl;
   1346  1.1  christos 	struct tls_conn_settings *conn_info;
   1347  1.1  christos 	char hbuf[NI_MAXHOST];
   1348  1.1  christos 	char *peername;
   1349  1.1  christos 
   1350  1.1  christos 	DPRINTF((D_TLS|D_NET), "incoming TCP connection\n");
   1351  1.1  christos 	if (!tls_opt.global_TLS_CTX) {
   1352  1.1  christos 		logerror("global_TLS_CTX not initialized!");
   1353  1.1  christos 		return;
   1354  1.1  christos 	}
   1355  1.1  christos 
   1356  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1357  1.1  christos 	addrlen = sizeof(frominet);
   1358  1.1  christos 	if ((newsock = accept(fd, (struct sockaddr *)&frominet,
   1359  1.1  christos 	    &addrlen)) == -1) {
   1360  1.1  christos 		logerror("Error in accept(): %s", strerror(errno));
   1361  1.1  christos 		RESTORE_SIGNALS(omask);
   1362  1.1  christos 		return;
   1363  1.1  christos 	}
   1364  1.1  christos 	/* TODO: do we want an IP or a hostname? maybe even both? */
   1365  1.1  christos 	if ((rc = getnameinfo((struct sockaddr *)&frominet, addrlen,
   1366  1.1  christos 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
   1367  1.1  christos 		DPRINTF(D_NET, "could not get peername: %s", gai_strerror(rc));
   1368  1.1  christos 		peername = NULL;
   1369  1.1  christos 	}
   1370  1.1  christos 	else {
   1371  1.1  christos 		MALLOC(peername, strlen(hbuf)+1);
   1372  1.1  christos 		(void)strlcpy(peername, hbuf, strlen(hbuf)+1);
   1373  1.1  christos 	}
   1374  1.1  christos 
   1375  1.1  christos #ifdef LIBWRAP
   1376  1.1  christos 	request_init(&req, RQ_DAEMON, appname, RQ_FILE, newsock, NULL);
   1377  1.1  christos 	fromhost(&req);
   1378  1.1  christos 	if (!hosts_access(&req)) {
   1379  1.1  christos 		logerror("access from %s denied by hosts_access", peername);
   1380  1.1  christos 		shutdown(newsock, SHUT_RDWR);
   1381  1.1  christos 		close(newsock);
   1382  1.1  christos 		RESTORE_SIGNALS(omask);
   1383  1.1  christos 		return;
   1384  1.1  christos 	}
   1385  1.1  christos #endif
   1386  1.1  christos 
   1387  1.1  christos 	if ((fcntl(newsock, F_SETFL, O_NONBLOCK)) == -1) {
   1388  1.1  christos 		DPRINTF(D_NET, "Unable to fcntl(sock, O_NONBLOCK): %s\n",
   1389  1.1  christos 		    strerror(errno));
   1390  1.1  christos 	}
   1391  1.3   minskim 
   1392  1.1  christos 	if (!(ssl = SSL_new(tls_opt.global_TLS_CTX))) {
   1393  1.1  christos 		DPRINTF(D_TLS, "Unable to establish TLS: %s\n",
   1394  1.1  christos 		    ERR_error_string(ERR_get_error(), NULL));
   1395  1.1  christos 		close(newsock);
   1396  1.1  christos 		RESTORE_SIGNALS(omask);
   1397  1.3   minskim 		return;
   1398  1.1  christos 	}
   1399  1.1  christos 	if (!SSL_set_fd(ssl, newsock)) {
   1400  1.1  christos 		DPRINTF(D_TLS, "Unable to connect TLS to socket %d: %s\n",
   1401  1.1  christos 			newsock, ERR_error_string(ERR_get_error(), NULL));
   1402  1.1  christos 		SSL_free(ssl);
   1403  1.1  christos 		close(newsock);
   1404  1.1  christos 		RESTORE_SIGNALS(omask);
   1405  1.1  christos 		return;
   1406  1.1  christos 	}
   1407  1.1  christos 
   1408  1.1  christos 	if (!(conn_info = calloc(1, sizeof(*conn_info)))
   1409  1.1  christos 	    || !(conn_info->event = allocev())
   1410  1.1  christos 	    || !(conn_info->retryevent = allocev())) {
   1411  1.1  christos 		free(conn_info->event);
   1412  1.1  christos 		free(conn_info);
   1413  1.1  christos 		SSL_free(ssl);
   1414  1.1  christos 		close(newsock);
   1415  1.1  christos 		logerror("Unable to allocate memory to accept incoming "
   1416  1.1  christos 		    "TLS connection from %s", peername);
   1417  1.1  christos 		RESTORE_SIGNALS(omask);
   1418  1.1  christos 		return;
   1419  1.1  christos 	}
   1420  1.1  christos 	ST_CHANGE(conn_info->state, ST_NONE);
   1421  1.1  christos 	/* store connection details inside ssl object, used to verify
   1422  1.1  christos 	 * cert and immediately match against hostname */
   1423  1.1  christos 	conn_info->hostname = peername;
   1424  1.1  christos 	conn_info->sslptr = ssl;
   1425  1.1  christos 	conn_info->x509verify = getVerifySetting(tls_opt.x509verify);
   1426  1.1  christos 	conn_info->incoming = true;
   1427  1.1  christos 	SSL_set_app_data(ssl, conn_info);
   1428  1.1  christos 	SSL_set_accept_state(ssl);
   1429  1.1  christos 
   1430  1.1  christos 	assert(conn_info->event);
   1431  1.1  christos 	assert(conn_info->retryevent);
   1432  1.3   minskim 
   1433  1.1  christos 	ST_CHANGE(conn_info->state, ST_TCP_EST);
   1434  1.1  christos 	DPRINTF(D_TLS, "socket connection from %s accept()ed with fd %d, "
   1435  1.1  christos 		"calling SSL_accept()...\n",  peername, newsock);
   1436  1.1  christos 	dispatch_tls_accept(newsock, 0, conn_info);
   1437  1.1  christos 	RESTORE_SIGNALS(omask);
   1438  1.1  christos }
   1439  1.1  christos 
   1440  1.1  christos /*
   1441  1.1  christos  * Dispatch routine to read from outgoing TCP/TLS sockets.
   1442  1.3   minskim  *
   1443  1.1  christos  * I do not know if libevent can tell us the difference
   1444  1.1  christos  * between available data and an EOF. But it does not matter
   1445  1.1  christos  * because there should not be any incoming data.
   1446  1.1  christos  * So we close the connection either because the peer closed its
   1447  1.1  christos  * side or because the peer broke the protocol by sending us stuff  ;-)
   1448  1.1  christos  */
   1449  1.1  christos void
   1450  1.1  christos dispatch_tls_eof(int fd, short event, void *arg)
   1451  1.1  christos {
   1452  1.1  christos 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
   1453  1.1  christos 	sigset_t newmask, omask;
   1454  1.1  christos 	struct timeval tv;
   1455  1.3   minskim 
   1456  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1457  1.1  christos 	DPRINTF((D_TLS|D_EVENT|D_CALL), "dispatch_eof_tls(%d, %d, %p)\n",
   1458  1.1  christos 	    fd, event, arg);
   1459  1.1  christos 	assert(conn_info->state == ST_TLS_EST);
   1460  1.1  christos 	ST_CHANGE(conn_info->state, ST_EOF);
   1461  1.1  christos 	DEL_EVENT(conn_info->event);
   1462  1.1  christos 
   1463  1.1  christos 	free_tls_sslptr(conn_info);
   1464  1.1  christos 
   1465  1.1  christos 	/* this overwrites the EV_READ event */
   1466  1.1  christos 	tv.tv_sec = conn_info->reconnect;
   1467  1.1  christos 	tv.tv_usec = 0;
   1468  1.1  christos 	schedule_event(&conn_info->event, &tv, tls_reconnect, conn_info);
   1469  1.1  christos 	TLS_RECONNECT_BACKOFF(conn_info->reconnect);
   1470  1.1  christos 	RESTORE_SIGNALS(omask);
   1471  1.1  christos }
   1472  1.1  christos 
   1473  1.1  christos /*
   1474  1.1  christos  * Dispatch routine to read from TCP/TLS sockets.
   1475  1.1  christos  * NB: This gets called when the TCP socket has data available, thus
   1476  1.1  christos  *     we can call SSL_read() on it. But that does not mean the SSL buffer
   1477  1.1  christos  *     holds a complete record and SSL_read() lets us read any data now.
   1478  1.1  christos  */
   1479  1.1  christos /*ARGSUSED*/
   1480  1.1  christos void
   1481  1.1  christos dispatch_tls_read(int fd_lib, short event, void *arg)
   1482  1.1  christos {
   1483  1.1  christos 	struct TLS_Incoming_Conn *c = (struct TLS_Incoming_Conn *) arg;
   1484  1.1  christos 	int fd = c->socket;
   1485  1.1  christos 	int error;
   1486  1.2  christos 	int rc;
   1487  1.1  christos 	sigset_t newmask, omask;
   1488  1.1  christos 	bool retrying;
   1489  1.1  christos 
   1490  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1491  1.1  christos 	DPRINTF((D_TLS|D_EVENT|D_CALL), "active TLS socket %d\n", fd);
   1492  1.1  christos 	DPRINTF(D_TLS, "calling SSL_read(%p, %p, %zu)\n", c->tls_conn->sslptr,
   1493  1.1  christos 		&(c->inbuf[c->read_pos]), c->inbuflen - c->read_pos);
   1494  1.1  christos 	retrying = (c->tls_conn->state == ST_READING);
   1495  1.1  christos 	ST_CHANGE(c->tls_conn->state, ST_READING);
   1496  1.1  christos 	rc = SSL_read(c->tls_conn->sslptr, &(c->inbuf[c->read_pos]),
   1497  1.1  christos 		c->inbuflen - c->read_pos);
   1498  1.1  christos 	if (rc <= 0) {
   1499  1.1  christos 		error = tls_examine_error("SSL_read()", c->tls_conn->sslptr,
   1500  1.1  christos 		    c->tls_conn, rc);
   1501  1.1  christos 		switch (error) {
   1502  1.1  christos 		case TLS_RETRY_READ:
   1503  1.1  christos 			/* normal event loop will call us again */
   1504  1.1  christos 			break;
   1505  1.1  christos 		case TLS_RETRY_WRITE:
   1506  1.1  christos 			if (!retrying)
   1507  1.1  christos 				event_del(c->tls_conn->event);
   1508  1.1  christos 			event_set(c->tls_conn->retryevent, fd,
   1509  1.1  christos 				EV_WRITE, dispatch_tls_read, c);
   1510  1.1  christos 			EVENT_ADD(c->tls_conn->retryevent);
   1511  1.1  christos 			RESTORE_SIGNALS(omask);
   1512  1.1  christos 			return;
   1513  1.1  christos 		case TLS_TEMP_ERROR:
   1514  1.1  christos 			if (c->tls_conn->errorcount < TLS_MAXERRORCOUNT)
   1515  1.1  christos 				break;
   1516  1.1  christos 			/* FALLTHROUGH */
   1517  1.1  christos 		case TLS_PERM_ERROR:
   1518  1.1  christos 			/* there might be data in the inbuf, so only
   1519  1.1  christos 			 * mark for closing after message retrieval */
   1520  1.1  christos 			c->closenow = true;
   1521  1.1  christos 			break;
   1522  1.1  christos 		default:
   1523  1.1  christos 			break;
   1524  1.1  christos 		}
   1525  1.1  christos 	} else {
   1526  1.1  christos 		DPRINTF(D_TLS, "SSL_read() returned %d\n", rc);
   1527  1.1  christos 		c->errorcount = 0;
   1528  1.1  christos 		c->read_pos += rc;
   1529  1.1  christos 	}
   1530  1.1  christos 	if (retrying)
   1531  1.1  christos 		EVENT_ADD(c->tls_conn->event);
   1532  1.1  christos 	tls_split_messages(c);
   1533  1.1  christos 	if (c->closenow) {
   1534  1.1  christos 		free_tls_conn(c->tls_conn);
   1535  1.1  christos 		FREEPTR(c->inbuf);
   1536  1.1  christos 		SLIST_REMOVE(&TLS_Incoming_Head, c, TLS_Incoming_Conn, entries);
   1537  1.1  christos 		free(c);
   1538  1.1  christos 	} else
   1539  1.1  christos 		ST_CHANGE(c->tls_conn->state, ST_TLS_EST);
   1540  1.1  christos 	RESTORE_SIGNALS(omask);
   1541  1.1  christos }
   1542  1.1  christos 
   1543  1.1  christos /* moved message splitting out of dispatching function.
   1544  1.1  christos  * now we can call it recursively.
   1545  1.3   minskim  *
   1546  1.1  christos  * TODO: the code for oversized messages still needs testing,
   1547  1.1  christos  * especially for the skipping case.
   1548  1.1  christos  */
   1549  1.1  christos void
   1550  1.1  christos tls_split_messages(struct TLS_Incoming_Conn *c)
   1551  1.1  christos {
   1552  1.1  christos /* define only to make it better readable */
   1553  1.1  christos #define MSG_END_OFFSET (c->cur_msg_start + c->cur_msg_len)
   1554  1.1  christos 	size_t offset = 0;
   1555  1.1  christos 	size_t msglen = 0;
   1556  1.1  christos 	char *newbuf;
   1557  1.1  christos 	char buf_char;
   1558  1.3   minskim 
   1559  1.1  christos 	DPRINTF((D_TLS|D_CALL|D_DATA), "tls_split_messages() -- "
   1560  1.1  christos 		"incoming status is msg_start %zu, msg_len %zu, pos %zu\n",
   1561  1.1  christos 		c->cur_msg_start, c->cur_msg_len, c->read_pos);
   1562  1.1  christos 
   1563  1.1  christos 	if (!c->read_pos)
   1564  1.1  christos 		return;
   1565  1.3   minskim 
   1566  1.1  christos 	if (c->dontsave && c->read_pos < MSG_END_OFFSET) {
   1567  1.1  christos 		c->cur_msg_len -= c->read_pos;
   1568  1.1  christos 		c->read_pos = 0;
   1569  1.1  christos 	} else if (c->dontsave && c->read_pos == MSG_END_OFFSET) {
   1570  1.1  christos 		c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
   1571  1.1  christos 		c->dontsave = false;
   1572  1.1  christos 	} else if (c->dontsave && c->read_pos > MSG_END_OFFSET) {
   1573  1.1  christos 		/* move remaining input to start of buffer */
   1574  1.1  christos 		DPRINTF(D_DATA, "move inbuf of length %zu by %zu chars\n",
   1575  1.1  christos 		    c->read_pos - (MSG_END_OFFSET),
   1576  1.1  christos 		    MSG_END_OFFSET);
   1577  1.1  christos 		memmove(&c->inbuf[0],
   1578  1.1  christos 		    &c->inbuf[MSG_END_OFFSET],
   1579  1.1  christos 		    c->read_pos - (MSG_END_OFFSET));
   1580  1.1  christos 		c->read_pos -= (MSG_END_OFFSET);
   1581  1.1  christos 		c->cur_msg_start = c->cur_msg_len = 0;
   1582  1.1  christos 		c->dontsave = false;
   1583  1.1  christos 	}
   1584  1.1  christos 	if (c->read_pos < MSG_END_OFFSET) {
   1585  1.1  christos 		return;
   1586  1.1  christos 	}
   1587  1.3   minskim 
   1588  1.1  christos 	/* read length prefix, always at start of buffer */
   1589  1.1  christos 	while (isdigit((unsigned char)c->inbuf[offset])
   1590  1.1  christos 	    && offset < c->read_pos) {
   1591  1.1  christos 		msglen *= 10;
   1592  1.1  christos 		msglen += c->inbuf[offset] - '0';
   1593  1.1  christos 		offset++;
   1594  1.1  christos 	}
   1595  1.1  christos 	if (offset == c->read_pos) {
   1596  1.1  christos 		/* next invocation will have more data */
   1597  1.1  christos 		return;
   1598  1.1  christos 	}
   1599  1.1  christos 	if (c->inbuf[offset] == ' ') {
   1600  1.1  christos 		c->cur_msg_len = msglen;
   1601  1.1  christos 		c->cur_msg_start = offset + 1;
   1602  1.1  christos 		if (MSG_END_OFFSET+1 > c->inbuflen) {  /* +1 for the '\0' */
   1603  1.1  christos 			newbuf = realloc(c->inbuf, MSG_END_OFFSET+1);
   1604  1.1  christos 			if (newbuf) {
   1605  1.1  christos 				DPRINTF(D_DATA, "Reallocated inbuf\n");
   1606  1.1  christos 				c->inbuflen = MSG_END_OFFSET+1;
   1607  1.1  christos 				c->inbuf = newbuf;
   1608  1.1  christos 			} else {
   1609  1.1  christos 				logerror("Couldn't reallocate buffer, "
   1610  1.1  christos 				    "will skip this message");
   1611  1.1  christos 				c->dontsave = true;
   1612  1.1  christos 				c->cur_msg_len -= c->read_pos;
   1613  1.1  christos 				c->cur_msg_start = 0;
   1614  1.1  christos 				c->read_pos = 0;
   1615  1.1  christos 			}
   1616  1.1  christos 		}
   1617  1.1  christos 	} else {
   1618  1.1  christos 		/* found non-digit in prefix */
   1619  1.1  christos 		/* Question: would it be useful to skip this message and
   1620  1.1  christos 		 * try to find next message by looking for its beginning?
   1621  1.3   minskim 		 * IMHO not.
   1622  1.1  christos 		 */
   1623  1.1  christos 		logerror("Unable to handle TLS length prefix. "
   1624  1.1  christos 		    "Protocol error? Closing connection now.");
   1625  1.1  christos 		/* only set flag -- caller has to close then */
   1626  1.1  christos 		c->closenow = true;
   1627  1.1  christos 		return;
   1628  1.3   minskim 	}
   1629  1.3   minskim 	/* read one syslog message */
   1630  1.1  christos 	if (c->read_pos >= MSG_END_OFFSET) {
   1631  1.1  christos 		/* process complete msg */
   1632  1.1  christos 		assert(MSG_END_OFFSET+1 <= c->inbuflen);
   1633  1.1  christos 		/* message in c->inbuf is not NULL-terminated,
   1634  1.1  christos 		 * so this avoids a complete copy */
   1635  1.1  christos 		buf_char = c->inbuf[MSG_END_OFFSET];
   1636  1.1  christos 		c->inbuf[MSG_END_OFFSET] = '\0';
   1637  1.1  christos 		printline(c->tls_conn->hostname, &c->inbuf[c->cur_msg_start],
   1638  1.1  christos 		    RemoteAddDate ? ADDDATE : 0);
   1639  1.1  christos 		c->inbuf[MSG_END_OFFSET] = buf_char;
   1640  1.1  christos 
   1641  1.1  christos 		if (MSG_END_OFFSET == c->read_pos) {
   1642  1.1  christos 			/* no unprocessed data in buffer --> reset to empty */
   1643  1.1  christos 			c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
   1644  1.1  christos 		} else {
   1645  1.1  christos 			/* move remaining input to start of buffer */
   1646  1.1  christos 			DPRINTF(D_DATA, "move inbuf of length %zu by %zu "
   1647  1.1  christos 			    "chars\n", c->read_pos - (MSG_END_OFFSET),
   1648  1.1  christos 			    MSG_END_OFFSET);
   1649  1.1  christos 			memmove(&c->inbuf[0], &c->inbuf[MSG_END_OFFSET],
   1650  1.1  christos 			    c->read_pos - (MSG_END_OFFSET));
   1651  1.1  christos 			c->read_pos -= (MSG_END_OFFSET);
   1652  1.1  christos 			c->cur_msg_start = c->cur_msg_len = 0;
   1653  1.1  christos 		}
   1654  1.1  christos 	}
   1655  1.3   minskim 
   1656  1.1  christos 	/* shrink inbuf if too large */
   1657  1.1  christos 	if ((c->inbuflen > TLS_PERSIST_LINELENGTH)
   1658  1.1  christos 	 && (c->read_pos < TLS_LARGE_LINELENGTH)) {
   1659  1.1  christos 		newbuf = realloc(c->inbuf, TLS_LARGE_LINELENGTH);
   1660  1.1  christos 		if (newbuf) {
   1661  1.1  christos 			DPRINTF(D_DATA, "Shrink inbuf\n");
   1662  1.1  christos 			c->inbuflen = TLS_LARGE_LINELENGTH;
   1663  1.1  christos 			c->inbuf = newbuf;
   1664  1.1  christos 		} else {
   1665  1.1  christos 			logerror("Couldn't shrink inbuf");
   1666  1.1  christos 			/* no change necessary */
   1667  1.1  christos 		}
   1668  1.1  christos 	}
   1669  1.1  christos 	DPRINTF(D_DATA, "return with status: msg_start %zu, msg_len %zu, "
   1670  1.1  christos 	    "pos %zu\n", c->cur_msg_start, c->cur_msg_len, c->read_pos);
   1671  1.1  christos 
   1672  1.1  christos 	/* try to read another message */
   1673  1.1  christos 	if (c->read_pos > 10)
   1674  1.1  christos 		tls_split_messages(c);
   1675  1.1  christos 	return;
   1676  1.1  christos }
   1677  1.1  christos 
   1678  1.3   minskim /*
   1679  1.1  christos  * wrapper for dispatch_tls_send()
   1680  1.3   minskim  *
   1681  1.1  christos  * send one line with tls
   1682  1.1  christos  * f has to be of typ TLS
   1683  1.3   minskim  *
   1684  1.1  christos  * returns false if message cannot be sent right now,
   1685  1.1  christos  *	caller is responsible to enqueue it
   1686  1.1  christos  * returns true if message passed to dispatch_tls_send()
   1687  1.1  christos  *	delivery is not garantueed, but likely
   1688  1.1  christos  */
   1689  1.1  christos #define DEBUG_LINELENGTH 40
   1690  1.1  christos bool
   1691  1.1  christos tls_send(struct filed *f, char *line, size_t len, struct buf_queue *qentry)
   1692  1.1  christos {
   1693  1.1  christos 	struct tls_send_msg *smsg;
   1694  1.1  christos 
   1695  1.1  christos 	DPRINTF((D_TLS|D_CALL), "tls_send(f=%p, line=\"%.*s%s\", "
   1696  1.1  christos 	    "len=%zu) to %sconnected dest.\n", f,
   1697  1.1  christos 	    (int)(len > DEBUG_LINELENGTH ? DEBUG_LINELENGTH : len),
   1698  1.1  christos 	    line, (len > DEBUG_LINELENGTH ? "..." : ""),
   1699  1.1  christos 	    len, f->f_un.f_tls.tls_conn->sslptr ? "" : "un");
   1700  1.1  christos 
   1701  1.1  christos 	if(f->f_un.f_tls.tls_conn->state == ST_TLS_EST) {
   1702  1.1  christos 		/* send now */
   1703  1.1  christos 		if (!(smsg = calloc(1, sizeof(*smsg)))) {
   1704  1.1  christos 			logerror("Unable to allocate memory, drop message");
   1705  1.1  christos 			return false;
   1706  1.1  christos 		}
   1707  1.1  christos 		smsg->f = f;
   1708  1.1  christos 		smsg->line = line;
   1709  1.1  christos 		smsg->linelen = len;
   1710  1.1  christos 		(void)NEWREF(qentry->msg);
   1711  1.1  christos 		smsg->qentry = qentry;
   1712  1.1  christos 		DPRINTF(D_DATA, "now sending line: \"%.*s\"\n",
   1713  1.1  christos 		    (int)smsg->linelen, smsg->line);
   1714  1.1  christos 		dispatch_tls_send(0, 0, smsg);
   1715  1.1  christos 		return true;
   1716  1.1  christos 	} else {
   1717  1.1  christos 		/* other socket operation active, send later  */
   1718  1.1  christos 		DPRINTF(D_DATA, "connection not ready to send: \"%.*s\"\n",
   1719  1.1  christos 		    (int)len, line);
   1720  1.1  christos 		return false;
   1721  1.1  christos 	}
   1722  1.1  christos }
   1723  1.1  christos 
   1724  1.1  christos /*ARGSUSED*/
   1725  1.1  christos void
   1726  1.1  christos dispatch_tls_send(int fd, short event, void *arg)
   1727  1.1  christos {
   1728  1.1  christos 	struct tls_send_msg *smsg = (struct tls_send_msg *) arg;
   1729  1.1  christos 	struct tls_conn_settings *conn_info = smsg->f->f_un.f_tls.tls_conn;
   1730  1.1  christos 	struct filed *f = smsg->f;
   1731  1.1  christos 	int rc, error;
   1732  1.1  christos 	sigset_t newmask, omask;
   1733  1.1  christos 	bool retrying;
   1734  1.1  christos 	struct timeval tv;
   1735  1.3   minskim 
   1736  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1737  1.1  christos 	DPRINTF((D_TLS|D_CALL), "dispatch_tls_send(f=%p, buffer=%p, "
   1738  1.1  christos 	    "line@%p, len=%zu, offset=%zu) to %sconnected dest.\n",
   1739  1.1  christos 	    smsg->f, smsg->qentry->msg, smsg->line,
   1740  1.1  christos 	    smsg->linelen, smsg->offset,
   1741  1.1  christos 		conn_info->sslptr ? "" : "un");
   1742  1.1  christos 	assert(conn_info->state == ST_TLS_EST
   1743  1.1  christos 	    || conn_info->state == ST_WRITING);
   1744  1.1  christos 
   1745  1.1  christos 	retrying = (conn_info->state == ST_WRITING);
   1746  1.1  christos 	ST_CHANGE(conn_info->state, ST_WRITING);
   1747  1.1  christos 	rc = SSL_write(conn_info->sslptr,
   1748  1.1  christos 	    (smsg->line + smsg->offset),
   1749  1.1  christos 	    (smsg->linelen - smsg->offset));
   1750  1.1  christos 	if (0 >= rc) {
   1751  1.1  christos 		error = tls_examine_error("SSL_write()",
   1752  1.1  christos 		    conn_info->sslptr,
   1753  1.1  christos 		    conn_info, rc);
   1754  1.1  christos 		switch (error) {
   1755  1.1  christos 		case TLS_RETRY_READ:
   1756  1.1  christos 			/* collides with eof event */
   1757  1.1  christos 			if (!retrying)
   1758  1.1  christos 				event_del(conn_info->event);
   1759  1.1  christos 			event_set(conn_info->retryevent, fd, EV_READ,
   1760  1.1  christos 				dispatch_tls_send, smsg);
   1761  1.1  christos 			RETRYEVENT_ADD(conn_info->retryevent);
   1762  1.1  christos 			break;
   1763  1.1  christos 		case TLS_RETRY_WRITE:
   1764  1.1  christos 			event_set(conn_info->retryevent, fd, EV_WRITE,
   1765  1.1  christos 			    dispatch_tls_send, smsg);
   1766  1.1  christos 			RETRYEVENT_ADD(conn_info->retryevent);
   1767  1.1  christos 			break;
   1768  1.1  christos 		case TLS_PERM_ERROR:
   1769  1.1  christos 			/* no need to check active events */
   1770  1.1  christos 			free_tls_send_msg(smsg);
   1771  1.1  christos 			free_tls_sslptr(conn_info);
   1772  1.1  christos 			tv.tv_sec = conn_info->reconnect;
   1773  1.1  christos 			tv.tv_usec = 0;
   1774  1.1  christos 			schedule_event(&conn_info->event, &tv,
   1775  1.1  christos 			    tls_reconnect, conn_info);
   1776  1.1  christos 			TLS_RECONNECT_BACKOFF(conn_info->reconnect);
   1777  1.1  christos 			break;
   1778  1.1  christos 		default:
   1779  1.1  christos 			break;
   1780  1.1  christos 		}
   1781  1.1  christos 		RESTORE_SIGNALS(omask);
   1782  1.1  christos 		return;
   1783  1.1  christos 	} else if (rc < smsg->linelen) {
   1784  1.1  christos 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() wrote %d out of %zu "
   1785  1.1  christos 		    "bytes\n", rc, (smsg->linelen - smsg->offset));
   1786  1.1  christos 		smsg->offset += rc;
   1787  1.1  christos 		/* try again */
   1788  1.1  christos 		if (retrying)
   1789  1.1  christos 			EVENT_ADD(conn_info->event);
   1790  1.1  christos 		dispatch_tls_send(0, 0, smsg);
   1791  1.1  christos 		return;
   1792  1.1  christos 	} else if (rc == (smsg->linelen - smsg->offset)) {
   1793  1.1  christos 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() complete\n");
   1794  1.1  christos 		ST_CHANGE(conn_info->state, ST_TLS_EST);
   1795  1.1  christos 		free_tls_send_msg(smsg);
   1796  1.1  christos 		send_queue(0, 0, f);
   1797  1.1  christos 
   1798  1.1  christos 	} else {
   1799  1.1  christos 		/* should not be reached */
   1800  1.1  christos 		/*LINTED constcond */
   1801  1.1  christos 		assert(0);
   1802  1.1  christos 		DPRINTF((D_TLS|D_DATA), "unreachable code after SSL_write()\n");
   1803  1.1  christos 		ST_CHANGE(conn_info->state, ST_TLS_EST);
   1804  1.1  christos 		free_tls_send_msg(smsg);
   1805  1.1  christos 		send_queue(0, 0, f);
   1806  1.1  christos 	}
   1807  1.1  christos 	if (retrying && conn_info->event->ev_events)
   1808  1.1  christos 		EVENT_ADD(conn_info->event);
   1809  1.1  christos 	RESTORE_SIGNALS(omask);
   1810  1.1  christos }
   1811  1.1  christos 
   1812  1.1  christos /*
   1813  1.1  christos  * Close a SSL connection and its queue and its tls_conn.
   1814  1.1  christos  */
   1815  1.1  christos void
   1816  1.1  christos free_tls_conn(struct tls_conn_settings *conn_info)
   1817  1.1  christos {
   1818  1.1  christos 	DPRINTF(D_MEM, "free_tls_conn(conn_info@%p) with sslptr@%p\n",
   1819  1.1  christos 		conn_info, conn_info->sslptr);
   1820  1.1  christos 
   1821  1.1  christos 	if (conn_info->sslptr) {
   1822  1.1  christos 		conn_info->shutdown = true;
   1823  1.1  christos 		free_tls_sslptr(conn_info);
   1824  1.1  christos 	}
   1825  1.1  christos 	assert(conn_info->state == ST_NONE);
   1826  1.1  christos 
   1827  1.1  christos 	FREEPTR(conn_info->port);
   1828  1.1  christos 	FREEPTR(conn_info->subject);
   1829  1.1  christos 	FREEPTR(conn_info->hostname);
   1830  1.1  christos 	FREEPTR(conn_info->certfile);
   1831  1.1  christos 	FREEPTR(conn_info->fingerprint);
   1832  1.1  christos 	DEL_EVENT(conn_info->event);
   1833  1.1  christos 	DEL_EVENT(conn_info->retryevent);
   1834  1.1  christos 	FREEPTR(conn_info->event);
   1835  1.1  christos 	FREEPTR(conn_info->retryevent);
   1836  1.1  christos 	FREEPTR(conn_info);
   1837  1.1  christos 	DPRINTF(D_MEM2, "free_tls_conn(conn_info@%p) returns\n", conn_info);
   1838  1.1  christos }
   1839  1.1  christos 
   1840  1.1  christos /*
   1841  1.1  christos  * Dispatch routine for non-blocking TLS shutdown
   1842  1.1  christos  */
   1843  1.1  christos /*ARGSUSED*/
   1844  1.1  christos void
   1845  1.1  christos dispatch_SSL_shutdown(int fd, short event, void *arg)
   1846  1.1  christos {
   1847  1.1  christos 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
   1848  1.1  christos 	int rc, error;
   1849  1.1  christos 	sigset_t newmask, omask;
   1850  1.1  christos 	bool retrying;
   1851  1.3   minskim 
   1852  1.1  christos 	BLOCK_SIGNALS(omask, newmask);
   1853  1.1  christos 	DPRINTF((D_TLS|D_CALL),
   1854  1.1  christos 	    "dispatch_SSL_shutdown(conn_info@%p, fd %d)\n", conn_info, fd);
   1855  1.1  christos 	retrying = ((conn_info->state == ST_CLOSING0)
   1856  1.1  christos 	     || (conn_info->state == ST_CLOSING1)
   1857  1.1  christos 	     || (conn_info->state == ST_CLOSING2));
   1858  1.1  christos 	if (!retrying)
   1859  1.1  christos 		ST_CHANGE(conn_info->state, ST_CLOSING0);
   1860  1.1  christos 
   1861  1.1  christos 	rc = SSL_shutdown(conn_info->sslptr);
   1862  1.1  christos 	if (rc == 1) {	/* shutdown complete */
   1863  1.1  christos 		DPRINTF((D_TLS|D_NET), "Closed TLS connection to %s\n",
   1864  1.1  christos 		    conn_info->hostname);
   1865  1.1  christos 		ST_CHANGE(conn_info->state, ST_TCP_EST);  /* check this */
   1866  1.1  christos 		conn_info->accepted = false;
   1867  1.1  christos 		/* closing TCP comes below */
   1868  1.1  christos 	} else if (rc == 0) { /* unidirectional, now call a 2nd time */
   1869  1.1  christos 		/* problem: when connecting as a client to rsyslogd this
   1870  1.1  christos 		 * loops and I keep getting rc == 0
   1871  1.1  christos 		 * maybe I hit this bug?
   1872  1.1  christos 		 * http://www.mail-archive.com/openssl-dev@openssl.org/msg24105.html
   1873  1.3   minskim 		 *
   1874  1.1  christos 		 * anyway, now I use three closing states to make sure I abort
   1875  1.3   minskim 		 * after two rc = 0.
   1876  1.1  christos 		 */
   1877  1.1  christos 		if (conn_info->state == ST_CLOSING0) {
   1878  1.1  christos 			ST_CHANGE(conn_info->state, ST_CLOSING1);
   1879  1.1  christos 			dispatch_SSL_shutdown(fd, 0, conn_info);
   1880  1.1  christos 		} else if (conn_info->state == ST_CLOSING1) {
   1881  1.1  christos 			ST_CHANGE(conn_info->state, ST_CLOSING2);
   1882  1.1  christos 			dispatch_SSL_shutdown(fd, 0, conn_info);
   1883  1.1  christos 		} else if (conn_info->state == ST_CLOSING2) {
   1884  1.1  christos 			/* abort shutdown, jump to close TCP below */
   1885  1.1  christos 		} else
   1886  1.1  christos 			DPRINTF(D_TLS, "Unexpected connection state %d\n",
   1887  1.1  christos 				conn_info->state);
   1888  1.1  christos 			/* and abort here too*/
   1889  1.1  christos 	} else if (rc == -1 && conn_info->shutdown ) {
   1890  1.1  christos 		(void)tls_examine_error("SSL_shutdown()",
   1891  1.1  christos 			conn_info->sslptr, NULL, rc);
   1892  1.1  christos 		DPRINTF((D_TLS|D_NET), "Ignore error in SSL_shutdown()"
   1893  1.1  christos 			" and force connection shutdown.");
   1894  1.1  christos 		ST_CHANGE(conn_info->state, ST_TCP_EST);
   1895  1.1  christos 		conn_info->accepted = false;
   1896  1.1  christos 	} else if (rc == -1 && !conn_info->shutdown ) {
   1897  1.1  christos 		error = tls_examine_error("SSL_shutdown()",
   1898  1.1  christos 			conn_info->sslptr, NULL, rc);
   1899  1.1  christos 		switch (error) {
   1900  1.1  christos 		case TLS_RETRY_READ:
   1901  1.1  christos 			if (!retrying)
   1902  1.1  christos 				event_del(conn_info->event);
   1903  1.1  christos 			event_set(conn_info->retryevent, fd, EV_READ,
   1904  1.1  christos 			    dispatch_SSL_shutdown, conn_info);
   1905  1.1  christos 			EVENT_ADD(conn_info->retryevent);
   1906  1.1  christos 			RESTORE_SIGNALS(omask);
   1907  1.1  christos 			return;
   1908  1.1  christos 		case TLS_RETRY_WRITE:
   1909  1.1  christos 			if (!retrying)
   1910  1.1  christos 				event_del(conn_info->event);
   1911  1.1  christos 			event_set(conn_info->retryevent, fd, EV_WRITE,
   1912  1.1  christos 			    dispatch_SSL_shutdown, conn_info);
   1913  1.1  christos 			EVENT_ADD(conn_info->retryevent);
   1914  1.1  christos 			RESTORE_SIGNALS(omask);
   1915  1.1  christos 			return;
   1916  1.1  christos 		default:
   1917  1.1  christos 			/* force close() on the TCP connection */
   1918  1.1  christos 			ST_CHANGE(conn_info->state, ST_TCP_EST);
   1919  1.1  christos 			conn_info->accepted = false;
   1920  1.1  christos 			break;
   1921  1.1  christos 		}
   1922  1.1  christos 	}
   1923  1.1  christos 	if ((conn_info->state != ST_TLS_EST)
   1924  1.1  christos 	    && (conn_info->state != ST_NONE)
   1925  1.1  christos 	    && (conn_info->state != ST_CLOSING0)
   1926  1.1  christos 	    && (conn_info->state != ST_CLOSING1)) {
   1927  1.1  christos 		int sock = SSL_get_fd(conn_info->sslptr);
   1928  1.3   minskim 
   1929  1.1  christos 		if (shutdown(sock, SHUT_RDWR) == -1)
   1930  1.1  christos 			logerror("Cannot shutdown socket");
   1931  1.1  christos 		DEL_EVENT(conn_info->retryevent);
   1932  1.1  christos 		DEL_EVENT(conn_info->event);
   1933  1.1  christos 
   1934  1.1  christos 		if (close(sock) == -1)
   1935  1.1  christos 			logerror("Cannot close socket");
   1936  1.1  christos 		DPRINTF((D_TLS|D_NET), "Closed TCP connection to %s\n",
   1937  1.1  christos 		    conn_info->hostname);
   1938  1.1  christos 		ST_CHANGE(conn_info->state, ST_NONE);
   1939  1.1  christos 		FREE_SSL(conn_info->sslptr);
   1940  1.1  christos 	 }
   1941  1.1  christos 	RESTORE_SIGNALS(omask);
   1942  1.1  christos }
   1943  1.1  christos 
   1944  1.1  christos /*
   1945  1.1  christos  * Close a SSL object
   1946  1.1  christos  */
   1947  1.1  christos void
   1948  1.1  christos free_tls_sslptr(struct tls_conn_settings *conn_info)
   1949  1.1  christos {
   1950  1.1  christos 	int sock;
   1951  1.1  christos 	DPRINTF(D_MEM, "free_tls_sslptr(conn_info@%p)\n", conn_info);
   1952  1.1  christos 
   1953  1.1  christos 	if (!conn_info->sslptr) {
   1954  1.1  christos 		assert(conn_info->incoming == 1
   1955  1.1  christos 		    || conn_info->state == ST_NONE);
   1956  1.1  christos 		return;
   1957  1.1  christos 	} else {
   1958  1.1  christos 		sock = SSL_get_fd(conn_info->sslptr);
   1959  1.1  christos 		dispatch_SSL_shutdown(sock, 0, conn_info);
   1960  1.1  christos 	}
   1961  1.1  christos }
   1962  1.1  christos 
   1963  1.1  christos /* write self-generated certificates */
   1964  1.1  christos bool
   1965  1.1  christos write_x509files(EVP_PKEY *pkey, X509 *cert,
   1966  1.1  christos 	const char *keyfilename, const char *certfilename)
   1967  1.1  christos {
   1968  1.1  christos 	FILE *certfile, *keyfile;
   1969  1.3   minskim 
   1970  1.1  christos 	if (!(umask(0177),(keyfile  = fopen(keyfilename,  "a")))
   1971  1.1  christos 	    || !(umask(0122),(certfile = fopen(certfilename, "a")))) {
   1972  1.1  christos 		logerror("Unable to write to files \"%s\" and \"%s\"",
   1973  1.1  christos 		    keyfilename, certfilename);
   1974  1.1  christos 		return false;
   1975  1.1  christos 	}
   1976  1.1  christos 	if (!PEM_write_PrivateKey(keyfile, pkey, NULL, NULL, 0, NULL, NULL))
   1977  1.1  christos 		logerror("Unable to write key to \"%s\"", keyfilename);
   1978  1.1  christos 	if (!X509_print_fp(certfile, cert)
   1979  1.1  christos 	    || !PEM_write_X509(certfile, cert))
   1980  1.1  christos 		logerror("Unable to write certificate to \"%s\"",
   1981  1.1  christos 		    certfilename);
   1982  1.1  christos 
   1983  1.1  christos 	(void)fclose(keyfile);
   1984  1.1  christos 	(void)fclose(certfile);
   1985  1.1  christos 	return true;
   1986  1.1  christos }
   1987  1.1  christos 
   1988  1.1  christos 
   1989  1.1  christos /* adds all local IP addresses as subjectAltNames to cert x.
   1990  1.1  christos  * getifaddrs() should be quite portable among BSDs and Linux
   1991  1.1  christos  * but if not available the whole function can simply be removed.
   1992  1.1  christos  */
   1993  1.1  christos bool
   1994  1.1  christos x509_cert_add_subjectAltName(X509 *cert, X509V3_CTX *ctx)
   1995  1.1  christos {
   1996  1.1  christos 	struct ifaddrs *ifa = NULL, *ifp = NULL;
   1997  1.1  christos 	char ip[100];
   1998  1.1  christos 	char subjectAltName[2048];
   1999  1.1  christos 	int idx = 0;
   2000  1.1  christos 	socklen_t salen;
   2001  1.1  christos 	X509_EXTENSION *ext;
   2002  1.1  christos #ifdef notdef
   2003  1.1  christos 	STACK_OF(X509_EXTENSION) *extlist;
   2004  1.1  christos 	extlist = sk_X509_EXTENSION_new_null();
   2005  1.1  christos #endif
   2006  1.3   minskim 
   2007  1.1  christos 	if (getifaddrs (&ifp) == -1) {
   2008  1.1  christos 		logerror("Unable to get list of local interfaces");
   2009  1.1  christos 		return false;
   2010  1.1  christos 	}
   2011  1.3   minskim 
   2012  1.1  christos 	idx = snprintf(subjectAltName, sizeof(subjectAltName),
   2013  1.1  christos 	    "DNS:%s", LocalFQDN);
   2014  1.3   minskim 
   2015  1.1  christos 	for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
   2016  1.1  christos 		if(!ifa->ifa_addr)
   2017  1.1  christos 			continue;
   2018  1.3   minskim 
   2019  1.3   minskim 		/* only IP4 and IP6 addresses, but filter loopbacks */
   2020  1.1  christos 		if (ifa->ifa_addr->sa_family == AF_INET) {
   2021  1.1  christos 			struct sockaddr_in *addr =
   2022  1.1  christos 			    (struct sockaddr_in *)ifa->ifa_addr;
   2023  1.1  christos 			if (addr->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
   2024  1.1  christos 				continue;
   2025  1.1  christos 			salen = sizeof(struct sockaddr_in);
   2026  1.1  christos 		} else if (ifa->ifa_addr->sa_family == AF_INET6) {
   2027  1.1  christos 			struct in6_addr *addr6 =
   2028  1.1  christos 			    &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
   2029  1.1  christos 			if (IN6_IS_ADDR_LOOPBACK(addr6))
   2030  1.1  christos 				continue;
   2031  1.1  christos 			salen = sizeof(struct sockaddr_in6);
   2032  1.1  christos 		} else
   2033  1.1  christos 			continue;
   2034  1.3   minskim 
   2035  1.1  christos 		if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip),
   2036  1.1  christos 		    NULL, 0, NI_NUMERICHOST)) {
   2037  1.1  christos 			continue;
   2038  1.1  christos 		}
   2039  1.1  christos 
   2040  1.1  christos 		/* add IP to list */
   2041  1.1  christos 		idx += snprintf(&subjectAltName[idx],
   2042  1.1  christos 		    sizeof(subjectAltName)-idx, ", IP:%s", ip);
   2043  1.1  christos 	}
   2044  1.1  christos 	freeifaddrs (ifp);
   2045  1.1  christos 
   2046  1.1  christos 	ext = X509V3_EXT_conf_nid(NULL, ctx,
   2047  1.1  christos 	    NID_subject_alt_name, subjectAltName);
   2048  1.1  christos 	X509_add_ext(cert, ext, -1);
   2049  1.1  christos 	X509_EXTENSION_free(ext);
   2050  1.1  christos 
   2051  1.1  christos 	return true;
   2052  1.1  christos }
   2053  1.1  christos 
   2054  1.3   minskim /*
   2055  1.1  christos  * generates a private key and a X.509 certificate
   2056  1.1  christos  */
   2057  1.1  christos bool
   2058  1.1  christos mk_x509_cert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days)
   2059  1.1  christos {
   2060  1.1  christos 	X509	       *cert;
   2061  1.1  christos 	EVP_PKEY       *pk;
   2062  1.1  christos 	DSA	       *dsa;
   2063  1.1  christos 	X509_NAME      *name = NULL;
   2064  1.1  christos 	X509_EXTENSION *ex = NULL;
   2065  1.1  christos 	X509V3_CTX	ctx;
   2066  1.1  christos 
   2067  1.1  christos 	DPRINTF((D_CALL|D_TLS), "mk_x509_cert(%p, %p, %d, %d, %d)\n",
   2068  1.1  christos 	    x509p, pkeyp, bits, serial, days);
   2069  1.3   minskim 
   2070  1.1  christos 	if (pkeyp && *pkeyp)
   2071  1.1  christos 		pk = *pkeyp;
   2072  1.1  christos 	else if ((pk = EVP_PKEY_new()) == NULL) {
   2073  1.1  christos 		DPRINTF(D_TLS, "EVP_PKEY_new() failed\n");
   2074  1.1  christos 		return false;
   2075  1.1  christos 	}
   2076  1.1  christos 
   2077  1.1  christos 	if (x509p && *x509p)
   2078  1.1  christos 		cert = *x509p;
   2079  1.1  christos 	else if ((cert = X509_new()) == NULL) {
   2080  1.1  christos 		DPRINTF(D_TLS, "X509_new() failed\n");
   2081  1.1  christos 		return false;
   2082  1.1  christos 	}
   2083  1.1  christos 
   2084  1.1  christos 	dsa = DSA_generate_parameters(bits, NULL, 0,
   2085  1.1  christos 			    NULL, NULL, NULL, NULL);
   2086  1.1  christos 	if (!DSA_generate_key(dsa)) {
   2087  1.1  christos 		DPRINTF(D_TLS, "DSA_generate_key() failed\n");
   2088  1.1  christos 		return false;
   2089  1.1  christos 	}
   2090  1.1  christos 	if (!EVP_PKEY_assign_DSA(pk, dsa)) {
   2091  1.1  christos 		DPRINTF(D_TLS, "EVP_PKEY_assign_DSA() failed\n");
   2092  1.1  christos 		return false;
   2093  1.1  christos 	}
   2094  1.1  christos 
   2095  1.1  christos 	X509_set_version(cert, 3);
   2096  1.1  christos 	ASN1_INTEGER_set(X509_get_serialNumber(cert), serial);
   2097  1.1  christos 	X509_gmtime_adj(X509_get_notBefore(cert), 0);
   2098  1.1  christos 	X509_gmtime_adj(X509_get_notAfter(cert), (long)60 * 60 * 24 * days);
   2099  1.3   minskim 
   2100  1.1  christos 	if (!X509_set_pubkey(cert, pk)) {
   2101  1.1  christos 		DPRINTF(D_TLS, "X509_set_pubkey() failed\n");
   2102  1.1  christos 		return false;
   2103  1.1  christos 	}
   2104  1.1  christos 
   2105  1.1  christos 	/*
   2106  1.1  christos 	 * This function creates and adds the entry, working out the correct
   2107  1.1  christos 	 * string type and performing checks on its length. Normally we'd check
   2108  1.1  christos 	 * the return value for errors...
   2109  1.1  christos 	 */
   2110  1.1  christos 	name = X509_get_subject_name(cert);
   2111  1.1  christos 	/*
   2112  1.1  christos 	X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
   2113  1.1  christos 	    (unsigned char *)"The NetBSD Project", -1, -1, 0);
   2114  1.1  christos 	X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC,
   2115  1.1  christos 	    (unsigned char *)"syslogd", -1, -1, 0);
   2116  1.1  christos 	*/
   2117  1.1  christos 	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
   2118  1.1  christos 	    (unsigned char *) LocalFQDN, -1, -1, 0);
   2119  1.1  christos 	X509_set_issuer_name(cert, name);
   2120  1.1  christos 
   2121  1.1  christos 	/*
   2122  1.1  christos 	 * Add extension using V3 code: we can set the config file as NULL
   2123  1.1  christos 	 * because we wont reference any other sections.
   2124  1.1  christos 	 */
   2125  1.1  christos 	X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
   2126  1.3   minskim 
   2127  1.1  christos 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_comment,
   2128  1.1  christos 	    __UNCONST("auto-generated by the NetBSD syslogd"));
   2129  1.1  christos 	X509_add_ext(cert, ex, -1);
   2130  1.1  christos 	X509_EXTENSION_free(ex);
   2131  1.1  christos 
   2132  1.1  christos 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_ssl_server_name,
   2133  1.1  christos 	    LocalFQDN);
   2134  1.1  christos 	X509_add_ext(cert, ex, -1);
   2135  1.1  christos 	X509_EXTENSION_free(ex);
   2136  1.1  christos 
   2137  1.1  christos 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_cert_type,
   2138  1.1  christos 	    __UNCONST("server, client"));
   2139  1.1  christos 	X509_add_ext(cert, ex, -1);
   2140  1.1  christos 	X509_EXTENSION_free(ex);
   2141  1.1  christos 
   2142  1.1  christos 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_key_usage,
   2143  1.1  christos 	    __UNCONST("keyAgreement, keyEncipherment, "
   2144  1.1  christos 	    "nonRepudiation, digitalSignature"));
   2145  1.1  christos 	X509_add_ext(cert, ex, -1);
   2146  1.1  christos 	X509_EXTENSION_free(ex);
   2147  1.1  christos 
   2148  1.1  christos 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints,
   2149  1.1  christos 	    __UNCONST("critical,CA:FALSE"));
   2150  1.1  christos 	X509_add_ext(cert, ex, -1);
   2151  1.1  christos 	X509_EXTENSION_free(ex);
   2152  1.1  christos 
   2153  1.1  christos 	(void)x509_cert_add_subjectAltName(cert, &ctx);
   2154  1.1  christos 
   2155  1.1  christos 	if (!X509_sign(cert, pk, EVP_dss1())) {
   2156  1.1  christos 		DPRINTF(D_TLS, "X509_sign() failed\n");
   2157  1.1  christos 		return false;
   2158  1.1  christos 	}
   2159  1.1  christos 	if (X509_verify(cert, pk) != 1) {
   2160  1.1  christos 		DPRINTF(D_TLS, "X509_verify() failed\n");
   2161  1.1  christos 		return false;
   2162  1.1  christos 	}
   2163  1.1  christos 
   2164  1.1  christos 	*x509p = cert;
   2165  1.1  christos 	*pkeyp = pk;
   2166  1.1  christos 	return true;
   2167  1.1  christos }
   2168  1.1  christos 
   2169  1.1  christos void
   2170  1.1  christos free_tls_send_msg(struct tls_send_msg *msg)
   2171  1.1  christos {
   2172  1.1  christos 	if (!msg) {
   2173  1.1  christos 		DPRINTF((D_DATA), "invalid tls_send_msg_free(NULL)\n");
   2174  1.1  christos 		return;
   2175  1.1  christos 	}
   2176  1.1  christos 	DELREF(msg->qentry->msg);
   2177  1.1  christos 	(void)message_queue_remove(msg->f, msg->qentry);
   2178  1.1  christos 	FREEPTR(msg->line);
   2179  1.1  christos 	FREEPTR(msg);
   2180  1.1  christos }
   2181  1.1  christos #endif /* !DISABLE_TLS */
   2182