tor-resolve.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson
  2. * Copyright (c) 2007-2019, 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 "trunnel/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. int result = 0;
  232. uint8_t status;
  233. tor_assert(response);
  234. tor_assert(addr_out);
  235. socks4_server_reply_t *reply;
  236. ssize_t parsed = socks4_server_reply_parse(&reply,
  237. (const uint8_t *)response,
  238. len);
  239. if (parsed == -1) {
  240. log_warn(LD_PROTOCOL, "Failed parsing SOCKS4a response");
  241. result = -1; goto cleanup;
  242. }
  243. if (parsed == -2) {
  244. log_warn(LD_PROTOCOL,"Truncated socks response.");
  245. result = -1; goto cleanup;
  246. }
  247. if (socks4_server_reply_get_version(reply) != 0) { /* version: 0 */
  248. log_warn(LD_PROTOCOL,"Nonzero version in socks response: bad format.");
  249. result = -1; goto cleanup;
  250. }
  251. if (socks4_server_reply_get_port(reply) != 0) { /* port: 0 */
  252. log_warn(LD_PROTOCOL,"Nonzero port in socks response: bad format.");
  253. result = -1; goto cleanup;
  254. }
  255. status = socks4_server_reply_get_status(reply);
  256. if (status != 90) {
  257. log_warn(LD_NET,"Got status response '%d': socks request failed.", status);
  258. if (!strcasecmpend(hostname, ".onion")) {
  259. onion_warning(hostname);
  260. result = -1; goto cleanup;
  261. }
  262. result = -1; goto cleanup;
  263. }
  264. tor_addr_from_ipv4h(addr_out, socks4_server_reply_get_addr(reply));
  265. cleanup:
  266. socks4_server_reply_free(reply);
  267. return result;
  268. }
  269. /* It would be nice to let someone know what SOCKS5 issue a user may have */
  270. static const char *
  271. socks5_reason_to_string(char reason)
  272. {
  273. switch (reason) {
  274. case SOCKS5_SUCCEEDED:
  275. return "succeeded";
  276. case SOCKS5_GENERAL_ERROR:
  277. return "general error";
  278. case SOCKS5_NOT_ALLOWED:
  279. return "not allowed";
  280. case SOCKS5_NET_UNREACHABLE:
  281. return "network is unreachable";
  282. case SOCKS5_HOST_UNREACHABLE:
  283. return "host is unreachable";
  284. case SOCKS5_CONNECTION_REFUSED:
  285. return "connection refused";
  286. case SOCKS5_TTL_EXPIRED:
  287. return "ttl expired";
  288. case SOCKS5_COMMAND_NOT_SUPPORTED:
  289. return "command not supported";
  290. case SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED:
  291. return "address type not supported";
  292. default:
  293. return "unknown SOCKS5 code";
  294. }
  295. }
  296. /** Send a resolve request for <b>hostname</b> to the Tor listening on
  297. * <b>sockshost</b>:<b>socksport</b>. Store the resulting IPv4
  298. * address (in host order) into *<b>result_addr</b>.
  299. */
  300. static int
  301. do_resolve(const char *hostname,
  302. const tor_addr_t *sockshost, uint16_t socksport,
  303. int reverse, int version,
  304. tor_addr_t *result_addr, char **result_hostname)
  305. {
  306. int s = -1;
  307. struct sockaddr_storage ss;
  308. socklen_t socklen;
  309. uint8_t *req = NULL;
  310. ssize_t len = 0;
  311. tor_assert(hostname);
  312. tor_assert(result_addr);
  313. tor_assert(version == 4 || version == 5);
  314. tor_addr_make_unspec(result_addr);
  315. *result_hostname = NULL;
  316. s = tor_open_socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  317. if (s<0) {
  318. log_sock_error("creating_socket", -1);
  319. return -1;
  320. }
  321. socklen = tor_addr_to_sockaddr(sockshost, socksport,
  322. (struct sockaddr *)&ss, sizeof(ss));
  323. if (connect(s, (struct sockaddr*)&ss, socklen)) {
  324. log_sock_error("connecting to SOCKS host", s);
  325. goto err;
  326. }
  327. if (version == 5) {
  328. socks5_client_version_t *v = socks5_client_version_new();
  329. socks5_client_version_set_version(v, 5);
  330. socks5_client_version_set_n_methods(v, 1);
  331. socks5_client_version_setlen_methods(v, 1);
  332. socks5_client_version_set_methods(v, 0, 0x00);
  333. tor_assert(!socks5_client_version_check(v));
  334. ssize_t encoded_len = socks5_client_version_encoded_len(v);
  335. tor_assert(encoded_len > 0);
  336. uint8_t *buf = tor_malloc(encoded_len);
  337. encoded_len = socks5_client_version_encode(buf, encoded_len, v);
  338. tor_assert(encoded_len > 0);
  339. socks5_client_version_free(v);
  340. if (write_all_to_socket(s, (const char *)buf,
  341. encoded_len) != encoded_len) {
  342. log_err(LD_NET, "Error sending SOCKS5 method list.");
  343. tor_free(buf);
  344. goto err;
  345. }
  346. tor_free(buf);
  347. uint8_t method_buf[2];
  348. if (read_all_from_socket(s, (char *)method_buf, 2) != 2) {
  349. log_err(LD_NET, "Error reading SOCKS5 methods.");
  350. goto err;
  351. }
  352. socks5_server_method_t *m;
  353. ssize_t parsed = socks5_server_method_parse(&m, method_buf,
  354. sizeof(method_buf));
  355. if (parsed < 2) {
  356. log_err(LD_NET, "Failed to parse SOCKS5 method selection "
  357. "message");
  358. goto err;
  359. }
  360. uint8_t method = socks5_server_method_get_method(m);
  361. socks5_server_method_free(m);
  362. if (method != 0x00) {
  363. log_err(LD_NET, "Unrecognized socks authentication method: %u",
  364. (unsigned)method);
  365. goto err;
  366. }
  367. }
  368. if ((len = build_socks_resolve_request(&req, "", hostname, reverse,
  369. version))<0) {
  370. log_err(LD_BUG,"Error generating SOCKS request");
  371. tor_assert(!req);
  372. goto err;
  373. }
  374. if (write_all_to_socket(s, (const char *)req, len) != len) {
  375. log_sock_error("sending SOCKS request", s);
  376. tor_free(req);
  377. goto err;
  378. }
  379. tor_free(req);
  380. if (version == 4) {
  381. char reply_buf[RESPONSE_LEN_4];
  382. if (read_all_from_socket(s, reply_buf, RESPONSE_LEN_4) != RESPONSE_LEN_4) {
  383. log_err(LD_NET, "Error reading SOCKS4 response.");
  384. goto err;
  385. }
  386. if (parse_socks4a_resolve_response(hostname,
  387. reply_buf, RESPONSE_LEN_4,
  388. result_addr)<0) {
  389. goto err;
  390. }
  391. } else {
  392. uint8_t reply_buf[512];
  393. len = read_all_from_socket(s, (char *)reply_buf,
  394. sizeof(reply_buf));
  395. socks5_server_reply_t *reply;
  396. ssize_t parsed = socks5_server_reply_parse(&reply,
  397. reply_buf,
  398. len);
  399. if (parsed == -1) {
  400. log_err(LD_NET, "Failed parsing SOCKS5 response");
  401. goto err;
  402. }
  403. if (parsed == -2) {
  404. log_err(LD_NET, "Truncated SOCKS5 response");
  405. goto err;
  406. }
  407. /* Give a user some useful feedback about SOCKS5 errors */
  408. uint8_t reply_field = socks5_server_reply_get_reply(reply);
  409. if (reply_field != 0) {
  410. log_warn(LD_NET,"Got SOCKS5 status response '%u': %s",
  411. (unsigned)reply_field,
  412. socks5_reason_to_string(reply_field));
  413. if (reply_field == 4 && !strcasecmpend(hostname, ".onion")) {
  414. onion_warning(hostname);
  415. }
  416. socks5_server_reply_free(reply);
  417. goto err;
  418. }
  419. uint8_t atype = socks5_server_reply_get_atype(reply);
  420. if (atype == SOCKS5_ATYPE_IPV4) {
  421. /* IPv4 address */
  422. tor_addr_from_ipv4h(result_addr,
  423. socks5_server_reply_get_bind_addr_ipv4(reply));
  424. } else if (atype == SOCKS5_ATYPE_IPV6) {
  425. /* IPv6 address */
  426. tor_addr_from_ipv6_bytes(result_addr,
  427. (const char *)socks5_server_reply_getarray_bind_addr_ipv6(reply));
  428. } else if (atype == SOCKS5_ATYPE_HOSTNAME) {
  429. /* Domain name */
  430. domainname_t *dn =
  431. socks5_server_reply_get_bind_addr_domainname(reply);
  432. *result_hostname = tor_strdup(domainname_getstr_name(dn));
  433. }
  434. socks5_server_reply_free(reply);
  435. }
  436. tor_close_socket(s);
  437. return 0;
  438. err:
  439. tor_close_socket(s);
  440. return -1;
  441. }
  442. /** Print a usage message and exit. */
  443. static void
  444. usage(void)
  445. {
  446. puts("Syntax: tor-resolve [-4] [-5] [-v] [-x] [-p port] "
  447. "hostname [sockshost[:socksport]]");
  448. exit(1);
  449. }
  450. /** Entry point to tor-resolve */
  451. int
  452. main(int argc, char **argv)
  453. {
  454. tor_addr_t sockshost;
  455. uint16_t socksport = 0, port_option = 0;
  456. int isSocks4 = 0, isVerbose = 0, isReverse = 0;
  457. char **arg;
  458. int n_args;
  459. tor_addr_t result;
  460. char *result_hostname = NULL;
  461. init_logging(1);
  462. sandbox_disable_getaddrinfo_cache();
  463. arg = &argv[1];
  464. n_args = argc-1;
  465. if (!n_args)
  466. usage();
  467. if (!strcmp(arg[0],"--version")) {
  468. printf("Tor version %s.\n",VERSION);
  469. return 0;
  470. }
  471. while (n_args && *arg[0] == '-') {
  472. if (!strcmp("-v", arg[0]))
  473. isVerbose = 1;
  474. else if (!strcmp("-4", arg[0]))
  475. isSocks4 = 1;
  476. else if (!strcmp("-5", arg[0]))
  477. isSocks4 = 0;
  478. else if (!strcmp("-x", arg[0]))
  479. isReverse = 1;
  480. else if (!strcmp("-p", arg[0])) {
  481. int p;
  482. if (n_args < 2) {
  483. fprintf(stderr, "No arguments given to -p\n");
  484. usage();
  485. }
  486. p = atoi(arg[1]);
  487. if (p<1 || p > 65535) {
  488. fprintf(stderr, "-p requires a number between 1 and 65535\n");
  489. usage();
  490. }
  491. port_option = (uint16_t) p;
  492. ++arg; /* skip the port */
  493. --n_args;
  494. } else {
  495. fprintf(stderr, "Unrecognized flag '%s'\n", arg[0]);
  496. usage();
  497. }
  498. ++arg;
  499. --n_args;
  500. }
  501. if (isSocks4 && isReverse) {
  502. fprintf(stderr, "Reverse lookups not supported with SOCKS4a\n");
  503. usage();
  504. }
  505. log_severity_list_t *severities =
  506. tor_malloc_zero(sizeof(log_severity_list_t));
  507. if (isVerbose)
  508. set_log_severity_config(LOG_DEBUG, LOG_ERR, severities);
  509. else
  510. set_log_severity_config(LOG_WARN, LOG_ERR, severities);
  511. add_stream_log(severities, "<stderr>", fileno(stderr));
  512. tor_free(severities);
  513. if (n_args == 1) {
  514. log_debug(LD_CONFIG, "defaulting to localhost");
  515. tor_addr_from_ipv4h(&sockshost, 0x7f000001u); /* localhost */
  516. if (port_option) {
  517. log_debug(LD_CONFIG, "Using port %d", (int)port_option);
  518. socksport = port_option;
  519. } else {
  520. log_debug(LD_CONFIG, "defaulting to port 9050");
  521. socksport = 9050; /* 9050 */
  522. }
  523. } else if (n_args == 2) {
  524. if (tor_addr_port_lookup(arg[1], &sockshost, &socksport)<0) {
  525. fprintf(stderr, "Couldn't parse/resolve address %s", arg[1]);
  526. return 1;
  527. }
  528. if (socksport && port_option && socksport != port_option) {
  529. log_warn(LD_CONFIG, "Conflicting ports; using %d, not %d",
  530. (int)socksport, (int)port_option);
  531. } else if (port_option) {
  532. socksport = port_option;
  533. } else if (!socksport) {
  534. log_debug(LD_CONFIG, "defaulting to port 9050");
  535. socksport = 9050;
  536. }
  537. } else {
  538. usage();
  539. }
  540. if (network_init()<0) {
  541. log_err(LD_BUG,"Error initializing network; exiting.");
  542. return 1;
  543. }
  544. if (do_resolve(arg[0], &sockshost, socksport, isReverse,
  545. isSocks4 ? 4 : 5, &result,
  546. &result_hostname))
  547. return 1;
  548. if (result_hostname) {
  549. printf("%s\n", result_hostname);
  550. } else {
  551. printf("%s\n", fmt_addr(&result));
  552. }
  553. return 0;
  554. }