proxy.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * Network proxy abstraction in PuTTY
  3. *
  4. * A proxy layer, if necessary, wedges itself between the network
  5. * code and the higher level backend.
  6. */
  7. #include <assert.h>
  8. #include <ctype.h>
  9. #include <string.h>
  10. #include "putty.h"
  11. #include "network.h"
  12. #include "proxy.h"
  13. #define do_proxy_dns(conf) \
  14. (conf_get_int(conf, CONF_proxy_dns) == FORCE_ON || \
  15. (conf_get_int(conf, CONF_proxy_dns) == AUTO && \
  16. conf_get_int(conf, CONF_proxy_type) != PROXY_SOCKS4))
  17. static void proxy_negotiator_cleanup(ProxySocket *ps)
  18. {
  19. if (ps->pn) {
  20. proxy_negotiator_free(ps->pn);
  21. ps->pn = NULL;
  22. }
  23. if (ps->clientseat) {
  24. interactor_return_seat(ps->clientitr);
  25. ps->clientitr = NULL;
  26. ps->clientseat = NULL;
  27. }
  28. }
  29. /*
  30. * Call this when proxy negotiation is complete, so that this
  31. * socket can begin working normally.
  32. */
  33. void proxy_activate(ProxySocket *ps)
  34. {
  35. size_t output_before, output_after;
  36. proxy_negotiator_cleanup(ps);
  37. plug_log(ps->plug, PLUGLOG_CONNECT_SUCCESS, NULL, 0, NULL, 0);
  38. /* we want to ignore new receive events until we have sent
  39. * all of our buffered receive data.
  40. */
  41. sk_set_frozen(ps->sub_socket, true);
  42. /* how many bytes of output have we buffered? */
  43. output_before = bufchain_size(&ps->pending_oob_output_data) +
  44. bufchain_size(&ps->pending_output_data);
  45. /* and keep track of how many bytes do not get sent. */
  46. output_after = 0;
  47. /* send buffered OOB writes */
  48. while (bufchain_size(&ps->pending_oob_output_data) > 0) {
  49. ptrlen data = bufchain_prefix(&ps->pending_oob_output_data);
  50. output_after += sk_write_oob(ps->sub_socket, data.ptr, data.len);
  51. bufchain_consume(&ps->pending_oob_output_data, data.len);
  52. }
  53. /* send buffered normal writes */
  54. while (bufchain_size(&ps->pending_output_data) > 0) {
  55. ptrlen data = bufchain_prefix(&ps->pending_output_data);
  56. output_after += sk_write(ps->sub_socket, data.ptr, data.len);
  57. bufchain_consume(&ps->pending_output_data, data.len);
  58. }
  59. /* if we managed to send any data, let the higher levels know. */
  60. if (output_after < output_before)
  61. plug_sent(ps->plug, output_after);
  62. /* if we have a pending EOF to send, send it */
  63. if (ps->pending_eof) sk_write_eof(ps->sub_socket);
  64. /* if the backend wanted the socket unfrozen, try to unfreeze.
  65. * our set_frozen handler will flush buffered receive data before
  66. * unfreezing the actual underlying socket.
  67. */
  68. if (!ps->freeze)
  69. sk_set_frozen(&ps->sock, false);
  70. }
  71. /* basic proxy socket functions */
  72. static Plug *sk_proxy_plug (Socket *s, Plug *p)
  73. {
  74. ProxySocket *ps = container_of(s, ProxySocket, sock);
  75. Plug *ret = ps->plug;
  76. if (p)
  77. ps->plug = p;
  78. return ret;
  79. }
  80. static void sk_proxy_close (Socket *s)
  81. {
  82. ProxySocket *ps = container_of(s, ProxySocket, sock);
  83. sk_close(ps->sub_socket);
  84. sk_addr_free(ps->remote_addr);
  85. proxy_negotiator_cleanup(ps);
  86. bufchain_clear(&ps->output_from_negotiator);
  87. sfree(ps);
  88. }
  89. static size_t sk_proxy_write (Socket *s, const void *data, size_t len)
  90. {
  91. ProxySocket *ps = container_of(s, ProxySocket, sock);
  92. if (ps->pn) {
  93. bufchain_add(&ps->pending_output_data, data, len);
  94. return bufchain_size(&ps->pending_output_data);
  95. }
  96. return sk_write(ps->sub_socket, data, len);
  97. }
  98. static size_t sk_proxy_write_oob (Socket *s, const void *data, size_t len)
  99. {
  100. ProxySocket *ps = container_of(s, ProxySocket, sock);
  101. if (ps->pn) {
  102. bufchain_clear(&ps->pending_output_data);
  103. bufchain_clear(&ps->pending_oob_output_data);
  104. bufchain_add(&ps->pending_oob_output_data, data, len);
  105. return len;
  106. }
  107. return sk_write_oob(ps->sub_socket, data, len);
  108. }
  109. static void sk_proxy_write_eof (Socket *s)
  110. {
  111. ProxySocket *ps = container_of(s, ProxySocket, sock);
  112. if (ps->pn) {
  113. ps->pending_eof = true;
  114. return;
  115. }
  116. sk_write_eof(ps->sub_socket);
  117. }
  118. static void sk_proxy_set_frozen (Socket *s, bool is_frozen)
  119. {
  120. ProxySocket *ps = container_of(s, ProxySocket, sock);
  121. if (ps->pn) {
  122. ps->freeze = is_frozen;
  123. return;
  124. }
  125. /* handle any remaining buffered recv data first */
  126. if (bufchain_size(&ps->pending_input_data) > 0) {
  127. ps->freeze = is_frozen;
  128. /* loop while we still have buffered data, and while we are
  129. * unfrozen. the plug_receive call in the loop could result
  130. * in a call back into this function refreezing the socket,
  131. * so we have to check each time.
  132. */
  133. while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
  134. char databuf[512];
  135. ptrlen data = bufchain_prefix(&ps->pending_input_data);
  136. if (data.len > lenof(databuf))
  137. data.len = lenof(databuf);
  138. memcpy(databuf, data.ptr, data.len);
  139. bufchain_consume(&ps->pending_input_data, data.len);
  140. plug_receive(ps->plug, 0, databuf, data.len);
  141. }
  142. /* if we're still frozen, we'll have to wait for another
  143. * call from the backend to finish unbuffering the data.
  144. */
  145. if (ps->freeze) return;
  146. }
  147. sk_set_frozen(ps->sub_socket, is_frozen);
  148. }
  149. static const char * sk_proxy_socket_error (Socket *s)
  150. {
  151. ProxySocket *ps = container_of(s, ProxySocket, sock);
  152. if (ps->error != NULL || ps->sub_socket == NULL) {
  153. return ps->error;
  154. }
  155. return sk_socket_error(ps->sub_socket);
  156. }
  157. /* basic proxy plug functions */
  158. static void plug_proxy_log(Plug *plug, PlugLogType type, SockAddr *addr,
  159. int port, const char *error_msg, int error_code)
  160. {
  161. ProxySocket *ps = container_of(plug, ProxySocket, plugimpl);
  162. plug_log(ps->plug, type, addr, port, error_msg, error_code);
  163. }
  164. static void plug_proxy_closing(Plug *p, PlugCloseType type,
  165. const char *error_msg)
  166. {
  167. ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
  168. proxy_negotiator_cleanup(ps);
  169. plug_closing(ps->plug, type, error_msg);
  170. }
  171. static void proxy_negotiate(ProxySocket *ps)
  172. {
  173. assert(ps->pn);
  174. proxy_negotiator_process_queue(ps->pn);
  175. if (ps->pn->error) {
  176. char *err = dupprintf("Proxy error: %s", ps->pn->error);
  177. sfree(ps->pn->error);
  178. proxy_negotiator_cleanup(ps);
  179. plug_closing_error(ps->plug, err);
  180. sfree(err);
  181. return;
  182. } else if (ps->pn->aborted) {
  183. proxy_negotiator_cleanup(ps);
  184. plug_closing_user_abort(ps->plug);
  185. return;
  186. }
  187. while (bufchain_size(&ps->output_from_negotiator)) {
  188. ptrlen data = bufchain_prefix(&ps->output_from_negotiator);
  189. sk_write(ps->sub_socket, data.ptr, data.len);
  190. bufchain_consume(&ps->output_from_negotiator, data.len);
  191. }
  192. if (ps->pn->done)
  193. proxy_activate(ps);
  194. }
  195. static void plug_proxy_receive(
  196. Plug *p, int urgent, const char *data, size_t len)
  197. {
  198. ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
  199. if (ps->pn) {
  200. /* we will lose the urgentness of this data, but since most,
  201. * if not all, of this data will be consumed by the negotiation
  202. * process, hopefully it won't affect the protocol above us
  203. */
  204. bufchain_add(&ps->pending_input_data, data, len);
  205. proxy_negotiate(ps);
  206. } else {
  207. plug_receive(ps->plug, urgent, data, len);
  208. }
  209. }
  210. static void plug_proxy_sent (Plug *p, size_t bufsize)
  211. {
  212. ProxySocket *ps = container_of(p, ProxySocket, plugimpl);
  213. if (ps->pn)
  214. return;
  215. plug_sent(ps->plug, bufsize);
  216. }
  217. static int plug_proxy_accepting(Plug *p,
  218. accept_fn_t constructor, accept_ctx_t ctx)
  219. {
  220. unreachable("ProxySockets never create listening Sockets");
  221. }
  222. /*
  223. * This function can accept a NULL pointer as `addr', in which case
  224. * it will only check the host name.
  225. */
  226. static bool proxy_for_destination(SockAddr *addr, const char *hostname,
  227. int port, Conf *conf)
  228. {
  229. int s = 0, e = 0;
  230. char hostip[64];
  231. int hostip_len, hostname_len;
  232. const char *exclude_list;
  233. /*
  234. * Special local connections such as Unix-domain sockets
  235. * unconditionally cannot be proxied, even in proxy-localhost
  236. * mode. There just isn't any way to ask any known proxy type for
  237. * them.
  238. */
  239. if (addr && sk_address_is_special_local(addr))
  240. return false; /* do not proxy */
  241. /*
  242. * Check the host name and IP against the hard-coded
  243. * representations of `localhost'.
  244. */
  245. if (!conf_get_bool(conf, CONF_even_proxy_localhost) &&
  246. (sk_hostname_is_local(hostname) ||
  247. (addr && sk_address_is_local(addr))))
  248. return false; /* do not proxy */
  249. /* we want a string representation of the IP address for comparisons */
  250. if (addr) {
  251. sk_getaddr(addr, hostip, 64);
  252. hostip_len = strlen(hostip);
  253. } else
  254. hostip_len = 0; /* placate gcc; shouldn't be required */
  255. hostname_len = strlen(hostname);
  256. exclude_list = conf_get_str(conf, CONF_proxy_exclude_list);
  257. /* now parse the exclude list, and see if either our IP
  258. * or hostname matches anything in it.
  259. */
  260. while (exclude_list[s]) {
  261. while (exclude_list[s] &&
  262. (isspace((unsigned char)exclude_list[s]) ||
  263. exclude_list[s] == ',')) s++;
  264. if (!exclude_list[s]) break;
  265. e = s;
  266. while (exclude_list[e] &&
  267. (isalnum((unsigned char)exclude_list[e]) ||
  268. exclude_list[e] == '-' ||
  269. exclude_list[e] == '.' ||
  270. exclude_list[e] == '*')) e++;
  271. if (exclude_list[s] == '*') {
  272. /* wildcard at beginning of entry */
  273. if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
  274. exclude_list + s + 1, e - s - 1) == 0) ||
  275. strnicmp(hostname + hostname_len - (e - s - 1),
  276. exclude_list + s + 1, e - s - 1) == 0) {
  277. /* IP/hostname range excluded. do not use proxy. */
  278. return false;
  279. }
  280. } else if (exclude_list[e-1] == '*') {
  281. /* wildcard at end of entry */
  282. if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
  283. strnicmp(hostname, exclude_list + s, e - s - 1) == 0) {
  284. /* IP/hostname range excluded. do not use proxy. */
  285. return false;
  286. }
  287. } else {
  288. /* no wildcard at either end, so let's try an absolute
  289. * match (ie. a specific IP)
  290. */
  291. if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
  292. return false; /* IP/hostname excluded. do not use proxy. */
  293. if (strnicmp(hostname, exclude_list + s, e - s) == 0)
  294. return false; /* IP/hostname excluded. do not use proxy. */
  295. }
  296. s = e;
  297. /* Make sure we really have reached the next comma or end-of-string */
  298. while (exclude_list[s] &&
  299. !isspace((unsigned char)exclude_list[s]) &&
  300. exclude_list[s] != ',') s++;
  301. }
  302. /* no matches in the exclude list, so use the proxy */
  303. return true;
  304. }
  305. static char *dns_log_msg(const char *host, int addressfamily,
  306. const char *reason)
  307. {
  308. return dupprintf("Looking up host \"%s\"%s for %s", host,
  309. (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
  310. addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
  311. ""), reason);
  312. }
  313. SockAddr *name_lookup(const char *host, int port, char **canonicalname,
  314. Conf *conf, int addressfamily, LogContext *logctx,
  315. const char *reason)
  316. {
  317. if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
  318. do_proxy_dns(conf) &&
  319. proxy_for_destination(NULL, host, port, conf)) {
  320. if (logctx)
  321. logeventf(logctx, "Leaving host lookup to proxy of \"%s\""
  322. " (for %s)", host, reason);
  323. *canonicalname = dupstr(host);
  324. return sk_nonamelookup(host);
  325. } else {
  326. if (logctx)
  327. logevent_and_free(
  328. logctx, dns_log_msg(host, addressfamily, reason));
  329. return sk_namelookup(host, canonicalname, addressfamily);
  330. }
  331. }
  332. static const SocketVtable ProxySocket_sockvt = {
  333. .plug = sk_proxy_plug,
  334. .close = sk_proxy_close,
  335. .write = sk_proxy_write,
  336. .write_oob = sk_proxy_write_oob,
  337. .write_eof = sk_proxy_write_eof,
  338. .set_frozen = sk_proxy_set_frozen,
  339. .socket_error = sk_proxy_socket_error,
  340. .peer_info = NULL,
  341. };
  342. static const PlugVtable ProxySocket_plugvt = {
  343. .log = plug_proxy_log,
  344. .closing = plug_proxy_closing,
  345. .receive = plug_proxy_receive,
  346. .sent = plug_proxy_sent,
  347. .accepting = plug_proxy_accepting
  348. };
  349. static char *proxy_description(Interactor *itr)
  350. {
  351. ProxySocket *ps = container_of(itr, ProxySocket, interactor);
  352. assert(ps->pn);
  353. return dupprintf("%s connection to %s port %d", ps->pn->vt->type,
  354. conf_get_str(ps->conf, CONF_proxy_host),
  355. conf_get_int(ps->conf, CONF_proxy_port));
  356. }
  357. static LogPolicy *proxy_logpolicy(Interactor *itr)
  358. {
  359. ProxySocket *ps = container_of(itr, ProxySocket, interactor);
  360. return ps->clientlp;
  361. }
  362. static Seat *proxy_get_seat(Interactor *itr)
  363. {
  364. ProxySocket *ps = container_of(itr, ProxySocket, interactor);
  365. return ps->clientseat;
  366. }
  367. static void proxy_set_seat(Interactor *itr, Seat *seat)
  368. {
  369. ProxySocket *ps = container_of(itr, ProxySocket, interactor);
  370. ps->clientseat = seat;
  371. }
  372. static const InteractorVtable ProxySocket_interactorvt = {
  373. .description = proxy_description,
  374. .logpolicy = proxy_logpolicy,
  375. .get_seat = proxy_get_seat,
  376. .set_seat = proxy_set_seat,
  377. };
  378. static void proxy_prompts_callback(void *ctx)
  379. {
  380. proxy_negotiate((ProxySocket *)ctx);
  381. }
  382. prompts_t *proxy_new_prompts(ProxySocket *ps)
  383. {
  384. prompts_t *prs = new_prompts();
  385. prs->callback = proxy_prompts_callback;
  386. prs->callback_ctx = ps;
  387. return prs;
  388. }
  389. void proxy_spr_abort(ProxyNegotiator *pn, SeatPromptResult spr)
  390. {
  391. if (spr.kind == SPRK_SW_ABORT) {
  392. pn->error = spr_get_error_message(spr);
  393. } else {
  394. assert(spr.kind == SPRK_USER_ABORT);
  395. pn->aborted = true;
  396. }
  397. }
  398. Socket *new_connection(SockAddr *addr, const char *hostname,
  399. int port, bool privport,
  400. bool oobinline, bool nodelay, bool keepalive,
  401. Plug *plug, Conf *conf, Interactor *itr)
  402. {
  403. int type = conf_get_int(conf, CONF_proxy_type);
  404. if (type != PROXY_NONE &&
  405. proxy_for_destination(addr, hostname, port, conf))
  406. {
  407. ProxySocket *ps;
  408. SockAddr *proxy_addr;
  409. char *proxy_canonical_name;
  410. Socket *sret;
  411. if (type == PROXY_SSH &&
  412. (sret = sshproxy_new_connection(addr, hostname, port, privport,
  413. oobinline, nodelay, keepalive,
  414. plug, conf, itr)) != NULL)
  415. return sret;
  416. if ((sret = platform_new_connection(addr, hostname, port, privport,
  417. oobinline, nodelay, keepalive,
  418. plug, conf, itr)) != NULL)
  419. return sret;
  420. ps = snew(ProxySocket);
  421. ps->sock.vt = &ProxySocket_sockvt;
  422. ps->plugimpl.vt = &ProxySocket_plugvt;
  423. ps->interactor.vt = &ProxySocket_interactorvt;
  424. ps->conf = conf_copy(conf);
  425. ps->plug = plug;
  426. ps->remote_addr = addr; /* will need to be freed on close */
  427. ps->remote_port = port;
  428. ps->error = NULL;
  429. ps->pending_eof = false;
  430. ps->freeze = false;
  431. bufchain_init(&ps->pending_input_data);
  432. bufchain_init(&ps->pending_output_data);
  433. bufchain_init(&ps->pending_oob_output_data);
  434. bufchain_init(&ps->output_from_negotiator);
  435. ps->sub_socket = NULL;
  436. /*
  437. * If we've been given an Interactor by the caller, set ourselves
  438. * up to work with it.
  439. */
  440. if (itr) {
  441. ps->clientitr = itr;
  442. interactor_set_child(ps->clientitr, &ps->interactor);
  443. ps->clientlp = interactor_logpolicy(ps->clientitr);
  444. ps->clientseat = interactor_borrow_seat(ps->clientitr);
  445. }
  446. const ProxyNegotiatorVT *vt;
  447. switch (type) {
  448. case PROXY_HTTP:
  449. vt = &http_proxy_negotiator_vt;
  450. break;
  451. case PROXY_SOCKS4:
  452. vt = &socks4_proxy_negotiator_vt;
  453. break;
  454. case PROXY_SOCKS5:
  455. vt = &socks5_proxy_negotiator_vt;
  456. break;
  457. case PROXY_TELNET:
  458. vt = &telnet_proxy_negotiator_vt;
  459. break;
  460. default:
  461. ps->error = "Proxy error: Unknown proxy method";
  462. return &ps->sock;
  463. }
  464. ps->pn = proxy_negotiator_new(vt);
  465. ps->pn->ps = ps;
  466. ps->pn->done = false;
  467. ps->pn->error = NULL;
  468. ps->pn->aborted = false;
  469. ps->pn->input = &ps->pending_input_data;
  470. /* Provide an Interactor to the negotiator if and only if we
  471. * are usefully able to ask interactive questions of the user */
  472. ps->pn->itr = ps->clientseat ? &ps->interactor : NULL;
  473. bufchain_sink_init(ps->pn->output, &ps->output_from_negotiator);
  474. {
  475. char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
  476. " to %s:%d", vt->type,
  477. conf_get_str(conf, CONF_proxy_host),
  478. conf_get_int(conf, CONF_proxy_port),
  479. hostname, port);
  480. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  481. sfree(logmsg);
  482. }
  483. {
  484. char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
  485. conf_get_int(conf, CONF_addressfamily),
  486. "proxy");
  487. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  488. sfree(logmsg);
  489. }
  490. /* look-up proxy */
  491. proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
  492. &proxy_canonical_name,
  493. conf_get_int(conf, CONF_addressfamily));
  494. if (sk_addr_error(proxy_addr) != NULL) {
  495. ps->error = "Proxy error: Unable to resolve proxy host name";
  496. sk_addr_free(proxy_addr);
  497. return &ps->sock;
  498. }
  499. sfree(proxy_canonical_name);
  500. {
  501. char addrbuf[256], *logmsg;
  502. sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
  503. logmsg = dupprintf("Connecting to %s proxy at %s port %d",
  504. vt->type, addrbuf,
  505. conf_get_int(conf, CONF_proxy_port));
  506. plug_log(plug, PLUGLOG_PROXY_MSG, NULL, 0, logmsg, 0);
  507. sfree(logmsg);
  508. }
  509. /* create the actual socket we will be using,
  510. * connected to our proxy server and port.
  511. */
  512. ps->sub_socket = sk_new(proxy_addr,
  513. conf_get_int(conf, CONF_proxy_port),
  514. privport, oobinline,
  515. nodelay, keepalive, &ps->plugimpl);
  516. if (sk_socket_error(ps->sub_socket) != NULL)
  517. return &ps->sock;
  518. /* start the proxy negotiation process... */
  519. sk_set_frozen(ps->sub_socket, false);
  520. proxy_negotiate(ps);
  521. return &ps->sock;
  522. }
  523. /* no proxy, so just return the direct socket */
  524. return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
  525. }
  526. Socket *new_listener(const char *srcaddr, int port, Plug *plug,
  527. bool local_host_only, Conf *conf, int addressfamily)
  528. {
  529. /* TODO: SOCKS (and potentially others) support inbound
  530. * TODO: connections via the proxy. support them.
  531. */
  532. return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
  533. }