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