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