1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson
2 * Copyright (c) 2007-2021, The Tor Project, Inc.
4 /* See LICENSE for licensing information */
8 #include "lib/arch/bytes.h"
9 #include "lib/log/log.h"
10 #include "lib/malloc/malloc.h"
11 #include "lib/net/address.h"
12 #include "lib/net/resolve.h"
13 #include "lib/net/socket.h"
14 #include "lib/sandbox/sandbox.h"
15 #include "lib/string/util_string.h"
17 #include "lib/net/socks5_status.h"
18 #include "trunnel/socks5.h"
25 #ifdef HAVE_NETINET_IN_H
26 #include <netinet/in.h>
28 #ifdef HAVE_ARPA_INET_H
29 #include <arpa/inet.h>
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
34 #ifdef HAVE_SYS_TYPES_H
35 #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
46 #define RESPONSE_LEN_4 8
47 #define log_sock_error(act, _s) \
49 log_fn(LOG_ERR, LD_NET, "Error while %s: %s", act, \
50 tor_socket_strerror(tor_socket_errno(_s))); \
53 static void usage(void) ATTR_NORETURN
;
56 * Set <b>out</b> to a pointer to newly allocated buffer containing
57 * SOCKS4a RESOLVE request with <b>username</b> and <b>hostname</b>.
58 * Return number of bytes in the buffer if succeeded or -1 if failed.
61 build_socks4a_resolve_request(uint8_t **out
,
69 const char *errmsg
= NULL
;
70 uint8_t *output
= NULL
;
71 socks4_client_request_t
*rq
= socks4_client_request_new();
73 socks4_client_request_set_version(rq
, 4);
74 socks4_client_request_set_command(rq
, CMD_RESOLVE
);
75 socks4_client_request_set_port(rq
, 0);
76 socks4_client_request_set_addr(rq
, 0x00000001u
);
77 socks4_client_request_set_username(rq
, username
);
78 socks4_client_request_set_socks4a_addr_hostname(rq
, hostname
);
80 errmsg
= socks4_client_request_check(rq
);
85 ssize_t encoded_len
= socks4_client_request_encoded_len(rq
);
86 if (encoded_len
<= 0) {
87 errmsg
= "socks4_client_request_encoded_len failed";
91 output
= tor_malloc(encoded_len
);
92 memset(output
, 0, encoded_len
);
94 encoded_len
= socks4_client_request_encode(output
, encoded_len
, rq
);
95 if (encoded_len
<= 0) {
96 errmsg
= "socks4_client_request_encode failed";
103 socks4_client_request_free(rq
);
105 log_err(LD_NET
, "build_socks4a_resolve_request failed: %s", errmsg
);
109 return errmsg
? -1 : encoded_len
;
112 #define SOCKS5_ATYPE_HOSTNAME 0x03
113 #define SOCKS5_ATYPE_IPV4 0x01
114 #define SOCKS5_ATYPE_IPV6 0x04
117 * Set <b>out</b> to pointer to newly allocated buffer containing
118 * SOCKS5 RESOLVE/RESOLVE_PTR request with given <b>hostname<b>.
119 * Generate a reverse request if <b>reverse</b> is true.
120 * Return the number of bytes in the buffer if succeeded or -1 if failed.
123 build_socks5_resolve_request(uint8_t **out
,
124 const char *hostname
,
127 const char *errmsg
= NULL
;
128 uint8_t *outbuf
= NULL
;
133 is_ip_address
= tor_addr_parse(&addr
, hostname
) != -1;
134 if (!is_ip_address
&& reverse
) {
135 log_err(LD_GENERAL
, "Tried to do a reverse lookup on a non-IP!");
138 ipv6
= reverse
&& tor_addr_family(&addr
) == AF_INET6
;
139 addrlen
= reverse
? (ipv6
? 16 : 4) : 1 + strlen(hostname
);
140 if (addrlen
> UINT8_MAX
) {
141 log_err(LD_GENERAL
, "Hostname is too long!");
145 socks5_client_request_t
*rq
= socks5_client_request_new();
147 socks5_client_request_set_version(rq
, 5);
148 /* RESOLVE_PTR or RESOLVE */
149 socks5_client_request_set_command(rq
, reverse
? CMD_RESOLVE_PTR
:
151 socks5_client_request_set_reserved(rq
, 0);
153 uint8_t atype
= SOCKS5_ATYPE_HOSTNAME
;
155 atype
= ipv6
? SOCKS5_ATYPE_IPV6
: SOCKS5_ATYPE_IPV4
;
157 socks5_client_request_set_atype(rq
, atype
);
160 case SOCKS5_ATYPE_IPV4
: {
161 socks5_client_request_set_dest_addr_ipv4(rq
,
162 tor_addr_to_ipv4h(&addr
));
164 case SOCKS5_ATYPE_IPV6
: {
165 uint8_t *ipv6_array
=
166 socks5_client_request_getarray_dest_addr_ipv6(rq
);
168 tor_assert(ipv6_array
);
170 memcpy(ipv6_array
, tor_addr_to_in6_addr8(&addr
), 16);
173 case SOCKS5_ATYPE_HOSTNAME
: {
174 domainname_t
*dn
= domainname_new();
175 domainname_set_len(dn
, addrlen
- 1);
176 domainname_setlen_name(dn
, addrlen
- 1);
177 char *dn_buf
= domainname_getarray_name(dn
);
178 memcpy(dn_buf
, hostname
, addrlen
- 1);
180 errmsg
= domainname_check(dn
);
186 socks5_client_request_set_dest_addr_domainname(rq
, dn
);
190 tor_assert_unreached();
194 socks5_client_request_set_dest_port(rq
, 0);
196 errmsg
= socks5_client_request_check(rq
);
201 ssize_t encoded_len
= socks5_client_request_encoded_len(rq
);
202 if (encoded_len
< 0) {
203 errmsg
= "Cannot predict encoded length";
207 outbuf
= tor_malloc(encoded_len
);
208 memset(outbuf
, 0, encoded_len
);
210 encoded_len
= socks5_client_request_encode(outbuf
, encoded_len
, rq
);
211 if (encoded_len
< 0) {
212 errmsg
= "encoding failed";
219 socks5_client_request_free(rq
);
222 log_err(LD_NET
, "build_socks5_resolve_request failed with error: %s",
226 return errmsg
? -1 : encoded_len
;
229 /** Set *<b>out</b> to a newly allocated SOCKS4a resolve request with
230 * <b>username</b> and <b>hostname</b> as provided. Return the number
231 * of bytes in the request. */
233 build_socks_resolve_request(uint8_t **out
,
234 const char *username
,
235 const char *hostname
,
240 tor_assert(username
);
241 tor_assert(hostname
);
243 tor_assert(version
== 4 || version
== 5);
246 return build_socks4a_resolve_request(out
, username
, hostname
);
247 } else if (version
== 5) {
248 return build_socks5_resolve_request(out
, hostname
, reverse
);
251 tor_assert_unreached();
256 onion_hs_warning(const char *hostname
)
259 "%s is a hidden service; those don't have IP addresses. "
260 "You can use the AutomapHostsOnResolve option to have Tor return a "
261 "fake address for hidden services. Or you can have your "
262 "application send the address to Tor directly; we recommend an "
263 "application that uses SOCKS 5 with hostnames.",
268 onion_exit_warning(const char *hostname
)
271 "%s is a link pointing to an exit node; however, .exit domains"
272 "have been long defunct and are not valid anymore.",
276 /** Given a <b>len</b>-byte SOCKS4a response in <b>response</b>, set
277 * *<b>addr_out</b> to the address it contains (in host order).
278 * Return 0 on success, -1 on error.
281 parse_socks4a_resolve_response(const char *hostname
,
282 const char *response
, size_t len
,
283 tor_addr_t
*addr_out
)
287 tor_assert(response
);
288 tor_assert(addr_out
);
290 socks4_server_reply_t
*reply
;
292 ssize_t parsed
= socks4_server_reply_parse(&reply
,
293 (const uint8_t *)response
,
297 log_warn(LD_PROTOCOL
, "Failed parsing SOCKS4a response");
298 result
= -1; goto cleanup
;
302 log_warn(LD_PROTOCOL
,"Truncated socks response.");
303 result
= -1; goto cleanup
;
306 if (socks4_server_reply_get_version(reply
) != 0) { /* version: 0 */
307 log_warn(LD_PROTOCOL
,"Nonzero version in socks response: bad format.");
308 result
= -1; goto cleanup
;
310 if (socks4_server_reply_get_port(reply
) != 0) { /* port: 0 */
311 log_warn(LD_PROTOCOL
,"Nonzero port in socks response: bad format.");
312 result
= -1; goto cleanup
;
314 status
= socks4_server_reply_get_status(reply
);
316 log_warn(LD_NET
,"Got status response '%d': socks request failed.", status
);
317 if (!strcasecmpend(hostname
, ".onion")) {
318 onion_hs_warning(hostname
);
319 result
= -1; goto cleanup
;
322 if (!strcasecmpend(hostname
, ".exit")) {
323 onion_exit_warning(hostname
);
324 result
= -1; goto cleanup
;
327 result
= -1; goto cleanup
;
330 tor_addr_from_ipv4h(addr_out
, socks4_server_reply_get_addr(reply
));
333 socks4_server_reply_free(reply
);
337 /* It would be nice to let someone know what SOCKS5 issue a user may have */
339 socks5_reason_to_string(char reason
)
342 case SOCKS5_SUCCEEDED
:
344 case SOCKS5_GENERAL_ERROR
:
345 return "general error";
346 case SOCKS5_NOT_ALLOWED
:
347 return "not allowed";
348 case SOCKS5_NET_UNREACHABLE
:
349 return "network is unreachable";
350 case SOCKS5_HOST_UNREACHABLE
:
351 return "host is unreachable";
352 case SOCKS5_CONNECTION_REFUSED
:
353 return "connection refused";
354 case SOCKS5_TTL_EXPIRED
:
355 return "ttl expired";
356 case SOCKS5_COMMAND_NOT_SUPPORTED
:
357 return "command not supported";
358 case SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED
:
359 return "address type not supported";
361 return "unknown SOCKS5 code";
365 /** Send a resolve request for <b>hostname</b> to the Tor listening on
366 * <b>sockshost</b>:<b>socksport</b>. Store the resulting IPv4
367 * address (in host order) into *<b>result_addr</b>.
370 do_resolve(const char *hostname
,
371 const tor_addr_t
*sockshost
, uint16_t socksport
,
372 int reverse
, int version
,
373 tor_addr_t
*result_addr
, char **result_hostname
)
376 struct sockaddr_storage ss
;
381 tor_assert(hostname
);
382 tor_assert(result_addr
);
383 tor_assert(version
== 4 || version
== 5);
385 tor_addr_make_unspec(result_addr
);
386 *result_hostname
= NULL
;
388 s
= tor_open_socket(PF_INET
,SOCK_STREAM
,IPPROTO_TCP
);
390 log_sock_error("creating_socket", -1);
394 socklen
= tor_addr_to_sockaddr(sockshost
, socksport
,
395 (struct sockaddr
*)&ss
, sizeof(ss
));
397 if (connect(s
, (struct sockaddr
*)&ss
, socklen
)) {
398 log_sock_error("connecting to SOCKS host", s
);
403 socks5_client_version_t
*v
= socks5_client_version_new();
405 socks5_client_version_set_version(v
, 5);
406 socks5_client_version_set_n_methods(v
, 1);
407 socks5_client_version_setlen_methods(v
, 1);
408 socks5_client_version_set_methods(v
, 0, 0x00);
410 tor_assert(!socks5_client_version_check(v
));
411 ssize_t encoded_len
= socks5_client_version_encoded_len(v
);
412 tor_assert(encoded_len
> 0);
414 uint8_t *buf
= tor_malloc(encoded_len
);
415 encoded_len
= socks5_client_version_encode(buf
, encoded_len
, v
);
416 tor_assert(encoded_len
> 0);
418 socks5_client_version_free(v
);
420 if (write_all_to_socket(s
, (const char *)buf
,
421 encoded_len
) != encoded_len
) {
422 log_err(LD_NET
, "Error sending SOCKS5 method list.");
430 uint8_t method_buf
[2];
432 if (read_all_from_socket(s
, (char *)method_buf
, 2) != 2) {
433 log_err(LD_NET
, "Error reading SOCKS5 methods.");
437 socks5_server_method_t
*m
;
438 ssize_t parsed
= socks5_server_method_parse(&m
, method_buf
,
442 log_err(LD_NET
, "Failed to parse SOCKS5 method selection "
444 socks5_server_method_free(m
);
448 uint8_t method
= socks5_server_method_get_method(m
);
450 socks5_server_method_free(m
);
452 if (method
!= 0x00) {
453 log_err(LD_NET
, "Unrecognized socks authentication method: %u",
459 if ((len
= build_socks_resolve_request(&req
, "", hostname
, reverse
,
461 log_err(LD_BUG
,"Error generating SOCKS request");
465 if (write_all_to_socket(s
, (const char *)req
, len
) != len
) {
466 log_sock_error("sending SOCKS request", s
);
473 char reply_buf
[RESPONSE_LEN_4
];
474 if (read_all_from_socket(s
, reply_buf
, RESPONSE_LEN_4
) != RESPONSE_LEN_4
) {
475 log_err(LD_NET
, "Error reading SOCKS4 response.");
478 if (parse_socks4a_resolve_response(hostname
,
479 reply_buf
, RESPONSE_LEN_4
,
484 uint8_t reply_buf
[512];
486 len
= read_all_from_socket(s
, (char *)reply_buf
,
489 socks5_server_reply_t
*reply
;
491 ssize_t parsed
= socks5_server_reply_parse(&reply
,
495 log_err(LD_NET
, "Failed parsing SOCKS5 response");
500 log_err(LD_NET
, "Truncated SOCKS5 response");
504 /* Give a user some useful feedback about SOCKS5 errors */
505 uint8_t reply_field
= socks5_server_reply_get_reply(reply
);
506 if (reply_field
!= 0) {
507 log_warn(LD_NET
,"Got SOCKS5 status response '%u': %s",
508 (unsigned)reply_field
,
509 socks5_reason_to_string(reply_field
));
510 if (reply_field
== 4 && !strcasecmpend(hostname
, ".onion")) {
511 onion_hs_warning(hostname
);
514 if (reply_field
== 4 && !strcasecmpend(hostname
, ".exit")) {
515 onion_exit_warning(hostname
);
518 socks5_server_reply_free(reply
);
522 uint8_t atype
= socks5_server_reply_get_atype(reply
);
524 if (atype
== SOCKS5_ATYPE_IPV4
) {
526 tor_addr_from_ipv4h(result_addr
,
527 socks5_server_reply_get_bind_addr_ipv4(reply
));
528 } else if (atype
== SOCKS5_ATYPE_IPV6
) {
530 tor_addr_from_ipv6_bytes(result_addr
,
531 socks5_server_reply_getarray_bind_addr_ipv6(reply
));
532 } else if (atype
== SOCKS5_ATYPE_HOSTNAME
) {
535 socks5_server_reply_get_bind_addr_domainname(reply
);
537 *result_hostname
= tor_strdup(domainname_getstr_name(dn
));
540 socks5_server_reply_free(reply
);
550 /** Print a usage message and exit. */
554 puts("Syntax: tor-resolve [-4] [-5] [-v] [-x] [-p port] "
555 "hostname [sockshost[:socksport]]");
559 /** Entry point to tor-resolve */
561 main(int argc
, char **argv
)
563 tor_addr_t sockshost
;
564 uint16_t socksport
= 0, port_option
= 0;
565 int isSocks4
= 0, isVerbose
= 0, isReverse
= 0;
569 char *result_hostname
= NULL
;
572 sandbox_disable_getaddrinfo_cache();
580 if (!strcmp(arg
[0],"--version")) {
581 printf("Tor version %s.\n",VERSION
);
584 while (n_args
&& *arg
[0] == '-') {
585 if (!strcmp("-v", arg
[0]))
587 else if (!strcmp("-4", arg
[0]))
589 else if (!strcmp("-5", arg
[0]))
591 else if (!strcmp("-x", arg
[0]))
593 else if (!strcmp("-p", arg
[0])) {
596 fprintf(stderr
, "No arguments given to -p\n");
600 if (p
<1 || p
> 65535) {
601 fprintf(stderr
, "-p requires a number between 1 and 65535\n");
604 port_option
= (uint16_t) p
;
605 ++arg
; /* skip the port */
608 fprintf(stderr
, "Unrecognized flag '%s'\n", arg
[0]);
615 if (isSocks4
&& isReverse
) {
616 fprintf(stderr
, "Reverse lookups not supported with SOCKS4a\n");
620 log_severity_list_t
*severities
=
621 tor_malloc_zero(sizeof(log_severity_list_t
));
623 set_log_severity_config(LOG_DEBUG
, LOG_ERR
, severities
);
625 set_log_severity_config(LOG_WARN
, LOG_ERR
, severities
);
626 add_stream_log(severities
, "<stderr>", fileno(stderr
));
627 tor_free(severities
);
630 log_debug(LD_CONFIG
, "defaulting to localhost");
631 tor_addr_from_ipv4h(&sockshost
, 0x7f000001u
); /* localhost */
633 log_debug(LD_CONFIG
, "Using port %d", (int)port_option
);
634 socksport
= port_option
;
636 log_debug(LD_CONFIG
, "defaulting to port 9050");
637 socksport
= 9050; /* 9050 */
639 } else if (n_args
== 2) {
640 if (tor_addr_port_lookup(arg
[1], &sockshost
, &socksport
)<0) {
641 fprintf(stderr
, "Couldn't parse/resolve address %s", arg
[1]);
644 if (socksport
&& port_option
&& socksport
!= port_option
) {
645 log_warn(LD_CONFIG
, "Conflicting ports; using %d, not %d",
646 (int)socksport
, (int)port_option
);
647 } else if (port_option
) {
648 socksport
= port_option
;
649 } else if (!socksport
) {
650 log_debug(LD_CONFIG
, "defaulting to port 9050");
657 if (network_init()<0) {
658 log_err(LD_BUG
,"Error initializing network; exiting.");
662 if (do_resolve(arg
[0], &sockshost
, socksport
, isReverse
,
663 isSocks4
? 4 : 5, &result
,
667 if (result_hostname
) {
668 printf("%s\n", result_hostname
);
670 printf("%s\n", fmt_addr(&result
));