xref: /illumos-gate/usr/src/cmd/cmd-inet/usr.bin/nc/socks.c (revision 8361acf58a302751348aac091ab09484f3ecfb8c)
1 /*	$OpenBSD: socks.c,v 1.17 2006/09/25 04:51:20 ray Exp $	*/
2 
3 /*
4  * Copyright (c) 1999 Niklas Hallqvist.  All rights reserved.
5  * Copyright (c) 2004, 2005 Damien Miller.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
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  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32 
33 #include <err.h>
34 #include <errno.h>
35 #include <netdb.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <resolv.h>
41 #include <strings.h>
42 #include "atomicio.h"
43 
44 #define	SOCKS_PORT	"1080"
45 #define	HTTP_PROXY_PORT	"3128"
46 #define	HTTP_MAXHDRS	64
47 #define	SOCKS_V5	5
48 #define	SOCKS_V4	4
49 #define	SOCKS_NOAUTH	0
50 #define	SOCKS_NOMETHOD	0xff
51 #define	SOCKS_CONNECT	1
52 #define	SOCKS_IPV4	1
53 #define	SOCKS_DOMAIN	3
54 #define	SOCKS_IPV6	4
55 
56 #define	HTTP_10_407	"HTTP/1.0 407 "
57 #define	HTTP_10_200	"HTTP/1.0 200 "
58 #define	HTTP_11_200	"HTTP/1.1 200 "
59 
60 int remote_connect(const char *, const char *, struct addrinfo);
61 int socks_connect(const char *, const char *,
62 	    const char *, const char *, struct addrinfo, int,
63 	    const char *);
64 
65 /*
66  * Convert string representation of host (h) and service/port (p) into
67  * sockaddr structure and return 0 on success, -1 on failure.
68  * Indicate whether the host address is IPv4 (v4only) and numeric.
69  */
70 static int
decode_addrport(const char * h,const char * p,struct sockaddr * addr,socklen_t addrlen,int v4only,int numeric)71 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
72     socklen_t addrlen, int v4only, int numeric)
73 {
74 	int r;
75 	struct addrinfo hints, *res;
76 
77 	bzero(&hints, sizeof (hints));
78 	hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
79 	hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
80 	hints.ai_socktype = SOCK_STREAM;
81 	r = getaddrinfo(h, p, &hints, &res);
82 	/* Don't fatal when attempting to convert a numeric address */
83 	if (r != 0) {
84 		if (!numeric) {
85 			errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
86 			    gai_strerror(r));
87 		}
88 		return (-1);
89 	}
90 	if (addrlen < res->ai_addrlen) {
91 		freeaddrinfo(res);
92 		errx(1, "internal error: addrlen < res->ai_addrlen");
93 	}
94 	(void) memcpy(addr, res->ai_addr, res->ai_addrlen);
95 	freeaddrinfo(res);
96 	return (0);
97 }
98 
99 /*
100  * Read single line from a descriptor into buffer up to bufsz bytes,
101  * byte by byte. Returns length of the line (including ending NULL),
102  * exits upon failure.
103  */
104 static int
proxy_read_line(int fd,char * buf,size_t bufsz)105 proxy_read_line(int fd, char *buf, size_t bufsz)
106 {
107 	size_t off;
108 
109 	for (off = 0; ; ) {
110 		if (off >= bufsz)
111 			errx(1, "proxy read too long");
112 		if (atomicio(read, fd, buf + off, 1) != 1)
113 			err(1, "proxy read");
114 		/* Skip CR */
115 		if (buf[off] == '\r')
116 			continue;
117 		if (buf[off] == '\n') {
118 			buf[off] = '\0';
119 			break;
120 		}
121 		/*
122 		 * we rewite \r\n to NULL since socks_connect() relies
123 		 * on *buf being zero in that case.
124 		 */
125 		off++;
126 	}
127 	return (off);
128 }
129 
130 /*
131  * Read proxy password from user and return it. The arguments are used
132  * only for prompt construction.
133  */
134 static const char *
getproxypass(const char * proxyuser,const char * proxyhost)135 getproxypass(const char *proxyuser, const char *proxyhost)
136 {
137 	char prompt[512];
138 	const char *pw;
139 
140 	(void) snprintf(prompt, sizeof (prompt), "Proxy password for %s@%s: ",
141 	    proxyuser, proxyhost);
142 	if ((pw = getpassphrase(prompt)) == NULL)
143 		errx(1, "Unable to read proxy passphrase");
144 	return (pw);
145 }
146 
147 /* perform connection via proxy using SOCKSv[45] or HTTP proxy CONNECT */
148 int
socks_connect(const char * host,const char * port,const char * proxyhost,const char * proxyport,struct addrinfo proxyhints,int socksv,const char * proxyuser)149 socks_connect(const char *host, const char *port, const char *proxyhost,
150     const char *proxyport, struct addrinfo proxyhints, int socksv,
151     const char *proxyuser)
152 {
153 	int proxyfd, r, authretry = 0;
154 	size_t hlen, wlen;
155 	char buf[1024];
156 	size_t cnt;
157 	struct sockaddr_storage addr;
158 	struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
159 	struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
160 	in_port_t serverport;
161 	const char *proxypass = NULL;
162 
163 	if (proxyport == NULL)
164 		proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
165 
166 	/* Abuse API to lookup port */
167 	if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
168 	    sizeof (addr), 1, 1) == -1)
169 		errx(1, "unknown port \"%.64s\"", port);
170 	serverport = in4->sin_port;
171 
172 again:
173 	if (authretry++ > 3)
174 		errx(1, "Too many authentication failures");
175 
176 	proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
177 
178 	if (proxyfd < 0)
179 		return (-1);
180 
181 	if (socksv == 5) {
182 		if (decode_addrport(host, port, (struct sockaddr *)&addr,
183 		    sizeof (addr), 0, 1) == -1)
184 			addr.ss_family = 0; /* used in switch below */
185 
186 		/* Version 5, one method: no authentication */
187 		buf[0] = SOCKS_V5;
188 		buf[1] = 1;
189 		buf[2] = SOCKS_NOAUTH;
190 		cnt = atomicio(vwrite, proxyfd, buf, 3);
191 		if (cnt != 3)
192 			err(1, "write failed (%zu/3)", cnt);
193 
194 		cnt = atomicio(read, proxyfd, buf, 2);
195 		if (cnt != 2)
196 			err(1, "read failed (%zu/2)", cnt);
197 
198 		if ((unsigned char)buf[1] == SOCKS_NOMETHOD)
199 			errx(1, "authentication method negotiation failed");
200 
201 		switch (addr.ss_family) {
202 		case 0:
203 			/* Version 5, connect: domain name */
204 
205 			/* Max domain name length is 255 bytes */
206 			hlen = strlen(host);
207 			if (hlen > 255)
208 				errx(1, "host name too long for SOCKS5");
209 			buf[0] = SOCKS_V5;
210 			buf[1] = SOCKS_CONNECT;
211 			buf[2] = 0;
212 			buf[3] = SOCKS_DOMAIN;
213 			buf[4] = hlen;
214 			(void) memcpy(buf + 5, host, hlen);
215 			(void) memcpy(buf + 5 + hlen, &serverport,
216 			    sizeof (serverport));
217 			wlen = 5 + hlen + sizeof (serverport);
218 			break;
219 		case AF_INET:
220 			/* Version 5, connect: IPv4 address */
221 			buf[0] = SOCKS_V5;
222 			buf[1] = SOCKS_CONNECT;
223 			buf[2] = 0;
224 			buf[3] = SOCKS_IPV4;
225 			(void) memcpy(buf + 4, &in4->sin_addr,
226 			    sizeof (in4->sin_addr));
227 			(void) memcpy(buf + 8, &in4->sin_port,
228 			    sizeof (in4->sin_port));
229 			wlen = 4 + sizeof (in4->sin_addr) +
230 			    sizeof (in4->sin_port);
231 			break;
232 		case AF_INET6:
233 			/* Version 5, connect: IPv6 address */
234 			buf[0] = SOCKS_V5;
235 			buf[1] = SOCKS_CONNECT;
236 			buf[2] = 0;
237 			buf[3] = SOCKS_IPV6;
238 			(void) memcpy(buf + 4, &in6->sin6_addr,
239 			    sizeof (in6->sin6_addr));
240 			(void) memcpy(buf + 20, &in6->sin6_port,
241 			    sizeof (in6->sin6_port));
242 			wlen = 4 + sizeof (in6->sin6_addr) +
243 			    sizeof (in6->sin6_port);
244 			break;
245 		default:
246 			errx(1, "internal error: silly AF");
247 		}
248 
249 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
250 		if (cnt != wlen)
251 			err(1, "write failed (%zu/%zu)", cnt, wlen);
252 
253 		/*
254 		 * read proxy reply which is 4 byte "header", BND.ADDR
255 		 * and BND.PORT according to RFC 1928, section 6. BND.ADDR
256 		 * is 4 bytes in case of IPv4 which gives us 10 bytes in sum.
257 		 */
258 		cnt = atomicio(read, proxyfd, buf, 10);
259 		if (cnt != 10)
260 			err(1, "read failed (%zu/10)", cnt);
261 		if (buf[1] != 0)
262 			errx(1, "connection failed, SOCKS error %d", buf[1]);
263 	} else if (socksv == 4) {
264 		/* This will exit on lookup failure */
265 		(void) decode_addrport(host, port, (struct sockaddr *)&addr,
266 		    sizeof (addr), 1, 0);
267 
268 		/* Version 4 */
269 		buf[0] = SOCKS_V4;
270 		buf[1] = SOCKS_CONNECT;	/* connect */
271 		(void) memcpy(buf + 2, &in4->sin_port, sizeof (in4->sin_port));
272 		(void) memcpy(buf + 4, &in4->sin_addr, sizeof (in4->sin_addr));
273 		buf[8] = 0;	/* empty username */
274 		wlen = 9;
275 
276 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
277 		if (cnt != wlen)
278 			err(1, "write failed (%zu/%zu)", cnt, wlen);
279 
280 		/*
281 		 * SOCKSv4 proxy replies consists of 2 byte "header",
282 		 * port number and numeric IPv4 address which gives 8 bytes.
283 		 */
284 		cnt = atomicio(read, proxyfd, buf, 8);
285 		if (cnt != 8)
286 			err(1, "read failed (%zu/8)", cnt);
287 		if (buf[1] != 90)
288 			errx(1, "connection failed, SOCKS error %d", buf[1]);
289 	} else if (socksv == -1) {
290 		/* HTTP proxy CONNECT according to RFC 2817, section 5 */
291 
292 		/* Disallow bad chars in hostname */
293 		if (strcspn(host, "\r\n\t []:") != strlen(host))
294 			errx(1, "Invalid hostname");
295 
296 		/* Try to be sane about numeric IPv6 addresses */
297 		if (strchr(host, ':') != NULL) {
298 			r = snprintf(buf, sizeof (buf),
299 			    "CONNECT [%s]:%d HTTP/1.0\r\n",
300 			    host, ntohs(serverport));
301 		} else {
302 			r = snprintf(buf, sizeof (buf),
303 			    "CONNECT %s:%d HTTP/1.0\r\n",
304 			    host, ntohs(serverport));
305 		}
306 		if (r == -1 || (size_t)r >= sizeof (buf))
307 			errx(1, "hostname too long");
308 		r = strlen(buf);
309 
310 		cnt = atomicio(vwrite, proxyfd, buf, r);
311 		if (cnt != r)
312 			err(1, "write failed (%zu/%d)", cnt, r);
313 
314 		if (authretry > 1) {
315 			char resp[1024];
316 
317 			proxypass = getproxypass(proxyuser, proxyhost);
318 			r = snprintf(buf, sizeof (buf), "%s:%s",
319 			    proxyuser, proxypass);
320 			free((void *)proxypass);
321 			if (r == -1 || (size_t)r >= sizeof (buf) ||
322 			    b64_ntop((unsigned char *)buf, strlen(buf), resp,
323 			    sizeof (resp)) == -1)
324 				errx(1, "Proxy username/password too long");
325 			r = snprintf(buf, sizeof (buf), "Proxy-Authorization: "
326 			    "Basic %s\r\n", resp);
327 			if (r == -1 || (size_t)r >= sizeof (buf))
328 				errx(1, "Proxy auth response too long");
329 			r = strlen(buf);
330 			if ((cnt = atomicio(vwrite, proxyfd, buf, r)) != r)
331 				err(1, "write failed (%zu/%d)", cnt, r);
332 		}
333 
334 		/* Terminate headers */
335 		if ((r = atomicio(vwrite, proxyfd, "\r\n", 2)) != 2)
336 			err(1, "write failed (2/%d)", r);
337 
338 		/* Read status reply */
339 		(void) proxy_read_line(proxyfd, buf, sizeof (buf));
340 		if (proxyuser != NULL &&
341 		    strncmp(buf, HTTP_10_407, strlen(HTTP_10_407)) == 0) {
342 			if (authretry > 1) {
343 				(void) fprintf(stderr, "Proxy authentication "
344 				    "failed\n");
345 			}
346 			(void) close(proxyfd);
347 			goto again;
348 		} else if (strncmp(buf, HTTP_10_200,
349 		    strlen(HTTP_10_200)) != 0 && strncmp(buf, HTTP_11_200,
350 		    strlen(HTTP_11_200)) != 0)
351 			errx(1, "Proxy error: \"%s\"", buf);
352 
353 		/* Headers continue until we hit an empty line */
354 		for (r = 0; r < HTTP_MAXHDRS; r++) {
355 			(void) proxy_read_line(proxyfd, buf, sizeof (buf));
356 			if (*buf == '\0')
357 				break;
358 		}
359 		if (*buf != '\0')
360 			errx(1, "Too many proxy headers received");
361 	} else
362 		errx(1, "Unknown proxy protocol %d", socksv);
363 
364 	return (proxyfd);
365 }
366