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