xref: /minix/usr.sbin/syslogd/tls.c (revision 00b67f09)
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 #if !defined(NDEBUG) && defined(__minix)
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 #endif /* !defined(NDEBUG) && defined(__minix) */
85 
86 DH *get_dh1024(void);
87 /* DH parameter precomputed with "openssl dhparam -C -2 1024" */
88 #ifndef HEADER_DH_H
89 #include <openssl/dh.h>
90 #endif
91 DH *
92 get_dh1024(void)
93 {
94 	static const unsigned char dh1024_p[]={
95 		0x94,0xBC,0xC4,0x71,0xD4,0xD3,0x2B,0x17,0x69,0xEA,0x82,0x1B,
96 		0x0F,0x86,0x45,0x57,0xF8,0x86,0x2C,0xC8,0xF5,0x37,0x1F,0x1F,
97 		0x12,0xDA,0x2C,0x62,0x4C,0xF6,0x95,0xF0,0xE4,0x6A,0x63,0x00,
98 		0x32,0x54,0x5F,0xA9,0xAA,0x2E,0xD2,0xD3,0xA5,0x7A,0x4E,0xCF,
99 		0xE8,0x2A,0xF6,0xAB,0xAF,0xD3,0x71,0x3E,0x75,0x9E,0x6B,0xF3,
100 		0x2E,0x6D,0x97,0x42,0xC2,0x45,0xC0,0x03,0xE1,0x17,0xA4,0x39,
101 		0xF6,0x36,0xA7,0x11,0xBD,0x30,0xF6,0x6F,0x21,0xBF,0x28,0xE4,
102 		0xF9,0xE1,0x1E,0x48,0x72,0x58,0xA9,0xC8,0x61,0x65,0xDB,0x66,
103 		0x36,0xA3,0x77,0x0A,0x81,0x79,0x2C,0x45,0x1E,0x97,0xA6,0xB1,
104 		0xD9,0x25,0x9C,0x28,0x96,0x91,0x40,0xF8,0xF6,0x86,0x11,0x9C,
105 		0x88,0xEC,0xA6,0xBA,0x9F,0x4F,0x85,0x43 };
106 	static const unsigned char dh1024_g[]={ 0x02 };
107 	DH *dh;
108 
109 	if ((dh=DH_new()) == NULL)
110 		return NULL;
111 	dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
112 	dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
113 	if ((dh->p == NULL) || (dh->g == NULL)) {
114 		DH_free(dh);
115 		return NULL;
116 	}
117 	return dh;
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 	char *buf;
440 	unsigned char *ubuf;
441 	GENERAL_NAMES *gennames;
442 	GENERAL_NAME *gn;
443 	X509_NAME *x509name;
444 	X509_NAME_ENTRY *entry;
445 	ASN1_OCTET_STRING *asn1_ip, *asn1_cn_ip;
446 	int crit, idx;
447 
448 	DPRINTF((D_TLS|D_CALL), "match_hostnames(%p, \"%s\", \"%s\")\n",
449 	    cert, hostname, subject);
450 
451 	/* see if hostname is an IP */
452 	if ((subject  && (asn1_ip = a2i_IPADDRESS(subject )))
453 	 || (hostname && (asn1_ip = a2i_IPADDRESS(hostname))))
454 		/* nothing */;
455 	else
456 		asn1_ip = NULL;
457 
458 	if (!(gennames = X509_get_ext_d2i(cert, NID_subject_alt_name,
459 	    &crit, &idx))) {
460 		DPRINTF(D_TLS, "X509_get_ext_d2i() returned (%p,%d,%d) "
461 		    "--> no subjectAltName\n", gennames, crit, idx);
462 	} else {
463 		num = sk_GENERAL_NAME_num(gennames);
464 		if (asn1_ip) {
465 			/* first loop: check IPs */
466 			for (i = 0; i < num; ++i) {
467 				gn = sk_GENERAL_NAME_value(gennames, i);
468 				if (gn->type == GEN_IPADD
469 				    && !ASN1_OCTET_STRING_cmp(asn1_ip,
470 					gn->d.iPAddress))
471 					return true;
472 			}
473 		}
474 		/* second loop: check DNS names */
475 		for (i = 0; i < num; ++i) {
476 			gn = sk_GENERAL_NAME_value(gennames, i);
477 			if (gn->type == GEN_DNS) {
478 				buf = (char *)ASN1_STRING_data(gn->d.ia5);
479 				len = ASN1_STRING_length(gn->d.ia5);
480 				if (!strncasecmp(subject, buf, len)
481 				    || !strncasecmp(hostname, buf, 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_NAME_oneline(
708 			    X509_get_issuer_name(ctx->current_cert),
709 			    cur_issuerline, sizeof(cur_issuerline));
710 			DPRINTF(D_TLS, "openssl verify error:missing "
711 			    "cert for issuer=%s\n", cur_issuerline);
712 		}
713 	}
714 
715 	/*
716 	 * quite a lot of variables here,
717 	 * the big if/elseif covers all possible combinations.
718 	 *
719 	 * here is a list, ordered like the conditions below:
720 	 * - conn_info->x509verify
721 	 *   X509VERIFY_NONE:	   do not verify certificates,
722 	 *			   only log its subject and fingerprint
723 	 *   X509VERIFY_IFPRESENT: if we got her, then a cert is present,
724 	 *			   so check it normally
725 	 *   X509VERIFY_ALWAYS:	   normal certificate check
726 	 * - cur_depth:
727 	 *   > 0:  peer provided CA cert. remember if its valid,
728 	 *	   but always accept, because most checks work on depth 0
729 	 *   == 0: the peer's own cert. check this for final decision
730 	 * - preverify_ok:
731 	 *   true:  valid certificate chain from a trust anchor to this cert
732 	 *   false: no valid and trusted certificate chain
733 	 * - conn_info->incoming:
734 	 *   true:  we are the server, means we authenticate against all
735 	 *	    allowed attributes in tls_opt
736 	 *   false: otherwise we are client and conn_info has all attributes
737 	 *	    to check
738 	 * - conn_info->fingerprint (only if !conn_info->incoming)
739 	 *   NULL:  no fingerprint configured, only check certificate chain
740 	 *   !NULL: a peer cert with this fingerprint is trusted
741 	 *
742 	 */
743 	/* shortcut */
744 	if (cur_depth != 0) {
745 		FREEPTR(cur_fingerprint);
746 		FREEPTR(cur_subjectline);
747 		return 1;
748 	}
749 
750 	if (conn_info->x509verify == X509VERIFY_NONE)
751 		return accept_cert("disabled verification", conn_info,
752 		    cur_fingerprint, cur_subjectline);
753 
754 	/* implicit: (cur_depth == 0)
755 	 *	  && (conn_info->x509verify != X509VERIFY_NONE) */
756 	if (conn_info->incoming) {
757 		if (preverify_ok)
758 			return accept_cert("valid certificate chain",
759 			    conn_info, cur_fingerprint, cur_subjectline);
760 
761 		/* else: now check allowed client fingerprints/certs */
762 		SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
763 			if (match_fingerprint(cur_cert, cred->data)) {
764 				return accept_cert("matching fingerprint",
765 				    conn_info, cur_fingerprint,
766 				    cur_subjectline);
767 			}
768 		}
769 		SLIST_FOREACH_SAFE(cred, &tls_opt.cert_head,
770 			entries, tmp_cred) {
771 			if (match_certfile(cur_cert, cred->data))
772 				return accept_cert("matching certfile",
773 				    conn_info, cur_fingerprint,
774 				    cur_subjectline);
775 		}
776 		return deny_cert(conn_info, cur_fingerprint, cur_subjectline);
777 	}
778 
779 	/* implicit: (cur_depth == 0)
780 	 *	  && (conn_info->x509verify != X509VERIFY_NONE)
781 	 *	  && !conn_info->incoming */
782 	if (!conn_info->incoming && preverify_ok) {
783 		/* certificate chain OK. check subject/hostname */
784 		if (match_hostnames(cur_cert, conn_info->hostname,
785 		    conn_info->subject))
786 			return accept_cert("matching hostname/subject",
787 			    conn_info, cur_fingerprint, cur_subjectline);
788 		else
789 			return deny_cert(conn_info, cur_fingerprint,
790 			    cur_subjectline);
791 	} else if (!conn_info->incoming && !preverify_ok) {
792 		/* chain not OK. check fingerprint/subject/hostname */
793 		if (match_fingerprint(cur_cert, conn_info->fingerprint))
794 			return accept_cert("matching fingerprint", conn_info,
795 			    cur_fingerprint, cur_subjectline);
796 		else if (match_certfile(cur_cert, conn_info->certfile))
797 			return accept_cert("matching certfile", conn_info,
798 			    cur_fingerprint, cur_subjectline);
799 		else
800 			return deny_cert(conn_info, cur_fingerprint,
801 			    cur_subjectline);
802 	}
803 
804 	FREEPTR(cur_fingerprint);
805 	FREEPTR(cur_subjectline);
806 	return 0;
807 }
808 
809 /*
810  * Create TCP sockets for incoming TLS connections.
811  * To be used like socksetup(), hostname and port are optional,
812  * returns bound stream sockets.
813  */
814 struct socketEvent *
815 socksetup_tls(const int af, const char *bindhostname, const char *port)
816 {
817 	struct addrinfo hints, *res, *r;
818 	int error, maxs;
819 	const int on = 1;
820 	struct socketEvent *s, *socks;
821 
822 	if(!tls_opt.server
823 	|| !tls_opt.global_TLS_CTX)
824 		return NULL;
825 
826 	memset(&hints, 0, sizeof(hints));
827 	hints.ai_flags = AI_PASSIVE;
828 	hints.ai_family = af;
829 	hints.ai_socktype = SOCK_STREAM;
830 
831 	error = getaddrinfo(bindhostname, (port ? port : "syslog-tls"),
832 	    &hints, &res);
833 	if (error) {
834 		logerror("%s", gai_strerror(error));
835 		errno = 0;
836 		die(0, 0, NULL);
837 	}
838 
839 	/* Count max number of sockets we may open */
840 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
841 		continue;
842 	socks = malloc((maxs+1) * sizeof(*socks));
843 	if (!socks) {
844 		logerror("Unable to allocate memory for sockets");
845 		die(0, 0, NULL);
846 	}
847 
848 	socks->fd = 0;	 /* num of sockets counter at start of array */
849 	s = socks + 1;
850 	for (r = res; r; r = r->ai_next) {
851 		if ((s->fd = socket(r->ai_family, r->ai_socktype,
852 			r->ai_protocol)) == -1) {
853 			logerror("socket() failed: %s", strerror(errno));
854 			continue;
855 		}
856 		s->af = r->ai_family;
857 #if defined(__minix) && defined(INET6)
858 		if (r->ai_family == AF_INET6
859 		 && setsockopt(s->fd, IPPROTO_IPV6, IPV6_V6ONLY,
860 			&on, sizeof(on)) == -1) {
861 			logerror("setsockopt(IPV6_V6ONLY) failed: %s",
862 			    strerror(errno));
863 			close(s->fd);
864 			continue;
865 		}
866 #endif /* defined(__minix) && defined(INET6) */
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.
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 
1464 	BLOCK_SIGNALS(omask, newmask);
1465 	DPRINTF((D_TLS|D_EVENT|D_CALL), "dispatch_eof_tls(%d, %d, %p)\n",
1466 	    fd, event, arg);
1467 	assert(conn_info->state == ST_TLS_EST);
1468 	ST_CHANGE(conn_info->state, ST_EOF);
1469 	DEL_EVENT(conn_info->event);
1470 
1471 	free_tls_sslptr(conn_info);
1472 
1473 	/* this overwrites the EV_READ event */
1474 	tv.tv_sec = conn_info->reconnect;
1475 	tv.tv_usec = 0;
1476 	schedule_event(&conn_info->event, &tv, tls_reconnect, conn_info);
1477 	TLS_RECONNECT_BACKOFF(conn_info->reconnect);
1478 	RESTORE_SIGNALS(omask);
1479 }
1480 
1481 /*
1482  * Dispatch routine to read from TCP/TLS sockets.
1483  * NB: This gets called when the TCP socket has data available, thus
1484  *     we can call SSL_read() on it. But that does not mean the SSL buffer
1485  *     holds a complete record and SSL_read() lets us read any data now.
1486  */
1487 /*ARGSUSED*/
1488 void
1489 dispatch_tls_read(int fd_lib, short event, void *arg)
1490 {
1491 	struct TLS_Incoming_Conn *c = (struct TLS_Incoming_Conn *) arg;
1492 	int fd = c->socket;
1493 	int error;
1494 	int rc;
1495 	sigset_t newmask, omask;
1496 	bool retrying;
1497 
1498 	BLOCK_SIGNALS(omask, newmask);
1499 	DPRINTF((D_TLS|D_EVENT|D_CALL), "active TLS socket %d\n", fd);
1500 	DPRINTF(D_TLS, "calling SSL_read(%p, %p, %zu)\n", c->tls_conn->sslptr,
1501 		&(c->inbuf[c->read_pos]), c->inbuflen - c->read_pos);
1502 	retrying = (c->tls_conn->state == ST_READING);
1503 	ST_CHANGE(c->tls_conn->state, ST_READING);
1504 	rc = SSL_read(c->tls_conn->sslptr, &(c->inbuf[c->read_pos]),
1505 		c->inbuflen - c->read_pos);
1506 	if (rc <= 0) {
1507 		error = tls_examine_error("SSL_read()", c->tls_conn->sslptr,
1508 		    c->tls_conn, rc);
1509 		switch (error) {
1510 		case TLS_RETRY_READ:
1511 			/* normal event loop will call us again */
1512 			break;
1513 		case TLS_RETRY_WRITE:
1514 			if (!retrying)
1515 				event_del(c->tls_conn->event);
1516 			event_set(c->tls_conn->retryevent, fd,
1517 				EV_WRITE, dispatch_tls_read, c);
1518 			EVENT_ADD(c->tls_conn->retryevent);
1519 			RESTORE_SIGNALS(omask);
1520 			return;
1521 		case TLS_TEMP_ERROR:
1522 			if (c->tls_conn->errorcount < TLS_MAXERRORCOUNT)
1523 				break;
1524 			/* FALLTHROUGH */
1525 		case TLS_PERM_ERROR:
1526 			/* there might be data in the inbuf, so only
1527 			 * mark for closing after message retrieval */
1528 			c->closenow = true;
1529 			break;
1530 		default:
1531 			break;
1532 		}
1533 	} else {
1534 		DPRINTF(D_TLS, "SSL_read() returned %d\n", rc);
1535 		c->errorcount = 0;
1536 		c->read_pos += rc;
1537 	}
1538 	if (retrying)
1539 		EVENT_ADD(c->tls_conn->event);
1540 	tls_split_messages(c);
1541 	if (c->closenow) {
1542 		free_tls_conn(c->tls_conn);
1543 		FREEPTR(c->inbuf);
1544 		SLIST_REMOVE(&TLS_Incoming_Head, c, TLS_Incoming_Conn, entries);
1545 		free(c);
1546 	} else
1547 		ST_CHANGE(c->tls_conn->state, ST_TLS_EST);
1548 	RESTORE_SIGNALS(omask);
1549 }
1550 
1551 /* moved message splitting out of dispatching function.
1552  * now we can call it recursively.
1553  *
1554  * TODO: the code for oversized messages still needs testing,
1555  * especially for the skipping case.
1556  */
1557 void
1558 tls_split_messages(struct TLS_Incoming_Conn *c)
1559 {
1560 /* define only to make it better readable */
1561 #define MSG_END_OFFSET (c->cur_msg_start + c->cur_msg_len)
1562 	size_t offset = 0;
1563 	size_t msglen = 0;
1564 	char *newbuf;
1565 	char buf_char;
1566 
1567 	DPRINTF((D_TLS|D_CALL|D_DATA), "tls_split_messages() -- "
1568 		"incoming status is msg_start %zu, msg_len %zu, pos %zu\n",
1569 		c->cur_msg_start, c->cur_msg_len, c->read_pos);
1570 
1571 	if (!c->read_pos)
1572 		return;
1573 
1574 	if (c->dontsave && c->read_pos < MSG_END_OFFSET) {
1575 		c->cur_msg_len -= c->read_pos;
1576 		c->read_pos = 0;
1577 	} else if (c->dontsave && c->read_pos == MSG_END_OFFSET) {
1578 		c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
1579 		c->dontsave = false;
1580 	} else if (c->dontsave && c->read_pos > MSG_END_OFFSET) {
1581 		/* move remaining input to start of buffer */
1582 		DPRINTF(D_DATA, "move inbuf of length %zu by %zu chars\n",
1583 		    c->read_pos - (MSG_END_OFFSET),
1584 		    MSG_END_OFFSET);
1585 		memmove(&c->inbuf[0],
1586 		    &c->inbuf[MSG_END_OFFSET],
1587 		    c->read_pos - (MSG_END_OFFSET));
1588 		c->read_pos -= (MSG_END_OFFSET);
1589 		c->cur_msg_start = c->cur_msg_len = 0;
1590 		c->dontsave = false;
1591 	}
1592 	if (c->read_pos < MSG_END_OFFSET) {
1593 		return;
1594 	}
1595 
1596 	/* read length prefix, always at start of buffer */
1597 	while (isdigit((unsigned char)c->inbuf[offset])
1598 	    && offset < c->read_pos) {
1599 		msglen *= 10;
1600 		msglen += c->inbuf[offset] - '0';
1601 		offset++;
1602 	}
1603 	if (offset == c->read_pos) {
1604 		/* next invocation will have more data */
1605 		return;
1606 	}
1607 	if (c->inbuf[offset] == ' ') {
1608 		c->cur_msg_len = msglen;
1609 		c->cur_msg_start = offset + 1;
1610 		if (MSG_END_OFFSET+1 > c->inbuflen) {  /* +1 for the '\0' */
1611 			newbuf = realloc(c->inbuf, MSG_END_OFFSET+1);
1612 			if (newbuf) {
1613 				DPRINTF(D_DATA, "Reallocated inbuf\n");
1614 				c->inbuflen = MSG_END_OFFSET+1;
1615 				c->inbuf = newbuf;
1616 			} else {
1617 				logerror("Couldn't reallocate buffer, "
1618 				    "will skip this message");
1619 				c->dontsave = true;
1620 				c->cur_msg_len -= c->read_pos;
1621 				c->cur_msg_start = 0;
1622 				c->read_pos = 0;
1623 			}
1624 		}
1625 	} else {
1626 		/* found non-digit in prefix */
1627 		/* Question: would it be useful to skip this message and
1628 		 * try to find next message by looking for its beginning?
1629 		 * IMHO not.
1630 		 */
1631 		logerror("Unable to handle TLS length prefix. "
1632 		    "Protocol error? Closing connection now.");
1633 		/* only set flag -- caller has to close then */
1634 		c->closenow = true;
1635 		return;
1636 	}
1637 	/* read one syslog message */
1638 	if (c->read_pos >= MSG_END_OFFSET) {
1639 		/* process complete msg */
1640 		assert(MSG_END_OFFSET+1 <= c->inbuflen);
1641 		/* message in c->inbuf is not NULL-terminated,
1642 		 * so this avoids a complete copy */
1643 		buf_char = c->inbuf[MSG_END_OFFSET];
1644 		c->inbuf[MSG_END_OFFSET] = '\0';
1645 		printline(c->tls_conn->hostname, &c->inbuf[c->cur_msg_start],
1646 		    RemoteAddDate ? ADDDATE : 0);
1647 		c->inbuf[MSG_END_OFFSET] = buf_char;
1648 
1649 		if (MSG_END_OFFSET == c->read_pos) {
1650 			/* no unprocessed data in buffer --> reset to empty */
1651 			c->cur_msg_start = c->cur_msg_len = c->read_pos = 0;
1652 		} else {
1653 			/* move remaining input to start of buffer */
1654 			DPRINTF(D_DATA, "move inbuf of length %zu by %zu "
1655 			    "chars\n", c->read_pos - (MSG_END_OFFSET),
1656 			    MSG_END_OFFSET);
1657 			memmove(&c->inbuf[0], &c->inbuf[MSG_END_OFFSET],
1658 			    c->read_pos - (MSG_END_OFFSET));
1659 			c->read_pos -= (MSG_END_OFFSET);
1660 			c->cur_msg_start = c->cur_msg_len = 0;
1661 		}
1662 	}
1663 
1664 	/* shrink inbuf if too large */
1665 	if ((c->inbuflen > TLS_PERSIST_LINELENGTH)
1666 	 && (c->read_pos < TLS_LARGE_LINELENGTH)) {
1667 		newbuf = realloc(c->inbuf, TLS_LARGE_LINELENGTH);
1668 		if (newbuf) {
1669 			DPRINTF(D_DATA, "Shrink inbuf\n");
1670 			c->inbuflen = TLS_LARGE_LINELENGTH;
1671 			c->inbuf = newbuf;
1672 		} else {
1673 			logerror("Couldn't shrink inbuf");
1674 			/* no change necessary */
1675 		}
1676 	}
1677 	DPRINTF(D_DATA, "return with status: msg_start %zu, msg_len %zu, "
1678 	    "pos %zu\n", c->cur_msg_start, c->cur_msg_len, c->read_pos);
1679 
1680 	/* try to read another message */
1681 	if (c->read_pos > 10)
1682 		tls_split_messages(c);
1683 	return;
1684 }
1685 
1686 /*
1687  * wrapper for dispatch_tls_send()
1688  *
1689  * send one line with tls
1690  * f has to be of typ TLS
1691  *
1692  * returns false if message cannot be sent right now,
1693  *	caller is responsible to enqueue it
1694  * returns true if message passed to dispatch_tls_send()
1695  *	delivery is not garantueed, but likely
1696  */
1697 #define DEBUG_LINELENGTH 40
1698 bool
1699 tls_send(struct filed *f, char *line, size_t len, struct buf_queue *qentry)
1700 {
1701 	struct tls_send_msg *smsg;
1702 
1703 	DPRINTF((D_TLS|D_CALL), "tls_send(f=%p, line=\"%.*s%s\", "
1704 	    "len=%zu) to %sconnected dest.\n", f,
1705 	    (int)(len > DEBUG_LINELENGTH ? DEBUG_LINELENGTH : len),
1706 	    line, (len > DEBUG_LINELENGTH ? "..." : ""),
1707 	    len, f->f_un.f_tls.tls_conn->sslptr ? "" : "un");
1708 
1709 	if(f->f_un.f_tls.tls_conn->state == ST_TLS_EST) {
1710 		/* send now */
1711 		if (!(smsg = calloc(1, sizeof(*smsg)))) {
1712 			logerror("Unable to allocate memory, drop message");
1713 			return false;
1714 		}
1715 		smsg->f = f;
1716 		smsg->line = line;
1717 		smsg->linelen = len;
1718 		(void)NEWREF(qentry->msg);
1719 		smsg->qentry = qentry;
1720 		DPRINTF(D_DATA, "now sending line: \"%.*s\"\n",
1721 		    (int)smsg->linelen, smsg->line);
1722 		dispatch_tls_send(0, 0, smsg);
1723 		return true;
1724 	} else {
1725 		/* other socket operation active, send later  */
1726 		DPRINTF(D_DATA, "connection not ready to send: \"%.*s\"\n",
1727 		    (int)len, line);
1728 		return false;
1729 	}
1730 }
1731 
1732 /*ARGSUSED*/
1733 void
1734 dispatch_tls_send(int fd, short event, void *arg)
1735 {
1736 	struct tls_send_msg *smsg = (struct tls_send_msg *) arg;
1737 	struct tls_conn_settings *conn_info = smsg->f->f_un.f_tls.tls_conn;
1738 	struct filed *f = smsg->f;
1739 	int rc, error;
1740 	sigset_t newmask, omask;
1741 	bool retrying;
1742 	struct timeval tv;
1743 
1744 	BLOCK_SIGNALS(omask, newmask);
1745 	DPRINTF((D_TLS|D_CALL), "dispatch_tls_send(f=%p, buffer=%p, "
1746 	    "line@%p, len=%zu, offset=%zu) to %sconnected dest.\n",
1747 	    smsg->f, smsg->qentry->msg, smsg->line,
1748 	    smsg->linelen, smsg->offset,
1749 		conn_info->sslptr ? "" : "un");
1750 	assert(conn_info->state == ST_TLS_EST
1751 	    || conn_info->state == ST_WRITING);
1752 
1753 	retrying = (conn_info->state == ST_WRITING);
1754 	ST_CHANGE(conn_info->state, ST_WRITING);
1755 	rc = SSL_write(conn_info->sslptr,
1756 	    (smsg->line + smsg->offset),
1757 	    (smsg->linelen - smsg->offset));
1758 	if (0 >= rc) {
1759 		error = tls_examine_error("SSL_write()",
1760 		    conn_info->sslptr,
1761 		    conn_info, rc);
1762 		switch (error) {
1763 		case TLS_RETRY_READ:
1764 			/* collides with eof event */
1765 			if (!retrying)
1766 				event_del(conn_info->event);
1767 			event_set(conn_info->retryevent, fd, EV_READ,
1768 				dispatch_tls_send, smsg);
1769 			RETRYEVENT_ADD(conn_info->retryevent);
1770 			break;
1771 		case TLS_RETRY_WRITE:
1772 			event_set(conn_info->retryevent, fd, EV_WRITE,
1773 			    dispatch_tls_send, smsg);
1774 			RETRYEVENT_ADD(conn_info->retryevent);
1775 			break;
1776 		case TLS_PERM_ERROR:
1777 			/* no need to check active events */
1778 			free_tls_send_msg(smsg);
1779 			free_tls_sslptr(conn_info);
1780 			tv.tv_sec = conn_info->reconnect;
1781 			tv.tv_usec = 0;
1782 			schedule_event(&conn_info->event, &tv,
1783 			    tls_reconnect, conn_info);
1784 			TLS_RECONNECT_BACKOFF(conn_info->reconnect);
1785 			break;
1786 		default:
1787 			break;
1788 		}
1789 		RESTORE_SIGNALS(omask);
1790 		return;
1791 	} else if ((size_t)rc < smsg->linelen) {
1792 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() wrote %d out of %zu "
1793 		    "bytes\n", rc, (smsg->linelen - smsg->offset));
1794 		smsg->offset += rc;
1795 		/* try again */
1796 		if (retrying)
1797 			EVENT_ADD(conn_info->event);
1798 		dispatch_tls_send(0, 0, smsg);
1799 		return;
1800 	} else if ((size_t)rc == (smsg->linelen - smsg->offset)) {
1801 		DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() complete\n");
1802 		ST_CHANGE(conn_info->state, ST_TLS_EST);
1803 		free_tls_send_msg(smsg);
1804 		send_queue(0, 0, f);
1805 
1806 	} else {
1807 		/* should not be reached */
1808 		/*LINTED constcond */
1809 		assert(0);
1810 		DPRINTF((D_TLS|D_DATA), "unreachable code after SSL_write()\n");
1811 		ST_CHANGE(conn_info->state, ST_TLS_EST);
1812 		free_tls_send_msg(smsg);
1813 		send_queue(0, 0, f);
1814 	}
1815 	if (retrying && conn_info->event->ev_events)
1816 		EVENT_ADD(conn_info->event);
1817 	RESTORE_SIGNALS(omask);
1818 }
1819 
1820 /*
1821  * Close a SSL connection and its queue and its tls_conn.
1822  */
1823 void
1824 free_tls_conn(struct tls_conn_settings *conn_info)
1825 {
1826 	DPRINTF(D_MEM, "free_tls_conn(conn_info@%p) with sslptr@%p\n",
1827 		conn_info, conn_info->sslptr);
1828 
1829 	if (conn_info->sslptr) {
1830 		conn_info->shutdown = true;
1831 		free_tls_sslptr(conn_info);
1832 	}
1833 	assert(conn_info->state == ST_NONE);
1834 
1835 	FREEPTR(conn_info->port);
1836 	FREEPTR(conn_info->subject);
1837 	FREEPTR(conn_info->hostname);
1838 	FREEPTR(conn_info->certfile);
1839 	FREEPTR(conn_info->fingerprint);
1840 	DEL_EVENT(conn_info->event);
1841 	DEL_EVENT(conn_info->retryevent);
1842 	FREEPTR(conn_info->event);
1843 	FREEPTR(conn_info->retryevent);
1844 	FREEPTR(conn_info);
1845 	DPRINTF(D_MEM2, "free_tls_conn(conn_info@%p) returns\n", conn_info);
1846 }
1847 
1848 /*
1849  * Dispatch routine for non-blocking TLS shutdown
1850  */
1851 /*ARGSUSED*/
1852 void
1853 dispatch_SSL_shutdown(int fd, short event, void *arg)
1854 {
1855 	struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg;
1856 	int rc, error;
1857 	sigset_t newmask, omask;
1858 	bool retrying;
1859 
1860 	BLOCK_SIGNALS(omask, newmask);
1861 	DPRINTF((D_TLS|D_CALL),
1862 	    "dispatch_SSL_shutdown(conn_info@%p, fd %d)\n", conn_info, fd);
1863 	retrying = ((conn_info->state == ST_CLOSING0)
1864 	     || (conn_info->state == ST_CLOSING1)
1865 	     || (conn_info->state == ST_CLOSING2));
1866 	if (!retrying)
1867 		ST_CHANGE(conn_info->state, ST_CLOSING0);
1868 
1869 	rc = SSL_shutdown(conn_info->sslptr);
1870 	if (rc == 1) {	/* shutdown complete */
1871 		DPRINTF((D_TLS|D_NET), "Closed TLS connection to %s\n",
1872 		    conn_info->hostname);
1873 		ST_CHANGE(conn_info->state, ST_TCP_EST);  /* check this */
1874 		conn_info->accepted = false;
1875 		/* closing TCP comes below */
1876 	} else if (rc == 0) { /* unidirectional, now call a 2nd time */
1877 		/* problem: when connecting as a client to rsyslogd this
1878 		 * loops and I keep getting rc == 0
1879 		 * maybe I hit this bug?
1880 		 * http://www.mail-archive.com/openssl-dev@openssl.org/msg24105.html
1881 		 *
1882 		 * anyway, now I use three closing states to make sure I abort
1883 		 * after two rc = 0.
1884 		 */
1885 		if (conn_info->state == ST_CLOSING0) {
1886 			ST_CHANGE(conn_info->state, ST_CLOSING1);
1887 			dispatch_SSL_shutdown(fd, 0, conn_info);
1888 		} else if (conn_info->state == ST_CLOSING1) {
1889 			ST_CHANGE(conn_info->state, ST_CLOSING2);
1890 			dispatch_SSL_shutdown(fd, 0, conn_info);
1891 		} else if (conn_info->state == ST_CLOSING2) {
1892 			/* abort shutdown, jump to close TCP below */
1893 		} else
1894 			DPRINTF(D_TLS, "Unexpected connection state %d\n",
1895 				conn_info->state);
1896 			/* and abort here too*/
1897 	} else if (rc == -1 && conn_info->shutdown ) {
1898 		(void)tls_examine_error("SSL_shutdown()",
1899 			conn_info->sslptr, NULL, rc);
1900 		DPRINTF((D_TLS|D_NET), "Ignore error in SSL_shutdown()"
1901 			" and force connection shutdown.");
1902 		ST_CHANGE(conn_info->state, ST_TCP_EST);
1903 		conn_info->accepted = false;
1904 	} else if (rc == -1 && !conn_info->shutdown ) {
1905 		error = tls_examine_error("SSL_shutdown()",
1906 			conn_info->sslptr, NULL, rc);
1907 		switch (error) {
1908 		case TLS_RETRY_READ:
1909 			if (!retrying)
1910 				event_del(conn_info->event);
1911 			event_set(conn_info->retryevent, fd, EV_READ,
1912 			    dispatch_SSL_shutdown, conn_info);
1913 			EVENT_ADD(conn_info->retryevent);
1914 			RESTORE_SIGNALS(omask);
1915 			return;
1916 		case TLS_RETRY_WRITE:
1917 			if (!retrying)
1918 				event_del(conn_info->event);
1919 			event_set(conn_info->retryevent, fd, EV_WRITE,
1920 			    dispatch_SSL_shutdown, conn_info);
1921 			EVENT_ADD(conn_info->retryevent);
1922 			RESTORE_SIGNALS(omask);
1923 			return;
1924 		default:
1925 			/* force close() on the TCP connection */
1926 			ST_CHANGE(conn_info->state, ST_TCP_EST);
1927 			conn_info->accepted = false;
1928 			break;
1929 		}
1930 	}
1931 	if ((conn_info->state != ST_TLS_EST)
1932 	    && (conn_info->state != ST_NONE)
1933 	    && (conn_info->state != ST_CLOSING0)
1934 	    && (conn_info->state != ST_CLOSING1)) {
1935 		int sock = SSL_get_fd(conn_info->sslptr);
1936 
1937 		if (shutdown(sock, SHUT_RDWR) == -1)
1938 			logerror("Cannot shutdown socket");
1939 		DEL_EVENT(conn_info->retryevent);
1940 		DEL_EVENT(conn_info->event);
1941 
1942 		if (close(sock) == -1)
1943 			logerror("Cannot close socket");
1944 		DPRINTF((D_TLS|D_NET), "Closed TCP connection to %s\n",
1945 		    conn_info->hostname);
1946 		ST_CHANGE(conn_info->state, ST_NONE);
1947 		FREE_SSL(conn_info->sslptr);
1948 	 }
1949 	RESTORE_SIGNALS(omask);
1950 }
1951 
1952 /*
1953  * Close a SSL object
1954  */
1955 void
1956 free_tls_sslptr(struct tls_conn_settings *conn_info)
1957 {
1958 	int sock;
1959 	DPRINTF(D_MEM, "free_tls_sslptr(conn_info@%p)\n", conn_info);
1960 
1961 	if (!conn_info->sslptr) {
1962 		assert(conn_info->incoming == 1
1963 		    || conn_info->state == ST_NONE);
1964 		return;
1965 	} else {
1966 		sock = SSL_get_fd(conn_info->sslptr);
1967 		dispatch_SSL_shutdown(sock, 0, conn_info);
1968 	}
1969 }
1970 
1971 /* write self-generated certificates */
1972 bool
1973 write_x509files(EVP_PKEY *pkey, X509 *cert,
1974 	const char *keyfilename, const char *certfilename)
1975 {
1976 	FILE *certfile, *keyfile;
1977 
1978 	if (!(umask(0177),(keyfile  = fopen(keyfilename,  "a")))) {
1979 		logerror("Unable to write to file \"%s\"", keyfilename);
1980 		return false;
1981 	}
1982 	if (!(umask(0122),(certfile = fopen(certfilename, "a")))) {
1983 		logerror("Unable to write to file \"%s\"", certfilename);
1984 		(void)fclose(keyfile);
1985 		return false;
1986 	}
1987 	if (!PEM_write_PrivateKey(keyfile, pkey, NULL, NULL, 0, NULL, NULL))
1988 		logerror("Unable to write key to \"%s\"", keyfilename);
1989 	if (!X509_print_fp(certfile, cert)
1990 	    || !PEM_write_X509(certfile, cert))
1991 		logerror("Unable to write certificate to \"%s\"",
1992 		    certfilename);
1993 
1994 	(void)fclose(keyfile);
1995 	(void)fclose(certfile);
1996 	return true;
1997 }
1998 
1999 
2000 /* adds all local IP addresses as subjectAltNames to cert x.
2001  * getifaddrs() should be quite portable among BSDs and Linux
2002  * but if not available the whole function can simply be removed.
2003  */
2004 bool
2005 x509_cert_add_subjectAltName(X509 *cert, X509V3_CTX *ctx)
2006 {
2007 	struct ifaddrs *ifa = NULL, *ifp = NULL;
2008 	char ip[100];
2009 	char subjectAltName[2048];
2010 	int idx = 0;
2011 	socklen_t salen;
2012 	X509_EXTENSION *ext;
2013 #ifdef notdef
2014 	STACK_OF(X509_EXTENSION) *extlist;
2015 	extlist = sk_X509_EXTENSION_new_null();
2016 #endif
2017 
2018 	if (getifaddrs (&ifp) == -1) {
2019 		logerror("Unable to get list of local interfaces");
2020 		return false;
2021 	}
2022 
2023 	idx = snprintf(subjectAltName, sizeof(subjectAltName),
2024 	    "DNS:%s", LocalFQDN);
2025 
2026 	for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
2027 		if(!ifa->ifa_addr)
2028 			continue;
2029 
2030 		/* only IP4 and IP6 addresses, but filter loopbacks */
2031 		if (ifa->ifa_addr->sa_family == AF_INET) {
2032 			struct sockaddr_in *addr =
2033 			    (struct sockaddr_in *)ifa->ifa_addr;
2034 			if (addr->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
2035 				continue;
2036 			salen = sizeof(struct sockaddr_in);
2037 		} else if (ifa->ifa_addr->sa_family == AF_INET6) {
2038 			struct in6_addr *addr6 =
2039 			    &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
2040 			if (IN6_IS_ADDR_LOOPBACK(addr6))
2041 				continue;
2042 			salen = sizeof(struct sockaddr_in6);
2043 		} else
2044 			continue;
2045 
2046 		if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip),
2047 		    NULL, 0, NI_NUMERICHOST)) {
2048 			continue;
2049 		}
2050 
2051 		/* add IP to list */
2052 		idx += snprintf(&subjectAltName[idx],
2053 		    sizeof(subjectAltName)-idx, ", IP:%s", ip);
2054 	}
2055 	freeifaddrs (ifp);
2056 
2057 	ext = X509V3_EXT_conf_nid(NULL, ctx,
2058 	    NID_subject_alt_name, subjectAltName);
2059 	X509_add_ext(cert, ext, -1);
2060 	X509_EXTENSION_free(ext);
2061 
2062 	return true;
2063 }
2064 
2065 /*
2066  * generates a private key and a X.509 certificate
2067  */
2068 bool
2069 mk_x509_cert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days)
2070 {
2071 	X509	       *cert;
2072 	EVP_PKEY       *pk;
2073 	DSA	       *dsa;
2074 	X509_NAME      *name = NULL;
2075 	X509_EXTENSION *ex = NULL;
2076 	X509V3_CTX	ctx;
2077 
2078 	DPRINTF((D_CALL|D_TLS), "mk_x509_cert(%p, %p, %d, %d, %d)\n",
2079 	    x509p, pkeyp, bits, serial, days);
2080 
2081 	if (pkeyp && *pkeyp)
2082 		pk = *pkeyp;
2083 	else if ((pk = EVP_PKEY_new()) == NULL) {
2084 		DPRINTF(D_TLS, "EVP_PKEY_new() failed\n");
2085 		return false;
2086 	}
2087 
2088 	if (x509p && *x509p)
2089 		cert = *x509p;
2090 	else if ((cert = X509_new()) == NULL) {
2091 		DPRINTF(D_TLS, "X509_new() failed\n");
2092 		return false;
2093 	}
2094 
2095 	dsa = DSA_generate_parameters(bits, NULL, 0,
2096 			    NULL, NULL, NULL, NULL);
2097 	if (!DSA_generate_key(dsa)) {
2098 		DPRINTF(D_TLS, "DSA_generate_key() failed\n");
2099 		return false;
2100 	}
2101 	if (!EVP_PKEY_assign_DSA(pk, dsa)) {
2102 		DPRINTF(D_TLS, "EVP_PKEY_assign_DSA() failed\n");
2103 		return false;
2104 	}
2105 
2106 	X509_set_version(cert, 3);
2107 	ASN1_INTEGER_set(X509_get_serialNumber(cert), serial);
2108 	X509_gmtime_adj(X509_get_notBefore(cert), 0);
2109 	X509_gmtime_adj(X509_get_notAfter(cert), (long)60 * 60 * 24 * days);
2110 
2111 	if (!X509_set_pubkey(cert, pk)) {
2112 		DPRINTF(D_TLS, "X509_set_pubkey() failed\n");
2113 		return false;
2114 	}
2115 
2116 	/*
2117 	 * This function creates and adds the entry, working out the correct
2118 	 * string type and performing checks on its length. Normally we'd check
2119 	 * the return value for errors...
2120 	 */
2121 	name = X509_get_subject_name(cert);
2122 	/*
2123 	X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
2124 	    (unsigned char *)"The NetBSD Project", -1, -1, 0);
2125 	X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC,
2126 	    (unsigned char *)"syslogd", -1, -1, 0);
2127 	*/
2128 	X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
2129 	    (unsigned char *) LocalFQDN, -1, -1, 0);
2130 	X509_set_issuer_name(cert, name);
2131 
2132 	/*
2133 	 * Add extension using V3 code: we can set the config file as NULL
2134 	 * because we wont reference any other sections.
2135 	 */
2136 	X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0);
2137 
2138 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_comment,
2139 	    __UNCONST("auto-generated by the NetBSD syslogd"));
2140 	X509_add_ext(cert, ex, -1);
2141 	X509_EXTENSION_free(ex);
2142 
2143 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_ssl_server_name,
2144 	    LocalFQDN);
2145 	X509_add_ext(cert, ex, -1);
2146 	X509_EXTENSION_free(ex);
2147 
2148 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_cert_type,
2149 	    __UNCONST("server, client"));
2150 	X509_add_ext(cert, ex, -1);
2151 	X509_EXTENSION_free(ex);
2152 
2153 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_key_usage,
2154 	    __UNCONST("keyAgreement, keyEncipherment, "
2155 	    "nonRepudiation, digitalSignature"));
2156 	X509_add_ext(cert, ex, -1);
2157 	X509_EXTENSION_free(ex);
2158 
2159 	ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints,
2160 	    __UNCONST("critical,CA:FALSE"));
2161 	X509_add_ext(cert, ex, -1);
2162 	X509_EXTENSION_free(ex);
2163 
2164 	(void)x509_cert_add_subjectAltName(cert, &ctx);
2165 
2166 	if (!X509_sign(cert, pk, EVP_dss1())) {
2167 		DPRINTF(D_TLS, "X509_sign() failed\n");
2168 		return false;
2169 	}
2170 	if (X509_verify(cert, pk) != 1) {
2171 		DPRINTF(D_TLS, "X509_verify() failed\n");
2172 		return false;
2173 	}
2174 
2175 	*x509p = cert;
2176 	*pkeyp = pk;
2177 	return true;
2178 }
2179 
2180 void
2181 free_tls_send_msg(struct tls_send_msg *msg)
2182 {
2183 	if (!msg) {
2184 		DPRINTF((D_DATA), "invalid tls_send_msg_free(NULL)\n");
2185 		return;
2186 	}
2187 	DELREF(msg->qentry->msg);
2188 	(void)message_queue_remove(msg->f, msg->qentry);
2189 	FREEPTR(msg->line);
2190 	FREEPTR(msg);
2191 }
2192 #endif /* !DISABLE_TLS */
2193