tor-resolve.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson
  2. * Copyright (c) 2007-2018, The Tor Project, Inc.
  3. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #include "lib/arch/bytes.h"
  7. #include "lib/log/log.h"
  8. #include "lib/malloc/malloc.h"
  9. #include "lib/net/address.h"
  10. #include "lib/net/resolve.h"
  11. #include "lib/net/socket.h"
  12. #include "lib/sandbox/sandbox.h"
  13. #include "lib/string/util_string.h"
  14. #include "lib/net/socks5_status.h"
  15. #include "socks5.h"
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <stdarg.h>
  19. #include <string.h>
  20. #ifdef HAVE_NETINET_IN_H
  21. #include <netinet/in.h>
  22. #endif
  23. #ifdef HAVE_ARPA_INET_H
  24. #include <arpa/inet.h>
  25. #endif
  26. #ifdef HAVE_SYS_SOCKET_H
  27. #include <sys/socket.h>
  28. #endif
  29. #ifdef HAVE_SYS_TYPES_H
  30. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  31. #endif
  32. #ifdef HAVE_ERRNO_H
  33. #include <errno.h>
  34. #endif
  35. #ifdef _WIN32
  36. #include <winsock2.h>
  37. #include <ws2tcpip.h>
  38. #endif
  39. #define RESPONSE_LEN_4 8
  40. #define log_sock_error(act, _s) \
  41. STMT_BEGIN log_fn(LOG_ERR, LD_NET, "Error while %s: %s", act, \
  42. tor_socket_strerror(tor_socket_errno(_s))); STMT_END
  43. static void usage(void) ATTR_NORETURN;
  44. /**
  45. * Set <b>out</b> to a pointer to newly allocated buffer containing
  46. * SOCKS4a RESOLVE request with <b>username</b> and <b>hostname</b>.
  47. * Return number of bytes in the buffer if succeeded or -1 if failed.
  48. */
  49. static ssize_t
  50. build_socks4a_resolve_request(uint8_t **out,
  51. const char *username,
  52. const char *hostname)
  53. {
  54. tor_assert(out);
  55. tor_assert(username);
  56. tor_assert(hostname);
  57. const char *errmsg = NULL;
  58. uint8_t *output = NULL;
  59. socks4_client_request_t *rq = socks4_client_request_new();
  60. socks4_client_request_set_version(rq, 4);
  61. socks4_client_request_set_command(rq, CMD_RESOLVE);
  62. socks4_client_request_set_port(rq, 0);
  63. socks4_client_request_set_addr(rq, 0x00000001u);
  64. socks4_client_request_set_username(rq, username);
  65. socks4_client_request_set_socks4a_addr_hostname(rq, hostname);
  66. errmsg = socks4_client_request_check(rq);
  67. if (errmsg) {
  68. goto cleanup;
  69. }
  70. ssize_t encoded_len = socks4_client_request_encoded_len(rq);
  71. if (encoded_len <= 0) {
  72. errmsg = "socks4_client_request_encoded_len failed";
  73. goto cleanup;
  74. }
  75. output = tor_malloc(encoded_len);
  76. memset(output, 0, encoded_len);
  77. encoded_len = socks4_client_request_encode(output, encoded_len, rq);
  78. if (encoded_len <= 0) {
  79. errmsg = "socks4_client_request_encode failed";
  80. goto cleanup;
  81. }
  82. *out = output;
  83. cleanup:
  84. socks4_client_request_free(rq);
  85. if (errmsg) {
  86. log_err(LD_NET, "build_socks4a_resolve_request failed: %s", errmsg);
  87. *out = NULL;
  88. tor_free(output);
  89. }
  90. return errmsg ? -1 : encoded_len;
  91. }
  92. #define SOCKS5_ATYPE_HOSTNAME 0x03
  93. #define SOCKS5_ATYPE_IPV4 0x01
  94. #define SOCKS5_ATYPE_IPV6 0x04
  95. /**
  96. * Set <b>out</b> to pointer to newly allocated buffer containing
  97. * SOCKS5 RESOLVE/RESOLVE_PTR request with given <b>hostname<b>.
  98. * Generate a reverse request if <b>reverse</b> is true.
  99. * Return the number of bytes in the buffer if succeeded or -1 if failed.
  100. */
  101. static ssize_t
  102. build_socks5_resolve_request(uint8_t **out,
  103. const char *hostname,
  104. int reverse)
  105. {
  106. const char *errmsg = NULL;
  107. uint8_t *outbuf = NULL;
  108. int is_ip_address;
  109. tor_addr_t addr;
  110. size_t addrlen;
  111. int ipv6;
  112. is_ip_address = tor_addr_parse(&addr, hostname) != -1;
  113. if (!is_ip_address && reverse) {
  114. log_err(LD_GENERAL, "Tried to do a reverse lookup on a non-IP!");
  115. return -1;
  116. }
  117. ipv6 = reverse && tor_addr_family(&addr) == AF_INET6;
  118. addrlen = reverse ? (ipv6 ? 16 : 4) : 1 + strlen(hostname);
  119. if (addrlen > UINT8_MAX) {
  120. log_err(LD_GENERAL, "Hostname is too long!");
  121. return -1;
  122. }
  123. socks5_client_request_t *rq = socks5_client_request_new();
  124. socks5_client_request_set_version(rq, 5);
  125. /* RESOLVE_PTR or RESOLVE */
  126. socks5_client_request_set_command(rq, reverse ? CMD_RESOLVE_PTR :
  127. CMD_RESOLVE);
  128. socks5_client_request_set_reserved(rq, 0);
  129. uint8_t atype = SOCKS5_ATYPE_HOSTNAME;
  130. if (reverse)
  131. atype = ipv6 ? SOCKS5_ATYPE_IPV6 : SOCKS5_ATYPE_IPV4;
  132. socks5_client_request_set_atype(rq, atype);
  133. switch (atype) {
  134. case SOCKS5_ATYPE_IPV4: {
  135. socks5_client_request_set_dest_addr_ipv4(rq,
  136. tor_addr_to_ipv4h(&addr));
  137. } break;
  138. case SOCKS5_ATYPE_IPV6: {
  139. uint8_t *ipv6_array =
  140. socks5_client_request_getarray_dest_addr_ipv6(rq);
  141. tor_assert(ipv6_array);
  142. memcpy(ipv6_array, tor_addr_to_in6_addr8(&addr), 16);
  143. } break;
  144. case SOCKS5_ATYPE_HOSTNAME: {
  145. domainname_t *dn = domainname_new();
  146. domainname_set_len(dn, addrlen - 1);
  147. domainname_setlen_name(dn, addrlen - 1);
  148. char *dn_buf = domainname_getarray_name(dn);
  149. memcpy(dn_buf, hostname, addrlen - 1);
  150. errmsg = domainname_check(dn);
  151. if (errmsg) {
  152. domainname_free(dn);
  153. goto cleanup;
  154. } else {
  155. socks5_client_request_set_dest_addr_domainname(rq, dn);
  156. }
  157. } break;
  158. default:
  159. tor_assert_unreached();
  160. break;
  161. }
  162. socks5_client_request_set_dest_port(rq, 0);
  163. errmsg = socks5_client_request_check(rq);
  164. if (errmsg) {
  165. goto cleanup;
  166. }
  167. ssize_t encoded_len = socks5_client_request_encoded_len(rq);
  168. if (encoded_len < 0) {
  169. errmsg = "Cannot predict encoded length";
  170. goto cleanup;
  171. }
  172. outbuf = tor_malloc(encoded_len);
  173. memset(outbuf, 0, encoded_len);
  174. encoded_len = socks5_client_request_encode(outbuf, encoded_len, rq);
  175. if (encoded_len < 0) {
  176. errmsg = "encoding failed";
  177. goto cleanup;
  178. }
  179. *out = outbuf;
  180. cleanup:
  181. socks5_client_request_free(rq);
  182. if (errmsg) {
  183. tor_free(outbuf);
  184. log_err(LD_NET, "build_socks5_resolve_request failed with error: %s",
  185. errmsg);
  186. }
  187. return errmsg ? -1 : encoded_len;
  188. }
  189. /** Set *<b>out</b> to a newly allocated SOCKS4a resolve request with
  190. * <b>username</b> and <b>hostname</b> as provided. Return the number
  191. * of bytes in the request. */
  192. static ssize_t
  193. build_socks_resolve_request(uint8_t **out,
  194. const char *username,
  195. const char *hostname,
  196. int reverse,
  197. int version)
  198. {
  199. tor_assert(out);
  200. tor_assert(username);
  201. tor_assert(hostname);
  202. tor_assert(version == 4 || version == 5);
  203. if (version == 4) {
  204. return build_socks4a_resolve_request(out, username, hostname);
  205. } else if (version == 5) {
  206. return build_socks5_resolve_request(out, hostname, reverse);
  207. }
  208. tor_assert_unreached();
  209. return -1;
  210. }
  211. static void
  212. onion_warning(const char *hostname)
  213. {
  214. log_warn(LD_NET,
  215. "%s is a hidden service; those don't have IP addresses. "
  216. "You can use the AutomapHostsOnResolve option to have Tor return a "
  217. "fake address for hidden services. Or you can have your "
  218. "application send the address to Tor directly; we recommend an "
  219. "application that uses SOCKS 5 with hostnames.",
  220. hostname);
  221. }
  222. /** Given a <b>len</b>-byte SOCKS4a response in <b>response</b>, set
  223. * *<b>addr_out</b> to the address it contains (in host order).
  224. * Return 0 on success, -1 on error.
  225. */
  226. static int
  227. parse_socks4a_resolve_response(const char *hostname,
  228. const char *response, size_t len,
  229. tor_addr_t *addr_out)
  230. {
  231. uint8_t status;
  232. tor_assert(response);
  233. tor_assert(addr_out);
  234. if (len < RESPONSE_LEN_4) {
  235. log_warn(LD_PROTOCOL,"Truncated socks response.");
  236. return -1;
  237. }
  238. if (((uint8_t)response[0])!=0) { /* version: 0 */
  239. log_warn(LD_PROTOCOL,"Nonzero version in socks response: bad format.");
  240. return -1;
  241. }
  242. status = (uint8_t)response[1];
  243. if (get_uint16(response+2)!=0) { /* port: 0 */
  244. log_warn(LD_PROTOCOL,"Nonzero port in socks response: bad format.");
  245. return -1;
  246. }
  247. if (status != 90) {
  248. log_warn(LD_NET,"Got status response '%d': socks request failed.", status);
  249. if (!strcasecmpend(hostname, ".onion")) {
  250. onion_warning(hostname);
  251. return -1;
  252. }
  253. return -1;
  254. }
  255. tor_addr_from_ipv4n(addr_out, get_uint32(response+4));
  256. return 0;
  257. }
  258. /* It would be nice to let someone know what SOCKS5 issue a user may have */
  259. static const char *
  260. socks5_reason_to_string(char reason)
  261. {
  262. switch (reason) {
  263. case SOCKS5_SUCCEEDED:
  264. return "succeeded";
  265. case SOCKS5_GENERAL_ERROR:
  266. return "general error";
  267. case SOCKS5_NOT_ALLOWED:
  268. return "not allowed";
  269. case SOCKS5_NET_UNREACHABLE:
  270. return "network is unreachable";
  271. case SOCKS5_HOST_UNREACHABLE:
  272. return "host is unreachable";
  273. case SOCKS5_CONNECTION_REFUSED:
  274. return "connection refused";
  275. case SOCKS5_TTL_EXPIRED:
  276. return "ttl expired";
  277. case SOCKS5_COMMAND_NOT_SUPPORTED:
  278. return "command not supported";
  279. case SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED:
  280. return "address type not supported";
  281. default:
  282. return "unknown SOCKS5 code";
  283. }
  284. }
  285. /** Send a resolve request for <b>hostname</b> to the Tor listening on
  286. * <b>sockshost</b>:<b>socksport</b>. Store the resulting IPv4
  287. * address (in host order) into *<b>result_addr</b>.
  288. */
  289. static int
  290. do_resolve(const char *hostname,
  291. const tor_addr_t *sockshost, uint16_t socksport,
  292. int reverse, int version,
  293. tor_addr_t *result_addr, char **result_hostname)
  294. {
  295. int s = -1;
  296. struct sockaddr_storage ss;
  297. socklen_t socklen;
  298. uint8_t *req = NULL;
  299. ssize_t len = 0;
  300. tor_assert(hostname);
  301. tor_assert(result_addr);
  302. tor_assert(version == 4 || version == 5);
  303. tor_addr_make_unspec(result_addr);
  304. *result_hostname = NULL;
  305. s = tor_open_socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  306. if (s<0) {
  307. log_sock_error("creating_socket", -1);
  308. return -1;
  309. }
  310. socklen = tor_addr_to_sockaddr(sockshost, socksport,
  311. (struct sockaddr *)&ss, sizeof(ss));
  312. if (connect(s, (struct sockaddr*)&ss, socklen)) {
  313. log_sock_error("connecting to SOCKS host", s);
  314. goto err;
  315. }
  316. if (version == 5) {
  317. char method_buf[2];
  318. if (write_all_to_socket(s, (const char *)"\x05\x01\x00", 3) != 3) {
  319. log_err(LD_NET, "Error sending SOCKS5 method list.");
  320. goto err;
  321. }
  322. if (read_all_from_socket(s, method_buf, 2) != 2) {
  323. log_err(LD_NET, "Error reading SOCKS5 methods.");
  324. goto err;
  325. }
  326. if (method_buf[0] != '\x05') {
  327. log_err(LD_NET, "Unrecognized socks version: %u",
  328. (unsigned)method_buf[0]);
  329. goto err;
  330. }
  331. if (method_buf[1] != '\x00') {
  332. log_err(LD_NET, "Unrecognized socks authentication method: %u",
  333. (unsigned)method_buf[1]);
  334. goto err;
  335. }
  336. }
  337. if ((len = build_socks_resolve_request(&req, "", hostname, reverse,
  338. version))<0) {
  339. log_err(LD_BUG,"Error generating SOCKS request");
  340. tor_assert(!req);
  341. goto err;
  342. }
  343. if (write_all_to_socket(s, (const char *)req, len) != len) {
  344. log_sock_error("sending SOCKS request", s);
  345. tor_free(req);
  346. goto err;
  347. }
  348. tor_free(req);
  349. if (version == 4) {
  350. char reply_buf[RESPONSE_LEN_4];
  351. if (read_all_from_socket(s, reply_buf, RESPONSE_LEN_4) != RESPONSE_LEN_4) {
  352. log_err(LD_NET, "Error reading SOCKS4 response.");
  353. goto err;
  354. }
  355. if (parse_socks4a_resolve_response(hostname,
  356. reply_buf, RESPONSE_LEN_4,
  357. result_addr)<0) {
  358. goto err;
  359. }
  360. } else {
  361. char reply_buf[16];
  362. if (read_all_from_socket(s, reply_buf, 4) != 4) {
  363. log_err(LD_NET, "Error reading SOCKS5 response.");
  364. goto err;
  365. }
  366. if (reply_buf[0] != 5) {
  367. log_err(LD_NET, "Bad SOCKS5 reply version.");
  368. goto err;
  369. }
  370. /* Give a user some useful feedback about SOCKS5 errors */
  371. if (reply_buf[1] != 0) {
  372. log_warn(LD_NET,"Got SOCKS5 status response '%u': %s",
  373. (unsigned)reply_buf[1],
  374. socks5_reason_to_string(reply_buf[1]));
  375. if (reply_buf[1] == 4 && !strcasecmpend(hostname, ".onion")) {
  376. onion_warning(hostname);
  377. }
  378. goto err;
  379. }
  380. if (reply_buf[3] == 1) {
  381. /* IPv4 address */
  382. if (read_all_from_socket(s, reply_buf, 4) != 4) {
  383. log_err(LD_NET, "Error reading address in socks5 response.");
  384. goto err;
  385. }
  386. tor_addr_from_ipv4n(result_addr, get_uint32(reply_buf));
  387. } else if (reply_buf[3] == 4) {
  388. /* IPv6 address */
  389. if (read_all_from_socket(s, reply_buf, 16) != 16) {
  390. log_err(LD_NET, "Error reading address in socks5 response.");
  391. goto err;
  392. }
  393. tor_addr_from_ipv6_bytes(result_addr, reply_buf);
  394. } else if (reply_buf[3] == 3) {
  395. /* Domain name */
  396. size_t result_len;
  397. if (read_all_from_socket(s, reply_buf, 1) != 1) {
  398. log_err(LD_NET, "Error reading address_length in socks5 response.");
  399. goto err;
  400. }
  401. result_len = *(uint8_t*)(reply_buf);
  402. *result_hostname = tor_malloc(result_len+1);
  403. if (read_all_from_socket(s, *result_hostname, result_len)
  404. != (int) result_len) {
  405. log_err(LD_NET, "Error reading hostname in socks5 response.");
  406. goto err;
  407. }
  408. (*result_hostname)[result_len] = '\0';
  409. }
  410. }
  411. tor_close_socket(s);
  412. return 0;
  413. err:
  414. tor_close_socket(s);
  415. return -1;
  416. }
  417. /** Print a usage message and exit. */
  418. static void
  419. usage(void)
  420. {
  421. puts("Syntax: tor-resolve [-4] [-5] [-v] [-x] [-p port] "
  422. "hostname [sockshost[:socksport]]");
  423. exit(1);
  424. }
  425. /** Entry point to tor-resolve */
  426. int
  427. main(int argc, char **argv)
  428. {
  429. tor_addr_t sockshost;
  430. uint16_t socksport = 0, port_option = 0;
  431. int isSocks4 = 0, isVerbose = 0, isReverse = 0;
  432. char **arg;
  433. int n_args;
  434. tor_addr_t result;
  435. char *result_hostname = NULL;
  436. init_logging(1);
  437. sandbox_disable_getaddrinfo_cache();
  438. arg = &argv[1];
  439. n_args = argc-1;
  440. if (!n_args)
  441. usage();
  442. if (!strcmp(arg[0],"--version")) {
  443. printf("Tor version %s.\n",VERSION);
  444. return 0;
  445. }
  446. while (n_args && *arg[0] == '-') {
  447. if (!strcmp("-v", arg[0]))
  448. isVerbose = 1;
  449. else if (!strcmp("-4", arg[0]))
  450. isSocks4 = 1;
  451. else if (!strcmp("-5", arg[0]))
  452. isSocks4 = 0;
  453. else if (!strcmp("-x", arg[0]))
  454. isReverse = 1;
  455. else if (!strcmp("-p", arg[0])) {
  456. int p;
  457. if (n_args < 2) {
  458. fprintf(stderr, "No arguments given to -p\n");
  459. usage();
  460. }
  461. p = atoi(arg[1]);
  462. if (p<1 || p > 65535) {
  463. fprintf(stderr, "-p requires a number between 1 and 65535\n");
  464. usage();
  465. }
  466. port_option = (uint16_t) p;
  467. ++arg; /* skip the port */
  468. --n_args;
  469. } else {
  470. fprintf(stderr, "Unrecognized flag '%s'\n", arg[0]);
  471. usage();
  472. }
  473. ++arg;
  474. --n_args;
  475. }
  476. if (isSocks4 && isReverse) {
  477. fprintf(stderr, "Reverse lookups not supported with SOCKS4a\n");
  478. usage();
  479. }
  480. log_severity_list_t *severities =
  481. tor_malloc_zero(sizeof(log_severity_list_t));
  482. if (isVerbose)
  483. set_log_severity_config(LOG_DEBUG, LOG_ERR, severities);
  484. else
  485. set_log_severity_config(LOG_WARN, LOG_ERR, severities);
  486. add_stream_log(severities, "<stderr>", fileno(stderr));
  487. tor_free(severities);
  488. if (n_args == 1) {
  489. log_debug(LD_CONFIG, "defaulting to localhost");
  490. tor_addr_from_ipv4h(&sockshost, 0x7f000001u); /* localhost */
  491. if (port_option) {
  492. log_debug(LD_CONFIG, "Using port %d", (int)port_option);
  493. socksport = port_option;
  494. } else {
  495. log_debug(LD_CONFIG, "defaulting to port 9050");
  496. socksport = 9050; /* 9050 */
  497. }
  498. } else if (n_args == 2) {
  499. if (tor_addr_port_lookup(arg[1], &sockshost, &socksport)<0) {
  500. fprintf(stderr, "Couldn't parse/resolve address %s", arg[1]);
  501. return 1;
  502. }
  503. if (socksport && port_option && socksport != port_option) {
  504. log_warn(LD_CONFIG, "Conflicting ports; using %d, not %d",
  505. (int)socksport, (int)port_option);
  506. } else if (port_option) {
  507. socksport = port_option;
  508. } else if (!socksport) {
  509. log_debug(LD_CONFIG, "defaulting to port 9050");
  510. socksport = 9050;
  511. }
  512. } else {
  513. usage();
  514. }
  515. if (network_init()<0) {
  516. log_err(LD_BUG,"Error initializing network; exiting.");
  517. return 1;
  518. }
  519. if (do_resolve(arg[0], &sockshost, socksport, isReverse,
  520. isSocks4 ? 4 : 5, &result,
  521. &result_hostname))
  522. return 1;
  523. if (result_hostname) {
  524. printf("%s\n", result_hostname);
  525. } else {
  526. printf("%s\n", fmt_addr(&result));
  527. }
  528. return 0;
  529. }