xref: /minix/usr.sbin/syslogd/tls.c (revision ebfedea0)
1 /*	$NetBSD: tls.c,v 1.11 2013/05/27 23:15:51 christos 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.11 2013/05/27 23:15:51 christos 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(void)
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 		s->af = r->ai_family;
855 #if defined(__minix) && defined(INET6)
856 		if (r->ai_family == AF_INET6
857 		 && setsockopt(s->fd, IPPROTO_IPV6, IPV6_V6ONLY,
858 			&on, sizeof(on)) == -1) {
859 			logerror("setsockopt(IPV6_V6ONLY) failed: %s",
860 			    strerror(errno));
861 			close(s->fd);
862 			continue;
863 		}
864 #endif /* defined(__minix) && defined(INET6) */
865 		if (setsockopt(s->fd, SOL_SOCKET, SO_REUSEADDR,
866 			&on, sizeof(on)) == -1) {
867 			DPRINTF(D_NET, "Unable to setsockopt(): %s\n",
868 			    strerror(errno));
869 		}
870 		if ((error = bind(s->fd, r->ai_addr, r->ai_addrlen)) == -1) {
871 			logerror("bind() failed: %s", strerror(errno));
872 			/* is there a better way to handle a EADDRINUSE? */
873 			close(s->fd);
874 			continue;
875 		}
876 		if (listen(s->fd, TLSBACKLOG) == -1) {
877 			logerror("listen() failed: %s", strerror(errno));
878 			close(s->fd);
879 			continue;
880 		}
881 		s->ev = allocev();
882 		event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
883 		    dispatch_socket_accept, s->ev);
884 		EVENT_ADD(s->ev);
885 
886 		socks->fd = socks->fd + 1;  /* num counter */
887 		s++;
888 	}
889 
890 	if (socks->fd == 0) {
891 		free (socks);
892 		if(Debug)
893 			return NULL;
894 		else
895 			die(0, 0, NULL);
896 	}
897 	if (res)
898 		freeaddrinfo(res);
899 
900 	return socks;
901 }
902 
903 /*
904  * Dispatch routine for non-blocking SSL_connect()
905  * Has to be idempotent in case of TLS_RETRY (~ EAGAIN),
906  * so we can continue a slow handshake.
907  */
908 /*ARGSUSED*/
909 void
910 dispatch_SSL_connect(int fd, short event, void *arg)
911 {
912 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
913 	SSL *ssl = conn_info->sslptr;
914 	int rc, error;
915 	sigset_t newmask, omask;
916 	struct timeval tv;
917 
918 	BLOCK_SIGNALS(omask, newmask);
919 	DPRINTF((D_TLS|D_CALL), "dispatch_SSL_connect(conn_info@%p, fd %d)\n",
920 	    conn_info, fd);
921 	assert(conn_info->state == ST_TCP_EST
922 	    || conn_info->state == ST_CONNECTING);
923 
924 	ST_CHANGE(conn_info->state, ST_CONNECTING);
925 	rc = SSL_connect(ssl);
926 	if (0 >= rc) {
927 		error = tls_examine_error("SSL_connect()",
928 		    conn_info->sslptr, NULL, rc);
929 		switch (error) {
930 		case TLS_RETRY_READ:
931 			event_set(conn_info->retryevent, fd, EV_READ,
932 			    dispatch_SSL_connect, conn_info);
933 			EVENT_ADD(conn_info->retryevent);
934 			break;
935 		case TLS_RETRY_WRITE:
936 			event_set(conn_info->retryevent, fd, EV_WRITE,
937 			    dispatch_SSL_connect, conn_info);
938 			EVENT_ADD(conn_info->retryevent);
939 			break;
940 		default: /* should not happen,
941 			  * ... but does if the cert is not accepted */
942 			logerror("Cannot establish TLS connection "
943 			    "to \"%s\" -- TLS handshake aborted "
944 			    "before certificate authentication.",
945 			    conn_info->hostname);
946 			ST_CHANGE(conn_info->state, ST_NONE);
947 			conn_info->reconnect = 5 * TLS_RECONNECT_SEC;
948 			tv.tv_sec = conn_info->reconnect;
949 			tv.tv_usec = 0;
950 			schedule_event(&conn_info->event, &tv,
951 			    tls_reconnect, conn_info);
952 			break;
953 		}
954 		RESTORE_SIGNALS(omask);
955 		return;
956 	}
957 	/* else */
958 	conn_info->reconnect = TLS_RECONNECT_SEC;
959 	event_set(conn_info->event, fd, EV_READ, dispatch_tls_eof, conn_info);
960 	EVENT_ADD(conn_info->event);
961 
962 	DPRINTF(D_TLS, "TLS connection established.\n");
963 	ST_CHANGE(conn_info->state, ST_TLS_EST);
964 
965 	send_queue(0, 0, get_f_by_conninfo(conn_info));
966 	RESTORE_SIGNALS(omask);
967 }
968 
969 /*
970  * establish TLS connection
971  */
972 bool
973 tls_connect(struct tls_conn_settings *conn_info)
974 {
975 	struct addrinfo hints, *res, *res1;
976 	int    error, rc, sock;
977 	const int one = 1;
978 	char   buf[MAXLINE];
979 	SSL    *ssl = NULL;
980 
981 	DPRINTF((D_TLS|D_CALL), "tls_connect(conn_info@%p)\n", conn_info);
982 	assert(conn_info->state == ST_NONE);
983 
984 	if(!tls_opt.global_TLS_CTX)
985 		return false;
986 
987 	memset(&hints, 0, sizeof(hints));
988 	hints.ai_family = AF_UNSPEC;
989 	hints.ai_socktype = SOCK_STREAM;
990 	hints.ai_protocol = 0;
991 	hints.ai_flags = AI_CANONNAME;
992 	error = getaddrinfo(conn_info->hostname,
993 	    (conn_info->port ? conn_info->port : "syslog-tls"), &hints, &res);
994 	if (error) {
995 		logerror("%s", gai_strerror(error));
996 		return false;
997 	}
998 
999 	sock = -1;
1000 	for (res1 = res; res1; res1 = res1->ai_next) {
1001 		if ((sock = socket(res1->ai_family, res1->ai_socktype,
1002 		    res1->ai_protocol)) == -1) {
1003 			DPRINTF(D_NET, "Unable to open socket.\n");
1004 			continue;
1005 		}
1006 		if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
1007 			&one, sizeof(one)) == -1) {
1008 			DPRINTF(D_NET, "Unable to setsockopt(): %s\n",
1009 			    strerror(errno));
1010 		}
1011 		if (connect(sock, res1->ai_addr, res1->ai_addrlen) == -1) {
1012 			DPRINTF(D_NET, "Unable to connect() to %s: %s\n",
1013 			    res1->ai_canonname, strerror(errno));
1014 			close(sock);
1015 			sock = -1;
1016 			continue;
1017 		}
1018 		ST_CHANGE(conn_info->state, ST_TCP_EST);
1019 
1020 		if (!(ssl = SSL_new(tls_opt.global_TLS_CTX))) {
1021 			ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
1022 			DPRINTF(D_TLS, "Unable to establish TLS: %s\n", buf);
1023 			close(sock);
1024 			sock = -1;
1025 			ST_CHANGE(conn_info->state, ST_NONE);
1026 			continue;
1027 		}
1028 		if (!SSL_set_fd(ssl, sock)) {
1029 			ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
1030 			DPRINTF(D_TLS, "Unable to connect TLS to socket: %s\n",
1031 			    buf);
1032 			FREE_SSL(ssl);
1033 			close(sock);
1034 			sock = -1;
1035 			ST_CHANGE(conn_info->state, ST_NONE);
1036 			continue;
1037 		}
1038 
1039 		SSL_set_app_data(ssl, conn_info);
1040 		SSL_set_connect_state(ssl);
1041 		while ((rc = ERR_get_error()) != 0) {
1042 			ERR_error_string_n(rc, buf, sizeof(buf));
1043 			DPRINTF(D_TLS, "Found SSL error in queue: %s\n", buf);
1044 		}
1045 		errno = 0;  /* reset to be sure we get the right one later on */
1046 
1047 		if ((fcntl(sock, F_SETFL, O_NONBLOCK)) == -1) {
1048 			DPRINTF(D_NET, "Unable to fcntl(sock, O_NONBLOCK): "
1049 			    "%s\n", strerror(errno));
1050 		}
1051 
1052 		/* now we have a TCP connection, so assume we can
1053 		 * use that and do not have to try another res */
1054 		conn_info->sslptr = ssl;
1055 
1056 		assert(conn_info->state == ST_TCP_EST);
1057 		assert(conn_info->event);
1058 		assert(conn_info->retryevent);
1059 
1060 		freeaddrinfo(res);
1061 		dispatch_SSL_connect(sock, 0, conn_info);
1062 		return true;
1063 	}
1064 	/* still no connection after for loop */
1065 	DPRINTF((D_TLS|D_NET), "Unable to establish a TCP connection to %s\n",
1066 	    conn_info->hostname);
1067 	freeaddrinfo(res);
1068 
1069 	assert(conn_info->state == ST_NONE);
1070 	if (sock != -1)
1071 		close(sock);
1072 	if (ssl) {
1073 		SSL_shutdown(ssl);
1074 		SSL_free(ssl);
1075 	}
1076 	return false;
1077 }
1078 
1079 int
1080 tls_examine_error(const char *functionname, const SSL *ssl,
1081 	struct tls_conn_settings *tls_conn, const int rc)
1082 {
1083 	int ssl_error, err_error;
1084 
1085 	ssl_error = SSL_get_error(ssl, rc);
1086 	DPRINTF(D_TLS, "%s returned rc %d and error %s: %s\n", functionname,
1087 		rc, SSL_ERRCODE[ssl_error], ERR_error_string(ssl_error, NULL));
1088 	switch (ssl_error) {
1089 	case SSL_ERROR_WANT_READ:
1090 		return TLS_RETRY_READ;
1091 	case SSL_ERROR_WANT_WRITE:
1092 		return TLS_RETRY_WRITE;
1093 	case SSL_ERROR_SYSCALL:
1094 		DPRINTF(D_TLS, "SSL_ERROR_SYSCALL: ");
1095 		err_error = ERR_get_error();
1096 		if ((rc == -1) && (err_error == 0)) {
1097 			DPRINTF(D_TLS, "socket I/O error: %s\n",
1098 			    strerror(errno));
1099 		} else if ((rc == 0) && (err_error == 0)) {
1100 			DPRINTF(D_TLS, "unexpected EOF from %s\n",
1101 			    tls_conn ? tls_conn->hostname : NULL);
1102 		} else {
1103 			DPRINTF(D_TLS, "no further info\n");
1104 		}
1105 		return TLS_PERM_ERROR;
1106 	case SSL_ERROR_ZERO_RETURN:
1107 		logerror("TLS connection closed by %s",
1108 		    tls_conn ? tls_conn->hostname : NULL);
1109 		return TLS_PERM_ERROR;
1110 	case SSL_ERROR_SSL:
1111 		logerror("internal SSL error, error queue gives %s",
1112 		    ERR_error_string(ERR_get_error(), NULL));
1113 		return TLS_PERM_ERROR;
1114 	default:
1115 		break;
1116 	}
1117 	if (tls_conn)
1118 		tls_conn->errorcount++;
1119 	/* TODO: is this ever reached? */
1120 	return TLS_TEMP_ERROR;
1121 }
1122 
1123 
1124 bool
1125 parse_tls_destination(const char *p, struct filed *f, size_t linenum)
1126 {
1127 	const char *q;
1128 
1129 	if ((*p++ != '@') || *p++ != '[') {
1130 		logerror("parse_tls_destination() on non-TLS action "
1131 		    "in config line %zu", linenum);
1132 		return false;
1133 	}
1134 
1135 	if (!(q = strchr(p, ']'))) {
1136 		logerror("Unterminated [ "
1137 		    "in config line %zu", linenum);
1138 		return false;
1139 	}
1140 
1141 	if (!(f->f_un.f_tls.tls_conn =
1142 		calloc(1, sizeof(*f->f_un.f_tls.tls_conn)))
1143 	 || !(f->f_un.f_tls.tls_conn->event = allocev())
1144 	 || !(f->f_un.f_tls.tls_conn->retryevent = allocev())) {
1145 		if (f->f_un.f_tls.tls_conn)
1146 			free(f->f_un.f_tls.tls_conn->event);
1147 		free(f->f_un.f_tls.tls_conn);
1148 		logerror("Couldn't allocate memory for TLS config");
1149 		return false;
1150 	}
1151 	/* default values */
1152 	f->f_un.f_tls.tls_conn->x509verify = X509VERIFY_ALWAYS;
1153 	f->f_un.f_tls.tls_conn->reconnect = TLS_RECONNECT_SEC;
1154 
1155 	if (!(copy_string(&(f->f_un.f_tls.tls_conn->hostname), p, q))) {
1156 		logerror("Unable to read TLS server name"
1157 		    "in config line %zu", linenum);
1158 		free_tls_conn(f->f_un.f_tls.tls_conn);
1159 		return false;
1160 	}
1161 	p = ++q;
1162 
1163 	if (*p == ':') {
1164 		p++; q++;
1165 		while (isalnum((unsigned char)*q))
1166 			q++;
1167 		if (!(copy_string(&(f->f_un.f_tls.tls_conn->port), p, q))) {
1168 			logerror("Unable to read TLS port or service name"
1169 				" after ':' in config line %zu", linenum);
1170 			free_tls_conn(f->f_un.f_tls.tls_conn);
1171 			return false;
1172 		}
1173 		p = q;
1174 	}
1175 	/* allow whitespace for readability? */
1176 	while (isblank((unsigned char)*p))
1177 		p++;
1178 	if (*p == '(') {
1179 		p++;
1180 		while (*p != ')') {
1181 			if (copy_config_value_quoted("subject=\"",
1182 			    &(f->f_un.f_tls.tls_conn->subject), &p)
1183 			    || copy_config_value_quoted("fingerprint=\"",
1184 			    &(f->f_un.f_tls.tls_conn->fingerprint), &p)
1185 			    || copy_config_value_quoted("cert=\"",
1186 			    &(f->f_un.f_tls.tls_conn->certfile), &p)) {
1187 			/* nothing */
1188 			} else if (!strcmp(p, "verify=")) {
1189 				q = p += sizeof("verify=")-1;
1190 				/* "" are optional */
1191 				if (*p == '\"') { p++; q++; }
1192 				while (isalpha((unsigned char)*q)) q++;
1193 				f->f_un.f_tls.tls_conn->x509verify =
1194 				    getVerifySetting(p);
1195 				if (*q == '\"') q++;  /* "" are optional */
1196 				p = q;
1197 			} else {
1198 				logerror("unknown keyword %s "
1199 				    "in config line %zu", p, linenum);
1200 			}
1201 			while (*p == ',' || isblank((unsigned char)*p))
1202 				p++;
1203 			if (*p == '\0') {
1204 				logerror("unterminated ("
1205 				    "in config line %zu", linenum);
1206 			}
1207 		}
1208 	}
1209 
1210 	DPRINTF((D_TLS|D_PARSE),
1211 	    "got TLS config: host %s, port %s, "
1212 	    "subject: %s, certfile: %s, fingerprint: %s\n",
1213 	    f->f_un.f_tls.tls_conn->hostname,
1214 	    f->f_un.f_tls.tls_conn->port,
1215 	    f->f_un.f_tls.tls_conn->subject,
1216 	    f->f_un.f_tls.tls_conn->certfile,
1217 	    f->f_un.f_tls.tls_conn->fingerprint);
1218 	return true;
1219 }
1220 
1221 /*
1222  * Dispatch routine (triggered by timer) to reconnect to a lost TLS server
1223  */
1224 /*ARGSUSED*/
1225 void
1226 tls_reconnect(int fd, short event, void *arg)
1227 {
1228 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
1229 
1230 	DPRINTF((D_TLS|D_CALL|D_EVENT), "tls_reconnect(conn_info@%p, "
1231 	    "server %s)\n", conn_info, conn_info->hostname);
1232 	if (conn_info->sslptr) {
1233 		conn_info->shutdown = true;
1234 		free_tls_sslptr(conn_info);
1235 	}
1236 	assert(conn_info->state == ST_NONE);
1237 
1238 	if (!tls_connect(conn_info)) {
1239 		if (conn_info->reconnect > TLS_RECONNECT_GIVEUP) {
1240 			logerror("Unable to connect to TLS server %s, "
1241 			    "giving up now", conn_info->hostname);
1242 			message_queue_freeall(get_f_by_conninfo(conn_info));
1243 			/* free the message queue; but do not free the
1244 			 * tls_conn_settings nor change the f_type to F_UNUSED.
1245 			 * that way one can still trigger a reconnect
1246 			 * with a SIGUSR1
1247 			 */
1248 		} else {
1249 			struct timeval tv;
1250 			logerror("Unable to connect to TLS server %s, "
1251 			    "try again in %d sec", conn_info->hostname,
1252 			    conn_info->reconnect);
1253 			tv.tv_sec = conn_info->reconnect;
1254 			tv.tv_usec = 0;
1255 			schedule_event(&conn_info->event, &tv,
1256 			    tls_reconnect, conn_info);
1257 			TLS_RECONNECT_BACKOFF(conn_info->reconnect);
1258 		}
1259 	} else {
1260 		assert(conn_info->state == ST_TLS_EST
1261 		    || conn_info->state == ST_CONNECTING
1262 		    || conn_info->state == ST_NONE);
1263 	}
1264 }
1265 /*
1266  * Dispatch routine for accepting TLS connections.
1267  * Has to be idempotent in case of TLS_RETRY (~ EAGAIN),
1268  * so we can continue a slow handshake.
1269  */
1270 /*ARGSUSED*/
1271 void
1272 dispatch_tls_accept(int fd, short event, void *arg)
1273 {
1274 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
1275 	int rc, error;
1276 	struct TLS_Incoming_Conn *tls_in;
1277 	sigset_t newmask, omask;
1278 
1279 	DPRINTF((D_TLS|D_CALL),
1280 		"dispatch_tls_accept(conn_info@%p, fd %d)\n", conn_info, fd);
1281 	assert(conn_info->event);
1282 	assert(conn_info->retryevent);
1283 	BLOCK_SIGNALS(omask, newmask);
1284 
1285 	ST_CHANGE(conn_info->state, ST_ACCEPTING);
1286 	rc = SSL_accept(conn_info->sslptr);
1287 	if (0 >= rc) {
1288 		error = tls_examine_error("SSL_accept()",
1289 		    conn_info->sslptr, NULL, rc);
1290 		switch (error) {
1291 		case TLS_RETRY_READ:
1292 			event_set(conn_info->retryevent, fd, EV_READ,
1293 			    dispatch_tls_accept, conn_info);
1294 			EVENT_ADD(conn_info->retryevent);
1295 			break;
1296 		case TLS_RETRY_WRITE:
1297 			event_set(conn_info->retryevent, fd, EV_WRITE,
1298 			    dispatch_tls_accept, conn_info);
1299 			EVENT_ADD(conn_info->retryevent);
1300 			break;
1301 		default: /* should not happen */
1302 			free_tls_conn(conn_info);
1303 			break;
1304 		}
1305 		RESTORE_SIGNALS(omask);
1306 		return;
1307 	}
1308 	/* else */
1309 	CALLOC(tls_in, sizeof(*tls_in));
1310 	CALLOC(tls_in->inbuf, (size_t)TLS_MIN_LINELENGTH);
1311 
1312 	tls_in->tls_conn = conn_info;
1313 	tls_in->socket = SSL_get_fd(conn_info->sslptr);
1314 	tls_in->inbuf[0] = '\0';
1315 	tls_in->inbuflen = TLS_MIN_LINELENGTH;
1316 	SLIST_INSERT_HEAD(&TLS_Incoming_Head, tls_in, entries);
1317 
1318 	event_set(conn_info->event, tls_in->socket, EV_READ | EV_PERSIST,
1319 	    dispatch_tls_read, tls_in);
1320 	EVENT_ADD(conn_info->event);
1321 	ST_CHANGE(conn_info->state, ST_TLS_EST);
1322 
1323 	loginfo("established TLS connection from %s with certificate "
1324 	    "%s (%s)", conn_info->hostname, conn_info->subject,
1325 	    conn_info->fingerprint);
1326 	RESTORE_SIGNALS(omask);
1327 	/*
1328 	 * We could also listen to EOF kevents -- but I do not think
1329 	 * that would be useful, because we still had to read() the buffer
1330 	 * before closing the socket.
1331 	 */
1332 }
1333 
1334 /*
1335  * Dispatch routine for accepting TCP connections and preparing
1336  * the tls_conn_settings object for a following SSL_accept().
1337  */
1338 /*ARGSUSED*/
1339 void
1340 dispatch_socket_accept(int fd, short event, void *ev)
1341 {
1342 #ifdef LIBWRAP
1343 	struct request_info req;
1344 #endif
1345 	struct sockaddr_storage frominet;
1346 	socklen_t addrlen;
1347 	int newsock, rc;
1348 	sigset_t newmask, omask;
1349 	SSL *ssl;
1350 	struct tls_conn_settings *conn_info;
1351 	char hbuf[NI_MAXHOST];
1352 	char *peername;
1353 
1354 	DPRINTF((D_TLS|D_NET), "incoming TCP connection\n");
1355 	if (!tls_opt.global_TLS_CTX) {
1356 		logerror("global_TLS_CTX not initialized!");
1357 		return;
1358 	}
1359 
1360 	BLOCK_SIGNALS(omask, newmask);
1361 	addrlen = sizeof(frominet);
1362 	if ((newsock = accept(fd, (struct sockaddr *)&frominet,
1363 	    &addrlen)) == -1) {
1364 		logerror("Error in accept(): %s", strerror(errno));
1365 		RESTORE_SIGNALS(omask);
1366 		return;
1367 	}
1368 	/* TODO: do we want an IP or a hostname? maybe even both? */
1369 	if ((rc = getnameinfo((struct sockaddr *)&frominet, addrlen,
1370 	    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1371 		DPRINTF(D_NET, "could not get peername: %s", gai_strerror(rc));
1372 		peername = NULL;
1373 	}
1374 	else {
1375 		size_t len = strlen(hbuf) + 1;
1376 		MALLOC(peername, len);
1377 		(void)memcpy(peername, hbuf, len);
1378 	}
1379 
1380 #ifdef LIBWRAP
1381 	request_init(&req, RQ_DAEMON, appname, RQ_FILE, newsock, NULL);
1382 	fromhost(&req);
1383 	if (!hosts_access(&req)) {
1384 		logerror("access from %s denied by hosts_access", peername);
1385 		shutdown(newsock, SHUT_RDWR);
1386 		close(newsock);
1387 		RESTORE_SIGNALS(omask);
1388 		return;
1389 	}
1390 #endif
1391 
1392 	if ((fcntl(newsock, F_SETFL, O_NONBLOCK)) == -1) {
1393 		DPRINTF(D_NET, "Unable to fcntl(sock, O_NONBLOCK): %s\n",
1394 		    strerror(errno));
1395 	}
1396 
1397 	if (!(ssl = SSL_new(tls_opt.global_TLS_CTX))) {
1398 		DPRINTF(D_TLS, "Unable to establish TLS: %s\n",
1399 		    ERR_error_string(ERR_get_error(), NULL));
1400 		close(newsock);
1401 		RESTORE_SIGNALS(omask);
1402 		return;
1403 	}
1404 	if (!SSL_set_fd(ssl, newsock)) {
1405 		DPRINTF(D_TLS, "Unable to connect TLS to socket %d: %s\n",
1406 			newsock, ERR_error_string(ERR_get_error(), NULL));
1407 		SSL_free(ssl);
1408 		close(newsock);
1409 		RESTORE_SIGNALS(omask);
1410 		return;
1411 	}
1412 
1413 	if (!(conn_info = calloc(1, sizeof(*conn_info)))
1414 	    || !(conn_info->event = allocev())
1415 	    || !(conn_info->retryevent = allocev())) {
1416 		if (conn_info)
1417 			free(conn_info->event);
1418 		free(conn_info);
1419 		SSL_free(ssl);
1420 		close(newsock);
1421 		logerror("Unable to allocate memory to accept incoming "
1422 		    "TLS connection from %s", peername);
1423 		RESTORE_SIGNALS(omask);
1424 		return;
1425 	}
1426 	ST_CHANGE(conn_info->state, ST_NONE);
1427 	/* store connection details inside ssl object, used to verify
1428 	 * cert and immediately match against hostname */
1429 	conn_info->hostname = peername;
1430 	conn_info->sslptr = ssl;
1431 	conn_info->x509verify = getVerifySetting(tls_opt.x509verify);
1432 	conn_info->incoming = true;
1433 	SSL_set_app_data(ssl, conn_info);
1434 	SSL_set_accept_state(ssl);
1435 
1436 	assert(conn_info->event);
1437 	assert(conn_info->retryevent);
1438 
1439 	ST_CHANGE(conn_info->state, ST_TCP_EST);
1440 	DPRINTF(D_TLS, "socket connection from %s accept()ed with fd %d, "
1441 		"calling SSL_accept()...\n",  peername, newsock);
1442 	dispatch_tls_accept(newsock, 0, conn_info);
1443 	RESTORE_SIGNALS(omask);
1444 }
1445 
1446 /*
1447  * Dispatch routine to read from outgoing TCP/TLS sockets.
1448  *
1449  * I do not know if libevent can tell us the difference
1450  * between available data and an EOF. But it does not matter
1451  * because there should not be any incoming data.
1452  * So we close the connection either because the peer closed its
1453  * side or because the peer broke the protocol by sending us stuff  ;-)
1454  */
1455 void
1456 dispatch_tls_eof(int fd, short event, void *arg)
1457 {
1458 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
1459 	sigset_t newmask, omask;
1460 	struct timeval tv;
1461 
1462 	BLOCK_SIGNALS(omask, newmask);
1463 	DPRINTF((D_TLS|D_EVENT|D_CALL), "dispatch_eof_tls(%d, %d, %p)\n",
1464 	    fd, event, arg);
1465 	assert(conn_info->state == ST_TLS_EST);
1466 	ST_CHANGE(conn_info->state, ST_EOF);
1467 	DEL_EVENT(conn_info->event);
1468 
1469 	free_tls_sslptr(conn_info);
1470 
1471 	/* this overwrites the EV_READ event */
1472 	tv.tv_sec = conn_info->reconnect;
1473 	tv.tv_usec = 0;
1474 	schedule_event(&conn_info->event, &tv, tls_reconnect, conn_info);
1475 	TLS_RECONNECT_BACKOFF(conn_info->reconnect);
1476 	RESTORE_SIGNALS(omask);
1477 }
1478 
1479 /*
1480  * Dispatch routine to read from TCP/TLS sockets.
1481  * NB: This gets called when the TCP socket has data available, thus
1482  *     we can call SSL_read() on it. But that does not mean the SSL buffer
1483  *     holds a complete record and SSL_read() lets us read any data now.
1484  */
1485 /*ARGSUSED*/
1486 void
1487 dispatch_tls_read(int fd_lib, short event, void *arg)
1488 {
1489 	struct TLS_Incoming_Conn *c = (struct TLS_Incoming_Conn *) arg;
1490 	int fd = c->socket;
1491 	int error;
1492 	int rc;
1493 	sigset_t newmask, omask;
1494 	bool retrying;
1495 
1496 	BLOCK_SIGNALS(omask, newmask);
1497 	DPRINTF((D_TLS|D_EVENT|D_CALL), "active TLS socket %d\n", fd);
1498 	DPRINTF(D_TLS, "calling SSL_read(%p, %p, %zu)\n", c->tls_conn->sslptr,
1499 		&(c->inbuf[c->read_pos]), c->inbuflen - c->read_pos);
1500 	retrying = (c->tls_conn->state == ST_READING);
1501 	ST_CHANGE(c->tls_conn->state, ST_READING);
1502 	rc = SSL_read(c->tls_conn->sslptr, &(c->inbuf[c->read_pos]),
1503 		c->inbuflen - c->read_pos);
1504 	if (rc <= 0) {
1505 		error = tls_examine_error("SSL_read()", c->tls_conn->sslptr,
1506 		    c->tls_conn, rc);
1507 		switch (error) {
1508 		case TLS_RETRY_READ:
1509 			/* normal event loop will call us again */
1510 			break;
1511 		case TLS_RETRY_WRITE:
1512 			if (!retrying)
1513 				event_del(c->tls_conn->event);
1514 			event_set(c->tls_conn->retryevent, fd,
1515 				EV_WRITE, dispatch_tls_read, c);
1516 			EVENT_ADD(c->tls_conn->retryevent);
1517 			RESTORE_SIGNALS(omask);
1518 			return;
1519 		case TLS_TEMP_ERROR:
1520 			if (c->tls_conn->errorcount < TLS_MAXERRORCOUNT)
1521 				break;
1522 			/* FALLTHROUGH */
1523 		case TLS_PERM_ERROR:
1524 			/* there might be data in the inbuf, so only
1525 			 * mark for closing after message retrieval */
1526 			c->closenow = true;
1527 			break;
1528 		default:
1529 			break;
1530 		}
1531 	} else {
1532 		DPRINTF(D_TLS, "SSL_read() returned %d\n", rc);
1533 		c->errorcount = 0;
1534 		c->read_pos += rc;
1535 	}
1536 	if (retrying)
1537 		EVENT_ADD(c->tls_conn->event);
1538 	tls_split_messages(c);
1539 	if (c->closenow) {
1540 		free_tls_conn(c->tls_conn);
1541 		FREEPTR(c->inbuf);
1542 		SLIST_REMOVE(&TLS_Incoming_Head, c, TLS_Incoming_Conn, entries);
1543 		free(c);
1544 	} else
1545 		ST_CHANGE(c->tls_conn->state, ST_TLS_EST);
1546 	RESTORE_SIGNALS(omask);
1547 }
1548 
1549 /* moved message splitting out of dispatching function.
1550  * now we can call it recursively.
1551  *
1552  * TODO: the code for oversized messages still needs testing,
1553  * especially for the skipping case.
1554  */
1555 void
1556 tls_split_messages(struct TLS_Incoming_Conn *c)
1557 {
1558 /* define only to make it better readable */
1559 #define MSG_END_OFFSET (c->cur_msg_start + c->cur_msg_len)
1560 	size_t offset = 0;
1561 	size_t msglen = 0;
1562 	char *newbuf;
1563 	char buf_char;
1564 
1565 	DPRINTF((D_TLS|D_CALL|D_DATA), "tls_split_messages() -- "
1566 		"incoming status is msg_start %zu, msg_len %zu, pos %zu\n",
1567 		c->cur_msg_start, c->cur_msg_len, c->read_pos);
1568 
1569 	if (!c->read_pos)
1570 		return;
1571 
1572 	if (c->dontsave && c->read_pos < MSG_END_OFFSET) {
1573 		c->cur_msg_len -= c->read_pos;
1574 		c->read_pos = 0;
1575 	} else if (c->dontsave && c->read_pos == MSG_END_OFFSET) {
1576 		c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
1577 		c->dontsave = false;
1578 	} else if (c->dontsave && c->read_pos > MSG_END_OFFSET) {
1579 		/* move remaining input to start of buffer */
1580 		DPRINTF(D_DATA, "move inbuf of length %zu by %zu chars\n",
1581 		    c->read_pos - (MSG_END_OFFSET),
1582 		    MSG_END_OFFSET);
1583 		memmove(&c->inbuf[0],
1584 		    &c->inbuf[MSG_END_OFFSET],
1585 		    c->read_pos - (MSG_END_OFFSET));
1586 		c->read_pos -= (MSG_END_OFFSET);
1587 		c->cur_msg_start = c->cur_msg_len = 0;
1588 		c->dontsave = false;
1589 	}
1590 	if (c->read_pos < MSG_END_OFFSET) {
1591 		return;
1592 	}
1593 
1594 	/* read length prefix, always at start of buffer */
1595 	while (isdigit((unsigned char)c->inbuf[offset])
1596 	    && offset < c->read_pos) {
1597 		msglen *= 10;
1598 		msglen += c->inbuf[offset] - '0';
1599 		offset++;
1600 	}
1601 	if (offset == c->read_pos) {
1602 		/* next invocation will have more data */
1603 		return;
1604 	}
1605 	if (c->inbuf[offset] == ' ') {
1606 		c->cur_msg_len = msglen;
1607 		c->cur_msg_start = offset + 1;
1608 		if (MSG_END_OFFSET+1 > c->inbuflen) {  /* +1 for the '\0' */
1609 			newbuf = realloc(c->inbuf, MSG_END_OFFSET+1);
1610 			if (newbuf) {
1611 				DPRINTF(D_DATA, "Reallocated inbuf\n");
1612 				c->inbuflen = MSG_END_OFFSET+1;
1613 				c->inbuf = newbuf;
1614 			} else {
1615 				logerror("Couldn't reallocate buffer, "
1616 				    "will skip this message");
1617 				c->dontsave = true;
1618 				c->cur_msg_len -= c->read_pos;
1619 				c->cur_msg_start = 0;
1620 				c->read_pos = 0;
1621 			}
1622 		}
1623 	} else {
1624 		/* found non-digit in prefix */
1625 		/* Question: would it be useful to skip this message and
1626 		 * try to find next message by looking for its beginning?
1627 		 * IMHO not.
1628 		 */
1629 		logerror("Unable to handle TLS length prefix. "
1630 		    "Protocol error? Closing connection now.");
1631 		/* only set flag -- caller has to close then */
1632 		c->closenow = true;
1633 		return;
1634 	}
1635 	/* read one syslog message */
1636 	if (c->read_pos >= MSG_END_OFFSET) {
1637 		/* process complete msg */
1638 		assert(MSG_END_OFFSET+1 <= c->inbuflen);
1639 		/* message in c->inbuf is not NULL-terminated,
1640 		 * so this avoids a complete copy */
1641 		buf_char = c->inbuf[MSG_END_OFFSET];
1642 		c->inbuf[MSG_END_OFFSET] = '\0';
1643 		printline(c->tls_conn->hostname, &c->inbuf[c->cur_msg_start],
1644 		    RemoteAddDate ? ADDDATE : 0);
1645 		c->inbuf[MSG_END_OFFSET] = buf_char;
1646 
1647 		if (MSG_END_OFFSET == c->read_pos) {
1648 			/* no unprocessed data in buffer --> reset to empty */
1649 			c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
1650 		} else {
1651 			/* move remaining input to start of buffer */
1652 			DPRINTF(D_DATA, "move inbuf of length %zu by %zu "
1653 			    "chars\n", c->read_pos - (MSG_END_OFFSET),
1654 			    MSG_END_OFFSET);
1655 			memmove(&c->inbuf[0], &c->inbuf[MSG_END_OFFSET],
1656 			    c->read_pos - (MSG_END_OFFSET));
1657 			c->read_pos -= (MSG_END_OFFSET);
1658 			c->cur_msg_start = c->cur_msg_len = 0;
1659 		}
1660 	}
1661 
1662 	/* shrink inbuf if too large */
1663 	if ((c->inbuflen > TLS_PERSIST_LINELENGTH)
1664 	 && (c->read_pos < TLS_LARGE_LINELENGTH)) {
1665 		newbuf = realloc(c->inbuf, TLS_LARGE_LINELENGTH);
1666 		if (newbuf) {
1667 			DPRINTF(D_DATA, "Shrink inbuf\n");
1668 			c->inbuflen = TLS_LARGE_LINELENGTH;
1669 			c->inbuf = newbuf;
1670 		} else {
1671 			logerror("Couldn't shrink inbuf");
1672 			/* no change necessary */
1673 		}
1674 	}
1675 	DPRINTF(D_DATA, "return with status: msg_start %zu, msg_len %zu, "
1676 	    "pos %zu\n", c->cur_msg_start, c->cur_msg_len, c->read_pos);
1677 
1678 	/* try to read another message */
1679 	if (c->read_pos > 10)
1680 		tls_split_messages(c);
1681 	return;
1682 }
1683 
1684 /*
1685  * wrapper for dispatch_tls_send()
1686  *
1687  * send one line with tls
1688  * f has to be of typ TLS
1689  *
1690  * returns false if message cannot be sent right now,
1691  *	caller is responsible to enqueue it
1692  * returns true if message passed to dispatch_tls_send()
1693  *	delivery is not garantueed, but likely
1694  */
1695 #define DEBUG_LINELENGTH 40
1696 bool
1697 tls_send(struct filed *f, char *line, size_t len, struct buf_queue *qentry)
1698 {
1699 	struct tls_send_msg *smsg;
1700 
1701 	DPRINTF((D_TLS|D_CALL), "tls_send(f=%p, line=\"%.*s%s\", "
1702 	    "len=%zu) to %sconnected dest.\n", f,
1703 	    (int)(len > DEBUG_LINELENGTH ? DEBUG_LINELENGTH : len),
1704 	    line, (len > DEBUG_LINELENGTH ? "..." : ""),
1705 	    len, f->f_un.f_tls.tls_conn->sslptr ? "" : "un");
1706 
1707 	if(f->f_un.f_tls.tls_conn->state == ST_TLS_EST) {
1708 		/* send now */
1709 		if (!(smsg = calloc(1, sizeof(*smsg)))) {
1710 			logerror("Unable to allocate memory, drop message");
1711 			return false;
1712 		}
1713 		smsg->f = f;
1714 		smsg->line = line;
1715 		smsg->linelen = len;
1716 		(void)NEWREF(qentry->msg);
1717 		smsg->qentry = qentry;
1718 		DPRINTF(D_DATA, "now sending line: \"%.*s\"\n",
1719 		    (int)smsg->linelen, smsg->line);
1720 		dispatch_tls_send(0, 0, smsg);
1721 		return true;
1722 	} else {
1723 		/* other socket operation active, send later  */
1724 		DPRINTF(D_DATA, "connection not ready to send: \"%.*s\"\n",
1725 		    (int)len, line);
1726 		return false;
1727 	}
1728 }
1729 
1730 /*ARGSUSED*/
1731 void
1732 dispatch_tls_send(int fd, short event, void *arg)
1733 {
1734 	struct tls_send_msg *smsg = (struct tls_send_msg *) arg;
1735 	struct tls_conn_settings *conn_info = smsg->f->f_un.f_tls.tls_conn;
1736 	struct filed *f = smsg->f;
1737 	int rc, error;
1738 	sigset_t newmask, omask;
1739 	bool retrying;
1740 	struct timeval tv;
1741 
1742 	BLOCK_SIGNALS(omask, newmask);
1743 	DPRINTF((D_TLS|D_CALL), "dispatch_tls_send(f=%p, buffer=%p, "
1744 	    "line@%p, len=%zu, offset=%zu) to %sconnected dest.\n",
1745 	    smsg->f, smsg->qentry->msg, smsg->line,
1746 	    smsg->linelen, smsg->offset,
1747 		conn_info->sslptr ? "" : "un");
1748 	assert(conn_info->state == ST_TLS_EST
1749 	    || conn_info->state == ST_WRITING);
1750 
1751 	retrying = (conn_info->state == ST_WRITING);
1752 	ST_CHANGE(conn_info->state, ST_WRITING);
1753 	rc = SSL_write(conn_info->sslptr,
1754 	    (smsg->line + smsg->offset),
1755 	    (smsg->linelen - smsg->offset));
1756 	if (0 >= rc) {
1757 		error = tls_examine_error("SSL_write()",
1758 		    conn_info->sslptr,
1759 		    conn_info, rc);
1760 		switch (error) {
1761 		case TLS_RETRY_READ:
1762 			/* collides with eof event */
1763 			if (!retrying)
1764 				event_del(conn_info->event);
1765 			event_set(conn_info->retryevent, fd, EV_READ,
1766 				dispatch_tls_send, smsg);
1767 			RETRYEVENT_ADD(conn_info->retryevent);
1768 			break;
1769 		case TLS_RETRY_WRITE:
1770 			event_set(conn_info->retryevent, fd, EV_WRITE,
1771 			    dispatch_tls_send, smsg);
1772 			RETRYEVENT_ADD(conn_info->retryevent);
1773 			break;
1774 		case TLS_PERM_ERROR:
1775 			/* no need to check active events */
1776 			free_tls_send_msg(smsg);
1777 			free_tls_sslptr(conn_info);
1778 			tv.tv_sec = conn_info->reconnect;
1779 			tv.tv_usec = 0;
1780 			schedule_event(&conn_info->event, &tv,
1781 			    tls_reconnect, conn_info);
1782 			TLS_RECONNECT_BACKOFF(conn_info->reconnect);
1783 			break;
1784 		default:
1785 			break;
1786 		}
1787 		RESTORE_SIGNALS(omask);
1788 		return;
1789 	} else if ((size_t)rc < smsg->linelen) {
1790 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() wrote %d out of %zu "
1791 		    "bytes\n", rc, (smsg->linelen - smsg->offset));
1792 		smsg->offset += rc;
1793 		/* try again */
1794 		if (retrying)
1795 			EVENT_ADD(conn_info->event);
1796 		dispatch_tls_send(0, 0, smsg);
1797 		return;
1798 	} else if ((size_t)rc == (smsg->linelen - smsg->offset)) {
1799 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() complete\n");
1800 		ST_CHANGE(conn_info->state, ST_TLS_EST);
1801 		free_tls_send_msg(smsg);
1802 		send_queue(0, 0, f);
1803 
1804 	} else {
1805 		/* should not be reached */
1806 		/*LINTED constcond */
1807 		assert(0);
1808 		DPRINTF((D_TLS|D_DATA), "unreachable code after SSL_write()\n");
1809 		ST_CHANGE(conn_info->state, ST_TLS_EST);
1810 		free_tls_send_msg(smsg);
1811 		send_queue(0, 0, f);
1812 	}
1813 	if (retrying && conn_info->event->ev_events)
1814 		EVENT_ADD(conn_info->event);
1815 	RESTORE_SIGNALS(omask);
1816 }
1817 
1818 /*
1819  * Close a SSL connection and its queue and its tls_conn.
1820  */
1821 void
1822 free_tls_conn(struct tls_conn_settings *conn_info)
1823 {
1824 	DPRINTF(D_MEM, "free_tls_conn(conn_info@%p) with sslptr@%p\n",
1825 		conn_info, conn_info->sslptr);
1826 
1827 	if (conn_info->sslptr) {
1828 		conn_info->shutdown = true;
1829 		free_tls_sslptr(conn_info);
1830 	}
1831 	assert(conn_info->state == ST_NONE);
1832 
1833 	FREEPTR(conn_info->port);
1834 	FREEPTR(conn_info->subject);
1835 	FREEPTR(conn_info->hostname);
1836 	FREEPTR(conn_info->certfile);
1837 	FREEPTR(conn_info->fingerprint);
1838 	DEL_EVENT(conn_info->event);
1839 	DEL_EVENT(conn_info->retryevent);
1840 	FREEPTR(conn_info->event);
1841 	FREEPTR(conn_info->retryevent);
1842 	FREEPTR(conn_info);
1843 	DPRINTF(D_MEM2, "free_tls_conn(conn_info@%p) returns\n", conn_info);
1844 }
1845 
1846 /*
1847  * Dispatch routine for non-blocking TLS shutdown
1848  */
1849 /*ARGSUSED*/
1850 void
1851 dispatch_SSL_shutdown(int fd, short event, void *arg)
1852 {
1853 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
1854 	int rc, error;
1855 	sigset_t newmask, omask;
1856 	bool retrying;
1857 
1858 	BLOCK_SIGNALS(omask, newmask);
1859 	DPRINTF((D_TLS|D_CALL),
1860 	    "dispatch_SSL_shutdown(conn_info@%p, fd %d)\n", conn_info, fd);
1861 	retrying = ((conn_info->state == ST_CLOSING0)
1862 	     || (conn_info->state == ST_CLOSING1)
1863 	     || (conn_info->state == ST_CLOSING2));
1864 	if (!retrying)
1865 		ST_CHANGE(conn_info->state, ST_CLOSING0);
1866 
1867 	rc = SSL_shutdown(conn_info->sslptr);
1868 	if (rc == 1) {	/* shutdown complete */
1869 		DPRINTF((D_TLS|D_NET), "Closed TLS connection to %s\n",
1870 		    conn_info->hostname);
1871 		ST_CHANGE(conn_info->state, ST_TCP_EST);  /* check this */
1872 		conn_info->accepted = false;
1873 		/* closing TCP comes below */
1874 	} else if (rc == 0) { /* unidirectional, now call a 2nd time */
1875 		/* problem: when connecting as a client to rsyslogd this
1876 		 * loops and I keep getting rc == 0
1877 		 * maybe I hit this bug?
1878 		 * http://www.mail-archive.com/openssl-dev@openssl.org/msg24105.html
1879 		 *
1880 		 * anyway, now I use three closing states to make sure I abort
1881 		 * after two rc = 0.
1882 		 */
1883 		if (conn_info->state == ST_CLOSING0) {
1884 			ST_CHANGE(conn_info->state, ST_CLOSING1);
1885 			dispatch_SSL_shutdown(fd, 0, conn_info);
1886 		} else if (conn_info->state == ST_CLOSING1) {
1887 			ST_CHANGE(conn_info->state, ST_CLOSING2);
1888 			dispatch_SSL_shutdown(fd, 0, conn_info);
1889 		} else if (conn_info->state == ST_CLOSING2) {
1890 			/* abort shutdown, jump to close TCP below */
1891 		} else
1892 			DPRINTF(D_TLS, "Unexpected connection state %d\n",
1893 				conn_info->state);
1894 			/* and abort here too*/
1895 	} else if (rc == -1 && conn_info->shutdown ) {
1896 		(void)tls_examine_error("SSL_shutdown()",
1897 			conn_info->sslptr, NULL, rc);
1898 		DPRINTF((D_TLS|D_NET), "Ignore error in SSL_shutdown()"
1899 			" and force connection shutdown.");
1900 		ST_CHANGE(conn_info->state, ST_TCP_EST);
1901 		conn_info->accepted = false;
1902 	} else if (rc == -1 && !conn_info->shutdown ) {
1903 		error = tls_examine_error("SSL_shutdown()",
1904 			conn_info->sslptr, NULL, rc);
1905 		switch (error) {
1906 		case TLS_RETRY_READ:
1907 			if (!retrying)
1908 				event_del(conn_info->event);
1909 			event_set(conn_info->retryevent, fd, EV_READ,
1910 			    dispatch_SSL_shutdown, conn_info);
1911 			EVENT_ADD(conn_info->retryevent);
1912 			RESTORE_SIGNALS(omask);
1913 			return;
1914 		case TLS_RETRY_WRITE:
1915 			if (!retrying)
1916 				event_del(conn_info->event);
1917 			event_set(conn_info->retryevent, fd, EV_WRITE,
1918 			    dispatch_SSL_shutdown, conn_info);
1919 			EVENT_ADD(conn_info->retryevent);
1920 			RESTORE_SIGNALS(omask);
1921 			return;
1922 		default:
1923 			/* force close() on the TCP connection */
1924 			ST_CHANGE(conn_info->state, ST_TCP_EST);
1925 			conn_info->accepted = false;
1926 			break;
1927 		}
1928 	}
1929 	if ((conn_info->state != ST_TLS_EST)
1930 	    && (conn_info->state != ST_NONE)
1931 	    && (conn_info->state != ST_CLOSING0)
1932 	    && (conn_info->state != ST_CLOSING1)) {
1933 		int sock = SSL_get_fd(conn_info->sslptr);
1934 
1935 		if (shutdown(sock, SHUT_RDWR) == -1)
1936 			logerror("Cannot shutdown socket");
1937 		DEL_EVENT(conn_info->retryevent);
1938 		DEL_EVENT(conn_info->event);
1939 
1940 		if (close(sock) == -1)
1941 			logerror("Cannot close socket");
1942 		DPRINTF((D_TLS|D_NET), "Closed TCP connection to %s\n",
1943 		    conn_info->hostname);
1944 		ST_CHANGE(conn_info->state, ST_NONE);
1945 		FREE_SSL(conn_info->sslptr);
1946 	 }
1947 	RESTORE_SIGNALS(omask);
1948 }
1949 
1950 /*
1951  * Close a SSL object
1952  */
1953 void
1954 free_tls_sslptr(struct tls_conn_settings *conn_info)
1955 {
1956 	int sock;
1957 	DPRINTF(D_MEM, "free_tls_sslptr(conn_info@%p)\n", conn_info);
1958 
1959 	if (!conn_info->sslptr) {
1960 		assert(conn_info->incoming == 1
1961 		    || conn_info->state == ST_NONE);
1962 		return;
1963 	} else {
1964 		sock = SSL_get_fd(conn_info->sslptr);
1965 		dispatch_SSL_shutdown(sock, 0, conn_info);
1966 	}
1967 }
1968 
1969 /* write self-generated certificates */
1970 bool
1971 write_x509files(EVP_PKEY *pkey, X509 *cert,
1972 	const char *keyfilename, const char *certfilename)
1973 {
1974 	FILE *certfile, *keyfile;
1975 
1976 	if (!(umask(0177),(keyfile  = fopen(keyfilename,  "a")))) {
1977 		logerror("Unable to write to file \"%s\"", keyfilename);
1978 		return false;
1979 	}
1980 	if (!(umask(0122),(certfile = fopen(certfilename, "a")))) {
1981 		logerror("Unable to write to file \"%s\"", certfilename);
1982 		(void)fclose(keyfile);
1983 		return false;
1984 	}
1985 	if (!PEM_write_PrivateKey(keyfile, pkey, NULL, NULL, 0, NULL, NULL))
1986 		logerror("Unable to write key to \"%s\"", keyfilename);
1987 	if (!X509_print_fp(certfile, cert)
1988 	    || !PEM_write_X509(certfile, cert))
1989 		logerror("Unable to write certificate to \"%s\"",
1990 		    certfilename);
1991 
1992 	(void)fclose(keyfile);
1993 	(void)fclose(certfile);
1994 	return true;
1995 }
1996 
1997 
1998 /* adds all local IP addresses as subjectAltNames to cert x.
1999  * getifaddrs() should be quite portable among BSDs and Linux
2000  * but if not available the whole function can simply be removed.
2001  */
2002 bool
2003 x509_cert_add_subjectAltName(X509 *cert, X509V3_CTX *ctx)
2004 {
2005 	struct ifaddrs *ifa = NULL, *ifp = NULL;
2006 	char ip[100];
2007 	char subjectAltName[2048];
2008 	int idx = 0;
2009 	socklen_t salen;
2010 	X509_EXTENSION *ext;
2011 #ifdef notdef
2012 	STACK_OF(X509_EXTENSION) *extlist;
2013 	extlist = sk_X509_EXTENSION_new_null();
2014 #endif
2015 
2016 	if (getifaddrs (&ifp) == -1) {
2017 		logerror("Unable to get list of local interfaces");
2018 		return false;
2019 	}
2020 
2021 	idx = snprintf(subjectAltName, sizeof(subjectAltName),
2022 	    "DNS:%s", LocalFQDN);
2023 
2024 	for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
2025 		if(!ifa->ifa_addr)
2026 			continue;
2027 
2028 		/* only IP4 and IP6 addresses, but filter loopbacks */
2029 		if (ifa->ifa_addr->sa_family == AF_INET) {
2030 			struct sockaddr_in *addr =
2031 			    (struct sockaddr_in *)ifa->ifa_addr;
2032 			if (addr->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
2033 				continue;
2034 			salen = sizeof(struct sockaddr_in);
2035 		} else if (ifa->ifa_addr->sa_family == AF_INET6) {
2036 			struct in6_addr *addr6 =
2037 			    &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
2038 			if (IN6_IS_ADDR_LOOPBACK(addr6))
2039 				continue;
2040 			salen = sizeof(struct sockaddr_in6);
2041 		} else
2042 			continue;
2043 
2044 		if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip),
2045 		    NULL, 0, NI_NUMERICHOST)) {
2046 			continue;
2047 		}
2048 
2049 		/* add IP to list */
2050 		idx += snprintf(&subjectAltName[idx],
2051 		    sizeof(subjectAltName)-idx, ", IP:%s", ip);
2052 	}
2053 	freeifaddrs (ifp);
2054 
2055 	ext = X509V3_EXT_conf_nid(NULL, ctx,
2056 	    NID_subject_alt_name, subjectAltName);
2057 	X509_add_ext(cert, ext, -1);
2058 	X509_EXTENSION_free(ext);
2059 
2060 	return true;
2061 }
2062 
2063 /*
2064  * generates a private key and a X.509 certificate
2065  */
2066 bool
2067 mk_x509_cert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days)
2068 {
2069 	X509	       *cert;
2070 	EVP_PKEY       *pk;
2071 	DSA	       *dsa;
2072 	X509_NAME      *name = NULL;
2073 	X509_EXTENSION *ex = NULL;
2074 	X509V3_CTX	ctx;
2075 
2076 	DPRINTF((D_CALL|D_TLS), "mk_x509_cert(%p, %p, %d, %d, %d)\n",
2077 	    x509p, pkeyp, bits, serial, days);
2078 
2079 	if (pkeyp && *pkeyp)
2080 		pk = *pkeyp;
2081 	else if ((pk = EVP_PKEY_new()) == NULL) {
2082 		DPRINTF(D_TLS, "EVP_PKEY_new() failed\n");
2083 		return false;
2084 	}
2085 
2086 	if (x509p && *x509p)
2087 		cert = *x509p;
2088 	else if ((cert = X509_new()) == NULL) {
2089 		DPRINTF(D_TLS, "X509_new() failed\n");
2090 		return false;
2091 	}
2092 
2093 	dsa = DSA_generate_parameters(bits, NULL, 0,
2094 			    NULL, NULL, NULL, NULL);
2095 	if (!DSA_generate_key(dsa)) {
2096 		DPRINTF(D_TLS, "DSA_generate_key() failed\n");
2097 		return false;
2098 	}
2099 	if (!EVP_PKEY_assign_DSA(pk, dsa)) {
2100 		DPRINTF(D_TLS, "EVP_PKEY_assign_DSA() failed\n");
2101 		return false;
2102 	}
2103 
2104 	X509_set_version(cert, 3);
2105 	ASN1_INTEGER_set(X509_get_serialNumber(cert), serial);
2106 	X509_gmtime_adj(X509_get_notBefore(cert), 0);
2107 	X509_gmtime_adj(X509_get_notAfter(cert), (long)60 * 60 * 24 * days);
2108 
2109 	if (!X509_set_pubkey(cert, pk)) {
2110 		DPRINTF(D_TLS, "X509_set_pubkey() failed\n");
2111 		return false;
2112 	}
2113 
2114 	/*
2115 	 * This function creates and adds the entry, working out the correct
2116 	 * string type and performing checks on its length. Normally we'd check
2117 	 * the return value for errors...
2118 	 */
2119 	name = X509_get_subject_name(cert);
2120 	/*
2121 	X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
2122 	    (unsigned char *)"The NetBSD Project", -1, -1, 0);
2123 	X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC,
2124 	    (unsigned char *)"syslogd", -1, -1, 0);
2125 	*/
2126 	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2127 	    (unsigned char *) LocalFQDN, -1, -1, 0);
2128 	X509_set_issuer_name(cert, name);
2129 
2130 	/*
2131 	 * Add extension using V3 code: we can set the config file as NULL
2132 	 * because we wont reference any other sections.
2133 	 */
2134 	X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
2135 
2136 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_comment,
2137 	    __UNCONST("auto-generated by the NetBSD syslogd"));
2138 	X509_add_ext(cert, ex, -1);
2139 	X509_EXTENSION_free(ex);
2140 
2141 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_ssl_server_name,
2142 	    LocalFQDN);
2143 	X509_add_ext(cert, ex, -1);
2144 	X509_EXTENSION_free(ex);
2145 
2146 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_cert_type,
2147 	    __UNCONST("server, client"));
2148 	X509_add_ext(cert, ex, -1);
2149 	X509_EXTENSION_free(ex);
2150 
2151 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_key_usage,
2152 	    __UNCONST("keyAgreement, keyEncipherment, "
2153 	    "nonRepudiation, digitalSignature"));
2154 	X509_add_ext(cert, ex, -1);
2155 	X509_EXTENSION_free(ex);
2156 
2157 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints,
2158 	    __UNCONST("critical,CA:FALSE"));
2159 	X509_add_ext(cert, ex, -1);
2160 	X509_EXTENSION_free(ex);
2161 
2162 	(void)x509_cert_add_subjectAltName(cert, &ctx);
2163 
2164 	if (!X509_sign(cert, pk, EVP_dss1())) {
2165 		DPRINTF(D_TLS, "X509_sign() failed\n");
2166 		return false;
2167 	}
2168 	if (X509_verify(cert, pk) != 1) {
2169 		DPRINTF(D_TLS, "X509_verify() failed\n");
2170 		return false;
2171 	}
2172 
2173 	*x509p = cert;
2174 	*pkeyp = pk;
2175 	return true;
2176 }
2177 
2178 void
2179 free_tls_send_msg(struct tls_send_msg *msg)
2180 {
2181 	if (!msg) {
2182 		DPRINTF((D_DATA), "invalid tls_send_msg_free(NULL)\n");
2183 		return;
2184 	}
2185 	DELREF(msg->qentry->msg);
2186 	(void)message_queue_remove(msg->f, msg->qentry);
2187 	FREEPTR(msg->line);
2188 	FREEPTR(msg);
2189 }
2190 #endif /* !DISABLE_TLS */
2191