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