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