2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1998-2016 Dag-Erling Smørgrav
5 * Copyright (c) 2013 Michael Gmelin <freebsd@grem.de>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/socket.h>
40 #include <netinet/in.h>
57 #include <openssl/x509v3.h>
64 /*** Local data **************************************************************/
67 * Error messages for resolver errors
69 static struct fetcherr netdb_errlist[] = {
71 { EAI_ADDRFAMILY, FETCH_RESOLV, "Address family for host not supported" },
74 { EAI_NODATA, FETCH_RESOLV, "No address for host" },
76 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
77 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
78 { EAI_NONAME, FETCH_RESOLV, "Host does not resolve" },
79 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
83 * SOCKS5 error enumerations
88 SOCKS5_ERR_READ_METHOD,
91 SOCKS5_ERR_NOTIMPLEMENTED,
92 SOCKS5_ERR_HOSTNAME_SIZE,
95 SOCKS5_ERR_NON_VER5_RESP,
97 SOCKS5_ERR_NOT_ALLOWED,
98 SOCKS5_ERR_NET_UNREACHABLE,
99 SOCKS5_ERR_HOST_UNREACHABLE,
100 SOCKS5_ERR_CONN_REFUSED,
101 SOCKS5_ERR_TTL_EXPIRED,
102 SOCKS5_ERR_COM_UNSUPPORTED,
103 SOCKS5_ERR_ADDR_UNSUPPORTED,
104 SOCKS5_ERR_UNSPECIFIED,
105 /* Configuration errors */
107 SOCKS5_ERR_BAD_PROXY_FORMAT,
112 * Error messages for SOCKS5 errors
114 static struct fetcherr socks5_errlist[] = {
115 /* SOCKS5 protocol errors */
116 { SOCKS5_ERR_SELECTION, FETCH_ABORT, "SOCKS5: Failed to send selection method" },
117 { SOCKS5_ERR_READ_METHOD, FETCH_ABORT, "SOCKS5: Failed to read method" },
118 { SOCKS5_ERR_VER5_ONLY, FETCH_PROTO, "SOCKS5: Only version 5 is implemented" },
119 { SOCKS5_ERR_NOMETHODS, FETCH_PROTO, "SOCKS5: No acceptable methods" },
120 { SOCKS5_ERR_NOTIMPLEMENTED, FETCH_PROTO, "SOCKS5: Method currently not implemented" },
121 { SOCKS5_ERR_HOSTNAME_SIZE, FETCH_PROTO, "SOCKS5: Hostname size is above 256 bytes" },
122 { SOCKS5_ERR_REQUEST, FETCH_PROTO, "SOCKS5: Failed to request" },
123 { SOCKS5_ERR_REPLY, FETCH_PROTO, "SOCKS5: Failed to receive reply" },
124 { SOCKS5_ERR_NON_VER5_RESP, FETCH_PROTO, "SOCKS5: Server responded with a non-version 5 response" },
125 { SOCKS5_ERR_GENERAL, FETCH_ABORT, "SOCKS5: General server failure" },
126 { SOCKS5_ERR_NOT_ALLOWED, FETCH_AUTH, "SOCKS5: Connection not allowed by ruleset" },
127 { SOCKS5_ERR_NET_UNREACHABLE, FETCH_NETWORK, "SOCKS5: Network unreachable" },
128 { SOCKS5_ERR_HOST_UNREACHABLE, FETCH_ABORT, "SOCKS5: Host unreachable" },
129 { SOCKS5_ERR_CONN_REFUSED, FETCH_ABORT, "SOCKS5: Connection refused" },
130 { SOCKS5_ERR_TTL_EXPIRED, FETCH_TIMEOUT, "SOCKS5: TTL expired" },
131 { SOCKS5_ERR_COM_UNSUPPORTED, FETCH_PROTO, "SOCKS5: Command not supported" },
132 { SOCKS5_ERR_ADDR_UNSUPPORTED, FETCH_ABORT, "SOCKS5: Address type not supported" },
133 { SOCKS5_ERR_UNSPECIFIED, FETCH_UNKNOWN, "SOCKS5: Unspecified error" },
134 /* Configuration error */
135 { SOCKS5_ERR_BAD_HOST, FETCH_ABORT, "SOCKS5: Bad proxy host" },
136 { SOCKS5_ERR_BAD_PROXY_FORMAT, FETCH_ABORT, "SOCKS5: Bad proxy format" },
137 { SOCKS5_ERR_BAD_PORT, FETCH_ABORT, "SOCKS5: Bad port" }
141 static const char ENDL[2] = "\r\n";
144 /*** Error-reporting functions ***********************************************/
147 * Map error code to string
149 static struct fetcherr *
150 fetch_finderr(struct fetcherr *p, int e)
152 while (p->num != -1 && p->num != e)
161 fetch_seterr(struct fetcherr *p, int e)
163 p = fetch_finderr(p, e);
164 fetchLastErrCode = p->cat;
165 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
169 * Set error code according to errno
176 fetchLastErrCode = FETCH_OK;
183 fetchLastErrCode = FETCH_AUTH;
186 case EISDIR: /* XXX */
187 fetchLastErrCode = FETCH_UNAVAIL;
190 fetchLastErrCode = FETCH_MEMORY;
194 fetchLastErrCode = FETCH_TEMP;
197 fetchLastErrCode = FETCH_EXISTS;
200 fetchLastErrCode = FETCH_FULL;
208 fetchLastErrCode = FETCH_NETWORK;
212 fetchLastErrCode = FETCH_ABORT;
215 fetchLastErrCode = FETCH_TIMEOUT;
219 fetchLastErrCode = FETCH_DOWN;
222 fetchLastErrCode = FETCH_UNKNOWN;
224 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
229 * Emit status message
232 fetch_info(const char *fmt, ...)
237 vfprintf(stderr, fmt, ap);
243 /*** Network-related utility functions ***************************************/
246 * Return the default port for a scheme
249 fetch_default_port(const char *scheme)
253 if ((se = getservbyname(scheme, "tcp")) != NULL)
254 return (ntohs(se->s_port));
255 if (strcmp(scheme, SCHEME_FTP) == 0)
256 return (FTP_DEFAULT_PORT);
257 if (strcmp(scheme, SCHEME_HTTP) == 0)
258 return (HTTP_DEFAULT_PORT);
263 * Return the default proxy port for a scheme
266 fetch_default_proxy_port(const char *scheme)
268 if (strcmp(scheme, SCHEME_FTP) == 0)
269 return (FTP_DEFAULT_PROXY_PORT);
270 if (strcmp(scheme, SCHEME_HTTP) == 0)
271 return (HTTP_DEFAULT_PROXY_PORT);
277 * Create a connection for an existing descriptor.
285 /* allocate and fill connection structure */
286 if ((conn = calloc(1, sizeof(*conn))) == NULL)
288 fcntl(sd, F_SETFD, FD_CLOEXEC);
289 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
297 * Bump a connection's reference count.
300 fetch_ref(conn_t *conn)
312 fetch_resolve(const char *addr, int port, int af)
314 char hbuf[256], sbuf[8];
315 struct addrinfo hints, *res;
316 const char *hb, *he, *sep;
317 const char *host, *service;
320 /* first, check for a bracketed IPv6 address */
323 if ((sep = strchr(hb, ']')) == NULL) {
330 sep = strchrnul(hb, ':');
334 /* see if we need to copy the host name */
336 len = snprintf(hbuf, sizeof(hbuf),
337 "%.*s", (int)(he - hb), hb);
340 if (len >= (int)sizeof(hbuf)) {
341 errno = ENAMETOOLONG;
349 /* was it followed by a service name? */
350 if (*sep == '\0' && port != 0) {
351 if (port < 1 || port > 65535) {
355 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0)
358 } else if (*sep != '\0') {
365 memset(&hints, 0, sizeof(hints));
366 hints.ai_family = af;
367 hints.ai_socktype = SOCK_STREAM;
368 hints.ai_flags = AI_ADDRCONFIG;
369 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
381 * Bind a socket to a specific local address
384 fetch_bind(int sd, int af, const char *addr)
386 struct addrinfo *cliai, *ai;
389 if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
391 for (ai = cliai; ai != NULL; ai = ai->ai_next)
392 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
397 return (err == 0 ? 0 : -1);
402 * SOCKS5 connection initiation, based on RFC 1928
403 * Default DNS resolution over SOCKS5
406 fetch_socks5_init(conn_t *conn, const char *host, int port, int verbose)
409 * Size is based on largest packet prefix (4 bytes) +
410 * Largest FQDN (256) + one byte size (1) +
413 unsigned char buf[BUFF_SIZE];
418 fetch_info("Initializing SOCKS5 connection: %s:%d", host, port);
420 /* Connection initialization */
422 *ptr++ = SOCKS_VERSION_5;
423 *ptr++ = SOCKS_CONNECTION;
426 if (fetch_write(conn, buf, 3) != 3) {
427 ret = SOCKS5_ERR_SELECTION;
431 /* Verify response from SOCKS5 server */
432 if (fetch_read(conn, buf, 2) != 2) {
433 ret = SOCKS5_ERR_READ_METHOD;
438 if (ptr[0] != SOCKS_VERSION_5) {
439 ret = SOCKS5_ERR_VER5_ONLY;
442 if (ptr[1] == SOCKS_NOMETHODS) {
443 ret = SOCKS5_ERR_NOMETHODS;
446 else if (ptr[1] != SOCKS5_NOTIMPLEMENTED) {
447 ret = SOCKS5_ERR_NOTIMPLEMENTED;
452 *ptr++ = SOCKS_VERSION_5;
453 *ptr++ = SOCKS_CONNECTION;
455 /* Encode all targets as a hostname to avoid DNS leaks */
456 *ptr++ = SOCKS_ATYP_DOMAINNAME;
457 if (strlen(host) > FQDN_SIZE) {
458 ret = SOCKS5_ERR_HOSTNAME_SIZE;
461 *ptr++ = strlen(host);
462 memcpy(ptr, host, strlen(host));
463 ptr = ptr + strlen(host);
466 *ptr++ = port & 0x00ff;
467 *ptr++ = (port & 0xff00) >> 8;
469 if (fetch_write(conn, buf, ptr - buf) != ptr - buf) {
470 ret = SOCKS5_ERR_REQUEST;
474 /* BND.ADDR is variable length, read the largest on non-blocking socket */
475 if (!fetch_read(conn, buf, BUFF_SIZE)) {
476 ret = SOCKS5_ERR_REPLY;
481 if (*ptr++ != SOCKS_VERSION_5) {
482 ret = SOCKS5_ERR_NON_VER5_RESP;
489 case SOCKS_GENERAL_FAILURE:
490 ret = SOCKS5_ERR_GENERAL;
492 case SOCKS_CONNECTION_NOT_ALLOWED:
493 ret = SOCKS5_ERR_NOT_ALLOWED;
495 case SOCKS_NETWORK_UNREACHABLE:
496 ret = SOCKS5_ERR_NET_UNREACHABLE;
498 case SOCKS_HOST_UNREACHABLE:
499 ret = SOCKS5_ERR_HOST_UNREACHABLE;
501 case SOCKS_CONNECTION_REFUSED:
502 ret = SOCKS5_ERR_CONN_REFUSED;
504 case SOCKS_TTL_EXPIRED:
505 ret = SOCKS5_ERR_TTL_EXPIRED;
507 case SOCKS_COMMAND_NOT_SUPPORTED:
508 ret = SOCKS5_ERR_COM_UNSUPPORTED;
510 case SOCKS_ADDRESS_NOT_SUPPORTED:
511 ret = SOCKS5_ERR_ADDR_UNSUPPORTED;
514 ret = SOCKS5_ERR_UNSPECIFIED;
526 * Perform SOCKS5 initialization
529 fetch_socks5_getenv(char **host, int *port)
531 char *socks5env, *endptr, *ext;
532 const char *portDelim;
536 if ((socks5env = getenv("SOCKS5_PROXY")) == NULL || *socks5env == '\0') {
543 * IPv6 addresses begin and end in brackets. Set the port delimiter
544 * accordingly and search for it so we can do appropriate validation.
546 if (socks5env[0] == '[')
549 slen = strlen(socks5env);
550 ext = strstr(socks5env, portDelim);
551 if (socks5env[0] == '[') {
552 if (socks5env[slen - 1] == ']') {
553 *host = strndup(socks5env, slen);
554 } else if (ext != NULL) {
555 *host = strndup(socks5env, ext - socks5env + 1);
557 socks5_seterr(SOCKS5_ERR_BAD_PROXY_FORMAT);
561 *host = strndup(socks5env, ext - socks5env);
565 fprintf(stderr, "Failure to allocate memory, exiting.\n");
569 *port = 1080; /* Default port as defined in RFC1928 */
571 ext += strlen(portDelim);
573 *port = strtoimax(ext, (char **)&endptr, 10);
574 if (*endptr != '\0' || errno != 0 || *port < 0 ||
578 socks5_seterr(SOCKS5_ERR_BAD_PORT);
588 * Establish a TCP connection to the specified port on the specified host.
591 fetch_connect(const char *host, int port, int af, int verbose)
593 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
594 const char *bindaddr;
596 int err = 0, sd = -1;
600 DEBUGF("---> %s:%d\n", host, port);
603 * Check if SOCKS5_PROXY env variable is set. fetch_socks5_getenv
604 * will either set sockshost = NULL or allocate memory in all cases.
607 if (!fetch_socks5_getenv(&sockshost, &socksport))
610 /* Not using SOCKS5 proxy */
611 if (sockshost == NULL) {
612 /* resolve server address */
614 fetch_info("resolving server address: %s:%d", host,
616 if ((sais = fetch_resolve(host, port, af)) == NULL)
619 /* resolve client address */
620 bindaddr = getenv("FETCH_BIND_ADDRESS");
621 if (bindaddr != NULL && *bindaddr != '\0') {
623 fetch_info("resolving client address: %s",
625 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
629 /* resolve socks5 proxy address */
631 fetch_info("resolving SOCKS5 server address: %s:%d",
632 sockshost, socksport);
633 if ((sais = fetch_resolve(sockshost, socksport, af)) == NULL) {
634 socks5_seterr(SOCKS5_ERR_BAD_HOST);
639 /* try each server address in turn */
640 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
642 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
644 /* attempt to bind to client address */
645 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
646 if (cai->ai_family != sai->ai_family)
648 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
653 fetch_info("failed to bind to %s", bindaddr);
656 /* attempt to connect to server address */
657 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
659 /* clean up before next attempt */
664 if (verbose && sockshost == NULL) {
665 fetch_info("failed to connect to %s:%d", host, port);
667 } else if (sockshost != NULL) {
670 "failed to connect to SOCKS5 server %s:%d",
671 sockshost, socksport);
672 socks5_seterr(SOCKS5_ERR_CONN_REFUSED);
678 if ((conn = fetch_reopen(sd)) == NULL)
682 if (!fetch_socks5_init(conn, host, port, verbose))
694 /* Fully close if it was opened; otherwise just don't leak the fd. */
708 * Convert characters A-Z to lowercase (intentionally avoid any locale
709 * specific conversions).
712 fetch_ssl_tolower(char in)
714 if (in >= 'A' && in <= 'Z')
721 * isalpha implementation that intentionally avoids any locale specific
725 fetch_ssl_isalpha(char in)
727 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
731 * Check if passed hostnames a and b are equal.
734 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
741 for (i = 0; i < alen; ++i) {
742 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
749 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
750 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
751 * numeric characters. Double hyphens (like they're found in IDN a-labels
752 * 'xn--') are not allowed. Empty labels are invalid.
755 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
759 if (!len || l[0] == '-' || l[len-1] == '-')
761 for (i = 0; i < len; ++i) {
762 if (!isdigit(l[i]) &&
763 !fetch_ssl_isalpha(l[i]) &&
764 !(l[i] == '*' && wcok) &&
765 !(l[i] == '-' && l[i - 1] != '-'))
772 * Check if host name consists only of numbers. This might indicate an IP
773 * address, which is not a good idea for CN wildcard comparison.
776 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
780 for (i = 0; i < len; ++i) {
781 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
789 * Check if the host name h passed matches the pattern passed in m which
790 * is usually part of subjectAltName or CN of a certificate presented to
791 * the client. This includes wildcard matching. The algorithm is based on
792 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
795 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
798 int delta, hdotidx, mdot1idx, wcidx;
799 const char *hdot, *mdot1, *mdot2;
800 const char *wc; /* wildcard */
802 if (!(h && *h && m && *m))
804 if ((wc = strnstr(m, "*", mlen)) == NULL)
805 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
807 /* hostname should not be just dots and numbers */
808 if (fetch_ssl_hname_is_only_numbers(h, hlen))
810 /* only one wildcard allowed in pattern */
811 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
814 * there must be at least two more domain labels and
815 * wildcard has to be in the leftmost label (RFC6125)
817 mdot1 = strnstr(m, ".", mlen);
818 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
820 mdot1idx = mdot1 - m;
821 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
822 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
824 /* hostname must contain a dot and not be the 1st char */
825 hdot = strnstr(h, ".", hlen);
826 if (hdot == NULL || hdot == h)
830 * host part of hostname must be at least as long as
831 * pattern it's supposed to match
833 if (hdotidx < mdot1idx)
836 * don't allow wildcards in non-traditional domain names
837 * (IDN, A-label, U-label...)
839 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
840 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
842 /* match domain part (part after first dot) */
843 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
846 /* match part left of wildcard */
847 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
849 /* match part right of wildcard */
850 delta = mdot1idx - wcidx - 1;
851 if (!fetch_ssl_hname_equal(hdot - delta, delta,
852 mdot1 - delta, delta))
854 /* all tests succeeded, it's a match */
859 * Get numeric host address info - returns NULL if host was not an IP
860 * address. The caller is responsible for deallocation using
863 static struct addrinfo *
864 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
866 struct addrinfo hints, *res;
869 host = (char *)malloc(len + 1);
870 memcpy(host, hostname, len);
872 memset(&hints, 0, sizeof(hints));
873 hints.ai_family = PF_UNSPEC;
874 hints.ai_socktype = SOCK_STREAM;
875 hints.ai_protocol = 0;
876 hints.ai_flags = AI_NUMERICHOST;
877 /* port is not relevant for this purpose */
878 if (getaddrinfo(host, "443", &hints, &res) != 0)
885 * Compare ip address in addrinfo with address passes.
888 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
893 if (lhost->ai_family == AF_INET && rhostlen == 4) {
894 left = (void *)&((struct sockaddr_in*)(void *)
895 lhost->ai_addr)->sin_addr.s_addr;
897 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
898 left = (void *)&((struct sockaddr_in6 *)(void *)
899 lhost->ai_addr)->sin6_addr;
903 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
907 * Compare ip address in addrinfo with host passed. If host is not an IP
908 * address, comparison will fail.
911 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
914 struct addrinfo *raddr;
919 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
920 return 0; /* not a numeric host */
922 if (laddr->ai_family == raddr->ai_family) {
923 if (laddr->ai_family == AF_INET) {
924 rip = (char *)&((struct sockaddr_in *)(void *)
925 raddr->ai_addr)->sin_addr.s_addr;
926 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
928 } else if (laddr->ai_family == AF_INET6) {
929 rip = (char *)&((struct sockaddr_in6 *)(void *)
930 raddr->ai_addr)->sin6_addr;
931 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
941 * Verify server certificate by subjectAltName.
944 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
945 const char *host, struct addrinfo *ip)
947 const GENERAL_NAME *name;
952 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
953 #if OPENSSL_VERSION_NUMBER < 0x10000000L
955 * This is a workaround, since the following line causes
956 * alignment issues in clang:
957 * name = sk_GENERAL_NAME_value(altnames, i);
958 * OpenSSL explicitly warns not to use those macros
959 * directly, but there isn't much choice (and there
960 * shouldn't be any ill side effects)
962 name = (GENERAL_NAME *)SKM_sk_value(void, altnames, i);
964 name = sk_GENERAL_NAME_value(altnames, i);
966 #if OPENSSL_VERSION_NUMBER < 0x10100000L
967 ns = (const char *)ASN1_STRING_data(name->d.ia5);
969 ns = (const char *)ASN1_STRING_get0_data(name->d.ia5);
971 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
973 if (name->type == GEN_DNS && ip == NULL &&
974 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
976 else if (name->type == GEN_IPADD && ip != NULL &&
977 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
984 * Verify server certificate by CN.
987 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
990 ASN1_STRING *namedata;
991 X509_NAME_ENTRY *nameentry;
992 int cnlen, lastpos, loc, ret;
999 /* get most specific CN (last entry in list) and compare */
1000 while ((lastpos = X509_NAME_get_index_by_NID(subject,
1001 NID_commonName, lastpos)) != -1)
1005 nameentry = X509_NAME_get_entry(subject, loc);
1006 namedata = X509_NAME_ENTRY_get_data(nameentry);
1007 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
1009 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
1011 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
1019 * Verify that server certificate subjectAltName/CN matches
1020 * hostname. First check, if there are alternative subject names. If yes,
1021 * those have to match. Only if those don't exist it falls back to
1022 * checking the subject's CN.
1025 fetch_ssl_verify_hname(X509 *cert, const char *host)
1027 struct addrinfo *ip;
1028 STACK_OF(GENERAL_NAME) *altnames;
1033 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
1034 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
1037 if (altnames != NULL) {
1038 ret = fetch_ssl_verify_altname(altnames, host, ip);
1040 subject = X509_get_subject_name(cert);
1041 if (subject != NULL)
1042 ret = fetch_ssl_verify_cn(subject, host, ip);
1047 if (altnames != NULL)
1048 GENERAL_NAMES_free(altnames);
1053 * Configure transport security layer based on environment.
1056 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
1058 long ssl_ctx_options;
1060 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv3 | SSL_OP_NO_TICKET;
1061 if (getenv("SSL_NO_TLS1") != NULL)
1062 ssl_ctx_options |= SSL_OP_NO_TLSv1;
1063 if (getenv("SSL_NO_TLS1_1") != NULL)
1064 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
1065 if (getenv("SSL_NO_TLS1_2") != NULL)
1066 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
1068 fetch_info("SSL options: %lx", ssl_ctx_options);
1069 SSL_CTX_set_options(ctx, ssl_ctx_options);
1074 * Configure peer verification based on environment.
1076 #define LOCAL_CERT_FILE _PATH_LOCALBASE "/etc/ssl/cert.pem"
1077 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
1079 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
1081 X509_LOOKUP *crl_lookup;
1082 X509_STORE *crl_store;
1083 const char *ca_cert_file, *ca_cert_path, *crl_file;
1085 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
1086 ca_cert_file = getenv("SSL_CA_CERT_FILE");
1087 if (ca_cert_file == NULL &&
1088 access(LOCAL_CERT_FILE, R_OK) == 0)
1089 ca_cert_file = LOCAL_CERT_FILE;
1090 if (ca_cert_file == NULL &&
1091 access(BASE_CERT_FILE, R_OK) == 0)
1092 ca_cert_file = BASE_CERT_FILE;
1093 ca_cert_path = getenv("SSL_CA_CERT_PATH");
1095 fetch_info("Peer verification enabled");
1096 if (ca_cert_file != NULL)
1097 fetch_info("Using CA cert file: %s",
1099 if (ca_cert_path != NULL)
1100 fetch_info("Using CA cert path: %s",
1102 if (ca_cert_file == NULL && ca_cert_path == NULL)
1103 fetch_info("Using OpenSSL default "
1104 "CA cert file and path");
1106 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
1107 fetch_ssl_cb_verify_crt);
1108 if (ca_cert_file != NULL || ca_cert_path != NULL)
1109 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
1112 SSL_CTX_set_default_verify_paths(ctx);
1113 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
1115 fetch_info("Using CRL file: %s", crl_file);
1116 crl_store = SSL_CTX_get_cert_store(ctx);
1117 crl_lookup = X509_STORE_add_lookup(crl_store,
1118 X509_LOOKUP_file());
1119 if (crl_lookup == NULL ||
1120 !X509_load_crl_file(crl_lookup, crl_file,
1121 X509_FILETYPE_PEM)) {
1123 "Could not load CRL file %s\n",
1127 X509_STORE_set_flags(crl_store,
1128 X509_V_FLAG_CRL_CHECK |
1129 X509_V_FLAG_CRL_CHECK_ALL);
1136 * Configure client certificate based on environment.
1139 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
1141 const char *client_cert_file, *client_key_file;
1143 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
1144 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
1145 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
1147 fetch_info("Using client cert file: %s",
1149 fetch_info("Using client key file: %s",
1152 if (SSL_CTX_use_certificate_chain_file(ctx,
1153 client_cert_file) != 1) {
1155 "Could not load client certificate %s\n",
1159 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
1160 SSL_FILETYPE_PEM) != 1) {
1162 "Could not load client key %s\n",
1171 * Callback for SSL certificate verification, this is called on server
1172 * cert verification. It takes no decision, but informs the user in case
1173 * verification failed.
1176 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
1184 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
1185 (name = X509_get_subject_name(crt)) != NULL)
1186 str = X509_NAME_oneline(name, 0, 0);
1187 fprintf(stderr, "Certificate verification failed for %s\n",
1188 str != NULL ? str : "no relevant certificate");
1197 * Enable SSL on a connection.
1200 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
1207 /* Init the SSL library and context */
1208 if (!SSL_library_init()){
1209 fprintf(stderr, "SSL library init failed\n");
1213 SSL_load_error_strings();
1215 conn->ssl_meth = SSLv23_client_method();
1216 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
1217 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
1219 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
1220 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
1222 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
1225 conn->ssl = SSL_new(conn->ssl_ctx);
1226 if (conn->ssl == NULL) {
1227 fprintf(stderr, "SSL context creation failed\n");
1230 SSL_set_fd(conn->ssl, conn->sd);
1232 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
1233 if (!SSL_set_tlsext_host_name(conn->ssl,
1234 __DECONST(struct url *, URL)->host)) {
1236 "TLS server name indication extension failed for host %s\n",
1241 while ((ret = SSL_connect(conn->ssl)) == -1) {
1242 ssl_err = SSL_get_error(conn->ssl, ret);
1243 if (ssl_err != SSL_ERROR_WANT_READ &&
1244 ssl_err != SSL_ERROR_WANT_WRITE) {
1245 ERR_print_errors_fp(stderr);
1249 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
1251 if (conn->ssl_cert == NULL) {
1252 fprintf(stderr, "No server SSL certificate\n");
1256 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
1258 fetch_info("Verify hostname");
1259 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
1261 "SSL certificate subject doesn't match host %s\n",
1268 fetch_info("%s connection established using %s",
1269 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
1270 name = X509_get_subject_name(conn->ssl_cert);
1271 str = X509_NAME_oneline(name, 0, 0);
1272 fetch_info("Certificate subject: %s", str);
1274 name = X509_get_issuer_name(conn->ssl_cert);
1275 str = X509_NAME_oneline(name, 0, 0);
1276 fetch_info("Certificate issuer: %s", str);
1285 fprintf(stderr, "SSL support disabled\n");
1290 #define FETCH_READ_WAIT -2
1291 #define FETCH_READ_ERROR -1
1292 #define FETCH_READ_DONE 0
1296 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1301 rlen = SSL_read(ssl, buf, len);
1303 ssl_err = SSL_get_error(ssl, rlen);
1304 if (ssl_err == SSL_ERROR_WANT_READ ||
1305 ssl_err == SSL_ERROR_WANT_WRITE) {
1306 return (FETCH_READ_WAIT);
1308 ERR_print_errors_fp(stderr);
1309 return (FETCH_READ_ERROR);
1317 fetch_socket_read(int sd, char *buf, size_t len)
1321 rlen = read(sd, buf, len);
1323 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1324 return (FETCH_READ_WAIT);
1326 return (FETCH_READ_ERROR);
1332 * Read a character from a connection w/ timeout
1335 fetch_read(conn_t *conn, char *buf, size_t len)
1337 struct timeval now, timeout, delta;
1342 if (fetchTimeout > 0) {
1343 gettimeofday(&timeout, NULL);
1344 timeout.tv_sec += fetchTimeout;
1348 memset(&pfd, 0, sizeof pfd);
1350 pfd.events = POLLIN | POLLERR;
1354 * The socket is non-blocking. Instead of the canonical
1355 * poll() -> read(), we do the following:
1357 * 1) call read() or SSL_read().
1358 * 2) if we received some data, return it.
1359 * 3) if an error occurred, return -1.
1360 * 4) if read() or SSL_read() signaled EOF, return.
1361 * 5) if we did not receive any data but we're not at EOF,
1364 * In the SSL case, this is necessary because if we
1365 * receive a close notification, we have to call
1366 * SSL_read() one additional time after we've read
1367 * everything we received.
1369 * In the non-SSL case, it may improve performance (very
1370 * slightly) when reading small amounts of data.
1373 if (conn->ssl != NULL)
1374 rlen = fetch_ssl_read(conn->ssl, buf, len);
1377 rlen = fetch_socket_read(conn->sd, buf, len);
1380 } else if (rlen == FETCH_READ_ERROR) {
1384 // assert(rlen == FETCH_READ_WAIT);
1385 if (fetchTimeout > 0) {
1386 gettimeofday(&now, NULL);
1387 if (!timercmp(&timeout, &now, >)) {
1392 timersub(&timeout, &now, &delta);
1393 deltams = delta.tv_sec * 1000 +
1394 delta.tv_usec / 1000;;
1398 if (poll(&pfd, 1, deltams) < 0) {
1399 if (errno == EINTR && fetchRestartCalls)
1410 * Read a line of text from a connection w/ timeout
1412 #define MIN_BUF_SIZE 1024
1415 fetch_getln(conn_t *conn)
1422 if (conn->buf == NULL) {
1423 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1427 conn->bufsize = MIN_BUF_SIZE;
1430 conn->buf[0] = '\0';
1434 len = fetch_read(conn, &c, 1);
1439 conn->buf[conn->buflen++] = c;
1440 if (conn->buflen == conn->bufsize) {
1442 tmpsize = conn->bufsize * 2 + 1;
1443 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1448 conn->bufsize = tmpsize;
1450 } while (c != '\n');
1452 conn->buf[conn->buflen] = '\0';
1453 DEBUGF("<<< %s", conn->buf);
1459 * Write to a connection w/ timeout
1462 fetch_write(conn_t *conn, const char *buf, size_t len)
1466 iov.iov_base = __DECONST(char *, buf);
1468 return fetch_writev(conn, &iov, 1);
1472 * Write a vector to a connection w/ timeout
1473 * Note: can modify the iovec.
1476 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1478 struct timeval now, timeout, delta;
1480 ssize_t wlen, total;
1483 memset(&pfd, 0, sizeof pfd);
1486 pfd.events = POLLOUT | POLLERR;
1487 gettimeofday(&timeout, NULL);
1488 timeout.tv_sec += fetchTimeout;
1492 while (iovcnt > 0) {
1493 while (fetchTimeout && pfd.revents == 0) {
1494 gettimeofday(&now, NULL);
1495 if (!timercmp(&timeout, &now, >)) {
1500 timersub(&timeout, &now, &delta);
1501 deltams = delta.tv_sec * 1000 +
1502 delta.tv_usec / 1000;
1505 if (poll(&pfd, 1, deltams) < 0) {
1506 /* POSIX compliance */
1507 if (errno == EAGAIN)
1509 if (errno == EINTR && fetchRestartCalls)
1516 if (conn->ssl != NULL)
1517 wlen = SSL_write(conn->ssl,
1518 iov->iov_base, iov->iov_len);
1521 wlen = writev(conn->sd, iov, iovcnt);
1523 /* we consider a short write a failure */
1524 /* XXX perhaps we shouldn't in the SSL case */
1530 if (errno == EINTR && fetchRestartCalls)
1535 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1536 wlen -= iov->iov_len;
1541 iov->iov_len -= wlen;
1542 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1550 * Write a line of text to a connection w/ timeout
1553 fetch_putln(conn_t *conn, const char *str, size_t len)
1555 struct iovec iov[2];
1558 DEBUGF(">>> %s\n", str);
1559 iov[0].iov_base = __DECONST(char *, str);
1560 iov[0].iov_len = len;
1561 iov[1].iov_base = __DECONST(char *, ENDL);
1562 iov[1].iov_len = sizeof(ENDL);
1564 ret = fetch_writev(conn, &iov[1], 1);
1566 ret = fetch_writev(conn, iov, 2);
1577 fetch_close(conn_t *conn)
1581 if (--conn->ref > 0)
1585 SSL_shutdown(conn->ssl);
1586 SSL_set_connect_state(conn->ssl);
1587 SSL_free(conn->ssl);
1590 if (conn->ssl_ctx) {
1591 SSL_CTX_free(conn->ssl_ctx);
1592 conn->ssl_ctx = NULL;
1594 if (conn->ssl_cert) {
1595 X509_free(conn->ssl_cert);
1596 conn->ssl_cert = NULL;
1599 ret = close(conn->sd);
1606 /*** Directory-related utility functions *************************************/
1609 fetch_add_entry(struct url_ent **p, int *size, int *len,
1610 const char *name, struct url_stat *us)
1612 struct url_ent *tmp;
1619 if (*len >= *size - 1) {
1620 tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1626 *size = (*size * 2 + 1);
1631 snprintf(tmp->name, PATH_MAX, "%s", name);
1632 memcpy(&tmp->stat, us, sizeof(*us));
1635 (++tmp)->name[0] = 0;
1641 /*** Authentication-related utility functions ********************************/
1644 fetch_read_word(FILE *f)
1646 static char word[1024];
1648 if (fscanf(f, " %1023s ", word) != 1)
1654 fetch_netrc_open(void)
1661 if ((p = getenv("NETRC")) != NULL) {
1662 DEBUGF("NETRC=%s\n", p);
1663 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1664 fetch_info("$NETRC specifies a file name "
1665 "longer than PATH_MAX");
1669 if ((p = getenv("HOME")) == NULL) {
1670 if ((pwd = getpwuid(getuid())) == NULL ||
1671 (p = pwd->pw_dir) == NULL)
1674 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1678 if ((fd = open(fn, O_RDONLY)) < 0) {
1680 DEBUGF("%s: %s\n", fn, strerror(serrno));
1687 * Get authentication data for a URL from .netrc
1690 fetch_netrc_auth(struct url *url)
1696 if (url->netrcfd < 0)
1697 url->netrcfd = fetch_netrc_open();
1698 if (url->netrcfd < 0)
1700 if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1702 DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1703 close(url->netrcfd);
1709 DEBUGF("searching netrc for %s\n", url->host);
1710 while ((word = fetch_read_word(f)) != NULL) {
1711 if (strcmp(word, "default") == 0) {
1712 DEBUGF("using default netrc settings\n");
1715 if (strcmp(word, "machine") == 0 &&
1716 (word = fetch_read_word(f)) != NULL &&
1717 strcasecmp(word, url->host) == 0) {
1718 DEBUGF("using netrc settings for %s\n", word);
1724 while ((word = fetch_read_word(f)) != NULL) {
1725 if (strcmp(word, "login") == 0) {
1726 if ((word = fetch_read_word(f)) == NULL)
1728 if (snprintf(url->user, sizeof(url->user),
1729 "%s", word) > (int)sizeof(url->user)) {
1730 fetch_info("login name in .netrc is too long");
1731 url->user[0] = '\0';
1733 } else if (strcmp(word, "password") == 0) {
1734 if ((word = fetch_read_word(f)) == NULL)
1736 if (snprintf(url->pwd, sizeof(url->pwd),
1737 "%s", word) > (int)sizeof(url->pwd)) {
1738 fetch_info("password in .netrc is too long");
1741 } else if (strcmp(word, "account") == 0) {
1742 if ((word = fetch_read_word(f)) == NULL)
1744 /* XXX not supported! */
1761 * The no_proxy environment variable specifies a set of domains for
1762 * which the proxy should not be consulted; the contents is a comma-,
1763 * or space-separated list of domain names. A single asterisk will
1764 * override all proxy variables and no transactions will be proxied
1765 * (for compatibility with lynx and curl, see the discussion at
1766 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1769 fetch_no_proxy_match(const char *host)
1771 const char *no_proxy, *p, *q;
1772 size_t h_len, d_len;
1774 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1775 (no_proxy = getenv("no_proxy")) == NULL)
1778 /* asterisk matches any hostname */
1779 if (strcmp(no_proxy, "*") == 0)
1782 h_len = strlen(host);
1785 /* position p at the beginning of a domain suffix */
1786 while (*p == ',' || isspace((unsigned char)*p))
1789 /* position q at the first separator character */
1790 for (q = p; *q; ++q)
1791 if (*q == ',' || isspace((unsigned char)*q))
1795 if (d_len > 0 && h_len >= d_len &&
1796 strncasecmp(host + h_len - d_len,
1798 /* domain name matches */