1 /* $NetBSD: tls.c,v 1.5 2010/05/13 17:52:12 tnozaki Exp $ */ 2 3 /*- 4 * Copyright (c) 2008 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Martin Sch�tte. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. All advertising materials mentioning features or use of this software 19 * must display the following acknowledgement: 20 * This product includes software developed by the NetBSD 21 * Foundation, Inc. and its contributors. 22 * 4. Neither the name of The NetBSD Foundation nor the names of its 23 * contributors may be used to endorse or promote products derived 24 * from this software without specific prior written permission. 25 * 26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 36 * POSSIBILITY OF SUCH DAMAGE. 37 */ 38 /* 39 * tls.c TLS related code for syslogd 40 * 41 * implements the TLS init and handshake callbacks with all required 42 * checks from http://tools.ietf.org/html/draft-ietf-syslog-transport-tls-13 43 * 44 * Martin Sch�tte 45 */ 46 47 #include <sys/cdefs.h> 48 __RCSID("$NetBSD: tls.c,v 1.5 2010/05/13 17:52:12 tnozaki 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() 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 wether 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(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(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 free(f->f_un.f_tls.tls_conn->event); 1143 free(f->f_un.f_tls.tls_conn); 1144 logerror("Couldn't allocate memory for TLS config"); 1145 return false; 1146 } 1147 /* default values */ 1148 f->f_un.f_tls.tls_conn->x509verify = X509VERIFY_ALWAYS; 1149 f->f_un.f_tls.tls_conn->reconnect = TLS_RECONNECT_SEC; 1150 1151 if (!(copy_string(&(f->f_un.f_tls.tls_conn->hostname), p, q))) { 1152 logerror("Unable to read TLS server name" 1153 "in config line %zu", linenum); 1154 free_tls_conn(f->f_un.f_tls.tls_conn); 1155 return false; 1156 } 1157 p = ++q; 1158 1159 if (*p == ':') { 1160 p++; q++; 1161 while (isalnum((unsigned char)*q)) 1162 q++; 1163 if (!(copy_string(&(f->f_un.f_tls.tls_conn->port), p, q))) { 1164 logerror("Unable to read TLS port or service name" 1165 " after ':' in config line %zu", linenum); 1166 free_tls_conn(f->f_un.f_tls.tls_conn); 1167 return false; 1168 } 1169 p = q; 1170 } 1171 /* allow whitespace for readability? */ 1172 while (isblank((unsigned char)*p)) 1173 p++; 1174 if (*p == '(') { 1175 p++; 1176 while (*p != ')') { 1177 if (copy_config_value_quoted("subject=\"", 1178 &(f->f_un.f_tls.tls_conn->subject), &p) 1179 || copy_config_value_quoted("fingerprint=\"", 1180 &(f->f_un.f_tls.tls_conn->fingerprint), &p) 1181 || copy_config_value_quoted("cert=\"", 1182 &(f->f_un.f_tls.tls_conn->certfile), &p)) { 1183 /* nothing */ 1184 } else if (!strcmp(p, "verify=")) { 1185 q = p += sizeof("verify=")-1; 1186 /* "" are optional */ 1187 if (*p == '\"') { p++; q++; } 1188 while (isalpha((unsigned char)*q)) q++; 1189 f->f_un.f_tls.tls_conn->x509verify = 1190 getVerifySetting(p); 1191 if (*q == '\"') q++; /* "" are optional */ 1192 p = q; 1193 } else { 1194 logerror("unknown keyword %s " 1195 "in config line %zu", p, linenum); 1196 } 1197 while (*p == ',' || isblank((unsigned char)*p)) 1198 p++; 1199 if (*p == '\0') { 1200 logerror("unterminated (" 1201 "in config line %zu", linenum); 1202 } 1203 } 1204 } 1205 1206 DPRINTF((D_TLS|D_PARSE), 1207 "got TLS config: host %s, port %s, " 1208 "subject: %s, certfile: %s, fingerprint: %s\n", 1209 f->f_un.f_tls.tls_conn->hostname, 1210 f->f_un.f_tls.tls_conn->port, 1211 f->f_un.f_tls.tls_conn->subject, 1212 f->f_un.f_tls.tls_conn->certfile, 1213 f->f_un.f_tls.tls_conn->fingerprint); 1214 return true; 1215 } 1216 1217 /* 1218 * Dispatch routine (triggered by timer) to reconnect to a lost TLS server 1219 */ 1220 /*ARGSUSED*/ 1221 void 1222 tls_reconnect(int fd, short event, void *arg) 1223 { 1224 struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg; 1225 1226 DPRINTF((D_TLS|D_CALL|D_EVENT), "tls_reconnect(conn_info@%p, " 1227 "server %s)\n", conn_info, conn_info->hostname); 1228 if (conn_info->sslptr) { 1229 conn_info->shutdown = true; 1230 free_tls_sslptr(conn_info); 1231 } 1232 assert(conn_info->state == ST_NONE); 1233 1234 if (!tls_connect(conn_info)) { 1235 if (conn_info->reconnect > TLS_RECONNECT_GIVEUP) { 1236 logerror("Unable to connect to TLS server %s, " 1237 "giving up now", conn_info->hostname); 1238 message_queue_freeall(get_f_by_conninfo(conn_info)); 1239 /* free the message queue; but do not free the 1240 * tls_conn_settings nor change the f_type to F_UNUSED. 1241 * that way one can still trigger a reconnect 1242 * with a SIGUSR1 1243 */ 1244 } else { 1245 struct timeval tv; 1246 logerror("Unable to connect to TLS server %s, " 1247 "try again in %d sec", conn_info->hostname, 1248 conn_info->reconnect); 1249 tv.tv_sec = conn_info->reconnect; 1250 tv.tv_usec = 0; 1251 schedule_event(&conn_info->event, &tv, 1252 tls_reconnect, conn_info); 1253 TLS_RECONNECT_BACKOFF(conn_info->reconnect); 1254 } 1255 } else { 1256 assert(conn_info->state == ST_TLS_EST 1257 || conn_info->state == ST_CONNECTING 1258 || conn_info->state == ST_NONE); 1259 } 1260 } 1261 /* 1262 * Dispatch routine for accepting TLS connections. 1263 * Has to be idempotent in case of TLS_RETRY (~ EAGAIN), 1264 * so we can continue a slow handshake. 1265 */ 1266 /*ARGSUSED*/ 1267 void 1268 dispatch_tls_accept(int fd, short event, void *arg) 1269 { 1270 struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg; 1271 int rc, error; 1272 struct TLS_Incoming_Conn *tls_in; 1273 sigset_t newmask, omask; 1274 1275 DPRINTF((D_TLS|D_CALL), 1276 "dispatch_tls_accept(conn_info@%p, fd %d)\n", conn_info, fd); 1277 assert(conn_info->event); 1278 assert(conn_info->retryevent); 1279 BLOCK_SIGNALS(omask, newmask); 1280 1281 ST_CHANGE(conn_info->state, ST_ACCEPTING); 1282 rc = SSL_accept(conn_info->sslptr); 1283 if (0 >= rc) { 1284 error = tls_examine_error("SSL_accept()", 1285 conn_info->sslptr, NULL, rc); 1286 switch (error) { 1287 case TLS_RETRY_READ: 1288 event_set(conn_info->retryevent, fd, EV_READ, 1289 dispatch_tls_accept, conn_info); 1290 EVENT_ADD(conn_info->retryevent); 1291 break; 1292 case TLS_RETRY_WRITE: 1293 event_set(conn_info->retryevent, fd, EV_WRITE, 1294 dispatch_tls_accept, conn_info); 1295 EVENT_ADD(conn_info->retryevent); 1296 break; 1297 default: /* should not happen */ 1298 free_tls_conn(conn_info); 1299 break; 1300 } 1301 RESTORE_SIGNALS(omask); 1302 return; 1303 } 1304 /* else */ 1305 CALLOC(tls_in, sizeof(*tls_in)); 1306 CALLOC(tls_in->inbuf, (size_t)TLS_MIN_LINELENGTH); 1307 1308 tls_in->tls_conn = conn_info; 1309 tls_in->socket = SSL_get_fd(conn_info->sslptr); 1310 tls_in->inbuf[0] = '\0'; 1311 tls_in->inbuflen = TLS_MIN_LINELENGTH; 1312 SLIST_INSERT_HEAD(&TLS_Incoming_Head, tls_in, entries); 1313 1314 event_set(conn_info->event, tls_in->socket, EV_READ | EV_PERSIST, 1315 dispatch_tls_read, tls_in); 1316 EVENT_ADD(conn_info->event); 1317 ST_CHANGE(conn_info->state, ST_TLS_EST); 1318 1319 loginfo("established TLS connection from %s with certificate " 1320 "%s (%s)", conn_info->hostname, conn_info->subject, 1321 conn_info->fingerprint); 1322 RESTORE_SIGNALS(omask); 1323 /* 1324 * We could also listen to EOF kevents -- but I do not think 1325 * that would be useful, because we still had to read() the buffer 1326 * before closing the socket. 1327 */ 1328 } 1329 1330 /* 1331 * Dispatch routine for accepting TCP connections and preparing 1332 * the tls_conn_settings object for a following SSL_accept(). 1333 */ 1334 /*ARGSUSED*/ 1335 void 1336 dispatch_socket_accept(int fd, short event, void *ev) 1337 { 1338 #ifdef LIBWRAP 1339 struct request_info req; 1340 #endif 1341 struct sockaddr_storage frominet; 1342 socklen_t addrlen; 1343 int newsock, rc; 1344 sigset_t newmask, omask; 1345 SSL *ssl; 1346 struct tls_conn_settings *conn_info; 1347 char hbuf[NI_MAXHOST]; 1348 char *peername; 1349 1350 DPRINTF((D_TLS|D_NET), "incoming TCP connection\n"); 1351 if (!tls_opt.global_TLS_CTX) { 1352 logerror("global_TLS_CTX not initialized!"); 1353 return; 1354 } 1355 1356 BLOCK_SIGNALS(omask, newmask); 1357 addrlen = sizeof(frominet); 1358 if ((newsock = accept(fd, (struct sockaddr *)&frominet, 1359 &addrlen)) == -1) { 1360 logerror("Error in accept(): %s", strerror(errno)); 1361 RESTORE_SIGNALS(omask); 1362 return; 1363 } 1364 /* TODO: do we want an IP or a hostname? maybe even both? */ 1365 if ((rc = getnameinfo((struct sockaddr *)&frominet, addrlen, 1366 hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST|NI_NUMERICSERV)) != 0) { 1367 DPRINTF(D_NET, "could not get peername: %s", gai_strerror(rc)); 1368 peername = NULL; 1369 } 1370 else { 1371 MALLOC(peername, strlen(hbuf)+1); 1372 (void)strlcpy(peername, hbuf, strlen(hbuf)+1); 1373 } 1374 1375 #ifdef LIBWRAP 1376 request_init(&req, RQ_DAEMON, appname, RQ_FILE, newsock, NULL); 1377 fromhost(&req); 1378 if (!hosts_access(&req)) { 1379 logerror("access from %s denied by hosts_access", peername); 1380 shutdown(newsock, SHUT_RDWR); 1381 close(newsock); 1382 RESTORE_SIGNALS(omask); 1383 return; 1384 } 1385 #endif 1386 1387 if ((fcntl(newsock, F_SETFL, O_NONBLOCK)) == -1) { 1388 DPRINTF(D_NET, "Unable to fcntl(sock, O_NONBLOCK): %s\n", 1389 strerror(errno)); 1390 } 1391 1392 if (!(ssl = SSL_new(tls_opt.global_TLS_CTX))) { 1393 DPRINTF(D_TLS, "Unable to establish TLS: %s\n", 1394 ERR_error_string(ERR_get_error(), NULL)); 1395 close(newsock); 1396 RESTORE_SIGNALS(omask); 1397 return; 1398 } 1399 if (!SSL_set_fd(ssl, newsock)) { 1400 DPRINTF(D_TLS, "Unable to connect TLS to socket %d: %s\n", 1401 newsock, ERR_error_string(ERR_get_error(), NULL)); 1402 SSL_free(ssl); 1403 close(newsock); 1404 RESTORE_SIGNALS(omask); 1405 return; 1406 } 1407 1408 if (!(conn_info = calloc(1, sizeof(*conn_info))) 1409 || !(conn_info->event = allocev()) 1410 || !(conn_info->retryevent = allocev())) { 1411 free(conn_info->event); 1412 free(conn_info); 1413 SSL_free(ssl); 1414 close(newsock); 1415 logerror("Unable to allocate memory to accept incoming " 1416 "TLS connection from %s", peername); 1417 RESTORE_SIGNALS(omask); 1418 return; 1419 } 1420 ST_CHANGE(conn_info->state, ST_NONE); 1421 /* store connection details inside ssl object, used to verify 1422 * cert and immediately match against hostname */ 1423 conn_info->hostname = peername; 1424 conn_info->sslptr = ssl; 1425 conn_info->x509verify = getVerifySetting(tls_opt.x509verify); 1426 conn_info->incoming = true; 1427 SSL_set_app_data(ssl, conn_info); 1428 SSL_set_accept_state(ssl); 1429 1430 assert(conn_info->event); 1431 assert(conn_info->retryevent); 1432 1433 ST_CHANGE(conn_info->state, ST_TCP_EST); 1434 DPRINTF(D_TLS, "socket connection from %s accept()ed with fd %d, " 1435 "calling SSL_accept()...\n", peername, newsock); 1436 dispatch_tls_accept(newsock, 0, conn_info); 1437 RESTORE_SIGNALS(omask); 1438 } 1439 1440 /* 1441 * Dispatch routine to read from outgoing TCP/TLS sockets. 1442 * 1443 * I do not know if libevent can tell us the difference 1444 * between available data and an EOF. But it does not matter 1445 * because there should not be any incoming data. 1446 * So we close the connection either because the peer closed its 1447 * side or because the peer broke the protocol by sending us stuff ;-) 1448 */ 1449 void 1450 dispatch_tls_eof(int fd, short event, void *arg) 1451 { 1452 struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg; 1453 sigset_t newmask, omask; 1454 struct timeval tv; 1455 1456 BLOCK_SIGNALS(omask, newmask); 1457 DPRINTF((D_TLS|D_EVENT|D_CALL), "dispatch_eof_tls(%d, %d, %p)\n", 1458 fd, event, arg); 1459 assert(conn_info->state == ST_TLS_EST); 1460 ST_CHANGE(conn_info->state, ST_EOF); 1461 DEL_EVENT(conn_info->event); 1462 1463 free_tls_sslptr(conn_info); 1464 1465 /* this overwrites the EV_READ event */ 1466 tv.tv_sec = conn_info->reconnect; 1467 tv.tv_usec = 0; 1468 schedule_event(&conn_info->event, &tv, tls_reconnect, conn_info); 1469 TLS_RECONNECT_BACKOFF(conn_info->reconnect); 1470 RESTORE_SIGNALS(omask); 1471 } 1472 1473 /* 1474 * Dispatch routine to read from TCP/TLS sockets. 1475 * NB: This gets called when the TCP socket has data available, thus 1476 * we can call SSL_read() on it. But that does not mean the SSL buffer 1477 * holds a complete record and SSL_read() lets us read any data now. 1478 */ 1479 /*ARGSUSED*/ 1480 void 1481 dispatch_tls_read(int fd_lib, short event, void *arg) 1482 { 1483 struct TLS_Incoming_Conn *c = (struct TLS_Incoming_Conn *) arg; 1484 int fd = c->socket; 1485 int error; 1486 int rc; 1487 sigset_t newmask, omask; 1488 bool retrying; 1489 1490 BLOCK_SIGNALS(omask, newmask); 1491 DPRINTF((D_TLS|D_EVENT|D_CALL), "active TLS socket %d\n", fd); 1492 DPRINTF(D_TLS, "calling SSL_read(%p, %p, %zu)\n", c->tls_conn->sslptr, 1493 &(c->inbuf[c->read_pos]), c->inbuflen - c->read_pos); 1494 retrying = (c->tls_conn->state == ST_READING); 1495 ST_CHANGE(c->tls_conn->state, ST_READING); 1496 rc = SSL_read(c->tls_conn->sslptr, &(c->inbuf[c->read_pos]), 1497 c->inbuflen - c->read_pos); 1498 if (rc <= 0) { 1499 error = tls_examine_error("SSL_read()", c->tls_conn->sslptr, 1500 c->tls_conn, rc); 1501 switch (error) { 1502 case TLS_RETRY_READ: 1503 /* normal event loop will call us again */ 1504 break; 1505 case TLS_RETRY_WRITE: 1506 if (!retrying) 1507 event_del(c->tls_conn->event); 1508 event_set(c->tls_conn->retryevent, fd, 1509 EV_WRITE, dispatch_tls_read, c); 1510 EVENT_ADD(c->tls_conn->retryevent); 1511 RESTORE_SIGNALS(omask); 1512 return; 1513 case TLS_TEMP_ERROR: 1514 if (c->tls_conn->errorcount < TLS_MAXERRORCOUNT) 1515 break; 1516 /* FALLTHROUGH */ 1517 case TLS_PERM_ERROR: 1518 /* there might be data in the inbuf, so only 1519 * mark for closing after message retrieval */ 1520 c->closenow = true; 1521 break; 1522 default: 1523 break; 1524 } 1525 } else { 1526 DPRINTF(D_TLS, "SSL_read() returned %d\n", rc); 1527 c->errorcount = 0; 1528 c->read_pos += rc; 1529 } 1530 if (retrying) 1531 EVENT_ADD(c->tls_conn->event); 1532 tls_split_messages(c); 1533 if (c->closenow) { 1534 free_tls_conn(c->tls_conn); 1535 FREEPTR(c->inbuf); 1536 SLIST_REMOVE(&TLS_Incoming_Head, c, TLS_Incoming_Conn, entries); 1537 free(c); 1538 } else 1539 ST_CHANGE(c->tls_conn->state, ST_TLS_EST); 1540 RESTORE_SIGNALS(omask); 1541 } 1542 1543 /* moved message splitting out of dispatching function. 1544 * now we can call it recursively. 1545 * 1546 * TODO: the code for oversized messages still needs testing, 1547 * especially for the skipping case. 1548 */ 1549 void 1550 tls_split_messages(struct TLS_Incoming_Conn *c) 1551 { 1552 /* define only to make it better readable */ 1553 #define MSG_END_OFFSET (c->cur_msg_start + c->cur_msg_len) 1554 size_t offset = 0; 1555 size_t msglen = 0; 1556 char *newbuf; 1557 char buf_char; 1558 1559 DPRINTF((D_TLS|D_CALL|D_DATA), "tls_split_messages() -- " 1560 "incoming status is msg_start %zu, msg_len %zu, pos %zu\n", 1561 c->cur_msg_start, c->cur_msg_len, c->read_pos); 1562 1563 if (!c->read_pos) 1564 return; 1565 1566 if (c->dontsave && c->read_pos < MSG_END_OFFSET) { 1567 c->cur_msg_len -= c->read_pos; 1568 c->read_pos = 0; 1569 } else if (c->dontsave && c->read_pos == MSG_END_OFFSET) { 1570 c->cur_msg_start = c->cur_msg_len = c->read_pos = 0; 1571 c->dontsave = false; 1572 } else if (c->dontsave && c->read_pos > MSG_END_OFFSET) { 1573 /* move remaining input to start of buffer */ 1574 DPRINTF(D_DATA, "move inbuf of length %zu by %zu chars\n", 1575 c->read_pos - (MSG_END_OFFSET), 1576 MSG_END_OFFSET); 1577 memmove(&c->inbuf[0], 1578 &c->inbuf[MSG_END_OFFSET], 1579 c->read_pos - (MSG_END_OFFSET)); 1580 c->read_pos -= (MSG_END_OFFSET); 1581 c->cur_msg_start = c->cur_msg_len = 0; 1582 c->dontsave = false; 1583 } 1584 if (c->read_pos < MSG_END_OFFSET) { 1585 return; 1586 } 1587 1588 /* read length prefix, always at start of buffer */ 1589 while (isdigit((unsigned char)c->inbuf[offset]) 1590 && offset < c->read_pos) { 1591 msglen *= 10; 1592 msglen += c->inbuf[offset] - '0'; 1593 offset++; 1594 } 1595 if (offset == c->read_pos) { 1596 /* next invocation will have more data */ 1597 return; 1598 } 1599 if (c->inbuf[offset] == ' ') { 1600 c->cur_msg_len = msglen; 1601 c->cur_msg_start = offset + 1; 1602 if (MSG_END_OFFSET+1 > c->inbuflen) { /* +1 for the '\0' */ 1603 newbuf = realloc(c->inbuf, MSG_END_OFFSET+1); 1604 if (newbuf) { 1605 DPRINTF(D_DATA, "Reallocated inbuf\n"); 1606 c->inbuflen = MSG_END_OFFSET+1; 1607 c->inbuf = newbuf; 1608 } else { 1609 logerror("Couldn't reallocate buffer, " 1610 "will skip this message"); 1611 c->dontsave = true; 1612 c->cur_msg_len -= c->read_pos; 1613 c->cur_msg_start = 0; 1614 c->read_pos = 0; 1615 } 1616 } 1617 } else { 1618 /* found non-digit in prefix */ 1619 /* Question: would it be useful to skip this message and 1620 * try to find next message by looking for its beginning? 1621 * IMHO not. 1622 */ 1623 logerror("Unable to handle TLS length prefix. " 1624 "Protocol error? Closing connection now."); 1625 /* only set flag -- caller has to close then */ 1626 c->closenow = true; 1627 return; 1628 } 1629 /* read one syslog message */ 1630 if (c->read_pos >= MSG_END_OFFSET) { 1631 /* process complete msg */ 1632 assert(MSG_END_OFFSET+1 <= c->inbuflen); 1633 /* message in c->inbuf is not NULL-terminated, 1634 * so this avoids a complete copy */ 1635 buf_char = c->inbuf[MSG_END_OFFSET]; 1636 c->inbuf[MSG_END_OFFSET] = '\0'; 1637 printline(c->tls_conn->hostname, &c->inbuf[c->cur_msg_start], 1638 RemoteAddDate ? ADDDATE : 0); 1639 c->inbuf[MSG_END_OFFSET] = buf_char; 1640 1641 if (MSG_END_OFFSET == c->read_pos) { 1642 /* no unprocessed data in buffer --> reset to empty */ 1643 c->cur_msg_start = c->cur_msg_len = c->read_pos = 0; 1644 } else { 1645 /* move remaining input to start of buffer */ 1646 DPRINTF(D_DATA, "move inbuf of length %zu by %zu " 1647 "chars\n", c->read_pos - (MSG_END_OFFSET), 1648 MSG_END_OFFSET); 1649 memmove(&c->inbuf[0], &c->inbuf[MSG_END_OFFSET], 1650 c->read_pos - (MSG_END_OFFSET)); 1651 c->read_pos -= (MSG_END_OFFSET); 1652 c->cur_msg_start = c->cur_msg_len = 0; 1653 } 1654 } 1655 1656 /* shrink inbuf if too large */ 1657 if ((c->inbuflen > TLS_PERSIST_LINELENGTH) 1658 && (c->read_pos < TLS_LARGE_LINELENGTH)) { 1659 newbuf = realloc(c->inbuf, TLS_LARGE_LINELENGTH); 1660 if (newbuf) { 1661 DPRINTF(D_DATA, "Shrink inbuf\n"); 1662 c->inbuflen = TLS_LARGE_LINELENGTH; 1663 c->inbuf = newbuf; 1664 } else { 1665 logerror("Couldn't shrink inbuf"); 1666 /* no change necessary */ 1667 } 1668 } 1669 DPRINTF(D_DATA, "return with status: msg_start %zu, msg_len %zu, " 1670 "pos %zu\n", c->cur_msg_start, c->cur_msg_len, c->read_pos); 1671 1672 /* try to read another message */ 1673 if (c->read_pos > 10) 1674 tls_split_messages(c); 1675 return; 1676 } 1677 1678 /* 1679 * wrapper for dispatch_tls_send() 1680 * 1681 * send one line with tls 1682 * f has to be of typ TLS 1683 * 1684 * returns false if message cannot be sent right now, 1685 * caller is responsible to enqueue it 1686 * returns true if message passed to dispatch_tls_send() 1687 * delivery is not garantueed, but likely 1688 */ 1689 #define DEBUG_LINELENGTH 40 1690 bool 1691 tls_send(struct filed *f, char *line, size_t len, struct buf_queue *qentry) 1692 { 1693 struct tls_send_msg *smsg; 1694 1695 DPRINTF((D_TLS|D_CALL), "tls_send(f=%p, line=\"%.*s%s\", " 1696 "len=%zu) to %sconnected dest.\n", f, 1697 (int)(len > DEBUG_LINELENGTH ? DEBUG_LINELENGTH : len), 1698 line, (len > DEBUG_LINELENGTH ? "..." : ""), 1699 len, f->f_un.f_tls.tls_conn->sslptr ? "" : "un"); 1700 1701 if(f->f_un.f_tls.tls_conn->state == ST_TLS_EST) { 1702 /* send now */ 1703 if (!(smsg = calloc(1, sizeof(*smsg)))) { 1704 logerror("Unable to allocate memory, drop message"); 1705 return false; 1706 } 1707 smsg->f = f; 1708 smsg->line = line; 1709 smsg->linelen = len; 1710 (void)NEWREF(qentry->msg); 1711 smsg->qentry = qentry; 1712 DPRINTF(D_DATA, "now sending line: \"%.*s\"\n", 1713 (int)smsg->linelen, smsg->line); 1714 dispatch_tls_send(0, 0, smsg); 1715 return true; 1716 } else { 1717 /* other socket operation active, send later */ 1718 DPRINTF(D_DATA, "connection not ready to send: \"%.*s\"\n", 1719 (int)len, line); 1720 return false; 1721 } 1722 } 1723 1724 /*ARGSUSED*/ 1725 void 1726 dispatch_tls_send(int fd, short event, void *arg) 1727 { 1728 struct tls_send_msg *smsg = (struct tls_send_msg *) arg; 1729 struct tls_conn_settings *conn_info = smsg->f->f_un.f_tls.tls_conn; 1730 struct filed *f = smsg->f; 1731 int rc, error; 1732 sigset_t newmask, omask; 1733 bool retrying; 1734 struct timeval tv; 1735 1736 BLOCK_SIGNALS(omask, newmask); 1737 DPRINTF((D_TLS|D_CALL), "dispatch_tls_send(f=%p, buffer=%p, " 1738 "line@%p, len=%zu, offset=%zu) to %sconnected dest.\n", 1739 smsg->f, smsg->qentry->msg, smsg->line, 1740 smsg->linelen, smsg->offset, 1741 conn_info->sslptr ? "" : "un"); 1742 assert(conn_info->state == ST_TLS_EST 1743 || conn_info->state == ST_WRITING); 1744 1745 retrying = (conn_info->state == ST_WRITING); 1746 ST_CHANGE(conn_info->state, ST_WRITING); 1747 rc = SSL_write(conn_info->sslptr, 1748 (smsg->line + smsg->offset), 1749 (smsg->linelen - smsg->offset)); 1750 if (0 >= rc) { 1751 error = tls_examine_error("SSL_write()", 1752 conn_info->sslptr, 1753 conn_info, rc); 1754 switch (error) { 1755 case TLS_RETRY_READ: 1756 /* collides with eof event */ 1757 if (!retrying) 1758 event_del(conn_info->event); 1759 event_set(conn_info->retryevent, fd, EV_READ, 1760 dispatch_tls_send, smsg); 1761 RETRYEVENT_ADD(conn_info->retryevent); 1762 break; 1763 case TLS_RETRY_WRITE: 1764 event_set(conn_info->retryevent, fd, EV_WRITE, 1765 dispatch_tls_send, smsg); 1766 RETRYEVENT_ADD(conn_info->retryevent); 1767 break; 1768 case TLS_PERM_ERROR: 1769 /* no need to check active events */ 1770 free_tls_send_msg(smsg); 1771 free_tls_sslptr(conn_info); 1772 tv.tv_sec = conn_info->reconnect; 1773 tv.tv_usec = 0; 1774 schedule_event(&conn_info->event, &tv, 1775 tls_reconnect, conn_info); 1776 TLS_RECONNECT_BACKOFF(conn_info->reconnect); 1777 break; 1778 default: 1779 break; 1780 } 1781 RESTORE_SIGNALS(omask); 1782 return; 1783 } else if ((size_t)rc < smsg->linelen) { 1784 DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() wrote %d out of %zu " 1785 "bytes\n", rc, (smsg->linelen - smsg->offset)); 1786 smsg->offset += rc; 1787 /* try again */ 1788 if (retrying) 1789 EVENT_ADD(conn_info->event); 1790 dispatch_tls_send(0, 0, smsg); 1791 return; 1792 } else if ((size_t)rc == (smsg->linelen - smsg->offset)) { 1793 DPRINTF((D_TLS|D_DATA), "TLS: SSL_write() complete\n"); 1794 ST_CHANGE(conn_info->state, ST_TLS_EST); 1795 free_tls_send_msg(smsg); 1796 send_queue(0, 0, f); 1797 1798 } else { 1799 /* should not be reached */ 1800 /*LINTED constcond */ 1801 assert(0); 1802 DPRINTF((D_TLS|D_DATA), "unreachable code after SSL_write()\n"); 1803 ST_CHANGE(conn_info->state, ST_TLS_EST); 1804 free_tls_send_msg(smsg); 1805 send_queue(0, 0, f); 1806 } 1807 if (retrying && conn_info->event->ev_events) 1808 EVENT_ADD(conn_info->event); 1809 RESTORE_SIGNALS(omask); 1810 } 1811 1812 /* 1813 * Close a SSL connection and its queue and its tls_conn. 1814 */ 1815 void 1816 free_tls_conn(struct tls_conn_settings *conn_info) 1817 { 1818 DPRINTF(D_MEM, "free_tls_conn(conn_info@%p) with sslptr@%p\n", 1819 conn_info, conn_info->sslptr); 1820 1821 if (conn_info->sslptr) { 1822 conn_info->shutdown = true; 1823 free_tls_sslptr(conn_info); 1824 } 1825 assert(conn_info->state == ST_NONE); 1826 1827 FREEPTR(conn_info->port); 1828 FREEPTR(conn_info->subject); 1829 FREEPTR(conn_info->hostname); 1830 FREEPTR(conn_info->certfile); 1831 FREEPTR(conn_info->fingerprint); 1832 DEL_EVENT(conn_info->event); 1833 DEL_EVENT(conn_info->retryevent); 1834 FREEPTR(conn_info->event); 1835 FREEPTR(conn_info->retryevent); 1836 FREEPTR(conn_info); 1837 DPRINTF(D_MEM2, "free_tls_conn(conn_info@%p) returns\n", conn_info); 1838 } 1839 1840 /* 1841 * Dispatch routine for non-blocking TLS shutdown 1842 */ 1843 /*ARGSUSED*/ 1844 void 1845 dispatch_SSL_shutdown(int fd, short event, void *arg) 1846 { 1847 struct tls_conn_settings *conn_info = (struct tls_conn_settings *) arg; 1848 int rc, error; 1849 sigset_t newmask, omask; 1850 bool retrying; 1851 1852 BLOCK_SIGNALS(omask, newmask); 1853 DPRINTF((D_TLS|D_CALL), 1854 "dispatch_SSL_shutdown(conn_info@%p, fd %d)\n", conn_info, fd); 1855 retrying = ((conn_info->state == ST_CLOSING0) 1856 || (conn_info->state == ST_CLOSING1) 1857 || (conn_info->state == ST_CLOSING2)); 1858 if (!retrying) 1859 ST_CHANGE(conn_info->state, ST_CLOSING0); 1860 1861 rc = SSL_shutdown(conn_info->sslptr); 1862 if (rc == 1) { /* shutdown complete */ 1863 DPRINTF((D_TLS|D_NET), "Closed TLS connection to %s\n", 1864 conn_info->hostname); 1865 ST_CHANGE(conn_info->state, ST_TCP_EST); /* check this */ 1866 conn_info->accepted = false; 1867 /* closing TCP comes below */ 1868 } else if (rc == 0) { /* unidirectional, now call a 2nd time */ 1869 /* problem: when connecting as a client to rsyslogd this 1870 * loops and I keep getting rc == 0 1871 * maybe I hit this bug? 1872 * http://www.mail-archive.com/openssl-dev@openssl.org/msg24105.html 1873 * 1874 * anyway, now I use three closing states to make sure I abort 1875 * after two rc = 0. 1876 */ 1877 if (conn_info->state == ST_CLOSING0) { 1878 ST_CHANGE(conn_info->state, ST_CLOSING1); 1879 dispatch_SSL_shutdown(fd, 0, conn_info); 1880 } else if (conn_info->state == ST_CLOSING1) { 1881 ST_CHANGE(conn_info->state, ST_CLOSING2); 1882 dispatch_SSL_shutdown(fd, 0, conn_info); 1883 } else if (conn_info->state == ST_CLOSING2) { 1884 /* abort shutdown, jump to close TCP below */ 1885 } else 1886 DPRINTF(D_TLS, "Unexpected connection state %d\n", 1887 conn_info->state); 1888 /* and abort here too*/ 1889 } else if (rc == -1 && conn_info->shutdown ) { 1890 (void)tls_examine_error("SSL_shutdown()", 1891 conn_info->sslptr, NULL, rc); 1892 DPRINTF((D_TLS|D_NET), "Ignore error in SSL_shutdown()" 1893 " and force connection shutdown."); 1894 ST_CHANGE(conn_info->state, ST_TCP_EST); 1895 conn_info->accepted = false; 1896 } else if (rc == -1 && !conn_info->shutdown ) { 1897 error = tls_examine_error("SSL_shutdown()", 1898 conn_info->sslptr, NULL, rc); 1899 switch (error) { 1900 case TLS_RETRY_READ: 1901 if (!retrying) 1902 event_del(conn_info->event); 1903 event_set(conn_info->retryevent, fd, EV_READ, 1904 dispatch_SSL_shutdown, conn_info); 1905 EVENT_ADD(conn_info->retryevent); 1906 RESTORE_SIGNALS(omask); 1907 return; 1908 case TLS_RETRY_WRITE: 1909 if (!retrying) 1910 event_del(conn_info->event); 1911 event_set(conn_info->retryevent, fd, EV_WRITE, 1912 dispatch_SSL_shutdown, conn_info); 1913 EVENT_ADD(conn_info->retryevent); 1914 RESTORE_SIGNALS(omask); 1915 return; 1916 default: 1917 /* force close() on the TCP connection */ 1918 ST_CHANGE(conn_info->state, ST_TCP_EST); 1919 conn_info->accepted = false; 1920 break; 1921 } 1922 } 1923 if ((conn_info->state != ST_TLS_EST) 1924 && (conn_info->state != ST_NONE) 1925 && (conn_info->state != ST_CLOSING0) 1926 && (conn_info->state != ST_CLOSING1)) { 1927 int sock = SSL_get_fd(conn_info->sslptr); 1928 1929 if (shutdown(sock, SHUT_RDWR) == -1) 1930 logerror("Cannot shutdown socket"); 1931 DEL_EVENT(conn_info->retryevent); 1932 DEL_EVENT(conn_info->event); 1933 1934 if (close(sock) == -1) 1935 logerror("Cannot close socket"); 1936 DPRINTF((D_TLS|D_NET), "Closed TCP connection to %s\n", 1937 conn_info->hostname); 1938 ST_CHANGE(conn_info->state, ST_NONE); 1939 FREE_SSL(conn_info->sslptr); 1940 } 1941 RESTORE_SIGNALS(omask); 1942 } 1943 1944 /* 1945 * Close a SSL object 1946 */ 1947 void 1948 free_tls_sslptr(struct tls_conn_settings *conn_info) 1949 { 1950 int sock; 1951 DPRINTF(D_MEM, "free_tls_sslptr(conn_info@%p)\n", conn_info); 1952 1953 if (!conn_info->sslptr) { 1954 assert(conn_info->incoming == 1 1955 || conn_info->state == ST_NONE); 1956 return; 1957 } else { 1958 sock = SSL_get_fd(conn_info->sslptr); 1959 dispatch_SSL_shutdown(sock, 0, conn_info); 1960 } 1961 } 1962 1963 /* write self-generated certificates */ 1964 bool 1965 write_x509files(EVP_PKEY *pkey, X509 *cert, 1966 const char *keyfilename, const char *certfilename) 1967 { 1968 FILE *certfile, *keyfile; 1969 1970 if (!(umask(0177),(keyfile = fopen(keyfilename, "a"))) 1971 || !(umask(0122),(certfile = fopen(certfilename, "a")))) { 1972 logerror("Unable to write to files \"%s\" and \"%s\"", 1973 keyfilename, certfilename); 1974 return false; 1975 } 1976 if (!PEM_write_PrivateKey(keyfile, pkey, NULL, NULL, 0, NULL, NULL)) 1977 logerror("Unable to write key to \"%s\"", keyfilename); 1978 if (!X509_print_fp(certfile, cert) 1979 || !PEM_write_X509(certfile, cert)) 1980 logerror("Unable to write certificate to \"%s\"", 1981 certfilename); 1982 1983 (void)fclose(keyfile); 1984 (void)fclose(certfile); 1985 return true; 1986 } 1987 1988 1989 /* adds all local IP addresses as subjectAltNames to cert x. 1990 * getifaddrs() should be quite portable among BSDs and Linux 1991 * but if not available the whole function can simply be removed. 1992 */ 1993 bool 1994 x509_cert_add_subjectAltName(X509 *cert, X509V3_CTX *ctx) 1995 { 1996 struct ifaddrs *ifa = NULL, *ifp = NULL; 1997 char ip[100]; 1998 char subjectAltName[2048]; 1999 int idx = 0; 2000 socklen_t salen; 2001 X509_EXTENSION *ext; 2002 #ifdef notdef 2003 STACK_OF(X509_EXTENSION) *extlist; 2004 extlist = sk_X509_EXTENSION_new_null(); 2005 #endif 2006 2007 if (getifaddrs (&ifp) == -1) { 2008 logerror("Unable to get list of local interfaces"); 2009 return false; 2010 } 2011 2012 idx = snprintf(subjectAltName, sizeof(subjectAltName), 2013 "DNS:%s", LocalFQDN); 2014 2015 for (ifa = ifp; ifa; ifa = ifa->ifa_next) { 2016 if(!ifa->ifa_addr) 2017 continue; 2018 2019 /* only IP4 and IP6 addresses, but filter loopbacks */ 2020 if (ifa->ifa_addr->sa_family == AF_INET) { 2021 struct sockaddr_in *addr = 2022 (struct sockaddr_in *)ifa->ifa_addr; 2023 if (addr->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) 2024 continue; 2025 salen = sizeof(struct sockaddr_in); 2026 } else if (ifa->ifa_addr->sa_family == AF_INET6) { 2027 struct in6_addr *addr6 = 2028 &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; 2029 if (IN6_IS_ADDR_LOOPBACK(addr6)) 2030 continue; 2031 salen = sizeof(struct sockaddr_in6); 2032 } else 2033 continue; 2034 2035 if (getnameinfo(ifa->ifa_addr, salen, ip, sizeof(ip), 2036 NULL, 0, NI_NUMERICHOST)) { 2037 continue; 2038 } 2039 2040 /* add IP to list */ 2041 idx += snprintf(&subjectAltName[idx], 2042 sizeof(subjectAltName)-idx, ", IP:%s", ip); 2043 } 2044 freeifaddrs (ifp); 2045 2046 ext = X509V3_EXT_conf_nid(NULL, ctx, 2047 NID_subject_alt_name, subjectAltName); 2048 X509_add_ext(cert, ext, -1); 2049 X509_EXTENSION_free(ext); 2050 2051 return true; 2052 } 2053 2054 /* 2055 * generates a private key and a X.509 certificate 2056 */ 2057 bool 2058 mk_x509_cert(X509 **x509p, EVP_PKEY **pkeyp, int bits, int serial, int days) 2059 { 2060 X509 *cert; 2061 EVP_PKEY *pk; 2062 DSA *dsa; 2063 X509_NAME *name = NULL; 2064 X509_EXTENSION *ex = NULL; 2065 X509V3_CTX ctx; 2066 2067 DPRINTF((D_CALL|D_TLS), "mk_x509_cert(%p, %p, %d, %d, %d)\n", 2068 x509p, pkeyp, bits, serial, days); 2069 2070 if (pkeyp && *pkeyp) 2071 pk = *pkeyp; 2072 else if ((pk = EVP_PKEY_new()) == NULL) { 2073 DPRINTF(D_TLS, "EVP_PKEY_new() failed\n"); 2074 return false; 2075 } 2076 2077 if (x509p && *x509p) 2078 cert = *x509p; 2079 else if ((cert = X509_new()) == NULL) { 2080 DPRINTF(D_TLS, "X509_new() failed\n"); 2081 return false; 2082 } 2083 2084 dsa = DSA_generate_parameters(bits, NULL, 0, 2085 NULL, NULL, NULL, NULL); 2086 if (!DSA_generate_key(dsa)) { 2087 DPRINTF(D_TLS, "DSA_generate_key() failed\n"); 2088 return false; 2089 } 2090 if (!EVP_PKEY_assign_DSA(pk, dsa)) { 2091 DPRINTF(D_TLS, "EVP_PKEY_assign_DSA() failed\n"); 2092 return false; 2093 } 2094 2095 X509_set_version(cert, 3); 2096 ASN1_INTEGER_set(X509_get_serialNumber(cert), serial); 2097 X509_gmtime_adj(X509_get_notBefore(cert), 0); 2098 X509_gmtime_adj(X509_get_notAfter(cert), (long)60 * 60 * 24 * days); 2099 2100 if (!X509_set_pubkey(cert, pk)) { 2101 DPRINTF(D_TLS, "X509_set_pubkey() failed\n"); 2102 return false; 2103 } 2104 2105 /* 2106 * This function creates and adds the entry, working out the correct 2107 * string type and performing checks on its length. Normally we'd check 2108 * the return value for errors... 2109 */ 2110 name = X509_get_subject_name(cert); 2111 /* 2112 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, 2113 (unsigned char *)"The NetBSD Project", -1, -1, 0); 2114 X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC, 2115 (unsigned char *)"syslogd", -1, -1, 0); 2116 */ 2117 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, 2118 (unsigned char *) LocalFQDN, -1, -1, 0); 2119 X509_set_issuer_name(cert, name); 2120 2121 /* 2122 * Add extension using V3 code: we can set the config file as NULL 2123 * because we wont reference any other sections. 2124 */ 2125 X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0); 2126 2127 ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_comment, 2128 __UNCONST("auto-generated by the NetBSD syslogd")); 2129 X509_add_ext(cert, ex, -1); 2130 X509_EXTENSION_free(ex); 2131 2132 ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_ssl_server_name, 2133 LocalFQDN); 2134 X509_add_ext(cert, ex, -1); 2135 X509_EXTENSION_free(ex); 2136 2137 ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_netscape_cert_type, 2138 __UNCONST("server, client")); 2139 X509_add_ext(cert, ex, -1); 2140 X509_EXTENSION_free(ex); 2141 2142 ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_key_usage, 2143 __UNCONST("keyAgreement, keyEncipherment, " 2144 "nonRepudiation, digitalSignature")); 2145 X509_add_ext(cert, ex, -1); 2146 X509_EXTENSION_free(ex); 2147 2148 ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_basic_constraints, 2149 __UNCONST("critical,CA:FALSE")); 2150 X509_add_ext(cert, ex, -1); 2151 X509_EXTENSION_free(ex); 2152 2153 (void)x509_cert_add_subjectAltName(cert, &ctx); 2154 2155 if (!X509_sign(cert, pk, EVP_dss1())) { 2156 DPRINTF(D_TLS, "X509_sign() failed\n"); 2157 return false; 2158 } 2159 if (X509_verify(cert, pk) != 1) { 2160 DPRINTF(D_TLS, "X509_verify() failed\n"); 2161 return false; 2162 } 2163 2164 *x509p = cert; 2165 *pkeyp = pk; 2166 return true; 2167 } 2168 2169 void 2170 free_tls_send_msg(struct tls_send_msg *msg) 2171 { 2172 if (!msg) { 2173 DPRINTF((D_DATA), "invalid tls_send_msg_free(NULL)\n"); 2174 return; 2175 } 2176 DELREF(msg->qentry->msg); 2177 (void)message_queue_remove(msg->f, msg->qentry); 2178 FREEPTR(msg->line); 2179 FREEPTR(msg); 2180 } 2181 #endif /* !DISABLE_TLS */ 2182