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