1 /*- 2 * Copyright (c) 1998-2014 Dag-Erling Smørgrav 3 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de> 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer 11 * in this position and unchanged. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. The name of the author may not be used to endorse or promote products 16 * derived from this software without specific prior written permission 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include <sys/cdefs.h> 31 __FBSDID("$FreeBSD$"); 32 33 #include <sys/param.h> 34 #include <sys/socket.h> 35 #include <sys/time.h> 36 #include <sys/uio.h> 37 38 #include <netinet/in.h> 39 40 #include <ctype.h> 41 #include <errno.h> 42 #include <fcntl.h> 43 #include <netdb.h> 44 #include <poll.h> 45 #include <pwd.h> 46 #include <stdarg.h> 47 #include <stdlib.h> 48 #include <stdio.h> 49 #include <string.h> 50 #include <unistd.h> 51 52 #ifdef WITH_SSL 53 #include <openssl/x509v3.h> 54 #endif 55 56 #include "fetch.h" 57 #include "common.h" 58 59 60 /*** Local data **************************************************************/ 61 62 /* 63 * Error messages for resolver errors 64 */ 65 static struct fetcherr netdb_errlist[] = { 66 #ifdef EAI_NODATA 67 { EAI_NODATA, FETCH_RESOLV, "Host not found" }, 68 #endif 69 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" }, 70 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" }, 71 { EAI_NONAME, FETCH_RESOLV, "No address record" }, 72 { -1, FETCH_UNKNOWN, "Unknown resolver error" } 73 }; 74 75 /* End-of-Line */ 76 static const char ENDL[2] = "\r\n"; 77 78 79 /*** Error-reporting functions ***********************************************/ 80 81 /* 82 * Map error code to string 83 */ 84 static struct fetcherr * 85 fetch_finderr(struct fetcherr *p, int e) 86 { 87 while (p->num != -1 && p->num != e) 88 p++; 89 return (p); 90 } 91 92 /* 93 * Set error code 94 */ 95 void 96 fetch_seterr(struct fetcherr *p, int e) 97 { 98 p = fetch_finderr(p, e); 99 fetchLastErrCode = p->cat; 100 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string); 101 } 102 103 /* 104 * Set error code according to errno 105 */ 106 void 107 fetch_syserr(void) 108 { 109 switch (errno) { 110 case 0: 111 fetchLastErrCode = FETCH_OK; 112 break; 113 case EPERM: 114 case EACCES: 115 case EROFS: 116 case EAUTH: 117 case ENEEDAUTH: 118 fetchLastErrCode = FETCH_AUTH; 119 break; 120 case ENOENT: 121 case EISDIR: /* XXX */ 122 fetchLastErrCode = FETCH_UNAVAIL; 123 break; 124 case ENOMEM: 125 fetchLastErrCode = FETCH_MEMORY; 126 break; 127 case EBUSY: 128 case EAGAIN: 129 fetchLastErrCode = FETCH_TEMP; 130 break; 131 case EEXIST: 132 fetchLastErrCode = FETCH_EXISTS; 133 break; 134 case ENOSPC: 135 fetchLastErrCode = FETCH_FULL; 136 break; 137 case EADDRINUSE: 138 case EADDRNOTAVAIL: 139 case ENETDOWN: 140 case ENETUNREACH: 141 case ENETRESET: 142 case EHOSTUNREACH: 143 fetchLastErrCode = FETCH_NETWORK; 144 break; 145 case ECONNABORTED: 146 case ECONNRESET: 147 fetchLastErrCode = FETCH_ABORT; 148 break; 149 case ETIMEDOUT: 150 fetchLastErrCode = FETCH_TIMEOUT; 151 break; 152 case ECONNREFUSED: 153 case EHOSTDOWN: 154 fetchLastErrCode = FETCH_DOWN; 155 break; 156 default: 157 fetchLastErrCode = FETCH_UNKNOWN; 158 } 159 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno)); 160 } 161 162 163 /* 164 * Emit status message 165 */ 166 void 167 fetch_info(const char *fmt, ...) 168 { 169 va_list ap; 170 171 va_start(ap, fmt); 172 vfprintf(stderr, fmt, ap); 173 va_end(ap); 174 fputc('\n', stderr); 175 } 176 177 178 /*** Network-related utility functions ***************************************/ 179 180 /* 181 * Return the default port for a scheme 182 */ 183 int 184 fetch_default_port(const char *scheme) 185 { 186 struct servent *se; 187 188 if ((se = getservbyname(scheme, "tcp")) != NULL) 189 return (ntohs(se->s_port)); 190 if (strcasecmp(scheme, SCHEME_FTP) == 0) 191 return (FTP_DEFAULT_PORT); 192 if (strcasecmp(scheme, SCHEME_HTTP) == 0) 193 return (HTTP_DEFAULT_PORT); 194 return (0); 195 } 196 197 /* 198 * Return the default proxy port for a scheme 199 */ 200 int 201 fetch_default_proxy_port(const char *scheme) 202 { 203 if (strcasecmp(scheme, SCHEME_FTP) == 0) 204 return (FTP_DEFAULT_PROXY_PORT); 205 if (strcasecmp(scheme, SCHEME_HTTP) == 0) 206 return (HTTP_DEFAULT_PROXY_PORT); 207 return (0); 208 } 209 210 211 /* 212 * Create a connection for an existing descriptor. 213 */ 214 conn_t * 215 fetch_reopen(int sd) 216 { 217 conn_t *conn; 218 int opt = 1; 219 220 /* allocate and fill connection structure */ 221 if ((conn = calloc(1, sizeof(*conn))) == NULL) 222 return (NULL); 223 fcntl(sd, F_SETFD, FD_CLOEXEC); 224 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt); 225 conn->sd = sd; 226 ++conn->ref; 227 return (conn); 228 } 229 230 231 /* 232 * Bump a connection's reference count. 233 */ 234 conn_t * 235 fetch_ref(conn_t *conn) 236 { 237 238 ++conn->ref; 239 return (conn); 240 } 241 242 243 /* 244 * Bind a socket to a specific local address 245 */ 246 int 247 fetch_bind(int sd, int af, const char *addr) 248 { 249 struct addrinfo hints, *res, *res0; 250 int err; 251 252 memset(&hints, 0, sizeof(hints)); 253 hints.ai_family = af; 254 hints.ai_socktype = SOCK_STREAM; 255 hints.ai_protocol = 0; 256 if ((err = getaddrinfo(addr, NULL, &hints, &res0)) != 0) 257 return (-1); 258 for (res = res0; res; res = res->ai_next) 259 if (bind(sd, res->ai_addr, res->ai_addrlen) == 0) 260 return (0); 261 return (-1); 262 } 263 264 265 /* 266 * Establish a TCP connection to the specified port on the specified host. 267 */ 268 conn_t * 269 fetch_connect(const char *host, int port, int af, int verbose) 270 { 271 conn_t *conn; 272 char pbuf[10]; 273 const char *bindaddr; 274 struct addrinfo hints, *res, *res0; 275 int sd, err; 276 277 DEBUG(fprintf(stderr, "---> %s:%d\n", host, port)); 278 279 if (verbose) 280 fetch_info("looking up %s", host); 281 282 /* look up host name and set up socket address structure */ 283 snprintf(pbuf, sizeof(pbuf), "%d", port); 284 memset(&hints, 0, sizeof(hints)); 285 hints.ai_family = af; 286 hints.ai_socktype = SOCK_STREAM; 287 hints.ai_protocol = 0; 288 if ((err = getaddrinfo(host, pbuf, &hints, &res0)) != 0) { 289 netdb_seterr(err); 290 return (NULL); 291 } 292 bindaddr = getenv("FETCH_BIND_ADDRESS"); 293 294 if (verbose) 295 fetch_info("connecting to %s:%d", host, port); 296 297 /* try to connect */ 298 for (sd = -1, res = res0; res; sd = -1, res = res->ai_next) { 299 if ((sd = socket(res->ai_family, res->ai_socktype, 300 res->ai_protocol)) == -1) 301 continue; 302 if (bindaddr != NULL && *bindaddr != '\0' && 303 fetch_bind(sd, res->ai_family, bindaddr) != 0) { 304 fetch_info("failed to bind to '%s'", bindaddr); 305 close(sd); 306 continue; 307 } 308 if (connect(sd, res->ai_addr, res->ai_addrlen) == 0 && 309 fcntl(sd, F_SETFL, O_NONBLOCK) == 0) 310 break; 311 close(sd); 312 } 313 freeaddrinfo(res0); 314 if (sd == -1) { 315 fetch_syserr(); 316 return (NULL); 317 } 318 319 if ((conn = fetch_reopen(sd)) == NULL) { 320 fetch_syserr(); 321 close(sd); 322 } 323 return (conn); 324 } 325 326 #ifdef WITH_SSL 327 /* 328 * Convert characters A-Z to lowercase (intentionally avoid any locale 329 * specific conversions). 330 */ 331 static char 332 fetch_ssl_tolower(char in) 333 { 334 if (in >= 'A' && in <= 'Z') 335 return (in + 32); 336 else 337 return (in); 338 } 339 340 /* 341 * isalpha implementation that intentionally avoids any locale specific 342 * conversions. 343 */ 344 static int 345 fetch_ssl_isalpha(char in) 346 { 347 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z')); 348 } 349 350 /* 351 * Check if passed hostnames a and b are equal. 352 */ 353 static int 354 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b, 355 size_t blen) 356 { 357 size_t i; 358 359 if (alen != blen) 360 return (0); 361 for (i = 0; i < alen; ++i) { 362 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i])) 363 return (0); 364 } 365 return (1); 366 } 367 368 /* 369 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9 370 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha- 371 * numeric characters. Double hyphens (like they're found in IDN a-labels 372 * 'xn--') are not allowed. Empty labels are invalid. 373 */ 374 static int 375 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok) 376 { 377 size_t i; 378 379 if (!len || l[0] == '-' || l[len-1] == '-') 380 return (0); 381 for (i = 0; i < len; ++i) { 382 if (!isdigit(l[i]) && 383 !fetch_ssl_isalpha(l[i]) && 384 !(l[i] == '*' && wcok) && 385 !(l[i] == '-' && l[i - 1] != '-')) 386 return (0); 387 } 388 return (1); 389 } 390 391 /* 392 * Check if host name consists only of numbers. This might indicate an IP 393 * address, which is not a good idea for CN wildcard comparison. 394 */ 395 static int 396 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len) 397 { 398 size_t i; 399 400 for (i = 0; i < len; ++i) { 401 if (!((hostname[i] >= '0' && hostname[i] <= '9') || 402 hostname[i] == '.')) 403 return (0); 404 } 405 return (1); 406 } 407 408 /* 409 * Check if the host name h passed matches the pattern passed in m which 410 * is usually part of subjectAltName or CN of a certificate presented to 411 * the client. This includes wildcard matching. The algorithm is based on 412 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280. 413 */ 414 static int 415 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m, 416 size_t mlen) 417 { 418 int delta, hdotidx, mdot1idx, wcidx; 419 const char *hdot, *mdot1, *mdot2; 420 const char *wc; /* wildcard */ 421 422 if (!(h && *h && m && *m)) 423 return (0); 424 if ((wc = strnstr(m, "*", mlen)) == NULL) 425 return (fetch_ssl_hname_equal(h, hlen, m, mlen)); 426 wcidx = wc - m; 427 /* hostname should not be just dots and numbers */ 428 if (fetch_ssl_hname_is_only_numbers(h, hlen)) 429 return (0); 430 /* only one wildcard allowed in pattern */ 431 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL) 432 return (0); 433 /* 434 * there must be at least two more domain labels and 435 * wildcard has to be in the leftmost label (RFC6125) 436 */ 437 mdot1 = strnstr(m, ".", mlen); 438 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4) 439 return (0); 440 mdot1idx = mdot1 - m; 441 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1); 442 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2) 443 return (0); 444 /* hostname must contain a dot and not be the 1st char */ 445 hdot = strnstr(h, ".", hlen); 446 if (hdot == NULL || hdot == h) 447 return (0); 448 hdotidx = hdot - h; 449 /* 450 * host part of hostname must be at least as long as 451 * pattern it's supposed to match 452 */ 453 if (hdotidx < mdot1idx) 454 return (0); 455 /* 456 * don't allow wildcards in non-traditional domain names 457 * (IDN, A-label, U-label...) 458 */ 459 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) || 460 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1)) 461 return (0); 462 /* match domain part (part after first dot) */ 463 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1, 464 mlen - mdot1idx)) 465 return (0); 466 /* match part left of wildcard */ 467 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx)) 468 return (0); 469 /* match part right of wildcard */ 470 delta = mdot1idx - wcidx - 1; 471 if (!fetch_ssl_hname_equal(hdot - delta, delta, 472 mdot1 - delta, delta)) 473 return (0); 474 /* all tests succeded, it's a match */ 475 return (1); 476 } 477 478 /* 479 * Get numeric host address info - returns NULL if host was not an IP 480 * address. The caller is responsible for deallocation using 481 * freeaddrinfo(3). 482 */ 483 static struct addrinfo * 484 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len) 485 { 486 struct addrinfo hints, *res; 487 char *host; 488 489 host = (char *)malloc(len + 1); 490 memcpy(host, hostname, len); 491 host[len] = '\0'; 492 memset(&hints, 0, sizeof(hints)); 493 hints.ai_family = PF_UNSPEC; 494 hints.ai_socktype = SOCK_STREAM; 495 hints.ai_protocol = 0; 496 hints.ai_flags = AI_NUMERICHOST; 497 /* port is not relevant for this purpose */ 498 if (getaddrinfo(host, "443", &hints, &res) != 0) 499 res = NULL; 500 free(host); 501 return res; 502 } 503 504 /* 505 * Compare ip address in addrinfo with address passes. 506 */ 507 static int 508 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost, 509 size_t rhostlen) 510 { 511 const void *left; 512 513 if (lhost->ai_family == AF_INET && rhostlen == 4) { 514 left = (void *)&((struct sockaddr_in*)(void *) 515 lhost->ai_addr)->sin_addr.s_addr; 516 #ifdef INET6 517 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) { 518 left = (void *)&((struct sockaddr_in6 *)(void *) 519 lhost->ai_addr)->sin6_addr; 520 #endif 521 } else 522 return (0); 523 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0); 524 } 525 526 /* 527 * Compare ip address in addrinfo with host passed. If host is not an IP 528 * address, comparison will fail. 529 */ 530 static int 531 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r, 532 size_t rlen) 533 { 534 struct addrinfo *raddr; 535 int ret; 536 char *rip; 537 538 ret = 0; 539 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL) 540 return 0; /* not a numeric host */ 541 542 if (laddr->ai_family == raddr->ai_family) { 543 if (laddr->ai_family == AF_INET) { 544 rip = (char *)&((struct sockaddr_in *)(void *) 545 raddr->ai_addr)->sin_addr.s_addr; 546 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4); 547 #ifdef INET6 548 } else if (laddr->ai_family == AF_INET6) { 549 rip = (char *)&((struct sockaddr_in6 *)(void *) 550 raddr->ai_addr)->sin6_addr; 551 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16); 552 #endif 553 } 554 555 } 556 freeaddrinfo(raddr); 557 return (ret); 558 } 559 560 /* 561 * Verify server certificate by subjectAltName. 562 */ 563 static int 564 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames, 565 const char *host, struct addrinfo *ip) 566 { 567 const GENERAL_NAME *name; 568 size_t nslen; 569 int i; 570 const char *ns; 571 572 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) { 573 #if OPENSSL_VERSION_NUMBER < 0x10000000L 574 /* 575 * This is a workaround, since the following line causes 576 * alignment issues in clang: 577 * name = sk_GENERAL_NAME_value(altnames, i); 578 * OpenSSL explicitly warns not to use those macros 579 * directly, but there isn't much choice (and there 580 * shouldn't be any ill side effects) 581 */ 582 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i); 583 #else 584 name = sk_GENERAL_NAME_value(altnames, i); 585 #endif 586 ns = (const char *)ASN1_STRING_data(name->d.ia5); 587 nslen = (size_t)ASN1_STRING_length(name->d.ia5); 588 589 if (name->type == GEN_DNS && ip == NULL && 590 fetch_ssl_hname_match(host, strlen(host), ns, nslen)) 591 return (1); 592 else if (name->type == GEN_IPADD && ip != NULL && 593 fetch_ssl_ipaddr_match_bin(ip, ns, nslen)) 594 return (1); 595 } 596 return (0); 597 } 598 599 /* 600 * Verify server certificate by CN. 601 */ 602 static int 603 fetch_ssl_verify_cn(X509_NAME *subject, const char *host, 604 struct addrinfo *ip) 605 { 606 ASN1_STRING *namedata; 607 X509_NAME_ENTRY *nameentry; 608 int cnlen, lastpos, loc, ret; 609 unsigned char *cn; 610 611 ret = 0; 612 lastpos = -1; 613 loc = -1; 614 cn = NULL; 615 /* get most specific CN (last entry in list) and compare */ 616 while ((lastpos = X509_NAME_get_index_by_NID(subject, 617 NID_commonName, lastpos)) != -1) 618 loc = lastpos; 619 620 if (loc > -1) { 621 nameentry = X509_NAME_get_entry(subject, loc); 622 namedata = X509_NAME_ENTRY_get_data(nameentry); 623 cnlen = ASN1_STRING_to_UTF8(&cn, namedata); 624 if (ip == NULL && 625 fetch_ssl_hname_match(host, strlen(host), cn, cnlen)) 626 ret = 1; 627 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen)) 628 ret = 1; 629 OPENSSL_free(cn); 630 } 631 return (ret); 632 } 633 634 /* 635 * Verify that server certificate subjectAltName/CN matches 636 * hostname. First check, if there are alternative subject names. If yes, 637 * those have to match. Only if those don't exist it falls back to 638 * checking the subject's CN. 639 */ 640 static int 641 fetch_ssl_verify_hname(X509 *cert, const char *host) 642 { 643 struct addrinfo *ip; 644 STACK_OF(GENERAL_NAME) *altnames; 645 X509_NAME *subject; 646 int ret; 647 648 ret = 0; 649 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host)); 650 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name, 651 NULL, NULL); 652 653 if (altnames != NULL) { 654 ret = fetch_ssl_verify_altname(altnames, host, ip); 655 } else { 656 subject = X509_get_subject_name(cert); 657 if (subject != NULL) 658 ret = fetch_ssl_verify_cn(subject, host, ip); 659 } 660 661 if (ip != NULL) 662 freeaddrinfo(ip); 663 if (altnames != NULL) 664 GENERAL_NAMES_free(altnames); 665 return (ret); 666 } 667 668 /* 669 * Configure transport security layer based on environment. 670 */ 671 static void 672 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose) 673 { 674 long ssl_ctx_options; 675 676 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_TICKET; 677 if (getenv("SSL_ALLOW_SSL3") == NULL) 678 ssl_ctx_options |= SSL_OP_NO_SSLv3; 679 if (getenv("SSL_NO_TLS1") != NULL) 680 ssl_ctx_options |= SSL_OP_NO_TLSv1; 681 if (getenv("SSL_NO_TLS1_1") != NULL) 682 ssl_ctx_options |= SSL_OP_NO_TLSv1_1; 683 if (getenv("SSL_NO_TLS1_2") != NULL) 684 ssl_ctx_options |= SSL_OP_NO_TLSv1_2; 685 if (verbose) 686 fetch_info("SSL options: %lx", ssl_ctx_options); 687 SSL_CTX_set_options(ctx, ssl_ctx_options); 688 } 689 690 691 /* 692 * Configure peer verification based on environment. 693 */ 694 #define LOCAL_CERT_FILE "/usr/local/etc/ssl/cert.pem" 695 #define BASE_CERT_FILE "/etc/ssl/cert.pem" 696 static int 697 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose) 698 { 699 X509_LOOKUP *crl_lookup; 700 X509_STORE *crl_store; 701 const char *ca_cert_file, *ca_cert_path, *crl_file; 702 703 if (getenv("SSL_NO_VERIFY_PEER") == NULL) { 704 ca_cert_file = getenv("SSL_CA_CERT_FILE"); 705 if (ca_cert_file == NULL && 706 access(LOCAL_CERT_FILE, R_OK) == 0) 707 ca_cert_file = LOCAL_CERT_FILE; 708 if (ca_cert_file == NULL) 709 ca_cert_file = BASE_CERT_FILE; 710 ca_cert_path = getenv("SSL_CA_CERT_PATH"); 711 if (verbose) { 712 fetch_info("Peer verification enabled"); 713 if (ca_cert_file != NULL) 714 fetch_info("Using CA cert file: %s", 715 ca_cert_file); 716 if (ca_cert_path != NULL) 717 fetch_info("Using CA cert path: %s", 718 ca_cert_path); 719 } 720 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, 721 fetch_ssl_cb_verify_crt); 722 SSL_CTX_load_verify_locations(ctx, ca_cert_file, 723 ca_cert_path); 724 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) { 725 if (verbose) 726 fetch_info("Using CRL file: %s", crl_file); 727 crl_store = SSL_CTX_get_cert_store(ctx); 728 crl_lookup = X509_STORE_add_lookup(crl_store, 729 X509_LOOKUP_file()); 730 if (crl_lookup == NULL || 731 !X509_load_crl_file(crl_lookup, crl_file, 732 X509_FILETYPE_PEM)) { 733 fprintf(stderr, 734 "Could not load CRL file %s\n", 735 crl_file); 736 return (0); 737 } 738 X509_STORE_set_flags(crl_store, 739 X509_V_FLAG_CRL_CHECK | 740 X509_V_FLAG_CRL_CHECK_ALL); 741 } 742 } 743 return (1); 744 } 745 746 /* 747 * Configure client certificate based on environment. 748 */ 749 static int 750 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose) 751 { 752 const char *client_cert_file, *client_key_file; 753 754 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) { 755 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ? 756 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file; 757 if (verbose) { 758 fetch_info("Using client cert file: %s", 759 client_cert_file); 760 fetch_info("Using client key file: %s", 761 client_key_file); 762 } 763 if (SSL_CTX_use_certificate_chain_file(ctx, 764 client_cert_file) != 1) { 765 fprintf(stderr, 766 "Could not load client certificate %s\n", 767 client_cert_file); 768 return (0); 769 } 770 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file, 771 SSL_FILETYPE_PEM) != 1) { 772 fprintf(stderr, 773 "Could not load client key %s\n", 774 client_key_file); 775 return (0); 776 } 777 } 778 return (1); 779 } 780 781 /* 782 * Callback for SSL certificate verification, this is called on server 783 * cert verification. It takes no decision, but informs the user in case 784 * verification failed. 785 */ 786 int 787 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx) 788 { 789 X509 *crt; 790 X509_NAME *name; 791 char *str; 792 793 str = NULL; 794 if (!verified) { 795 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL && 796 (name = X509_get_subject_name(crt)) != NULL) 797 str = X509_NAME_oneline(name, 0, 0); 798 fprintf(stderr, "Certificate verification failed for %s\n", 799 str != NULL ? str : "no relevant certificate"); 800 OPENSSL_free(str); 801 } 802 return (verified); 803 } 804 805 #endif 806 807 /* 808 * Enable SSL on a connection. 809 */ 810 int 811 fetch_ssl(conn_t *conn, const struct url *URL, int verbose) 812 { 813 #ifdef WITH_SSL 814 int ret, ssl_err; 815 X509_NAME *name; 816 char *str; 817 818 /* Init the SSL library and context */ 819 if (!SSL_library_init()){ 820 fprintf(stderr, "SSL library init failed\n"); 821 return (-1); 822 } 823 824 SSL_load_error_strings(); 825 826 conn->ssl_meth = SSLv23_client_method(); 827 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth); 828 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY); 829 830 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose); 831 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose)) 832 return (-1); 833 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose)) 834 return (-1); 835 836 conn->ssl = SSL_new(conn->ssl_ctx); 837 if (conn->ssl == NULL) { 838 fprintf(stderr, "SSL context creation failed\n"); 839 return (-1); 840 } 841 SSL_set_fd(conn->ssl, conn->sd); 842 843 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT) 844 if (!SSL_set_tlsext_host_name(conn->ssl, 845 __DECONST(struct url *, URL)->host)) { 846 fprintf(stderr, 847 "TLS server name indication extension failed for host %s\n", 848 URL->host); 849 return (-1); 850 } 851 #endif 852 while ((ret = SSL_connect(conn->ssl)) == -1) { 853 ssl_err = SSL_get_error(conn->ssl, ret); 854 if (ssl_err != SSL_ERROR_WANT_READ && 855 ssl_err != SSL_ERROR_WANT_WRITE) { 856 ERR_print_errors_fp(stderr); 857 return (-1); 858 } 859 } 860 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl); 861 862 if (conn->ssl_cert == NULL) { 863 fprintf(stderr, "No server SSL certificate\n"); 864 return (-1); 865 } 866 867 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) { 868 if (verbose) 869 fetch_info("Verify hostname"); 870 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) { 871 fprintf(stderr, 872 "SSL certificate subject doesn't match host %s\n", 873 URL->host); 874 return (-1); 875 } 876 } 877 878 if (verbose) { 879 fetch_info("%s connection established using %s", 880 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl)); 881 name = X509_get_subject_name(conn->ssl_cert); 882 str = X509_NAME_oneline(name, 0, 0); 883 fetch_info("Certificate subject: %s", str); 884 OPENSSL_free(str); 885 name = X509_get_issuer_name(conn->ssl_cert); 886 str = X509_NAME_oneline(name, 0, 0); 887 fetch_info("Certificate issuer: %s", str); 888 OPENSSL_free(str); 889 } 890 891 return (0); 892 #else 893 (void)conn; 894 (void)verbose; 895 fprintf(stderr, "SSL support disabled\n"); 896 return (-1); 897 #endif 898 } 899 900 #define FETCH_READ_WAIT -2 901 #define FETCH_READ_ERROR -1 902 #define FETCH_READ_DONE 0 903 904 #ifdef WITH_SSL 905 static ssize_t 906 fetch_ssl_read(SSL *ssl, char *buf, size_t len) 907 { 908 ssize_t rlen; 909 int ssl_err; 910 911 rlen = SSL_read(ssl, buf, len); 912 if (rlen < 0) { 913 ssl_err = SSL_get_error(ssl, rlen); 914 if (ssl_err == SSL_ERROR_WANT_READ || 915 ssl_err == SSL_ERROR_WANT_WRITE) { 916 return (FETCH_READ_WAIT); 917 } else { 918 ERR_print_errors_fp(stderr); 919 return (FETCH_READ_ERROR); 920 } 921 } 922 return (rlen); 923 } 924 #endif 925 926 static ssize_t 927 fetch_socket_read(int sd, char *buf, size_t len) 928 { 929 ssize_t rlen; 930 931 rlen = read(sd, buf, len); 932 if (rlen < 0) { 933 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls)) 934 return (FETCH_READ_WAIT); 935 else 936 return (FETCH_READ_ERROR); 937 } 938 return (rlen); 939 } 940 941 /* 942 * Read a character from a connection w/ timeout 943 */ 944 ssize_t 945 fetch_read(conn_t *conn, char *buf, size_t len) 946 { 947 struct timeval now, timeout, delta; 948 struct pollfd pfd; 949 ssize_t rlen; 950 int deltams; 951 952 if (fetchTimeout > 0) { 953 gettimeofday(&timeout, NULL); 954 timeout.tv_sec += fetchTimeout; 955 } 956 957 deltams = INFTIM; 958 memset(&pfd, 0, sizeof pfd); 959 pfd.fd = conn->sd; 960 pfd.events = POLLIN | POLLERR; 961 962 for (;;) { 963 /* 964 * The socket is non-blocking. Instead of the canonical 965 * poll() -> read(), we do the following: 966 * 967 * 1) call read() or SSL_read(). 968 * 2) if we received some data, return it. 969 * 3) if an error occurred, return -1. 970 * 4) if read() or SSL_read() signaled EOF, return. 971 * 5) if we did not receive any data but we're not at EOF, 972 * call poll(). 973 * 974 * In the SSL case, this is necessary because if we 975 * receive a close notification, we have to call 976 * SSL_read() one additional time after we've read 977 * everything we received. 978 * 979 * In the non-SSL case, it may improve performance (very 980 * slightly) when reading small amounts of data. 981 */ 982 #ifdef WITH_SSL 983 if (conn->ssl != NULL) 984 rlen = fetch_ssl_read(conn->ssl, buf, len); 985 else 986 #endif 987 rlen = fetch_socket_read(conn->sd, buf, len); 988 if (rlen >= 0) { 989 break; 990 } else if (rlen == FETCH_READ_ERROR) { 991 fetch_syserr(); 992 return (-1); 993 } 994 // assert(rlen == FETCH_READ_WAIT); 995 if (fetchTimeout > 0) { 996 gettimeofday(&now, NULL); 997 if (!timercmp(&timeout, &now, >)) { 998 errno = ETIMEDOUT; 999 fetch_syserr(); 1000 return (-1); 1001 } 1002 timersub(&timeout, &now, &delta); 1003 deltams = delta.tv_sec * 1000 + 1004 delta.tv_usec / 1000;; 1005 } 1006 errno = 0; 1007 pfd.revents = 0; 1008 if (poll(&pfd, 1, deltams) < 0) { 1009 if (errno == EINTR && fetchRestartCalls) 1010 continue; 1011 fetch_syserr(); 1012 return (-1); 1013 } 1014 } 1015 return (rlen); 1016 } 1017 1018 1019 /* 1020 * Read a line of text from a connection w/ timeout 1021 */ 1022 #define MIN_BUF_SIZE 1024 1023 1024 int 1025 fetch_getln(conn_t *conn) 1026 { 1027 char *tmp; 1028 size_t tmpsize; 1029 ssize_t len; 1030 char c; 1031 1032 if (conn->buf == NULL) { 1033 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) { 1034 errno = ENOMEM; 1035 return (-1); 1036 } 1037 conn->bufsize = MIN_BUF_SIZE; 1038 } 1039 1040 conn->buf[0] = '\0'; 1041 conn->buflen = 0; 1042 1043 do { 1044 len = fetch_read(conn, &c, 1); 1045 if (len == -1) 1046 return (-1); 1047 if (len == 0) 1048 break; 1049 conn->buf[conn->buflen++] = c; 1050 if (conn->buflen == conn->bufsize) { 1051 tmp = conn->buf; 1052 tmpsize = conn->bufsize * 2 + 1; 1053 if ((tmp = realloc(tmp, tmpsize)) == NULL) { 1054 errno = ENOMEM; 1055 return (-1); 1056 } 1057 conn->buf = tmp; 1058 conn->bufsize = tmpsize; 1059 } 1060 } while (c != '\n'); 1061 1062 conn->buf[conn->buflen] = '\0'; 1063 DEBUG(fprintf(stderr, "<<< %s", conn->buf)); 1064 return (0); 1065 } 1066 1067 1068 /* 1069 * Write to a connection w/ timeout 1070 */ 1071 ssize_t 1072 fetch_write(conn_t *conn, const char *buf, size_t len) 1073 { 1074 struct iovec iov; 1075 1076 iov.iov_base = __DECONST(char *, buf); 1077 iov.iov_len = len; 1078 return fetch_writev(conn, &iov, 1); 1079 } 1080 1081 /* 1082 * Write a vector to a connection w/ timeout 1083 * Note: can modify the iovec. 1084 */ 1085 ssize_t 1086 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt) 1087 { 1088 struct timeval now, timeout, delta; 1089 struct pollfd pfd; 1090 ssize_t wlen, total; 1091 int deltams; 1092 1093 memset(&pfd, 0, sizeof pfd); 1094 if (fetchTimeout) { 1095 pfd.fd = conn->sd; 1096 pfd.events = POLLOUT | POLLERR; 1097 gettimeofday(&timeout, NULL); 1098 timeout.tv_sec += fetchTimeout; 1099 } 1100 1101 total = 0; 1102 while (iovcnt > 0) { 1103 while (fetchTimeout && pfd.revents == 0) { 1104 gettimeofday(&now, NULL); 1105 if (!timercmp(&timeout, &now, >)) { 1106 errno = ETIMEDOUT; 1107 fetch_syserr(); 1108 return (-1); 1109 } 1110 timersub(&timeout, &now, &delta); 1111 deltams = delta.tv_sec * 1000 + 1112 delta.tv_usec / 1000; 1113 errno = 0; 1114 pfd.revents = 0; 1115 if (poll(&pfd, 1, deltams) < 0) { 1116 /* POSIX compliance */ 1117 if (errno == EAGAIN) 1118 continue; 1119 if (errno == EINTR && fetchRestartCalls) 1120 continue; 1121 return (-1); 1122 } 1123 } 1124 errno = 0; 1125 #ifdef WITH_SSL 1126 if (conn->ssl != NULL) 1127 wlen = SSL_write(conn->ssl, 1128 iov->iov_base, iov->iov_len); 1129 else 1130 #endif 1131 wlen = writev(conn->sd, iov, iovcnt); 1132 if (wlen == 0) { 1133 /* we consider a short write a failure */ 1134 /* XXX perhaps we shouldn't in the SSL case */ 1135 errno = EPIPE; 1136 fetch_syserr(); 1137 return (-1); 1138 } 1139 if (wlen < 0) { 1140 if (errno == EINTR && fetchRestartCalls) 1141 continue; 1142 return (-1); 1143 } 1144 total += wlen; 1145 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) { 1146 wlen -= iov->iov_len; 1147 iov++; 1148 iovcnt--; 1149 } 1150 if (iovcnt > 0) { 1151 iov->iov_len -= wlen; 1152 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen; 1153 } 1154 } 1155 return (total); 1156 } 1157 1158 1159 /* 1160 * Write a line of text to a connection w/ timeout 1161 */ 1162 int 1163 fetch_putln(conn_t *conn, const char *str, size_t len) 1164 { 1165 struct iovec iov[2]; 1166 int ret; 1167 1168 DEBUG(fprintf(stderr, ">>> %s\n", str)); 1169 iov[0].iov_base = __DECONST(char *, str); 1170 iov[0].iov_len = len; 1171 iov[1].iov_base = __DECONST(char *, ENDL); 1172 iov[1].iov_len = sizeof(ENDL); 1173 if (len == 0) 1174 ret = fetch_writev(conn, &iov[1], 1); 1175 else 1176 ret = fetch_writev(conn, iov, 2); 1177 if (ret == -1) 1178 return (-1); 1179 return (0); 1180 } 1181 1182 1183 /* 1184 * Close connection 1185 */ 1186 int 1187 fetch_close(conn_t *conn) 1188 { 1189 int ret; 1190 1191 if (--conn->ref > 0) 1192 return (0); 1193 #ifdef WITH_SSL 1194 if (conn->ssl) { 1195 SSL_shutdown(conn->ssl); 1196 SSL_set_connect_state(conn->ssl); 1197 SSL_free(conn->ssl); 1198 conn->ssl = NULL; 1199 } 1200 if (conn->ssl_ctx) { 1201 SSL_CTX_free(conn->ssl_ctx); 1202 conn->ssl_ctx = NULL; 1203 } 1204 if (conn->ssl_cert) { 1205 X509_free(conn->ssl_cert); 1206 conn->ssl_cert = NULL; 1207 } 1208 #endif 1209 ret = close(conn->sd); 1210 free(conn->buf); 1211 free(conn); 1212 return (ret); 1213 } 1214 1215 1216 /*** Directory-related utility functions *************************************/ 1217 1218 int 1219 fetch_add_entry(struct url_ent **p, int *size, int *len, 1220 const char *name, struct url_stat *us) 1221 { 1222 struct url_ent *tmp; 1223 1224 if (*p == NULL) { 1225 *size = 0; 1226 *len = 0; 1227 } 1228 1229 if (*len >= *size - 1) { 1230 tmp = realloc(*p, (*size * 2 + 1) * sizeof(**p)); 1231 if (tmp == NULL) { 1232 errno = ENOMEM; 1233 fetch_syserr(); 1234 return (-1); 1235 } 1236 *size = (*size * 2 + 1); 1237 *p = tmp; 1238 } 1239 1240 tmp = *p + *len; 1241 snprintf(tmp->name, PATH_MAX, "%s", name); 1242 memcpy(&tmp->stat, us, sizeof(*us)); 1243 1244 (*len)++; 1245 (++tmp)->name[0] = 0; 1246 1247 return (0); 1248 } 1249 1250 1251 /*** Authentication-related utility functions ********************************/ 1252 1253 static const char * 1254 fetch_read_word(FILE *f) 1255 { 1256 static char word[1024]; 1257 1258 if (fscanf(f, " %1023s ", word) != 1) 1259 return (NULL); 1260 return (word); 1261 } 1262 1263 /* 1264 * Get authentication data for a URL from .netrc 1265 */ 1266 int 1267 fetch_netrc_auth(struct url *url) 1268 { 1269 char fn[PATH_MAX]; 1270 const char *word; 1271 char *p; 1272 FILE *f; 1273 1274 if ((p = getenv("NETRC")) != NULL) { 1275 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) { 1276 fetch_info("$NETRC specifies a file name " 1277 "longer than PATH_MAX"); 1278 return (-1); 1279 } 1280 } else { 1281 if ((p = getenv("HOME")) != NULL) { 1282 struct passwd *pwd; 1283 1284 if ((pwd = getpwuid(getuid())) == NULL || 1285 (p = pwd->pw_dir) == NULL) 1286 return (-1); 1287 } 1288 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn)) 1289 return (-1); 1290 } 1291 1292 if ((f = fopen(fn, "r")) == NULL) 1293 return (-1); 1294 while ((word = fetch_read_word(f)) != NULL) { 1295 if (strcmp(word, "default") == 0) { 1296 DEBUG(fetch_info("Using default .netrc settings")); 1297 break; 1298 } 1299 if (strcmp(word, "machine") == 0 && 1300 (word = fetch_read_word(f)) != NULL && 1301 strcasecmp(word, url->host) == 0) { 1302 DEBUG(fetch_info("Using .netrc settings for %s", word)); 1303 break; 1304 } 1305 } 1306 if (word == NULL) 1307 goto ferr; 1308 while ((word = fetch_read_word(f)) != NULL) { 1309 if (strcmp(word, "login") == 0) { 1310 if ((word = fetch_read_word(f)) == NULL) 1311 goto ferr; 1312 if (snprintf(url->user, sizeof(url->user), 1313 "%s", word) > (int)sizeof(url->user)) { 1314 fetch_info("login name in .netrc is too long"); 1315 url->user[0] = '\0'; 1316 } 1317 } else if (strcmp(word, "password") == 0) { 1318 if ((word = fetch_read_word(f)) == NULL) 1319 goto ferr; 1320 if (snprintf(url->pwd, sizeof(url->pwd), 1321 "%s", word) > (int)sizeof(url->pwd)) { 1322 fetch_info("password in .netrc is too long"); 1323 url->pwd[0] = '\0'; 1324 } 1325 } else if (strcmp(word, "account") == 0) { 1326 if ((word = fetch_read_word(f)) == NULL) 1327 goto ferr; 1328 /* XXX not supported! */ 1329 } else { 1330 break; 1331 } 1332 } 1333 fclose(f); 1334 return (0); 1335 ferr: 1336 fclose(f); 1337 return (-1); 1338 } 1339 1340 /* 1341 * The no_proxy environment variable specifies a set of domains for 1342 * which the proxy should not be consulted; the contents is a comma-, 1343 * or space-separated list of domain names. A single asterisk will 1344 * override all proxy variables and no transactions will be proxied 1345 * (for compatability with lynx and curl, see the discussion at 1346 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>). 1347 */ 1348 int 1349 fetch_no_proxy_match(const char *host) 1350 { 1351 const char *no_proxy, *p, *q; 1352 size_t h_len, d_len; 1353 1354 if ((no_proxy = getenv("NO_PROXY")) == NULL && 1355 (no_proxy = getenv("no_proxy")) == NULL) 1356 return (0); 1357 1358 /* asterisk matches any hostname */ 1359 if (strcmp(no_proxy, "*") == 0) 1360 return (1); 1361 1362 h_len = strlen(host); 1363 p = no_proxy; 1364 do { 1365 /* position p at the beginning of a domain suffix */ 1366 while (*p == ',' || isspace((unsigned char)*p)) 1367 p++; 1368 1369 /* position q at the first separator character */ 1370 for (q = p; *q; ++q) 1371 if (*q == ',' || isspace((unsigned char)*q)) 1372 break; 1373 1374 d_len = q - p; 1375 if (d_len > 0 && h_len >= d_len && 1376 strncasecmp(host + h_len - d_len, 1377 p, d_len) == 0) { 1378 /* domain name matches */ 1379 return (1); 1380 } 1381 1382 p = q + 1; 1383 } while (*q); 1384 1385 return (0); 1386 } 1387