proto_socks.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. #include "core/or/or.h"
  7. #include "feature/client/addressmap.h"
  8. #include "lib/container/buffers.h"
  9. #include "core/mainloop/connection.h"
  10. #include "feature/control/control.h"
  11. #include "app/config/config.h"
  12. #include "lib/crypt_ops/crypto_util.h"
  13. #include "feature/relay/ext_orport.h"
  14. #include "core/proto/proto_socks.h"
  15. #include "core/or/reasons.h"
  16. #include "core/or/socks_request_st.h"
  17. #include "trunnel/socks5.h"
  18. #define SOCKS_VER_5 0x05 /* First octet of non-auth SOCKS5 messages */
  19. #define SOCKS_VER_4 0x04 /* SOCKS4 messages */
  20. #define SOCKS_AUTH 0x01 /* SOCKS5 auth messages */
  21. typedef enum {
  22. SOCKS_RESULT_INVALID = -1, /* Message invalid. */
  23. SOCKS_RESULT_TRUNCATED = 0, /* Message incomplete/truncated. */
  24. SOCKS_RESULT_DONE = 1, /* OK, we're done. */
  25. SOCKS_RESULT_MORE_EXPECTED = 2, /* OK, more messages expected. */
  26. } socks_result_t;
  27. static void socks_request_set_socks5_error(socks_request_t *req,
  28. socks5_reply_status_t reason);
  29. static socks_result_t parse_socks(const char *data,
  30. size_t datalen,
  31. socks_request_t *req,
  32. int log_sockstype,
  33. int safe_socks,
  34. size_t *drain_out);
  35. static int parse_socks_client(const uint8_t *data, size_t datalen,
  36. int state, char **reason,
  37. ssize_t *drain_out);
  38. /**
  39. * Wait this many seconds before warning the user about using SOCKS unsafely
  40. * again. */
  41. #define SOCKS_WARN_INTERVAL 5
  42. /** Warn that the user application has made an unsafe socks request using
  43. * protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
  44. * once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
  45. static void
  46. log_unsafe_socks_warning(int socks_protocol, const char *address,
  47. uint16_t port, int safe_socks)
  48. {
  49. static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
  50. if (safe_socks) {
  51. log_fn_ratelim(&socks_ratelim, LOG_WARN, LD_APP,
  52. "Your application (using socks%d to port %d) is giving "
  53. "Tor only an IP address. Applications that do DNS resolves "
  54. "themselves may leak information. Consider using Socks4A "
  55. "(e.g. via privoxy or socat) instead. For more information, "
  56. "please see https://wiki.torproject.org/TheOnionRouter/"
  57. "TorFAQ#SOCKSAndDNS.%s",
  58. socks_protocol,
  59. (int)port,
  60. safe_socks ? " Rejecting." : "");
  61. }
  62. control_event_client_status(LOG_WARN,
  63. "DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
  64. socks_protocol, address, (int)port);
  65. }
  66. /** Do not attempt to parse socks messages longer than this. This value is
  67. * actually significantly higher than the longest possible socks message. */
  68. #define MAX_SOCKS_MESSAGE_LEN 512
  69. /** Return a new socks_request_t. */
  70. socks_request_t *
  71. socks_request_new(void)
  72. {
  73. return tor_malloc_zero(sizeof(socks_request_t));
  74. }
  75. /** Free all storage held in the socks_request_t <b>req</b>. */
  76. void
  77. socks_request_free_(socks_request_t *req)
  78. {
  79. if (!req)
  80. return;
  81. if (req->username) {
  82. memwipe(req->username, 0x10, req->usernamelen);
  83. tor_free(req->username);
  84. }
  85. if (req->password) {
  86. memwipe(req->password, 0x04, req->passwordlen);
  87. tor_free(req->password);
  88. }
  89. memwipe(req, 0xCC, sizeof(socks_request_t));
  90. tor_free(req);
  91. }
  92. /**
  93. * Parse a single SOCKS4 request from buffer <b>raw_data</b> of length
  94. * <b>datalen</b> and update relevant fields of <b>req</b>. If SOCKS4a
  95. * request is detected, set <b>*is_socks4a<b> to true. Set <b>*drain_out</b>
  96. * to number of bytes we parsed so far.
  97. *
  98. * Return SOCKS_RESULT_DONE if parsing succeeded, SOCKS_RESULT_INVALID if
  99. * parsing failed because of invalid input or SOCKS_RESULT_TRUNCATED if it
  100. * failed due to incomplete (truncated) input.
  101. */
  102. static socks_result_t
  103. parse_socks4_request(const uint8_t *raw_data, socks_request_t *req,
  104. size_t datalen, int *is_socks4a, size_t *drain_out)
  105. {
  106. // http://ss5.sourceforge.net/socks4.protocol.txt
  107. // http://ss5.sourceforge.net/socks4A.protocol.txt
  108. socks_result_t res = SOCKS_RESULT_DONE;
  109. tor_addr_t destaddr;
  110. tor_assert(is_socks4a);
  111. tor_assert(drain_out);
  112. *is_socks4a = 0;
  113. *drain_out = 0;
  114. req->socks_version = SOCKS_VER_4;
  115. socks4_client_request_t *trunnel_req;
  116. ssize_t parsed =
  117. socks4_client_request_parse(&trunnel_req, raw_data, datalen);
  118. if (parsed == -1) {
  119. log_warn(LD_APP, "socks4: parsing failed - invalid request.");
  120. res = SOCKS_RESULT_INVALID;
  121. goto end;
  122. } else if (parsed == -2) {
  123. res = SOCKS_RESULT_TRUNCATED;
  124. if (datalen >= MAX_SOCKS_MESSAGE_LEN) {
  125. log_warn(LD_APP, "socks4: parsing failed - invalid request.");
  126. res = SOCKS_RESULT_INVALID;
  127. }
  128. goto end;
  129. }
  130. tor_assert(parsed >= 0);
  131. *drain_out = (size_t)parsed;
  132. uint8_t command = socks4_client_request_get_command(trunnel_req);
  133. req->command = command;
  134. req->port = socks4_client_request_get_port(trunnel_req);
  135. uint32_t dest_ip = socks4_client_request_get_addr(trunnel_req);
  136. if ((!req->port && req->command != SOCKS_COMMAND_RESOLVE) ||
  137. dest_ip == 0) {
  138. log_warn(LD_APP, "socks4: Port or DestIP is zero. Rejecting.");
  139. res = SOCKS_RESULT_INVALID;
  140. goto end;
  141. }
  142. *is_socks4a = (dest_ip >> 8) == 0;
  143. const char *username = socks4_client_request_get_username(trunnel_req);
  144. const size_t usernamelen = username ? strlen(username) : 0;
  145. if (username && usernamelen) {
  146. if (usernamelen > MAX_SOCKS_MESSAGE_LEN) {
  147. log_warn(LD_APP, "Socks4 user name too long; rejecting.");
  148. res = SOCKS_RESULT_INVALID;
  149. goto end;
  150. }
  151. tor_free(req->username);
  152. req->got_auth = 1;
  153. req->username = tor_strdup(username);
  154. req->usernamelen = usernamelen;
  155. }
  156. if (*is_socks4a) {
  157. // We cannot rely on trunnel here, as we want to detect if
  158. // we have abnormally long hostname field.
  159. const char *hostname = (char *)raw_data + SOCKS4_NETWORK_LEN +
  160. usernamelen + 1;
  161. size_t hostname_len = (char *)raw_data + datalen - hostname;
  162. if (hostname_len <= sizeof(req->address)) {
  163. const char *trunnel_hostname =
  164. socks4_client_request_get_socks4a_addr_hostname(trunnel_req);
  165. if (trunnel_hostname)
  166. strlcpy(req->address, trunnel_hostname, sizeof(req->address));
  167. } else {
  168. log_warn(LD_APP, "socks4: Destaddr too long. Rejecting.");
  169. res = SOCKS_RESULT_INVALID;
  170. goto end;
  171. }
  172. } else {
  173. tor_addr_from_ipv4h(&destaddr, dest_ip);
  174. if (!tor_addr_to_str(req->address, &destaddr,
  175. MAX_SOCKS_ADDR_LEN, 0)) {
  176. res = SOCKS_RESULT_INVALID;
  177. goto end;
  178. }
  179. }
  180. end:
  181. socks4_client_request_free(trunnel_req);
  182. return res;
  183. }
  184. /**
  185. * Validate SOCKS4/4a related fields in <b>req</b>. Expect SOCKS4a
  186. * if <b>is_socks4a</b> is true. If <b>log_sockstype</b> is true,
  187. * log a notice about possible DNS leaks on local system. If
  188. * <b>safe_socks</b> is true, reject insecure usage of SOCKS
  189. * protocol.
  190. *
  191. * Return SOCKS_RESULT_DONE if validation passed or
  192. * SOCKS_RESULT_INVALID if it failed.
  193. */
  194. static socks_result_t
  195. process_socks4_request(const socks_request_t *req, int is_socks4a,
  196. int log_sockstype, int safe_socks)
  197. {
  198. if (is_socks4a && !addressmap_have_mapping(req->address, 0)) {
  199. log_unsafe_socks_warning(4, req->address, req->port, safe_socks);
  200. if (safe_socks)
  201. return SOCKS_RESULT_INVALID;
  202. }
  203. if (req->command != SOCKS_COMMAND_CONNECT &&
  204. req->command != SOCKS_COMMAND_RESOLVE) {
  205. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  206. * socks4.) */
  207. log_warn(LD_APP, "socks4: command %d not recognized. Rejecting.",
  208. req->command);
  209. return SOCKS_RESULT_INVALID;
  210. }
  211. if (is_socks4a) {
  212. if (log_sockstype)
  213. log_notice(LD_APP,
  214. "Your application (using socks4a to port %d) instructed "
  215. "Tor to take care of the DNS resolution itself if "
  216. "necessary. This is good.", req->port);
  217. }
  218. if (!string_is_valid_dest(req->address)) {
  219. log_warn(LD_PROTOCOL,
  220. "Your application (using socks4 to port %d) gave Tor "
  221. "a malformed hostname: %s. Rejecting the connection.",
  222. req->port, escaped_safe_str_client(req->address));
  223. return SOCKS_RESULT_INVALID;
  224. }
  225. return SOCKS_RESULT_DONE;
  226. }
  227. /** Parse a single SOCKS5 version identifier/method selection message
  228. * from buffer <b>raw_data</b> (of length <b>datalen</b>). Update
  229. * relevant fields of <b>req</b> (if any). Set <b>*have_user_pass</b> to
  230. * true if username/password method is found. Set <b>*have_no_auth</b>
  231. * if no-auth method is found. Set <b>*drain_out</b> to number of bytes
  232. * we parsed so far.
  233. *
  234. * Return SOCKS_RESULT_DONE if parsing succeeded, SOCKS_RESULT_INVALID if
  235. * parsing failed because of invalid input or SOCKS_RESULT_TRUNCATED if it
  236. * failed due to incomplete (truncated) input.
  237. */
  238. static socks_result_t
  239. parse_socks5_methods_request(const uint8_t *raw_data, socks_request_t *req,
  240. size_t datalen, int *have_user_pass,
  241. int *have_no_auth, size_t *drain_out)
  242. {
  243. socks_result_t res = SOCKS_RESULT_DONE;
  244. socks5_client_version_t *trunnel_req;
  245. ssize_t parsed = socks5_client_version_parse(&trunnel_req, raw_data,
  246. datalen);
  247. (void)req;
  248. tor_assert(have_no_auth);
  249. tor_assert(have_user_pass);
  250. tor_assert(drain_out);
  251. *drain_out = 0;
  252. if (parsed == -1) {
  253. log_warn(LD_APP, "socks5: parsing failed - invalid version "
  254. "id/method selection message.");
  255. res = SOCKS_RESULT_INVALID;
  256. goto end;
  257. } else if (parsed == -2) {
  258. res = SOCKS_RESULT_TRUNCATED;
  259. if (datalen > MAX_SOCKS_MESSAGE_LEN) {
  260. log_warn(LD_APP, "socks5: parsing failed - invalid version "
  261. "id/method selection message.");
  262. res = SOCKS_RESULT_INVALID;
  263. }
  264. goto end;
  265. }
  266. tor_assert(parsed >= 0);
  267. *drain_out = (size_t)parsed;
  268. size_t n_methods = (size_t)socks5_client_version_get_n_methods(trunnel_req);
  269. if (n_methods == 0) {
  270. res = SOCKS_RESULT_INVALID;
  271. goto end;
  272. }
  273. *have_no_auth = 0;
  274. *have_user_pass = 0;
  275. for (size_t i = 0; i < n_methods; i++) {
  276. uint8_t method = socks5_client_version_get_methods(trunnel_req,
  277. i);
  278. if (method == SOCKS_USER_PASS) {
  279. *have_user_pass = 1;
  280. } else if (method == SOCKS_NO_AUTH) {
  281. *have_no_auth = 1;
  282. }
  283. }
  284. end:
  285. socks5_client_version_free(trunnel_req);
  286. return res;
  287. }
  288. /**
  289. * Validate and respond to version identifier/method selection message
  290. * we parsed in parse_socks5_methods_request (corresponding to <b>req</b>
  291. * and having user/pass method if <b>have_user_pass</b> is true, no-auth
  292. * method if <b>have_no_auth</b> is true). Set <b>req->reply</b> to
  293. * an appropriate response (in SOCKS5 wire format).
  294. *
  295. * On success, return SOCKS_RESULT_DONE. On failure, return
  296. * SOCKS_RESULT_INVALID.
  297. */
  298. static socks_result_t
  299. process_socks5_methods_request(socks_request_t *req, int have_user_pass,
  300. int have_no_auth)
  301. {
  302. socks_result_t res = SOCKS_RESULT_DONE;
  303. socks5_server_method_t *trunnel_resp = socks5_server_method_new();
  304. tor_assert(trunnel_resp);
  305. socks5_server_method_set_version(trunnel_resp, SOCKS_VER_5);
  306. if (have_user_pass && !(have_no_auth && req->socks_prefer_no_auth)) {
  307. req->auth_type = SOCKS_USER_PASS;
  308. socks5_server_method_set_method(trunnel_resp, SOCKS_USER_PASS);
  309. req->socks_version = SOCKS_VER_5;
  310. // FIXME: come up with better way to remember
  311. // that we negotiated auth
  312. log_debug(LD_APP,"socks5: accepted method 2 (username/password)");
  313. } else if (have_no_auth) {
  314. req->auth_type = SOCKS_NO_AUTH;
  315. socks5_server_method_set_method(trunnel_resp, SOCKS_NO_AUTH);
  316. req->socks_version = SOCKS_VER_5;
  317. log_debug(LD_APP,"socks5: accepted method 0 (no authentication)");
  318. } else {
  319. log_warn(LD_APP,
  320. "socks5: offered methods don't include 'no auth' or "
  321. "username/password. Rejecting.");
  322. socks5_server_method_set_method(trunnel_resp, 0xFF); // reject all
  323. res = SOCKS_RESULT_INVALID;
  324. }
  325. const char *errmsg = socks5_server_method_check(trunnel_resp);
  326. if (errmsg) {
  327. log_warn(LD_APP, "socks5: method selection validation failed: %s",
  328. errmsg);
  329. res = SOCKS_RESULT_INVALID;
  330. } else {
  331. ssize_t encoded =
  332. socks5_server_method_encode(req->reply, sizeof(req->reply),
  333. trunnel_resp);
  334. if (encoded < 0) {
  335. log_warn(LD_APP, "socks5: method selection encoding failed");
  336. res = SOCKS_RESULT_INVALID;
  337. } else {
  338. req->replylen = (size_t)encoded;
  339. }
  340. }
  341. socks5_server_method_free(trunnel_resp);
  342. return res;
  343. }
  344. /**
  345. * Parse SOCKS5/RFC1929 username/password request from buffer
  346. * <b>raw_data</b> of length <b>datalen</b> and update relevant
  347. * fields of <b>req</b>. Set <b>*drain_out</b> to number of bytes
  348. * we parsed so far.
  349. *
  350. * Return SOCKS_RESULT_DONE if parsing succeeded, SOCKS_RESULT_INVALID if
  351. * parsing failed because of invalid input or SOCKS_RESULT_TRUNCATED if it
  352. * failed due to incomplete (truncated) input.
  353. */
  354. static socks_result_t
  355. parse_socks5_userpass_auth(const uint8_t *raw_data, socks_request_t *req,
  356. size_t datalen, size_t *drain_out)
  357. {
  358. socks_result_t res = SOCKS_RESULT_DONE;
  359. socks5_client_userpass_auth_t *trunnel_req = NULL;
  360. ssize_t parsed = socks5_client_userpass_auth_parse(&trunnel_req, raw_data,
  361. datalen);
  362. tor_assert(drain_out);
  363. *drain_out = 0;
  364. if (parsed == -1) {
  365. log_warn(LD_APP, "socks5: parsing failed - invalid user/pass "
  366. "authentication message.");
  367. res = SOCKS_RESULT_INVALID;
  368. goto end;
  369. } else if (parsed == -2) {
  370. res = SOCKS_RESULT_TRUNCATED;
  371. goto end;
  372. }
  373. tor_assert(parsed >= 0);
  374. *drain_out = (size_t)parsed;
  375. uint8_t usernamelen =
  376. socks5_client_userpass_auth_get_username_len(trunnel_req);
  377. uint8_t passwordlen =
  378. socks5_client_userpass_auth_get_passwd_len(trunnel_req);
  379. const char *username =
  380. socks5_client_userpass_auth_getconstarray_username(trunnel_req);
  381. const char *password =
  382. socks5_client_userpass_auth_getconstarray_passwd(trunnel_req);
  383. if (usernamelen && username) {
  384. tor_free(req->username);
  385. req->username = tor_memdup_nulterm(username, usernamelen);
  386. req->usernamelen = usernamelen;
  387. }
  388. if (passwordlen && password) {
  389. tor_free(req->password);
  390. req->password = tor_memdup_nulterm(password, passwordlen);
  391. req->passwordlen = passwordlen;
  392. }
  393. /**
  394. * Yes, we allow username and/or password to be empty. Yes, that does
  395. * violate RFC 1929. However, some client software can send a username/
  396. * password message with these fields being empty and we want to allow them
  397. * to be used with Tor.
  398. */
  399. req->got_auth = 1;
  400. end:
  401. socks5_client_userpass_auth_free(trunnel_req);
  402. return res;
  403. }
  404. /**
  405. * Validate and respond to SOCKS5 username/password request we
  406. * parsed in parse_socks5_userpass_auth (corresponding to <b>req</b>.
  407. * Set <b>req->reply</b> to appropriate responsed. Return
  408. * SOCKS_RESULT_DONE on success or SOCKS_RESULT_INVALID on failure.
  409. */
  410. static socks_result_t
  411. process_socks5_userpass_auth(socks_request_t *req)
  412. {
  413. socks_result_t res = SOCKS_RESULT_DONE;
  414. socks5_server_userpass_auth_t *trunnel_resp =
  415. socks5_server_userpass_auth_new();
  416. tor_assert(trunnel_resp);
  417. if (req->socks_version != SOCKS_VER_5) {
  418. res = SOCKS_RESULT_INVALID;
  419. goto end;
  420. }
  421. if (req->auth_type != SOCKS_USER_PASS &&
  422. req->auth_type != SOCKS_NO_AUTH) {
  423. res = SOCKS_RESULT_INVALID;
  424. goto end;
  425. }
  426. socks5_server_userpass_auth_set_version(trunnel_resp, SOCKS_AUTH);
  427. socks5_server_userpass_auth_set_status(trunnel_resp, 0); // auth OK
  428. const char *errmsg = socks5_server_userpass_auth_check(trunnel_resp);
  429. if (errmsg) {
  430. log_warn(LD_APP, "socks5: server userpass auth validation failed: %s",
  431. errmsg);
  432. res = SOCKS_RESULT_INVALID;
  433. goto end;
  434. }
  435. ssize_t encoded = socks5_server_userpass_auth_encode(req->reply,
  436. sizeof(req->reply),
  437. trunnel_resp);
  438. if (encoded < 0) {
  439. log_warn(LD_APP, "socks5: server userpass auth encoding failed");
  440. res = SOCKS_RESULT_INVALID;
  441. goto end;
  442. }
  443. req->replylen = (size_t)encoded;
  444. end:
  445. socks5_server_userpass_auth_free(trunnel_resp);
  446. return res;
  447. }
  448. /**
  449. * Parse a single SOCKS5 client request (RFC 1928 section 4) from buffer
  450. * <b>raw_data</b> of length <b>datalen</b> and update relevant field of
  451. * <b>req</b>. Set <b>*drain_out</b> to number of bytes we parsed so far.
  452. *
  453. * Return SOCKS_RESULT_DONE if parsing succeeded, SOCKS_RESULT_INVALID if
  454. * parsing failed because of invalid input or SOCKS_RESULT_TRUNCATED if it
  455. * failed due to incomplete (truncated) input.
  456. */
  457. static socks_result_t
  458. parse_socks5_client_request(const uint8_t *raw_data, socks_request_t *req,
  459. size_t datalen, size_t *drain_out)
  460. {
  461. socks_result_t res = SOCKS_RESULT_DONE;
  462. tor_addr_t destaddr;
  463. socks5_client_request_t *trunnel_req = NULL;
  464. ssize_t parsed =
  465. socks5_client_request_parse(&trunnel_req, raw_data, datalen);
  466. if (parsed == -1) {
  467. log_warn(LD_APP, "socks5: parsing failed - invalid client request");
  468. res = SOCKS_RESULT_INVALID;
  469. goto end;
  470. } else if (parsed == -2) {
  471. res = SOCKS_RESULT_TRUNCATED;
  472. goto end;
  473. }
  474. tor_assert(parsed >= 0);
  475. *drain_out = (size_t)parsed;
  476. if (socks5_client_request_get_version(trunnel_req) != 5) {
  477. res = SOCKS_RESULT_INVALID;
  478. goto end;
  479. }
  480. req->command = socks5_client_request_get_command(trunnel_req);
  481. req->port = socks5_client_request_get_dest_port(trunnel_req);
  482. uint8_t atype = socks5_client_request_get_atype(trunnel_req);
  483. req->socks5_atyp = atype;
  484. switch (atype) {
  485. case 1: {
  486. uint32_t ipv4 = socks5_client_request_get_dest_addr_ipv4(trunnel_req);
  487. tor_addr_from_ipv4h(&destaddr, ipv4);
  488. tor_addr_to_str(req->address, &destaddr, sizeof(req->address), 1);
  489. } break;
  490. case 3: {
  491. const struct domainname_st *dns_name =
  492. socks5_client_request_getconst_dest_addr_domainname(trunnel_req);
  493. const char *hostname = domainname_getconstarray_name(dns_name);
  494. strlcpy(req->address, hostname, sizeof(req->address));
  495. } break;
  496. case 4: {
  497. const char *ipv6 =
  498. (const char *)socks5_client_request_getarray_dest_addr_ipv6(
  499. trunnel_req);
  500. tor_addr_from_ipv6_bytes(&destaddr, ipv6);
  501. tor_addr_to_str(req->address, &destaddr, sizeof(req->address), 1);
  502. } break;
  503. default: {
  504. res = -1;
  505. } break;
  506. }
  507. end:
  508. socks5_client_request_free(trunnel_req);
  509. return res;
  510. }
  511. /**
  512. * Validate and respond to SOCKS5 request we parsed in
  513. * parse_socks5_client_request (corresponding to <b>req</b>.
  514. * Write appropriate response to <b>req->reply</b> (in
  515. * SOCKS5 wire format). If <b>log_sockstype</b> is true, log a
  516. * notice about possible DNS leaks on local system. If
  517. * <b>safe_socks</b> is true, disallow insecure usage of SOCKS
  518. * protocol. Return SOCKS_RESULT_DONE on success or
  519. * SOCKS_RESULT_INVALID on failure.
  520. */
  521. static socks_result_t
  522. process_socks5_client_request(socks_request_t *req,
  523. int log_sockstype,
  524. int safe_socks)
  525. {
  526. socks_result_t res = SOCKS_RESULT_DONE;
  527. if (req->command != SOCKS_COMMAND_CONNECT &&
  528. req->command != SOCKS_COMMAND_RESOLVE &&
  529. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  530. socks_request_set_socks5_error(req,SOCKS5_COMMAND_NOT_SUPPORTED);
  531. res = SOCKS_RESULT_INVALID;
  532. goto end;
  533. }
  534. if (req->command == SOCKS_COMMAND_RESOLVE_PTR &&
  535. !string_is_valid_ipv4_address(req->address) &&
  536. !string_is_valid_ipv6_address(req->address)) {
  537. socks_request_set_socks5_error(req, SOCKS5_ADDRESS_TYPE_NOT_SUPPORTED);
  538. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  539. "hostname type. Rejecting.");
  540. res = SOCKS_RESULT_INVALID;
  541. goto end;
  542. }
  543. if (!string_is_valid_dest(req->address)) {
  544. socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
  545. log_warn(LD_PROTOCOL,
  546. "Your application (using socks5 to port %d) gave Tor "
  547. "a malformed hostname: %s. Rejecting the connection.",
  548. req->port, escaped_safe_str_client(req->address));
  549. res = SOCKS_RESULT_INVALID;
  550. goto end;
  551. }
  552. if (req->socks5_atyp == 1 || req->socks5_atyp == 4) {
  553. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  554. !addressmap_have_mapping(req->address,0)) {
  555. log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
  556. if (safe_socks) {
  557. socks_request_set_socks5_error(req, SOCKS5_NOT_ALLOWED);
  558. res = SOCKS_RESULT_INVALID;
  559. goto end;
  560. }
  561. }
  562. }
  563. if (log_sockstype)
  564. log_notice(LD_APP,
  565. "Your application (using socks5 to port %d) instructed "
  566. "Tor to take care of the DNS resolution itself if "
  567. "necessary. This is good.", req->port);
  568. end:
  569. return res;
  570. }
  571. /**
  572. * Handle (parse, validate, process, respond) a single SOCKS
  573. * message in buffer <b>raw_data</b> of length <b>datalen</b>.
  574. * Update relevant fields of <b>req</b>. If <b>log_sockstype</b>
  575. * is true, log a warning about possible DNS leaks on local
  576. * system. If <b>safe_socks</b> is true, disallow insecure
  577. * usage of SOCKS protocol. Set <b>*drain_out</b> to number
  578. * of bytes in <b>raw_data</b> that we processed so far and
  579. * that can be safely drained from buffer.
  580. *
  581. * Return:
  582. * - SOCKS_RESULT_DONE if succeeded and not expecting further
  583. * messages from client.
  584. * - SOCKS_RESULT_INVALID if any of the steps failed due to
  585. * request being invalid or unexpected given current state.
  586. * - SOCKS_RESULT_TRUNCATED if we do not found an expected
  587. * SOCKS message in its entirety (more stuff has to arrive
  588. * from client).
  589. * - SOCKS_RESULT_MORE_EXPECTED if we handled current message
  590. * successfully, but we expect more messages from the
  591. * client.
  592. */
  593. static socks_result_t
  594. handle_socks_message(const uint8_t *raw_data, size_t datalen,
  595. socks_request_t *req, int log_sockstype,
  596. int safe_socks, size_t *drain_out)
  597. {
  598. socks_result_t res = SOCKS_RESULT_DONE;
  599. uint8_t socks_version = raw_data[0];
  600. if (socks_version == SOCKS_AUTH)
  601. socks_version = SOCKS_VER_5; // SOCKS5 username/pass subnegotiation
  602. if (socks_version == SOCKS_VER_4) {
  603. if (datalen < SOCKS4_NETWORK_LEN) {
  604. res = 0;
  605. goto end;
  606. }
  607. int is_socks4a = 0;
  608. res = parse_socks4_request((const uint8_t *)raw_data, req, datalen,
  609. &is_socks4a, drain_out);
  610. if (res != SOCKS_RESULT_DONE) {
  611. goto end;
  612. }
  613. res = process_socks4_request(req, is_socks4a,log_sockstype,
  614. safe_socks);
  615. if (res != SOCKS_RESULT_DONE) {
  616. goto end;
  617. }
  618. goto end;
  619. } else if (socks_version == SOCKS_VER_5) {
  620. if (datalen < 2) { /* version and another byte */
  621. res = 0;
  622. goto end;
  623. }
  624. /* RFC1929 SOCKS5 username/password subnegotiation. */
  625. if (!req->got_auth && (raw_data[0] == 1 ||
  626. req->auth_type == SOCKS_USER_PASS)) {
  627. res = parse_socks5_userpass_auth(raw_data, req, datalen,
  628. drain_out);
  629. if (res != SOCKS_RESULT_DONE) {
  630. goto end;
  631. }
  632. res = process_socks5_userpass_auth(req);
  633. if (res != SOCKS_RESULT_DONE) {
  634. goto end;
  635. }
  636. res = SOCKS_RESULT_MORE_EXPECTED;
  637. goto end;
  638. } else if (req->socks_version != SOCKS_VER_5) {
  639. int have_user_pass=0, have_no_auth=0;
  640. res = parse_socks5_methods_request(raw_data, req, datalen,
  641. &have_user_pass,
  642. &have_no_auth,
  643. drain_out);
  644. if (res != SOCKS_RESULT_DONE) {
  645. goto end;
  646. }
  647. res = process_socks5_methods_request(req, have_user_pass,
  648. have_no_auth);
  649. if (res != SOCKS_RESULT_DONE) {
  650. goto end;
  651. }
  652. res = SOCKS_RESULT_MORE_EXPECTED;
  653. goto end;
  654. } else {
  655. res = parse_socks5_client_request(raw_data, req,
  656. datalen, drain_out);
  657. if (res != SOCKS_RESULT_DONE) {
  658. socks_request_set_socks5_error(req, SOCKS5_GENERAL_ERROR);
  659. goto end;
  660. }
  661. res = process_socks5_client_request(req, log_sockstype,
  662. safe_socks);
  663. if (res != SOCKS_RESULT_DONE) {
  664. goto end;
  665. }
  666. }
  667. } else {
  668. *drain_out = datalen;
  669. res = SOCKS_RESULT_INVALID;
  670. }
  671. end:
  672. return res;
  673. }
  674. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  675. * of the forms
  676. * - socks4: "socksheader username\\0"
  677. * - socks4a: "socksheader username\\0 destaddr\\0"
  678. * - socks5 phase one: "version #methods methods"
  679. * - socks5 phase two: "version command 0 addresstype..."
  680. * If it's a complete and valid handshake, and destaddr fits in
  681. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  682. * assign to <b>req</b>, and return 1.
  683. *
  684. * If it's invalid or too big, return -1.
  685. *
  686. * Else it's not all there yet, leave buf alone and return 0.
  687. *
  688. * If you want to specify the socks reply, write it into <b>req->reply</b>
  689. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  690. *
  691. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  692. * the connection is possibly leaking DNS requests locally or not.
  693. *
  694. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  695. *
  696. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  697. * undefined.
  698. */
  699. int
  700. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  701. int log_sockstype, int safe_socks)
  702. {
  703. int res = 0;
  704. size_t datalen = buf_datalen(buf);
  705. size_t n_drain;
  706. const char *head = NULL;
  707. socks_result_t socks_res;
  708. size_t n_pullup;
  709. if (buf_datalen(buf) < 2) { /* version and another byte */
  710. res = 0;
  711. goto end;
  712. }
  713. do {
  714. n_drain = 0;
  715. n_pullup = MIN(MAX_SOCKS_MESSAGE_LEN, buf_datalen(buf));
  716. buf_pullup(buf, n_pullup, &head, &datalen);
  717. tor_assert(head && datalen >= 2);
  718. socks_res = parse_socks(head, datalen, req, log_sockstype,
  719. safe_socks, &n_drain);
  720. if (socks_res == SOCKS_RESULT_INVALID)
  721. buf_clear(buf);
  722. else if (socks_res != SOCKS_RESULT_TRUNCATED && n_drain > 0)
  723. buf_drain(buf, n_drain);
  724. switch (socks_res) {
  725. case SOCKS_RESULT_INVALID:
  726. res = -1;
  727. break;
  728. case SOCKS_RESULT_DONE:
  729. res = 1;
  730. break;
  731. case SOCKS_RESULT_TRUNCATED:
  732. if (datalen == n_pullup)
  733. return 0;
  734. /* FALLTHRU */
  735. case SOCKS_RESULT_MORE_EXPECTED:
  736. res = 0;
  737. break;
  738. }
  739. } while (res == 0 && head && buf_datalen(buf) >= 2);
  740. end:
  741. return res;
  742. }
  743. /** Create a SOCKS5 reply message with <b>reason</b> in its REP field and
  744. * have Tor send it as error response to <b>req</b>.
  745. */
  746. static void
  747. socks_request_set_socks5_error(socks_request_t *req,
  748. socks5_reply_status_t reason)
  749. {
  750. socks5_server_reply_t *trunnel_resp = socks5_server_reply_new();
  751. tor_assert(trunnel_resp);
  752. socks5_server_reply_set_version(trunnel_resp, SOCKS_VER_5);
  753. socks5_server_reply_set_reply(trunnel_resp, reason);
  754. socks5_server_reply_set_atype(trunnel_resp, 0x01);
  755. const char *errmsg = socks5_server_reply_check(trunnel_resp);
  756. if (errmsg) {
  757. log_warn(LD_APP, "socks5: reply validation failed: %s",
  758. errmsg);
  759. goto end;
  760. }
  761. ssize_t encoded = socks5_server_reply_encode(req->reply,
  762. sizeof(req->reply),
  763. trunnel_resp);
  764. if (encoded < 0) {
  765. log_warn(LD_APP, "socks5: reply encoding failed: %d",
  766. (int)encoded);
  767. } else {
  768. req->replylen = (size_t)encoded;
  769. }
  770. end:
  771. socks5_server_reply_free(trunnel_resp);
  772. }
  773. static const char SOCKS_PROXY_IS_NOT_AN_HTTP_PROXY_MSG[] =
  774. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  775. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  776. "<html>\n"
  777. "<head>\n"
  778. "<title>This is a SOCKS Proxy, Not An HTTP Proxy</title>\n"
  779. "</head>\n"
  780. "<body>\n"
  781. "<h1>This is a SOCKs proxy, not an HTTP proxy.</h1>\n"
  782. "<p>\n"
  783. "It appears you have configured your web browser to use this Tor port as\n"
  784. "an HTTP proxy.\n"
  785. "</p><p>\n"
  786. "This is not correct: This port is configured as a SOCKS proxy, not\n"
  787. "an HTTP proxy. If you need an HTTP proxy tunnel, use the HTTPTunnelPort\n"
  788. "configuration option in place of, or in addition to, SOCKSPort.\n"
  789. "Please configure your client accordingly.\n"
  790. "</p>\n"
  791. "<p>\n"
  792. "See <a href=\"https://www.torproject.org/documentation.html\">"
  793. "https://www.torproject.org/documentation.html</a> for more "
  794. "information.\n"
  795. "</p>\n"
  796. "</body>\n"
  797. "</html>\n";
  798. /** Implementation helper to implement fetch_from_*_socks. Instead of looking
  799. * at a buffer's contents, we look at the <b>datalen</b> bytes of data in
  800. * <b>data</b>. Instead of removing data from the buffer, we set
  801. * <b>drain_out</b> to the amount of data that should be removed (or -1 if the
  802. * buffer should be cleared). Instead of pulling more data into the first
  803. * chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
  804. * we'd like to see in the input buffer, if they're available. */
  805. static int
  806. parse_socks(const char *data, size_t datalen, socks_request_t *req,
  807. int log_sockstype, int safe_socks, size_t *drain_out)
  808. {
  809. uint8_t first_octet;
  810. if (datalen < 2) {
  811. /* We always need at least 2 bytes. */
  812. return 0;
  813. }
  814. first_octet = get_uint8(data);
  815. if (first_octet == SOCKS_VER_5 || first_octet == SOCKS_VER_4 ||
  816. first_octet == SOCKS_AUTH) { // XXX: RFC 1929
  817. return handle_socks_message((const uint8_t *)data, datalen, req,
  818. log_sockstype, safe_socks, drain_out);
  819. }
  820. switch (first_octet) { /* which version of socks? */
  821. case 'G': /* get */
  822. case 'H': /* head */
  823. case 'P': /* put/post */
  824. case 'C': /* connect */
  825. strlcpy((char*)req->reply, SOCKS_PROXY_IS_NOT_AN_HTTP_PROXY_MSG,
  826. MAX_SOCKS_REPLY_LEN);
  827. req->replylen = strlen((char*)req->reply)+1;
  828. /* fall through */
  829. default: /* version is not socks4 or socks5 */
  830. log_warn(LD_APP,
  831. "Socks version %d not recognized. (This port is not an "
  832. "HTTP proxy; did you want to use HTTPTunnelPort?)",
  833. *(data));
  834. {
  835. /* Tell the controller the first 8 bytes. */
  836. char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
  837. control_event_client_status(LOG_WARN,
  838. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  839. escaped(tmp));
  840. tor_free(tmp);
  841. }
  842. return -1;
  843. }
  844. tor_assert_unreached();
  845. return -1;
  846. }
  847. /** Inspect a reply from SOCKS server stored in <b>buf</b> according
  848. * to <b>state</b>, removing the protocol data upon success. Return 0 on
  849. * incomplete response, 1 on success and -1 on error, in which case
  850. * <b>reason</b> is set to a descriptive message (free() when finished
  851. * with it).
  852. *
  853. * As a special case, 2 is returned when user/pass is required
  854. * during SOCKS5 handshake and user/pass is configured.
  855. */
  856. int
  857. fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
  858. {
  859. ssize_t drain = 0;
  860. int r;
  861. const char *head = NULL;
  862. size_t datalen = 0;
  863. if (buf_datalen(buf) < 2)
  864. return 0;
  865. buf_pullup(buf, MAX_SOCKS_MESSAGE_LEN, &head, &datalen);
  866. tor_assert(head && datalen >= 2);
  867. r = parse_socks_client((uint8_t*)head, datalen,
  868. state, reason, &drain);
  869. if (drain > 0)
  870. buf_drain(buf, drain);
  871. else if (drain < 0)
  872. buf_clear(buf);
  873. return r;
  874. }
  875. /** Implementation logic for fetch_from_*_socks_client. */
  876. static int
  877. parse_socks_client(const uint8_t *data, size_t datalen,
  878. int state, char **reason,
  879. ssize_t *drain_out)
  880. {
  881. unsigned int addrlen;
  882. *drain_out = 0;
  883. if (datalen < 2)
  884. return 0;
  885. switch (state) {
  886. case PROXY_SOCKS4_WANT_CONNECT_OK:
  887. /* Wait for the complete response */
  888. if (datalen < 8)
  889. return 0;
  890. if (data[1] != 0x5a) {
  891. *reason = tor_strdup(socks4_response_code_to_string(data[1]));
  892. return -1;
  893. }
  894. /* Success */
  895. *drain_out = 8;
  896. return 1;
  897. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  898. /* we don't have any credentials */
  899. if (data[1] != 0x00) {
  900. *reason = tor_strdup("server doesn't support any of our "
  901. "available authentication methods");
  902. return -1;
  903. }
  904. log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
  905. *drain_out = -1;
  906. return 1;
  907. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  908. /* we have a username and password. return 1 if we can proceed without
  909. * providing authentication, or 2 otherwise. */
  910. switch (data[1]) {
  911. case 0x00:
  912. log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
  913. "doesn't require authentication.");
  914. *drain_out = -1;
  915. return 1;
  916. case 0x02:
  917. log_info(LD_NET, "SOCKS 5 client: need authentication.");
  918. *drain_out = -1;
  919. return 2;
  920. /* fall through */
  921. }
  922. *reason = tor_strdup("server doesn't support any of our available "
  923. "authentication methods");
  924. return -1;
  925. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  926. /* handle server reply to rfc1929 authentication */
  927. if (data[1] != 0x00) {
  928. *reason = tor_strdup("authentication failed");
  929. return -1;
  930. }
  931. log_info(LD_NET, "SOCKS 5 client: authentication successful.");
  932. *drain_out = -1;
  933. return 1;
  934. case PROXY_SOCKS5_WANT_CONNECT_OK:
  935. /* response is variable length. BND.ADDR, etc, isn't needed
  936. * (don't bother with buf_pullup()), but make sure to eat all
  937. * the data used */
  938. /* wait for address type field to arrive */
  939. if (datalen < 4)
  940. return 0;
  941. switch (data[3]) {
  942. case 0x01: /* ip4 */
  943. addrlen = 4;
  944. break;
  945. case 0x04: /* ip6 */
  946. addrlen = 16;
  947. break;
  948. case 0x03: /* fqdn (can this happen here?) */
  949. if (datalen < 5)
  950. return 0;
  951. addrlen = 1 + data[4];
  952. break;
  953. default:
  954. *reason = tor_strdup("invalid response to connect request");
  955. return -1;
  956. }
  957. /* wait for address and port */
  958. if (datalen < 6 + addrlen)
  959. return 0;
  960. if (data[1] != 0x00) {
  961. *reason = tor_strdup(socks5_response_code_to_string(data[1]));
  962. return -1;
  963. }
  964. *drain_out = 6 + addrlen;
  965. return 1;
  966. }
  967. /* LCOV_EXCL_START */
  968. /* shouldn't get here if the input state is one we know about... */
  969. tor_assert(0);
  970. return -1;
  971. /* LCOV_EXCL_STOP */
  972. }