proto_socks.c 35 KB

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