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