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