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