1 /*	$OpenBSD: socks.c,v 1.15 2005/05/24 20:13:28 avsm Exp $	*/
2 
3 /*
4  * Copyright (c) 1999 Niklas Hallqvist.  All rights reserved.
5  * Copyright (c) 2004, 2005 Damien Miller.  All rights reserved.
6  * Copyright © 2013
7  *	Thorsten “mirabilos” Glaser <tg@mirbsd.org>
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
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  *
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/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 
35 #include <err.h>
36 #include <errno.h>
37 #include <netdb.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include "atomicio.h"
43 
44 __RCSID("$MirOS: src/usr.bin/nc/socks.c,v 1.9 2013/10/31 20:07:08 tg Exp $");
45 
46 #define SOCKS_PORT	"1080"
47 #define HTTP_PROXY_PORT	"3128"
48 #define HTTP_MAXHDRS	64
49 #define SOCKS_V5	5
50 #define SOCKS_V4	4
51 #define SOCKS_NOAUTH	0
52 #define SOCKS_NOMETHOD	0xff
53 #define SOCKS_CONNECT	1
54 #define SOCKS_IPV4	1
55 #define SOCKS_DOMAIN	3
56 #define SOCKS_IPV6	4
57 
58 int	remote_connect(const char *, const char *, struct addrinfo);
59 int	socks_connect(const char *host, const char *port, struct addrinfo hints,
60 	    const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
61 	    int socksv);
62 
63 static int
decode_addrport(const char * h,const char * p,struct sockaddr * addr,socklen_t addrlen,int v4only,int numeric)64 decode_addrport(const char *h, const char *p, struct sockaddr *addr,
65     socklen_t addrlen, int v4only, int numeric)
66 {
67 	int r;
68 	struct addrinfo hints, *res;
69 
70 	bzero(&hints, sizeof(hints));
71 	hints.ai_family = v4only ? PF_INET : PF_UNSPEC;
72 	hints.ai_flags = numeric ? AI_NUMERICHOST : 0;
73 	hints.ai_socktype = SOCK_STREAM;
74 	r = getaddrinfo(h, p, &hints, &res);
75 	/* Don't fatal when attempting to convert a numeric address */
76 	if (r != 0) {
77 		if (!numeric) {
78 			errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p,
79 			    gai_strerror(r));
80 		}
81 		return (-1);
82 	}
83 	if (addrlen < res->ai_addrlen) {
84 		freeaddrinfo(res);
85 		errx(1, "internal error: addrlen < res->ai_addrlen");
86 	}
87 	memcpy(addr, res->ai_addr, res->ai_addrlen);
88 	freeaddrinfo(res);
89 	return (0);
90 }
91 
92 static int
proxy_read_line(int fd,char * buf,size_t bufsz)93 proxy_read_line(int fd, char *buf, size_t bufsz)
94 {
95 	size_t off;
96 
97 	for(off = 0;;) {
98 		if (off >= bufsz)
99 			errx(1, "proxy read too long");
100 		if (atomicio(read, fd, buf + off, 1) != 1)
101 			err(1, "proxy read");
102 		/* Skip CR */
103 		if (buf[off] == '\r')
104 			continue;
105 		if (buf[off] == '\n') {
106 			buf[off] = '\0';
107 			break;
108 		}
109 		off++;
110 	}
111 	return (off);
112 }
113 
114 int
socks_connect(const char * host,const char * port,struct addrinfo hints,const char * proxyhost,const char * proxyport,struct addrinfo proxyhints,int socksv)115 socks_connect(const char *host, const char *port,
116     struct addrinfo hints __attribute__((__unused__)),
117     const char *proxyhost, const char *proxyport, struct addrinfo proxyhints,
118     int socksv)
119 {
120 	int proxyfd, r;
121 	size_t hlen, wlen;
122 	unsigned char buf[1024];
123 	size_t cnt;
124 	struct sockaddr_storage addr;
125 	struct sockaddr_in *in4 = (struct sockaddr_in *)&addr;
126 	struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr;
127 	in_port_t serverport;
128 
129 	if (proxyport == NULL)
130 		proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT;
131 
132 	proxyfd = remote_connect(proxyhost, proxyport, proxyhints);
133 
134 	if (proxyfd < 0)
135 		return (-1);
136 
137 	/* Abuse API to lookup port */
138 	if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr,
139 	    sizeof(addr), 1, 1) == -1)
140 		errx(1, "unknown port \"%.64s\"", port);
141 	serverport = in4->sin_port;
142 
143 	if (socksv == 5) {
144 		if (decode_addrport(host, port, (struct sockaddr *)&addr,
145 		    sizeof(addr), 0, 1) == -1)
146 			addr.ss_family = 0; /* used in switch below */
147 
148 		/* Version 5, one method: no authentication */
149 		buf[0] = SOCKS_V5;
150 		buf[1] = 1;
151 		buf[2] = SOCKS_NOAUTH;
152 		cnt = atomicio(vwrite, proxyfd, buf, 3);
153 		if (cnt != 3)
154 			err(1, "write failed (%zu/3)", cnt);
155 
156 		cnt = atomicio(read, proxyfd, buf, 2);
157 		if (cnt != 2)
158 			err(1, "read failed (%zu/3)", cnt);
159 
160 		if (buf[1] == SOCKS_NOMETHOD)
161 			errx(1, "authentication method negotiation failed");
162 
163 		switch (addr.ss_family) {
164 		case 0:
165 			/* Version 5, connect: domain name */
166 
167 			/* Max domain name length is 255 bytes */
168 			hlen = strlen(host);
169 			if (hlen > 255)
170 				errx(1, "host name too long for SOCKS5");
171 			buf[0] = SOCKS_V5;
172 			buf[1] = SOCKS_CONNECT;
173 			buf[2] = 0;
174 			buf[3] = SOCKS_DOMAIN;
175 			buf[4] = hlen;
176 			memcpy(buf + 5, host, hlen);
177 			memcpy(buf + 5 + hlen, &serverport, sizeof serverport);
178 			wlen = 7 + hlen;
179 			break;
180 		case AF_INET:
181 			/* Version 5, connect: IPv4 address */
182 			buf[0] = SOCKS_V5;
183 			buf[1] = SOCKS_CONNECT;
184 			buf[2] = 0;
185 			buf[3] = SOCKS_IPV4;
186 			memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
187 			memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port);
188 			wlen = 10;
189 			break;
190 		case AF_INET6:
191 			/* Version 5, connect: IPv6 address */
192 			buf[0] = SOCKS_V5;
193 			buf[1] = SOCKS_CONNECT;
194 			buf[2] = 0;
195 			buf[3] = SOCKS_IPV6;
196 			memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr);
197 			memcpy(buf + 20, &in6->sin6_port,
198 			    sizeof in6->sin6_port);
199 			wlen = 22;
200 			break;
201 		default:
202 			errx(1, "internal error: silly AF");
203 		}
204 
205 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
206 		if (cnt != wlen)
207 			err(1, "write failed (%zu/%zu)", cnt, wlen);
208 
209 		cnt = atomicio(read, proxyfd, buf, 10);
210 		if (cnt != 10)
211 			err(1, "read failed (%zu/10)", cnt);
212 		if (buf[1] != 0)
213 			errx(1, "connection failed, SOCKS error %u", buf[1]);
214 	} else if (socksv == 4) {
215 		/* This will exit on lookup failure */
216 		decode_addrport(host, port, (struct sockaddr *)&addr,
217 		    sizeof(addr), 1, 0);
218 
219 		/* Version 4 */
220 		buf[0] = SOCKS_V4;
221 		buf[1] = SOCKS_CONNECT;	/* connect */
222 		memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port);
223 		memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr);
224 		buf[8] = 0;	/* empty username */
225 		wlen = 9;
226 
227 		cnt = atomicio(vwrite, proxyfd, buf, wlen);
228 		if (cnt != wlen)
229 			err(1, "write failed (%zu/%zu)", cnt, wlen);
230 
231 		cnt = atomicio(read, proxyfd, buf, 8);
232 		if (cnt != 8)
233 			err(1, "read failed (%zu/8)", cnt);
234 		if (buf[1] != 90)
235 			errx(1, "connection failed, SOCKS error %u", buf[1]);
236 	} else if (socksv == -1) {
237 		/* HTTP proxy CONNECT */
238 
239 		/* Disallow bad chars in hostname */
240 		if (strcspn(host, "\r\n\t []:") != strlen(host))
241 			errx(1, "Invalid hostname");
242 
243 		/* Try to be sane about numeric IPv6 addresses */
244 		if (strchr(host, ':') != NULL) {
245 			r = snprintf((char *)buf, sizeof(buf),
246 			    "CONNECT [%s]:%u HTTP/1.0\r\n\r\n",
247 			    host, ntohs(serverport));
248 		} else {
249 			r = snprintf((char *)buf, sizeof(buf),
250 			    "CONNECT %s:%u HTTP/1.0\r\n\r\n",
251 			    host, ntohs(serverport));
252 		}
253 		if (r == -1 || (size_t)r >= sizeof(buf))
254 			errx(1, "hostname too long");
255 		r = strlen((char *)buf);
256 
257 		cnt = atomicio(vwrite, proxyfd, buf, r);
258 		if ((int)cnt != r)
259 			err(1, "write failed (%zu/%d)", cnt, r);
260 
261 		/* Read reply */
262 		for (r = 0; r < HTTP_MAXHDRS; r++) {
263 			proxy_read_line(proxyfd, (char *)buf, sizeof(buf));
264 			if (r == 0 && strncmp((char *)buf,
265 			    "HTTP/1.0 200 ", 12) != 0)
266 				errx(1, "Proxy error: \"%s\"", buf);
267 			/* Discard headers until we hit an empty line */
268 			if (*buf == '\0')
269 				break;
270 		}
271 	} else
272 		errx(1, "Unknown proxy protocol %d", socksv);
273 
274 	return (proxyfd);
275 }
276