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 #include <sys/param.h>
34 #include <sys/socket.h>
38 #include <netinet/in.h>
55 #include <openssl/x509v3.h>
62 /*** Local data **************************************************************/
65 * Error messages for resolver errors
67 static struct fetcherr netdb_errlist[] = {
69 { EAI_ADDRFAMILY, FETCH_RESOLV, "Address family for host not supported" },
72 { EAI_NODATA, FETCH_RESOLV, "No address for host" },
74 { EAI_AGAIN, FETCH_TEMP, "Transient resolver failure" },
75 { EAI_FAIL, FETCH_RESOLV, "Non-recoverable resolver failure" },
76 { EAI_NONAME, FETCH_RESOLV, "Host does not resolve" },
77 { -1, FETCH_UNKNOWN, "Unknown resolver error" }
81 * SOCKS5 error enumerations
86 SOCKS5_ERR_READ_METHOD,
89 SOCKS5_ERR_NOTIMPLEMENTED,
90 SOCKS5_ERR_HOSTNAME_SIZE,
93 SOCKS5_ERR_NON_VER5_RESP,
95 SOCKS5_ERR_NOT_ALLOWED,
96 SOCKS5_ERR_NET_UNREACHABLE,
97 SOCKS5_ERR_HOST_UNREACHABLE,
98 SOCKS5_ERR_CONN_REFUSED,
99 SOCKS5_ERR_TTL_EXPIRED,
100 SOCKS5_ERR_COM_UNSUPPORTED,
101 SOCKS5_ERR_ADDR_UNSUPPORTED,
102 SOCKS5_ERR_UNSPECIFIED,
103 /* Configuration errors */
105 SOCKS5_ERR_BAD_PROXY_FORMAT,
110 * Error messages for SOCKS5 errors
112 static struct fetcherr socks5_errlist[] = {
113 /* SOCKS5 protocol errors */
114 { SOCKS5_ERR_SELECTION, FETCH_ABORT, "SOCKS5: Failed to send selection method" },
115 { SOCKS5_ERR_READ_METHOD, FETCH_ABORT, "SOCKS5: Failed to read method" },
116 { SOCKS5_ERR_VER5_ONLY, FETCH_PROTO, "SOCKS5: Only version 5 is implemented" },
117 { SOCKS5_ERR_NOMETHODS, FETCH_PROTO, "SOCKS5: No acceptable methods" },
118 { SOCKS5_ERR_NOTIMPLEMENTED, FETCH_PROTO, "SOCKS5: Method currently not implemented" },
119 { SOCKS5_ERR_HOSTNAME_SIZE, FETCH_PROTO, "SOCKS5: Hostname size is above 256 bytes" },
120 { SOCKS5_ERR_REQUEST, FETCH_PROTO, "SOCKS5: Failed to request" },
121 { SOCKS5_ERR_REPLY, FETCH_PROTO, "SOCKS5: Failed to receive reply" },
122 { SOCKS5_ERR_NON_VER5_RESP, FETCH_PROTO, "SOCKS5: Server responded with a non-version 5 response" },
123 { SOCKS5_ERR_GENERAL, FETCH_ABORT, "SOCKS5: General server failure" },
124 { SOCKS5_ERR_NOT_ALLOWED, FETCH_AUTH, "SOCKS5: Connection not allowed by ruleset" },
125 { SOCKS5_ERR_NET_UNREACHABLE, FETCH_NETWORK, "SOCKS5: Network unreachable" },
126 { SOCKS5_ERR_HOST_UNREACHABLE, FETCH_ABORT, "SOCKS5: Host unreachable" },
127 { SOCKS5_ERR_CONN_REFUSED, FETCH_ABORT, "SOCKS5: Connection refused" },
128 { SOCKS5_ERR_TTL_EXPIRED, FETCH_TIMEOUT, "SOCKS5: TTL expired" },
129 { SOCKS5_ERR_COM_UNSUPPORTED, FETCH_PROTO, "SOCKS5: Command not supported" },
130 { SOCKS5_ERR_ADDR_UNSUPPORTED, FETCH_ABORT, "SOCKS5: Address type not supported" },
131 { SOCKS5_ERR_UNSPECIFIED, FETCH_UNKNOWN, "SOCKS5: Unspecified error" },
132 /* Configuration error */
133 { SOCKS5_ERR_BAD_HOST, FETCH_ABORT, "SOCKS5: Bad proxy host" },
134 { SOCKS5_ERR_BAD_PROXY_FORMAT, FETCH_ABORT, "SOCKS5: Bad proxy format" },
135 { SOCKS5_ERR_BAD_PORT, FETCH_ABORT, "SOCKS5: Bad port" }
139 static const char ENDL[2] = "\r\n";
142 /*** Error-reporting functions ***********************************************/
145 * Map error code to string
147 static struct fetcherr *
148 fetch_finderr(struct fetcherr *p, int e)
150 while (p->num != -1 && p->num != e)
159 fetch_seterr(struct fetcherr *p, int e)
161 p = fetch_finderr(p, e);
162 fetchLastErrCode = p->cat;
163 snprintf(fetchLastErrString, MAXERRSTRING, "%s", p->string);
167 * Set error code according to errno
174 fetchLastErrCode = FETCH_OK;
181 fetchLastErrCode = FETCH_AUTH;
184 case EISDIR: /* XXX */
185 fetchLastErrCode = FETCH_UNAVAIL;
188 fetchLastErrCode = FETCH_MEMORY;
192 fetchLastErrCode = FETCH_TEMP;
195 fetchLastErrCode = FETCH_EXISTS;
198 fetchLastErrCode = FETCH_FULL;
206 fetchLastErrCode = FETCH_NETWORK;
210 fetchLastErrCode = FETCH_ABORT;
213 fetchLastErrCode = FETCH_TIMEOUT;
217 fetchLastErrCode = FETCH_DOWN;
220 fetchLastErrCode = FETCH_UNKNOWN;
222 snprintf(fetchLastErrString, MAXERRSTRING, "%s", strerror(errno));
227 * Emit status message
230 fetch_info(const char *fmt, ...)
235 vfprintf(stderr, fmt, ap);
241 /*** Network-related utility functions ***************************************/
244 * Return the default port for a scheme
247 fetch_default_port(const char *scheme)
251 if ((se = getservbyname(scheme, "tcp")) != NULL)
252 return (ntohs(se->s_port));
253 if (strcmp(scheme, SCHEME_FTP) == 0)
254 return (FTP_DEFAULT_PORT);
255 if (strcmp(scheme, SCHEME_HTTP) == 0)
256 return (HTTP_DEFAULT_PORT);
261 * Return the default proxy port for a scheme
264 fetch_default_proxy_port(const char *scheme)
266 if (strcmp(scheme, SCHEME_FTP) == 0)
267 return (FTP_DEFAULT_PROXY_PORT);
268 if (strcmp(scheme, SCHEME_HTTP) == 0)
269 return (HTTP_DEFAULT_PROXY_PORT);
275 * Create a connection for an existing descriptor.
283 /* allocate and fill connection structure */
284 if ((conn = calloc(1, sizeof(*conn))) == NULL)
286 fcntl(sd, F_SETFD, FD_CLOEXEC);
287 setsockopt(sd, SOL_SOCKET, SO_NOSIGPIPE, &opt, sizeof opt);
295 * Bump a connection's reference count.
298 fetch_ref(conn_t *conn)
310 fetch_resolve(const char *addr, int port, int af)
312 char hbuf[256], sbuf[8];
313 struct addrinfo hints, *res;
314 const char *hb, *he, *sep;
315 const char *host, *service;
318 /* first, check for a bracketed IPv6 address */
321 if ((sep = strchr(hb, ']')) == NULL) {
328 sep = strchrnul(hb, ':');
332 /* see if we need to copy the host name */
334 len = snprintf(hbuf, sizeof(hbuf),
335 "%.*s", (int)(he - hb), hb);
338 if (len >= (int)sizeof(hbuf)) {
339 errno = ENAMETOOLONG;
347 /* was it followed by a service name? */
348 if (*sep == '\0' && port != 0) {
349 if (port < 1 || port > 65535) {
353 if (snprintf(sbuf, sizeof(sbuf), "%d", port) < 0)
356 } else if (*sep != '\0') {
363 memset(&hints, 0, sizeof(hints));
364 hints.ai_family = af;
365 hints.ai_socktype = SOCK_STREAM;
366 hints.ai_flags = AI_ADDRCONFIG;
367 if ((err = getaddrinfo(host, service, &hints, &res)) != 0) {
379 * Bind a socket to a specific local address
382 fetch_bind(int sd, int af, const char *addr)
384 struct addrinfo *cliai, *ai;
387 if ((cliai = fetch_resolve(addr, 0, af)) == NULL)
389 for (ai = cliai; ai != NULL; ai = ai->ai_next)
390 if ((err = bind(sd, ai->ai_addr, ai->ai_addrlen)) == 0)
395 return (err == 0 ? 0 : -1);
400 * SOCKS5 connection initiation, based on RFC 1928
401 * Default DNS resolution over SOCKS5
404 fetch_socks5_init(conn_t *conn, const char *host, int port, int verbose)
407 * Size is based on largest packet prefix (4 bytes) +
408 * Largest FQDN (256) + one byte size (1) +
411 unsigned char buf[BUFF_SIZE];
416 fetch_info("Initializing SOCKS5 connection: %s:%d", host, port);
418 /* Connection initialization */
420 *ptr++ = SOCKS_VERSION_5;
421 *ptr++ = SOCKS_CONNECTION;
424 if (fetch_write(conn, buf, 3) != 3) {
425 ret = SOCKS5_ERR_SELECTION;
429 /* Verify response from SOCKS5 server */
430 if (fetch_read(conn, buf, 2) != 2) {
431 ret = SOCKS5_ERR_READ_METHOD;
436 if (ptr[0] != SOCKS_VERSION_5) {
437 ret = SOCKS5_ERR_VER5_ONLY;
440 if (ptr[1] == SOCKS_NOMETHODS) {
441 ret = SOCKS5_ERR_NOMETHODS;
444 else if (ptr[1] != SOCKS5_NOTIMPLEMENTED) {
445 ret = SOCKS5_ERR_NOTIMPLEMENTED;
450 *ptr++ = SOCKS_VERSION_5;
451 *ptr++ = SOCKS_CONNECTION;
453 /* Encode all targets as a hostname to avoid DNS leaks */
454 *ptr++ = SOCKS_ATYP_DOMAINNAME;
455 if (strlen(host) > FQDN_SIZE) {
456 ret = SOCKS5_ERR_HOSTNAME_SIZE;
459 *ptr++ = strlen(host);
460 memcpy(ptr, host, strlen(host));
461 ptr = ptr + strlen(host);
464 *ptr++ = port & 0x00ff;
465 *ptr++ = (port & 0xff00) >> 8;
467 if (fetch_write(conn, buf, ptr - buf) != ptr - buf) {
468 ret = SOCKS5_ERR_REQUEST;
472 /* BND.ADDR is variable length, read the largest on non-blocking socket */
473 if (!fetch_read(conn, buf, BUFF_SIZE)) {
474 ret = SOCKS5_ERR_REPLY;
479 if (*ptr++ != SOCKS_VERSION_5) {
480 ret = SOCKS5_ERR_NON_VER5_RESP;
487 case SOCKS_GENERAL_FAILURE:
488 ret = SOCKS5_ERR_GENERAL;
490 case SOCKS_CONNECTION_NOT_ALLOWED:
491 ret = SOCKS5_ERR_NOT_ALLOWED;
493 case SOCKS_NETWORK_UNREACHABLE:
494 ret = SOCKS5_ERR_NET_UNREACHABLE;
496 case SOCKS_HOST_UNREACHABLE:
497 ret = SOCKS5_ERR_HOST_UNREACHABLE;
499 case SOCKS_CONNECTION_REFUSED:
500 ret = SOCKS5_ERR_CONN_REFUSED;
502 case SOCKS_TTL_EXPIRED:
503 ret = SOCKS5_ERR_TTL_EXPIRED;
505 case SOCKS_COMMAND_NOT_SUPPORTED:
506 ret = SOCKS5_ERR_COM_UNSUPPORTED;
508 case SOCKS_ADDRESS_NOT_SUPPORTED:
509 ret = SOCKS5_ERR_ADDR_UNSUPPORTED;
512 ret = SOCKS5_ERR_UNSPECIFIED;
524 * Perform SOCKS5 initialization
527 fetch_socks5_getenv(char **host, int *port)
529 char *socks5env, *endptr, *ext;
530 const char *portDelim;
534 if ((socks5env = getenv("SOCKS5_PROXY")) == NULL || *socks5env == '\0') {
541 * IPv6 addresses begin and end in brackets. Set the port delimiter
542 * accordingly and search for it so we can do appropriate validation.
544 if (socks5env[0] == '[')
547 slen = strlen(socks5env);
548 ext = strstr(socks5env, portDelim);
549 if (socks5env[0] == '[') {
550 if (socks5env[slen - 1] == ']') {
551 *host = strndup(socks5env, slen);
552 } else if (ext != NULL) {
553 *host = strndup(socks5env, ext - socks5env + 1);
555 socks5_seterr(SOCKS5_ERR_BAD_PROXY_FORMAT);
559 *host = strndup(socks5env, ext - socks5env);
563 fprintf(stderr, "Failure to allocate memory, exiting.\n");
567 *port = 1080; /* Default port as defined in RFC1928 */
569 ext += strlen(portDelim);
571 *port = strtoimax(ext, (char **)&endptr, 10);
572 if (*endptr != '\0' || errno != 0 || *port < 0 ||
576 socks5_seterr(SOCKS5_ERR_BAD_PORT);
586 * Establish a TCP connection to the specified port on the specified host.
589 fetch_connect(const char *host, int port, int af, int verbose)
591 struct addrinfo *cais = NULL, *sais = NULL, *cai, *sai;
592 const char *bindaddr;
594 int err = 0, sd = -1;
598 DEBUGF("---> %s:%d\n", host, port);
601 * Check if SOCKS5_PROXY env variable is set. fetch_socks5_getenv
602 * will either set sockshost = NULL or allocate memory in all cases.
605 if (!fetch_socks5_getenv(&sockshost, &socksport))
608 /* Not using SOCKS5 proxy */
609 if (sockshost == NULL) {
610 /* resolve server address */
612 fetch_info("resolving server address: %s:%d", host,
614 if ((sais = fetch_resolve(host, port, af)) == NULL)
617 /* resolve client address */
618 bindaddr = getenv("FETCH_BIND_ADDRESS");
619 if (bindaddr != NULL && *bindaddr != '\0') {
621 fetch_info("resolving client address: %s",
623 if ((cais = fetch_resolve(bindaddr, 0, af)) == NULL)
627 /* resolve socks5 proxy address */
629 fetch_info("resolving SOCKS5 server address: %s:%d",
630 sockshost, socksport);
631 if ((sais = fetch_resolve(sockshost, socksport, af)) == NULL) {
632 socks5_seterr(SOCKS5_ERR_BAD_HOST);
637 /* try each server address in turn */
638 for (err = 0, sai = sais; sai != NULL; sai = sai->ai_next) {
640 if ((sd = socket(sai->ai_family, SOCK_STREAM, 0)) < 0)
642 /* attempt to bind to client address */
643 for (err = 0, cai = cais; cai != NULL; cai = cai->ai_next) {
644 if (cai->ai_family != sai->ai_family)
646 if ((err = bind(sd, cai->ai_addr, cai->ai_addrlen)) == 0)
651 fetch_info("failed to bind to %s", bindaddr);
654 /* attempt to connect to server address */
655 if ((err = connect(sd, sai->ai_addr, sai->ai_addrlen)) == 0)
657 /* clean up before next attempt */
662 if (verbose && sockshost == NULL) {
663 fetch_info("failed to connect to %s:%d", host, port);
665 } else if (sockshost != NULL) {
668 "failed to connect to SOCKS5 server %s:%d",
669 sockshost, socksport);
670 socks5_seterr(SOCKS5_ERR_CONN_REFUSED);
676 if ((conn = fetch_reopen(sd)) == NULL)
680 if (!fetch_socks5_init(conn, host, port, verbose))
692 /* Fully close if it was opened; otherwise just don't leak the fd. */
706 * Convert characters A-Z to lowercase (intentionally avoid any locale
707 * specific conversions).
710 fetch_ssl_tolower(char in)
712 if (in >= 'A' && in <= 'Z')
719 * isalpha implementation that intentionally avoids any locale specific
723 fetch_ssl_isalpha(char in)
725 return ((in >= 'A' && in <= 'Z') || (in >= 'a' && in <= 'z'));
729 * Check if passed hostnames a and b are equal.
732 fetch_ssl_hname_equal(const char *a, size_t alen, const char *b,
739 for (i = 0; i < alen; ++i) {
740 if (fetch_ssl_tolower(a[i]) != fetch_ssl_tolower(b[i]))
747 * Check if domain label is traditional, meaning that only A-Z, a-z, 0-9
748 * and '-' (hyphen) are allowed. Hyphens have to be surrounded by alpha-
749 * numeric characters. Double hyphens (like they're found in IDN a-labels
750 * 'xn--') are not allowed. Empty labels are invalid.
753 fetch_ssl_is_trad_domain_label(const char *l, size_t len, int wcok)
757 if (!len || l[0] == '-' || l[len-1] == '-')
759 for (i = 0; i < len; ++i) {
760 if (!isdigit(l[i]) &&
761 !fetch_ssl_isalpha(l[i]) &&
762 !(l[i] == '*' && wcok) &&
763 !(l[i] == '-' && l[i - 1] != '-'))
770 * Check if host name consists only of numbers. This might indicate an IP
771 * address, which is not a good idea for CN wildcard comparison.
774 fetch_ssl_hname_is_only_numbers(const char *hostname, size_t len)
778 for (i = 0; i < len; ++i) {
779 if (!((hostname[i] >= '0' && hostname[i] <= '9') ||
787 * Check if the host name h passed matches the pattern passed in m which
788 * is usually part of subjectAltName or CN of a certificate presented to
789 * the client. This includes wildcard matching. The algorithm is based on
790 * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280.
793 fetch_ssl_hname_match(const char *h, size_t hlen, const char *m,
796 int delta, hdotidx, mdot1idx, wcidx;
797 const char *hdot, *mdot1, *mdot2;
798 const char *wc; /* wildcard */
800 if (!(h && *h && m && *m))
802 if ((wc = strnstr(m, "*", mlen)) == NULL)
803 return (fetch_ssl_hname_equal(h, hlen, m, mlen));
805 /* hostname should not be just dots and numbers */
806 if (fetch_ssl_hname_is_only_numbers(h, hlen))
808 /* only one wildcard allowed in pattern */
809 if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)
812 * there must be at least two more domain labels and
813 * wildcard has to be in the leftmost label (RFC6125)
815 mdot1 = strnstr(m, ".", mlen);
816 if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)
818 mdot1idx = mdot1 - m;
819 mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);
820 if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)
822 /* hostname must contain a dot and not be the 1st char */
823 hdot = strnstr(h, ".", hlen);
824 if (hdot == NULL || hdot == h)
828 * host part of hostname must be at least as long as
829 * pattern it's supposed to match
831 if (hdotidx < mdot1idx)
834 * don't allow wildcards in non-traditional domain names
835 * (IDN, A-label, U-label...)
837 if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||
838 !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))
840 /* match domain part (part after first dot) */
841 if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,
844 /* match part left of wildcard */
845 if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))
847 /* match part right of wildcard */
848 delta = mdot1idx - wcidx - 1;
849 if (!fetch_ssl_hname_equal(hdot - delta, delta,
850 mdot1 - delta, delta))
852 /* all tests succeeded, it's a match */
857 * Get numeric host address info - returns NULL if host was not an IP
858 * address. The caller is responsible for deallocation using
861 static struct addrinfo *
862 fetch_ssl_get_numeric_addrinfo(const char *hostname, size_t len)
864 struct addrinfo hints, *res;
867 host = (char *)malloc(len + 1);
868 memcpy(host, hostname, len);
870 memset(&hints, 0, sizeof(hints));
871 hints.ai_family = PF_UNSPEC;
872 hints.ai_socktype = SOCK_STREAM;
873 hints.ai_protocol = 0;
874 hints.ai_flags = AI_NUMERICHOST;
875 /* port is not relevant for this purpose */
876 if (getaddrinfo(host, "443", &hints, &res) != 0)
883 * Compare ip address in addrinfo with address passes.
886 fetch_ssl_ipaddr_match_bin(const struct addrinfo *lhost, const char *rhost,
891 if (lhost->ai_family == AF_INET && rhostlen == 4) {
892 left = (void *)&((struct sockaddr_in*)(void *)
893 lhost->ai_addr)->sin_addr.s_addr;
895 } else if (lhost->ai_family == AF_INET6 && rhostlen == 16) {
896 left = (void *)&((struct sockaddr_in6 *)(void *)
897 lhost->ai_addr)->sin6_addr;
901 return (!memcmp(left, (const void *)rhost, rhostlen) ? 1 : 0);
905 * Compare ip address in addrinfo with host passed. If host is not an IP
906 * address, comparison will fail.
909 fetch_ssl_ipaddr_match(const struct addrinfo *laddr, const char *r,
912 struct addrinfo *raddr;
917 if ((raddr = fetch_ssl_get_numeric_addrinfo(r, rlen)) == NULL)
918 return 0; /* not a numeric host */
920 if (laddr->ai_family == raddr->ai_family) {
921 if (laddr->ai_family == AF_INET) {
922 rip = (char *)&((struct sockaddr_in *)(void *)
923 raddr->ai_addr)->sin_addr.s_addr;
924 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 4);
926 } else if (laddr->ai_family == AF_INET6) {
927 rip = (char *)&((struct sockaddr_in6 *)(void *)
928 raddr->ai_addr)->sin6_addr;
929 ret = fetch_ssl_ipaddr_match_bin(laddr, rip, 16);
939 * Verify server certificate by subjectAltName.
942 fetch_ssl_verify_altname(STACK_OF(GENERAL_NAME) *altnames,
943 const char *host, struct addrinfo *ip)
945 const GENERAL_NAME *name;
950 for (i = 0; i < sk_GENERAL_NAME_num(altnames); ++i) {
951 name = sk_GENERAL_NAME_value(altnames, i);
952 ns = (const char *)ASN1_STRING_get0_data(name->d.ia5);
953 nslen = (size_t)ASN1_STRING_length(name->d.ia5);
955 if (name->type == GEN_DNS && ip == NULL &&
956 fetch_ssl_hname_match(host, strlen(host), ns, nslen))
958 else if (name->type == GEN_IPADD && ip != NULL &&
959 fetch_ssl_ipaddr_match_bin(ip, ns, nslen))
966 * Verify server certificate by CN.
969 fetch_ssl_verify_cn(X509_NAME *subject, const char *host,
972 ASN1_STRING *namedata;
973 X509_NAME_ENTRY *nameentry;
974 int cnlen, lastpos, loc, ret;
981 /* get most specific CN (last entry in list) and compare */
982 while ((lastpos = X509_NAME_get_index_by_NID(subject,
983 NID_commonName, lastpos)) != -1)
987 nameentry = X509_NAME_get_entry(subject, loc);
988 namedata = X509_NAME_ENTRY_get_data(nameentry);
989 cnlen = ASN1_STRING_to_UTF8(&cn, namedata);
991 fetch_ssl_hname_match(host, strlen(host), cn, cnlen))
993 else if (ip != NULL && fetch_ssl_ipaddr_match(ip, cn, cnlen))
1001 * Verify that server certificate subjectAltName/CN matches
1002 * hostname. First check, if there are alternative subject names. If yes,
1003 * those have to match. Only if those don't exist it falls back to
1004 * checking the subject's CN.
1007 fetch_ssl_verify_hname(X509 *cert, const char *host)
1009 struct addrinfo *ip;
1010 STACK_OF(GENERAL_NAME) *altnames;
1015 ip = fetch_ssl_get_numeric_addrinfo(host, strlen(host));
1016 altnames = X509_get_ext_d2i(cert, NID_subject_alt_name,
1019 if (altnames != NULL) {
1020 ret = fetch_ssl_verify_altname(altnames, host, ip);
1022 subject = X509_get_subject_name(cert);
1023 if (subject != NULL)
1024 ret = fetch_ssl_verify_cn(subject, host, ip);
1029 if (altnames != NULL)
1030 GENERAL_NAMES_free(altnames);
1035 * Configure transport security layer based on environment.
1038 fetch_ssl_setup_transport_layer(SSL_CTX *ctx, int verbose)
1040 long ssl_ctx_options;
1042 ssl_ctx_options = SSL_OP_ALL | SSL_OP_NO_SSLv3 | SSL_OP_NO_TICKET;
1043 if (getenv("SSL_NO_TLS1") != NULL)
1044 ssl_ctx_options |= SSL_OP_NO_TLSv1;
1045 if (getenv("SSL_NO_TLS1_1") != NULL)
1046 ssl_ctx_options |= SSL_OP_NO_TLSv1_1;
1047 if (getenv("SSL_NO_TLS1_2") != NULL)
1048 ssl_ctx_options |= SSL_OP_NO_TLSv1_2;
1050 fetch_info("SSL options: %lx", ssl_ctx_options);
1051 SSL_CTX_set_options(ctx, ssl_ctx_options);
1056 * Configure peer verification based on environment.
1058 #define LOCAL_CERT_FILE _PATH_LOCALBASE "/etc/ssl/cert.pem"
1059 #define BASE_CERT_FILE "/etc/ssl/cert.pem"
1061 fetch_ssl_setup_peer_verification(SSL_CTX *ctx, int verbose)
1063 X509_LOOKUP *crl_lookup;
1064 X509_STORE *crl_store;
1065 const char *ca_cert_file, *ca_cert_path, *crl_file;
1067 if (getenv("SSL_NO_VERIFY_PEER") == NULL) {
1068 ca_cert_file = getenv("SSL_CA_CERT_FILE");
1069 if (ca_cert_file == NULL &&
1070 access(LOCAL_CERT_FILE, R_OK) == 0)
1071 ca_cert_file = LOCAL_CERT_FILE;
1072 if (ca_cert_file == NULL &&
1073 access(BASE_CERT_FILE, R_OK) == 0)
1074 ca_cert_file = BASE_CERT_FILE;
1075 ca_cert_path = getenv("SSL_CA_CERT_PATH");
1077 fetch_info("Peer verification enabled");
1078 if (ca_cert_file != NULL)
1079 fetch_info("Using CA cert file: %s",
1081 if (ca_cert_path != NULL)
1082 fetch_info("Using CA cert path: %s",
1084 if (ca_cert_file == NULL && ca_cert_path == NULL)
1085 fetch_info("Using OpenSSL default "
1086 "CA cert file and path");
1088 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER,
1089 fetch_ssl_cb_verify_crt);
1090 if (ca_cert_file != NULL || ca_cert_path != NULL)
1091 SSL_CTX_load_verify_locations(ctx, ca_cert_file,
1094 SSL_CTX_set_default_verify_paths(ctx);
1095 if ((crl_file = getenv("SSL_CRL_FILE")) != NULL) {
1097 fetch_info("Using CRL file: %s", crl_file);
1098 crl_store = SSL_CTX_get_cert_store(ctx);
1099 crl_lookup = X509_STORE_add_lookup(crl_store,
1100 X509_LOOKUP_file());
1101 if (crl_lookup == NULL ||
1102 !X509_load_crl_file(crl_lookup, crl_file,
1103 X509_FILETYPE_PEM)) {
1105 "Could not load CRL file %s\n",
1109 X509_STORE_set_flags(crl_store,
1110 X509_V_FLAG_CRL_CHECK |
1111 X509_V_FLAG_CRL_CHECK_ALL);
1118 * Configure client certificate based on environment.
1121 fetch_ssl_setup_client_certificate(SSL_CTX *ctx, int verbose)
1123 const char *client_cert_file, *client_key_file;
1125 if ((client_cert_file = getenv("SSL_CLIENT_CERT_FILE")) != NULL) {
1126 client_key_file = getenv("SSL_CLIENT_KEY_FILE") != NULL ?
1127 getenv("SSL_CLIENT_KEY_FILE") : client_cert_file;
1129 fetch_info("Using client cert file: %s",
1131 fetch_info("Using client key file: %s",
1134 if (SSL_CTX_use_certificate_chain_file(ctx,
1135 client_cert_file) != 1) {
1137 "Could not load client certificate %s\n",
1141 if (SSL_CTX_use_PrivateKey_file(ctx, client_key_file,
1142 SSL_FILETYPE_PEM) != 1) {
1144 "Could not load client key %s\n",
1153 * Callback for SSL certificate verification, this is called on server
1154 * cert verification. It takes no decision, but informs the user in case
1155 * verification failed.
1158 fetch_ssl_cb_verify_crt(int verified, X509_STORE_CTX *ctx)
1166 if ((crt = X509_STORE_CTX_get_current_cert(ctx)) != NULL &&
1167 (name = X509_get_subject_name(crt)) != NULL)
1168 str = X509_NAME_oneline(name, 0, 0);
1169 fprintf(stderr, "Certificate verification failed for %s\n",
1170 str != NULL ? str : "no relevant certificate");
1179 * Enable SSL on a connection.
1182 fetch_ssl(conn_t *conn, const struct url *URL, int verbose)
1189 conn->ssl_meth = SSLv23_client_method();
1190 conn->ssl_ctx = SSL_CTX_new(conn->ssl_meth);
1191 SSL_CTX_set_mode(conn->ssl_ctx, SSL_MODE_AUTO_RETRY);
1193 fetch_ssl_setup_transport_layer(conn->ssl_ctx, verbose);
1194 if (!fetch_ssl_setup_peer_verification(conn->ssl_ctx, verbose))
1196 if (!fetch_ssl_setup_client_certificate(conn->ssl_ctx, verbose))
1199 conn->ssl = SSL_new(conn->ssl_ctx);
1200 if (conn->ssl == NULL) {
1201 fprintf(stderr, "SSL context creation failed\n");
1204 SSL_set_fd(conn->ssl, conn->sd);
1206 #if !defined(OPENSSL_NO_TLSEXT)
1207 if (!SSL_set_tlsext_host_name(conn->ssl,
1208 __DECONST(struct url *, URL)->host)) {
1210 "TLS server name indication extension failed for host %s\n",
1215 while ((ret = SSL_connect(conn->ssl)) == -1) {
1216 ssl_err = SSL_get_error(conn->ssl, ret);
1217 if (ssl_err != SSL_ERROR_WANT_READ &&
1218 ssl_err != SSL_ERROR_WANT_WRITE) {
1219 ERR_print_errors_fp(stderr);
1223 conn->ssl_cert = SSL_get_peer_certificate(conn->ssl);
1225 if (conn->ssl_cert == NULL) {
1226 fprintf(stderr, "No server SSL certificate\n");
1230 if (getenv("SSL_NO_VERIFY_HOSTNAME") == NULL) {
1232 fetch_info("Verify hostname");
1233 if (!fetch_ssl_verify_hname(conn->ssl_cert, URL->host)) {
1235 "SSL certificate subject doesn't match host %s\n",
1242 fetch_info("%s connection established using %s",
1243 SSL_get_version(conn->ssl), SSL_get_cipher(conn->ssl));
1244 name = X509_get_subject_name(conn->ssl_cert);
1245 str = X509_NAME_oneline(name, 0, 0);
1246 fetch_info("Certificate subject: %s", str);
1248 name = X509_get_issuer_name(conn->ssl_cert);
1249 str = X509_NAME_oneline(name, 0, 0);
1250 fetch_info("Certificate issuer: %s", str);
1259 fprintf(stderr, "SSL support disabled\n");
1264 #define FETCH_READ_WAIT -2
1265 #define FETCH_READ_ERROR -1
1266 #define FETCH_READ_DONE 0
1270 fetch_ssl_read(SSL *ssl, char *buf, size_t len)
1275 rlen = SSL_read(ssl, buf, len);
1277 ssl_err = SSL_get_error(ssl, rlen);
1278 if (ssl_err == SSL_ERROR_WANT_READ ||
1279 ssl_err == SSL_ERROR_WANT_WRITE) {
1280 return (FETCH_READ_WAIT);
1282 ERR_print_errors_fp(stderr);
1283 return (FETCH_READ_ERROR);
1291 fetch_socket_read(int sd, char *buf, size_t len)
1295 rlen = read(sd, buf, len);
1297 if (errno == EAGAIN || (errno == EINTR && fetchRestartCalls))
1298 return (FETCH_READ_WAIT);
1300 return (FETCH_READ_ERROR);
1306 * Read a character from a connection w/ timeout
1309 fetch_read(conn_t *conn, char *buf, size_t len)
1311 struct timeval now, timeout, delta;
1316 if (fetchTimeout > 0) {
1317 gettimeofday(&timeout, NULL);
1318 timeout.tv_sec += fetchTimeout;
1322 memset(&pfd, 0, sizeof pfd);
1324 pfd.events = POLLIN | POLLERR;
1328 * The socket is non-blocking. Instead of the canonical
1329 * poll() -> read(), we do the following:
1331 * 1) call read() or SSL_read().
1332 * 2) if we received some data, return it.
1333 * 3) if an error occurred, return -1.
1334 * 4) if read() or SSL_read() signaled EOF, return.
1335 * 5) if we did not receive any data but we're not at EOF,
1338 * In the SSL case, this is necessary because if we
1339 * receive a close notification, we have to call
1340 * SSL_read() one additional time after we've read
1341 * everything we received.
1343 * In the non-SSL case, it may improve performance (very
1344 * slightly) when reading small amounts of data.
1347 if (conn->ssl != NULL)
1348 rlen = fetch_ssl_read(conn->ssl, buf, len);
1351 rlen = fetch_socket_read(conn->sd, buf, len);
1354 } else if (rlen == FETCH_READ_ERROR) {
1358 // assert(rlen == FETCH_READ_WAIT);
1359 if (fetchTimeout > 0) {
1360 gettimeofday(&now, NULL);
1361 if (!timercmp(&timeout, &now, >)) {
1366 timersub(&timeout, &now, &delta);
1367 deltams = delta.tv_sec * 1000 +
1368 delta.tv_usec / 1000;;
1372 if (poll(&pfd, 1, deltams) < 0) {
1373 if (errno == EINTR && fetchRestartCalls)
1384 * Read a line of text from a connection w/ timeout
1386 #define MIN_BUF_SIZE 1024
1389 fetch_getln(conn_t *conn)
1396 if (conn->buf == NULL) {
1397 if ((conn->buf = malloc(MIN_BUF_SIZE)) == NULL) {
1401 conn->bufsize = MIN_BUF_SIZE;
1404 conn->buf[0] = '\0';
1408 len = fetch_read(conn, &c, 1);
1413 conn->buf[conn->buflen++] = c;
1414 if (conn->buflen == conn->bufsize) {
1416 tmpsize = conn->bufsize * 2 + 1;
1417 if ((tmp = realloc(tmp, tmpsize)) == NULL) {
1422 conn->bufsize = tmpsize;
1424 } while (c != '\n');
1426 conn->buf[conn->buflen] = '\0';
1427 DEBUGF("<<< %s", conn->buf);
1433 * Write to a connection w/ timeout
1436 fetch_write(conn_t *conn, const char *buf, size_t len)
1440 iov.iov_base = __DECONST(char *, buf);
1442 return fetch_writev(conn, &iov, 1);
1446 * Write a vector to a connection w/ timeout
1447 * Note: can modify the iovec.
1450 fetch_writev(conn_t *conn, struct iovec *iov, int iovcnt)
1452 struct timeval now, timeout, delta;
1454 ssize_t wlen, total;
1457 memset(&pfd, 0, sizeof pfd);
1460 pfd.events = POLLOUT | POLLERR;
1461 gettimeofday(&timeout, NULL);
1462 timeout.tv_sec += fetchTimeout;
1466 while (iovcnt > 0) {
1467 while (fetchTimeout && pfd.revents == 0) {
1468 gettimeofday(&now, NULL);
1469 if (!timercmp(&timeout, &now, >)) {
1474 timersub(&timeout, &now, &delta);
1475 deltams = delta.tv_sec * 1000 +
1476 delta.tv_usec / 1000;
1479 if (poll(&pfd, 1, deltams) < 0) {
1480 /* POSIX compliance */
1481 if (errno == EAGAIN)
1483 if (errno == EINTR && fetchRestartCalls)
1490 if (conn->ssl != NULL)
1491 wlen = SSL_write(conn->ssl,
1492 iov->iov_base, iov->iov_len);
1495 wlen = writev(conn->sd, iov, iovcnt);
1497 /* we consider a short write a failure */
1498 /* XXX perhaps we shouldn't in the SSL case */
1504 if (errno == EINTR && fetchRestartCalls)
1509 while (iovcnt > 0 && wlen >= (ssize_t)iov->iov_len) {
1510 wlen -= iov->iov_len;
1515 iov->iov_len -= wlen;
1516 iov->iov_base = __DECONST(char *, iov->iov_base) + wlen;
1524 * Write a line of text to a connection w/ timeout
1527 fetch_putln(conn_t *conn, const char *str, size_t len)
1529 struct iovec iov[2];
1532 DEBUGF(">>> %s\n", str);
1533 iov[0].iov_base = __DECONST(char *, str);
1534 iov[0].iov_len = len;
1535 iov[1].iov_base = __DECONST(char *, ENDL);
1536 iov[1].iov_len = sizeof(ENDL);
1538 ret = fetch_writev(conn, &iov[1], 1);
1540 ret = fetch_writev(conn, iov, 2);
1551 fetch_close(conn_t *conn)
1555 if (--conn->ref > 0)
1559 SSL_shutdown(conn->ssl);
1560 SSL_set_connect_state(conn->ssl);
1561 SSL_free(conn->ssl);
1564 if (conn->ssl_ctx) {
1565 SSL_CTX_free(conn->ssl_ctx);
1566 conn->ssl_ctx = NULL;
1568 if (conn->ssl_cert) {
1569 X509_free(conn->ssl_cert);
1570 conn->ssl_cert = NULL;
1573 ret = close(conn->sd);
1580 /*** Directory-related utility functions *************************************/
1583 fetch_add_entry(struct url_ent **p, int *size, int *len,
1584 const char *name, struct url_stat *us)
1586 struct url_ent *tmp;
1593 if (*len >= *size - 1) {
1594 tmp = reallocarray(*p, *size * 2 + 1, sizeof(**p));
1600 *size = (*size * 2 + 1);
1605 snprintf(tmp->name, PATH_MAX, "%s", name);
1606 memcpy(&tmp->stat, us, sizeof(*us));
1609 (++tmp)->name[0] = 0;
1615 /*** Authentication-related utility functions ********************************/
1618 fetch_read_word(FILE *f)
1620 static char word[1024];
1622 if (fscanf(f, " %1023s ", word) != 1)
1628 fetch_netrc_open(void)
1635 if ((p = getenv("NETRC")) != NULL) {
1636 DEBUGF("NETRC=%s\n", p);
1637 if (snprintf(fn, sizeof(fn), "%s", p) >= (int)sizeof(fn)) {
1638 fetch_info("$NETRC specifies a file name "
1639 "longer than PATH_MAX");
1643 if ((p = getenv("HOME")) == NULL) {
1644 if ((pwd = getpwuid(getuid())) == NULL ||
1645 (p = pwd->pw_dir) == NULL)
1648 if (snprintf(fn, sizeof(fn), "%s/.netrc", p) >= (int)sizeof(fn))
1652 if ((fd = open(fn, O_RDONLY)) < 0) {
1654 DEBUGF("%s: %s\n", fn, strerror(serrno));
1661 * Get authentication data for a URL from .netrc
1664 fetch_netrc_auth(struct url *url)
1670 if (url->netrcfd < 0)
1671 url->netrcfd = fetch_netrc_open();
1672 if (url->netrcfd < 0)
1674 if ((f = fdopen(url->netrcfd, "r")) == NULL) {
1676 DEBUGF("fdopen(netrcfd): %s", strerror(errno));
1677 close(url->netrcfd);
1683 DEBUGF("searching netrc for %s\n", url->host);
1684 while ((word = fetch_read_word(f)) != NULL) {
1685 if (strcmp(word, "default") == 0) {
1686 DEBUGF("using default netrc settings\n");
1689 if (strcmp(word, "machine") == 0 &&
1690 (word = fetch_read_word(f)) != NULL &&
1691 strcasecmp(word, url->host) == 0) {
1692 DEBUGF("using netrc settings for %s\n", word);
1698 while ((word = fetch_read_word(f)) != NULL) {
1699 if (strcmp(word, "login") == 0) {
1700 if ((word = fetch_read_word(f)) == NULL)
1702 if (snprintf(url->user, sizeof(url->user),
1703 "%s", word) > (int)sizeof(url->user)) {
1704 fetch_info("login name in .netrc is too long");
1705 url->user[0] = '\0';
1707 } else if (strcmp(word, "password") == 0) {
1708 if ((word = fetch_read_word(f)) == NULL)
1710 if (snprintf(url->pwd, sizeof(url->pwd),
1711 "%s", word) > (int)sizeof(url->pwd)) {
1712 fetch_info("password in .netrc is too long");
1715 } else if (strcmp(word, "account") == 0) {
1716 if ((word = fetch_read_word(f)) == NULL)
1718 /* XXX not supported! */
1735 * The no_proxy environment variable specifies a set of domains for
1736 * which the proxy should not be consulted; the contents is a comma-,
1737 * or space-separated list of domain names. A single asterisk will
1738 * override all proxy variables and no transactions will be proxied
1739 * (for compatibility with lynx and curl, see the discussion at
1740 * <http://curl.haxx.se/mail/archive_pre_oct_99/0009.html>).
1743 fetch_no_proxy_match(const char *host)
1745 const char *no_proxy, *p, *q;
1746 size_t h_len, d_len;
1748 if ((no_proxy = getenv("NO_PROXY")) == NULL &&
1749 (no_proxy = getenv("no_proxy")) == NULL)
1752 /* asterisk matches any hostname */
1753 if (strcmp(no_proxy, "*") == 0)
1756 h_len = strlen(host);
1759 /* position p at the beginning of a domain suffix */
1760 while (*p == ',' || isspace((unsigned char)*p))
1763 /* position q at the first separator character */
1764 for (q = p; *q; ++q)
1765 if (*q == ',' || isspace((unsigned char)*q))
1769 if (d_len > 0 && h_len >= d_len &&
1770 strncasecmp(host + h_len - d_len,
1772 /* domain name matches */