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