portfwd.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. /*
  2. * SSH port forwarding.
  3. */
  4. #include <assert.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "putty.h"
  8. #include "ssh.h"
  9. #include "channel.h"
  10. #include "proxy/socks.h"
  11. /*
  12. * Enumeration of values that live in the 'socks_state' field of
  13. * struct PortForwarding.
  14. */
  15. typedef enum {
  16. SOCKS_NONE, /* direct connection (no SOCKS, or SOCKS already done) */
  17. SOCKS_INITIAL, /* don't know if we're SOCKS 4 or 5 yet */
  18. SOCKS_4, /* expect a SOCKS 4 (or 4A) connection message */
  19. SOCKS_5_INITIAL, /* expect a SOCKS 5 preliminary message */
  20. SOCKS_5_CONNECT /* expect a SOCKS 5 connection message */
  21. } SocksState;
  22. typedef struct PortForwarding {
  23. SshChannel *c; /* channel structure held by SSH connection layer */
  24. ConnectionLayer *cl; /* the connection layer itself */
  25. /* Note that ssh need not be filled in if c is non-NULL */
  26. Socket *s;
  27. bool input_wanted;
  28. bool ready;
  29. SocksState socks_state;
  30. /*
  31. * `hostname' and `port' are the real hostname and port, once
  32. * we know what we're connecting to.
  33. */
  34. char *hostname;
  35. int port;
  36. /*
  37. * `socksbuf' is the buffer we use to accumulate the initial SOCKS
  38. * segment of the incoming data, plus anything after that that we
  39. * receive before we're ready to send data to the SSH server.
  40. */
  41. strbuf *socksbuf;
  42. size_t socksbuf_consumed;
  43. Plug plug;
  44. Channel chan;
  45. } PortForwarding;
  46. struct PortListener {
  47. ConnectionLayer *cl;
  48. Socket *s;
  49. bool is_dynamic;
  50. /*
  51. * `hostname' and `port' are the real hostname and port, for
  52. * ordinary forwardings.
  53. */
  54. char *hostname;
  55. int port;
  56. Plug plug;
  57. };
  58. static struct PortForwarding *new_portfwd_state(void)
  59. {
  60. struct PortForwarding *pf = snew(struct PortForwarding);
  61. pf->hostname = NULL;
  62. pf->socksbuf = NULL;
  63. return pf;
  64. }
  65. static void free_portfwd_state(struct PortForwarding *pf)
  66. {
  67. if (!pf)
  68. return;
  69. sfree(pf->hostname);
  70. if (pf->socksbuf)
  71. strbuf_free(pf->socksbuf);
  72. sfree(pf);
  73. }
  74. static struct PortListener *new_portlistener_state(void)
  75. {
  76. struct PortListener *pl = snew(struct PortListener);
  77. pl->hostname = NULL;
  78. return pl;
  79. }
  80. static void free_portlistener_state(struct PortListener *pl)
  81. {
  82. if (!pl)
  83. return;
  84. sfree(pl->hostname);
  85. sfree(pl);
  86. }
  87. static void pfd_close(struct PortForwarding *pf);
  88. static void pfd_closing(Plug *plug, PlugCloseType type, const char *error_msg)
  89. {
  90. struct PortForwarding *pf =
  91. container_of(plug, struct PortForwarding, plug);
  92. if (type != PLUGCLOSE_NORMAL) {
  93. /*
  94. * Socket error. Slam the connection instantly shut.
  95. */
  96. if (pf->c) {
  97. sshfwd_initiate_close(pf->c, error_msg);
  98. } else {
  99. /*
  100. * We might not have an SSH channel, if a socket error
  101. * occurred during SOCKS negotiation. If not, we must
  102. * clean ourself up without sshfwd_initiate_close's call
  103. * back to pfd_close.
  104. */
  105. pfd_close(pf);
  106. }
  107. } else {
  108. /*
  109. * Ordinary EOF received on socket. Send an EOF on the SSH
  110. * channel.
  111. */
  112. if (pf->c)
  113. sshfwd_write_eof(pf->c);
  114. }
  115. }
  116. static void pfl_terminate(struct PortListener *pl);
  117. static void pfl_closing(Plug *plug, PlugCloseType type, const char *error_msg)
  118. {
  119. struct PortListener *pl = (struct PortListener *) plug;
  120. pfl_terminate(pl);
  121. }
  122. static SshChannel *wrap_lportfwd_open(
  123. ConnectionLayer *cl, const char *hostname, int port,
  124. Socket *s, Channel *chan)
  125. {
  126. SocketEndpointInfo *pi;
  127. char *description;
  128. SshChannel *toret;
  129. pi = sk_peer_info(s);
  130. if (pi && pi->log_text) {
  131. description = dupprintf("forwarding from %s", pi->log_text);
  132. } else {
  133. description = dupstr("forwarding");
  134. }
  135. toret = ssh_lportfwd_open(cl, hostname, port, description, pi, chan);
  136. sk_free_endpoint_info(pi);
  137. sfree(description);
  138. return toret;
  139. }
  140. static char *ipv4_to_string(unsigned ipv4)
  141. {
  142. return dupprintf("%u.%u.%u.%u",
  143. (ipv4 >> 24) & 0xFF, (ipv4 >> 16) & 0xFF,
  144. (ipv4 >> 8) & 0xFF, (ipv4 ) & 0xFF);
  145. }
  146. static char *ipv6_to_string(ptrlen ipv6)
  147. {
  148. const unsigned char *addr = ipv6.ptr;
  149. assert(ipv6.len == 16);
  150. return dupprintf("%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x",
  151. (unsigned)GET_16BIT_MSB_FIRST(addr + 0),
  152. (unsigned)GET_16BIT_MSB_FIRST(addr + 2),
  153. (unsigned)GET_16BIT_MSB_FIRST(addr + 4),
  154. (unsigned)GET_16BIT_MSB_FIRST(addr + 6),
  155. (unsigned)GET_16BIT_MSB_FIRST(addr + 8),
  156. (unsigned)GET_16BIT_MSB_FIRST(addr + 10),
  157. (unsigned)GET_16BIT_MSB_FIRST(addr + 12),
  158. (unsigned)GET_16BIT_MSB_FIRST(addr + 14));
  159. }
  160. static void pfd_receive(Plug *plug, int urgent, const char *data, size_t len)
  161. {
  162. struct PortForwarding *pf =
  163. container_of(plug, struct PortForwarding, plug);
  164. if (len == 0)
  165. return;
  166. if (pf->socks_state != SOCKS_NONE) {
  167. BinarySource src[1];
  168. /*
  169. * Store all the data we've got in socksbuf.
  170. */
  171. put_data(pf->socksbuf, data, len);
  172. /*
  173. * Check the start of socksbuf to see if it's a valid and
  174. * complete message in the SOCKS exchange.
  175. */
  176. if (pf->socks_state == SOCKS_INITIAL) {
  177. /* Preliminary: check the first byte of the data (which we
  178. * _must_ have by now) to find out which SOCKS major
  179. * version we're speaking. */
  180. switch (pf->socksbuf->u[0]) {
  181. case SOCKS4_REQUEST_VERSION:
  182. pf->socks_state = SOCKS_4;
  183. break;
  184. case SOCKS5_REQUEST_VERSION:
  185. pf->socks_state = SOCKS_5_INITIAL;
  186. break;
  187. default:
  188. pfd_close(pf); /* unrecognised version */
  189. return;
  190. }
  191. }
  192. BinarySource_BARE_INIT(src, pf->socksbuf->u, pf->socksbuf->len);
  193. get_data(src, pf->socksbuf_consumed);
  194. while (pf->socks_state != SOCKS_NONE) {
  195. unsigned socks_version, message_type, reserved_byte;
  196. unsigned reply_code, port, ipv4, method;
  197. ptrlen methods;
  198. const char *socks4_hostname;
  199. strbuf *output;
  200. switch (pf->socks_state) {
  201. case SOCKS_INITIAL:
  202. case SOCKS_NONE:
  203. unreachable("These case values cannot appear");
  204. case SOCKS_4:
  205. /* SOCKS 4/4A connect message */
  206. socks_version = get_byte(src);
  207. message_type = get_byte(src);
  208. if (get_err(src) == BSE_OUT_OF_DATA)
  209. return;
  210. if (socks_version == SOCKS4_REQUEST_VERSION &&
  211. message_type == SOCKS_CMD_CONNECT) {
  212. /* CONNECT message */
  213. bool name_based = false;
  214. port = get_uint16(src);
  215. ipv4 = get_uint32(src);
  216. if (ipv4 >= SOCKS4A_NAME_FOLLOWS_BASE &&
  217. ipv4 < SOCKS4A_NAME_FOLLOWS_LIMIT) {
  218. /*
  219. * Addresses in this range indicate the SOCKS 4A
  220. * extension to specify a hostname, which comes
  221. * after the username.
  222. */
  223. name_based = true;
  224. }
  225. get_asciz(src); /* skip username */
  226. socks4_hostname = name_based ? get_asciz(src) : NULL;
  227. if (get_err(src) == BSE_OUT_OF_DATA)
  228. return;
  229. if (get_err(src))
  230. goto socks4_reject;
  231. pf->port = port;
  232. if (name_based) {
  233. pf->hostname = dupstr(socks4_hostname);
  234. } else {
  235. pf->hostname = ipv4_to_string(ipv4);
  236. }
  237. output = strbuf_new();
  238. put_byte(output, SOCKS4_REPLY_VERSION);
  239. put_byte(output, SOCKS4_RESP_SUCCESS);
  240. put_uint16(output, 0); /* null port field */
  241. put_uint32(output, 0); /* null address field */
  242. sk_write(pf->s, output->u, output->len);
  243. strbuf_free(output);
  244. pf->socks_state = SOCKS_NONE;
  245. pf->socksbuf_consumed = src->pos;
  246. break;
  247. }
  248. socks4_reject:
  249. output = strbuf_new();
  250. put_byte(output, SOCKS4_REPLY_VERSION);
  251. put_byte(output, SOCKS4_RESP_FAILURE);
  252. put_uint16(output, 0); /* null port field */
  253. put_uint32(output, 0); /* null address field */
  254. sk_write(pf->s, output->u, output->len);
  255. strbuf_free(output);
  256. pfd_close(pf);
  257. return;
  258. case SOCKS_5_INITIAL:
  259. /* SOCKS 5 initial method list */
  260. socks_version = get_byte(src);
  261. methods = get_pstring(src);
  262. method = SOCKS5_AUTH_REJECTED;
  263. /* Search the method list for AUTH_NONE, which is the
  264. * only one this client code can speak */
  265. for (size_t i = 0; i < methods.len; i++) {
  266. unsigned char this_method =
  267. ((const unsigned char *)methods.ptr)[i];
  268. if (this_method == SOCKS5_AUTH_NONE) {
  269. method = this_method;
  270. break;
  271. }
  272. }
  273. if (get_err(src) == BSE_OUT_OF_DATA)
  274. return;
  275. if (get_err(src))
  276. method = SOCKS5_AUTH_REJECTED;
  277. output = strbuf_new();
  278. put_byte(output, SOCKS5_REPLY_VERSION);
  279. put_byte(output, method);
  280. sk_write(pf->s, output->u, output->len);
  281. strbuf_free(output);
  282. if (method == SOCKS5_AUTH_REJECTED) {
  283. pfd_close(pf);
  284. return;
  285. }
  286. pf->socks_state = SOCKS_5_CONNECT;
  287. pf->socksbuf_consumed = src->pos;
  288. break;
  289. case SOCKS_5_CONNECT:
  290. /* SOCKS 5 connect message */
  291. socks_version = get_byte(src);
  292. message_type = get_byte(src);
  293. reserved_byte = get_byte(src);
  294. if (socks_version == SOCKS5_REQUEST_VERSION &&
  295. message_type == SOCKS_CMD_CONNECT &&
  296. reserved_byte == 0) {
  297. reply_code = SOCKS5_RESP_SUCCESS;
  298. switch (get_byte(src)) {
  299. case SOCKS5_ADDR_IPV4:
  300. pf->hostname = ipv4_to_string(get_uint32(src));
  301. break;
  302. case SOCKS5_ADDR_IPV6:
  303. pf->hostname = ipv6_to_string(get_data(src, 16));
  304. break;
  305. case SOCKS5_ADDR_HOSTNAME:
  306. pf->hostname = mkstr(get_pstring(src));
  307. break;
  308. default:
  309. pf->hostname = NULL;
  310. reply_code = SOCKS5_RESP_ADDRTYPE_NOT_SUPPORTED;
  311. break;
  312. }
  313. pf->port = get_uint16(src);
  314. } else {
  315. reply_code = SOCKS5_RESP_COMMAND_NOT_SUPPORTED;
  316. }
  317. if (get_err(src) == BSE_OUT_OF_DATA)
  318. return;
  319. if (get_err(src))
  320. reply_code = SOCKS5_RESP_FAILURE;
  321. output = strbuf_new();
  322. put_byte(output, SOCKS5_REPLY_VERSION);
  323. put_byte(output, reply_code);
  324. put_byte(output, 0); /* reserved */
  325. put_byte(output, SOCKS5_ADDR_IPV4); /* IPv4 address follows */
  326. put_uint32(output, 0); /* bound IPv4 address (unused) */
  327. put_uint16(output, 0); /* bound port number (unused) */
  328. sk_write(pf->s, output->u, output->len);
  329. strbuf_free(output);
  330. if (reply_code != SOCKS5_RESP_SUCCESS) {
  331. pfd_close(pf);
  332. return;
  333. }
  334. pf->socks_state = SOCKS_NONE;
  335. pf->socksbuf_consumed = src->pos;
  336. break;
  337. }
  338. }
  339. /*
  340. * We come here when we're ready to make an actual
  341. * connection.
  342. */
  343. /*
  344. * Freeze the socket until the SSH server confirms the
  345. * connection.
  346. */
  347. sk_set_frozen(pf->s, true);
  348. pf->c = wrap_lportfwd_open(pf->cl, pf->hostname, pf->port, pf->s,
  349. &pf->chan);
  350. }
  351. if (pf->ready)
  352. sshfwd_write(pf->c, data, len);
  353. }
  354. static void pfd_sent(Plug *plug, size_t bufsize)
  355. {
  356. struct PortForwarding *pf =
  357. container_of(plug, struct PortForwarding, plug);
  358. if (pf->c)
  359. sshfwd_unthrottle(pf->c, bufsize);
  360. }
  361. static const PlugVtable PortForwarding_plugvt = {
  362. .log = nullplug_log,
  363. .closing = pfd_closing,
  364. .receive = pfd_receive,
  365. .sent = pfd_sent,
  366. };
  367. static void pfd_chan_free(Channel *chan);
  368. static void pfd_open_confirmation(Channel *chan);
  369. static void pfd_open_failure(Channel *chan, const char *errtext);
  370. static size_t pfd_send(
  371. Channel *chan, bool is_stderr, const void *data, size_t len);
  372. static void pfd_send_eof(Channel *chan);
  373. static void pfd_set_input_wanted(Channel *chan, bool wanted);
  374. static char *pfd_log_close_msg(Channel *chan);
  375. static const ChannelVtable PortForwarding_channelvt = {
  376. .free = pfd_chan_free,
  377. .open_confirmation = pfd_open_confirmation,
  378. .open_failed = pfd_open_failure,
  379. .send = pfd_send,
  380. .send_eof = pfd_send_eof,
  381. .set_input_wanted = pfd_set_input_wanted,
  382. .log_close_msg = pfd_log_close_msg,
  383. .want_close = chan_default_want_close,
  384. .rcvd_exit_status = chan_no_exit_status,
  385. .rcvd_exit_signal = chan_no_exit_signal,
  386. .rcvd_exit_signal_numeric = chan_no_exit_signal_numeric,
  387. .run_shell = chan_no_run_shell,
  388. .run_command = chan_no_run_command,
  389. .run_subsystem = chan_no_run_subsystem,
  390. .enable_x11_forwarding = chan_no_enable_x11_forwarding,
  391. .enable_agent_forwarding = chan_no_enable_agent_forwarding,
  392. .allocate_pty = chan_no_allocate_pty,
  393. .set_env = chan_no_set_env,
  394. .send_break = chan_no_send_break,
  395. .send_signal = chan_no_send_signal,
  396. .change_window_size = chan_no_change_window_size,
  397. .request_response = chan_no_request_response,
  398. };
  399. Channel *portfwd_raw_new(ConnectionLayer *cl, Plug **plug, bool start_ready)
  400. {
  401. struct PortForwarding *pf;
  402. pf = new_portfwd_state();
  403. pf->plug.vt = &PortForwarding_plugvt;
  404. pf->chan.initial_fixed_window_size = 0;
  405. pf->chan.vt = &PortForwarding_channelvt;
  406. pf->input_wanted = true;
  407. pf->c = NULL;
  408. pf->cl = cl;
  409. pf->input_wanted = true;
  410. pf->ready = start_ready;
  411. pf->socks_state = SOCKS_NONE;
  412. pf->hostname = NULL;
  413. pf->port = 0;
  414. *plug = &pf->plug;
  415. return &pf->chan;
  416. }
  417. void portfwd_raw_free(Channel *pfchan)
  418. {
  419. struct PortForwarding *pf;
  420. assert(pfchan->vt == &PortForwarding_channelvt);
  421. pf = container_of(pfchan, struct PortForwarding, chan);
  422. free_portfwd_state(pf);
  423. }
  424. void portfwd_raw_setup(Channel *pfchan, Socket *s, SshChannel *sc)
  425. {
  426. struct PortForwarding *pf;
  427. assert(pfchan->vt == &PortForwarding_channelvt);
  428. pf = container_of(pfchan, struct PortForwarding, chan);
  429. pf->s = s;
  430. pf->c = sc;
  431. }
  432. /*
  433. * called when someone connects to the local port
  434. */
  435. static int pfl_accepting(Plug *p, accept_fn_t constructor, accept_ctx_t ctx)
  436. {
  437. struct PortListener *pl = container_of(p, struct PortListener, plug);
  438. struct PortForwarding *pf;
  439. Channel *chan;
  440. Plug *plug;
  441. Socket *s;
  442. const char *err;
  443. chan = portfwd_raw_new(pl->cl, &plug, false);
  444. s = constructor(ctx, plug);
  445. if ((err = sk_socket_error(s)) != NULL) {
  446. portfwd_raw_free(chan);
  447. return 1;
  448. }
  449. pf = container_of(chan, struct PortForwarding, chan);
  450. if (pl->is_dynamic) {
  451. pf->s = s;
  452. pf->socks_state = SOCKS_INITIAL;
  453. pf->socksbuf = strbuf_new();
  454. pf->socksbuf_consumed = 0;
  455. pf->port = 0; /* "hostname" buffer is so far empty */
  456. sk_set_frozen(s, false); /* we want to receive SOCKS _now_! */
  457. } else {
  458. pf->hostname = dupstr(pl->hostname);
  459. pf->port = pl->port;
  460. portfwd_raw_setup(
  461. chan, s,
  462. wrap_lportfwd_open(pl->cl, pf->hostname, pf->port, s, &pf->chan));
  463. }
  464. return 0;
  465. }
  466. static const PlugVtable PortListener_plugvt = {
  467. .log = nullplug_log,
  468. .closing = pfl_closing,
  469. .accepting = pfl_accepting,
  470. };
  471. /*
  472. * Add a new port-forwarding listener from srcaddr:port -> desthost:destport.
  473. *
  474. * desthost == NULL indicates dynamic SOCKS port forwarding.
  475. *
  476. * On success, returns NULL and fills in *pl_ret. On error, returns a
  477. * dynamically allocated error message string.
  478. */
  479. static char *pfl_listen(const char *desthost, int destport,
  480. const char *srcaddr, int port,
  481. ConnectionLayer *cl, Conf *conf,
  482. struct PortListener **pl_ret, int address_family)
  483. {
  484. const char *err;
  485. struct PortListener *pl;
  486. /*
  487. * Open socket.
  488. */
  489. pl = *pl_ret = new_portlistener_state();
  490. pl->plug.vt = &PortListener_plugvt;
  491. if (desthost) {
  492. pl->hostname = dupstr(desthost);
  493. pl->port = destport;
  494. pl->is_dynamic = false;
  495. } else
  496. pl->is_dynamic = true;
  497. pl->cl = cl;
  498. pl->s = new_listener(srcaddr, port, &pl->plug,
  499. !conf_get_bool(conf, CONF_lport_acceptall),
  500. conf, address_family);
  501. if ((err = sk_socket_error(pl->s)) != NULL) {
  502. char *err_ret = dupstr(err);
  503. sk_close(pl->s);
  504. free_portlistener_state(pl);
  505. *pl_ret = NULL;
  506. return err_ret;
  507. }
  508. return NULL;
  509. }
  510. static char *pfd_log_close_msg(Channel *chan)
  511. {
  512. return dupstr("Forwarded port closed");
  513. }
  514. static void pfd_close(struct PortForwarding *pf)
  515. {
  516. if (!pf)
  517. return;
  518. sk_close(pf->s);
  519. free_portfwd_state(pf);
  520. }
  521. /*
  522. * Terminate a listener.
  523. */
  524. static void pfl_terminate(struct PortListener *pl)
  525. {
  526. if (!pl)
  527. return;
  528. sk_close(pl->s);
  529. free_portlistener_state(pl);
  530. }
  531. static void pfd_set_input_wanted(Channel *chan, bool wanted)
  532. {
  533. assert(chan->vt == &PortForwarding_channelvt);
  534. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  535. pf->input_wanted = wanted;
  536. sk_set_frozen(pf->s, !pf->input_wanted);
  537. }
  538. static void pfd_chan_free(Channel *chan)
  539. {
  540. assert(chan->vt == &PortForwarding_channelvt);
  541. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  542. pfd_close(pf);
  543. }
  544. /*
  545. * Called to send data down the raw connection.
  546. */
  547. static size_t pfd_send(
  548. Channel *chan, bool is_stderr, const void *data, size_t len)
  549. {
  550. assert(chan->vt == &PortForwarding_channelvt);
  551. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  552. return sk_write(pf->s, data, len);
  553. }
  554. static void pfd_send_eof(Channel *chan)
  555. {
  556. assert(chan->vt == &PortForwarding_channelvt);
  557. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  558. sk_write_eof(pf->s);
  559. }
  560. static void pfd_open_confirmation(Channel *chan)
  561. {
  562. assert(chan->vt == &PortForwarding_channelvt);
  563. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  564. pf->ready = true;
  565. sk_set_frozen(pf->s, false);
  566. sk_write(pf->s, NULL, 0);
  567. if (pf->socksbuf) {
  568. sshfwd_write(pf->c, pf->socksbuf->u + pf->socksbuf_consumed,
  569. pf->socksbuf->len - pf->socksbuf_consumed);
  570. strbuf_free(pf->socksbuf);
  571. pf->socksbuf = NULL;
  572. }
  573. }
  574. static void pfd_open_failure(Channel *chan, const char *errtext)
  575. {
  576. assert(chan->vt == &PortForwarding_channelvt);
  577. PortForwarding *pf = container_of(chan, PortForwarding, chan);
  578. logeventf(pf->cl->logctx,
  579. "Forwarded connection refused by remote%s%s",
  580. errtext ? ": " : "", errtext ? errtext : "");
  581. }
  582. /* ----------------------------------------------------------------------
  583. * Code to manage the complete set of currently active port
  584. * forwardings, and update it from Conf.
  585. */
  586. struct PortFwdRecord {
  587. enum { DESTROY, KEEP, CREATE } status;
  588. int type;
  589. unsigned sport, dport;
  590. char *saddr, *daddr;
  591. char *sserv, *dserv;
  592. struct ssh_rportfwd *remote;
  593. int addressfamily;
  594. struct PortListener *local;
  595. };
  596. static int pfr_cmp(void *av, void *bv)
  597. {
  598. PortFwdRecord *a = (PortFwdRecord *) av;
  599. PortFwdRecord *b = (PortFwdRecord *) bv;
  600. int i;
  601. if (a->type > b->type)
  602. return +1;
  603. if (a->type < b->type)
  604. return -1;
  605. if (a->addressfamily > b->addressfamily)
  606. return +1;
  607. if (a->addressfamily < b->addressfamily)
  608. return -1;
  609. if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
  610. return i < 0 ? -1 : +1;
  611. if (a->sport > b->sport)
  612. return +1;
  613. if (a->sport < b->sport)
  614. return -1;
  615. if (a->type != 'D') {
  616. if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
  617. return i < 0 ? -1 : +1;
  618. if (a->dport > b->dport)
  619. return +1;
  620. if (a->dport < b->dport)
  621. return -1;
  622. }
  623. return 0;
  624. }
  625. static void pfr_free(PortFwdRecord *pfr)
  626. {
  627. /* Dispose of any listening socket. */
  628. if (pfr->local)
  629. pfl_terminate(pfr->local);
  630. sfree(pfr->saddr);
  631. sfree(pfr->daddr);
  632. sfree(pfr->sserv);
  633. sfree(pfr->dserv);
  634. sfree(pfr);
  635. }
  636. struct PortFwdManager {
  637. ConnectionLayer *cl;
  638. Conf *conf;
  639. tree234 *forwardings;
  640. };
  641. PortFwdManager *portfwdmgr_new(ConnectionLayer *cl)
  642. {
  643. PortFwdManager *mgr = snew(PortFwdManager);
  644. mgr->cl = cl;
  645. mgr->conf = NULL;
  646. mgr->forwardings = newtree234(pfr_cmp);
  647. return mgr;
  648. }
  649. void portfwdmgr_close(PortFwdManager *mgr, PortFwdRecord *pfr)
  650. {
  651. PortFwdRecord *realpfr = del234(mgr->forwardings, pfr);
  652. if (realpfr == pfr)
  653. pfr_free(pfr);
  654. }
  655. void portfwdmgr_close_all(PortFwdManager *mgr)
  656. {
  657. PortFwdRecord *pfr;
  658. while ((pfr = delpos234(mgr->forwardings, 0)) != NULL)
  659. pfr_free(pfr);
  660. }
  661. void portfwdmgr_free(PortFwdManager *mgr)
  662. {
  663. portfwdmgr_close_all(mgr);
  664. freetree234(mgr->forwardings);
  665. if (mgr->conf)
  666. conf_free(mgr->conf);
  667. sfree(mgr);
  668. }
  669. void portfwdmgr_config(PortFwdManager *mgr, Conf *conf)
  670. {
  671. PortFwdRecord *pfr;
  672. int i;
  673. char *key, *val;
  674. if (mgr->conf)
  675. conf_free(mgr->conf);
  676. mgr->conf = conf_copy(conf);
  677. /*
  678. * Go through the existing port forwardings and tag them
  679. * with status==DESTROY. Any that we want to keep will be
  680. * re-enabled (status==KEEP) as we go through the
  681. * configuration and find out which bits are the same as
  682. * they were before.
  683. */
  684. for (i = 0; (pfr = index234(mgr->forwardings, i)) != NULL; i++)
  685. pfr->status = DESTROY;
  686. for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
  687. val != NULL;
  688. val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
  689. char *kp, *kp2, *vp, *vp2;
  690. char address_family, type;
  691. int sport, dport, sserv, dserv;
  692. char *sports, *dports, *saddr, *host;
  693. kp = key;
  694. address_family = 'A';
  695. type = 'L';
  696. if (*kp == 'A' || *kp == '4' || *kp == '6')
  697. address_family = *kp++;
  698. if (*kp == 'L' || *kp == 'R')
  699. type = *kp++;
  700. if ((kp2 = host_strchr(kp, ':')) != NULL) {
  701. /*
  702. * There's a colon in the middle of the source port
  703. * string, which means that the part before it is
  704. * actually a source address.
  705. */
  706. char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
  707. saddr = host_strduptrim(saddr_tmp);
  708. sfree(saddr_tmp);
  709. sports = kp2+1;
  710. } else {
  711. saddr = NULL;
  712. sports = kp;
  713. }
  714. sport = atoi(sports);
  715. sserv = 0;
  716. if (sport == 0) {
  717. sserv = 1;
  718. sport = net_service_lookup(sports);
  719. if (!sport) {
  720. logeventf(mgr->cl->logctx, "Service lookup failed for source"
  721. " port \"%s\"", sports);
  722. }
  723. }
  724. if (type == 'L' && !strcmp(val, "D")) {
  725. /* dynamic forwarding */
  726. host = NULL;
  727. dports = NULL;
  728. dport = -1;
  729. dserv = 0;
  730. type = 'D';
  731. } else {
  732. /* ordinary forwarding */
  733. vp = val;
  734. vp2 = vp + host_strcspn(vp, ":");
  735. host = dupprintf("%.*s", (int)(vp2 - vp), vp);
  736. if (*vp2)
  737. vp2++;
  738. dports = vp2;
  739. dport = atoi(dports);
  740. dserv = 0;
  741. if (dport == 0) {
  742. dserv = 1;
  743. dport = net_service_lookup(dports);
  744. if (!dport) {
  745. logeventf(mgr->cl->logctx,
  746. "Service lookup failed for destination"
  747. " port \"%s\"", dports);
  748. }
  749. }
  750. }
  751. if (sport && dport) {
  752. /* Set up a description of the source port. */
  753. pfr = snew(PortFwdRecord);
  754. pfr->type = type;
  755. pfr->saddr = saddr;
  756. pfr->sserv = sserv ? dupstr(sports) : NULL;
  757. pfr->sport = sport;
  758. pfr->daddr = host;
  759. pfr->dserv = dserv ? dupstr(dports) : NULL;
  760. pfr->dport = dport;
  761. pfr->local = NULL;
  762. pfr->remote = NULL;
  763. pfr->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
  764. address_family == '6' ? ADDRTYPE_IPV6 :
  765. ADDRTYPE_UNSPEC);
  766. PortFwdRecord *existing = add234(mgr->forwardings, pfr);
  767. if (existing != pfr) {
  768. if (existing->status == DESTROY) {
  769. /*
  770. * We already have a port forwarding up and running
  771. * with precisely these parameters. Hence, no need
  772. * to do anything; simply re-tag the existing one
  773. * as KEEP.
  774. */
  775. existing->status = KEEP;
  776. }
  777. /*
  778. * Anything else indicates that there was a duplicate
  779. * in our input, which we'll silently ignore.
  780. */
  781. pfr_free(pfr);
  782. } else {
  783. pfr->status = CREATE;
  784. }
  785. } else {
  786. sfree(saddr);
  787. sfree(host);
  788. }
  789. }
  790. /*
  791. * Now go through and destroy any port forwardings which were
  792. * not re-enabled.
  793. */
  794. for (i = 0; (pfr = index234(mgr->forwardings, i)) != NULL; i++) {
  795. if (pfr->status == DESTROY) {
  796. char *message;
  797. message = dupprintf("%s port forwarding from %s%s%d",
  798. pfr->type == 'L' ? "local" :
  799. pfr->type == 'R' ? "remote" : "dynamic",
  800. pfr->saddr ? pfr->saddr : "",
  801. pfr->saddr ? ":" : "",
  802. pfr->sport);
  803. if (pfr->type != 'D') {
  804. char *msg2 = dupprintf("%s to %s:%d", message,
  805. pfr->daddr, pfr->dport);
  806. sfree(message);
  807. message = msg2;
  808. }
  809. logeventf(mgr->cl->logctx, "Cancelling %s", message);
  810. sfree(message);
  811. /* pfr->remote or pfr->local may be NULL if setting up a
  812. * forwarding failed. */
  813. if (pfr->remote) {
  814. /*
  815. * Cancel the port forwarding at the server
  816. * end.
  817. *
  818. * Actually closing the listening port on the server
  819. * side may fail - because in SSH-1 there's no message
  820. * in the protocol to request it!
  821. *
  822. * Instead, we simply remove the record of the
  823. * forwarding from our local end, so that any
  824. * connections the server tries to make on it are
  825. * rejected.
  826. */
  827. ssh_rportfwd_remove(mgr->cl, pfr->remote);
  828. pfr->remote = NULL;
  829. } else if (pfr->local) {
  830. pfl_terminate(pfr->local);
  831. pfr->local = NULL;
  832. }
  833. delpos234(mgr->forwardings, i);
  834. pfr_free(pfr);
  835. i--; /* so we don't skip one in the list */
  836. }
  837. }
  838. /*
  839. * And finally, set up any new port forwardings (status==CREATE).
  840. */
  841. for (i = 0; (pfr = index234(mgr->forwardings, i)) != NULL; i++) {
  842. if (pfr->status == CREATE) {
  843. char *sportdesc, *dportdesc;
  844. sportdesc = dupprintf("%s%s%s%s%d%s",
  845. pfr->saddr ? pfr->saddr : "",
  846. pfr->saddr ? ":" : "",
  847. pfr->sserv ? pfr->sserv : "",
  848. pfr->sserv ? "(" : "",
  849. pfr->sport,
  850. pfr->sserv ? ")" : "");
  851. if (pfr->type == 'D') {
  852. dportdesc = NULL;
  853. } else {
  854. dportdesc = dupprintf("%s:%s%s%d%s",
  855. pfr->daddr,
  856. pfr->dserv ? pfr->dserv : "",
  857. pfr->dserv ? "(" : "",
  858. pfr->dport,
  859. pfr->dserv ? ")" : "");
  860. }
  861. if (pfr->type == 'L') {
  862. char *err = pfl_listen(pfr->daddr, pfr->dport,
  863. pfr->saddr, pfr->sport,
  864. mgr->cl, conf, &pfr->local,
  865. pfr->addressfamily);
  866. logeventf(mgr->cl->logctx,
  867. "Local %sport %s forwarding to %s%s%s",
  868. pfr->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  869. pfr->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  870. sportdesc, dportdesc,
  871. err ? " failed: " : "", err ? err : "");
  872. if (err)
  873. sfree(err);
  874. } else if (pfr->type == 'D') {
  875. char *err = pfl_listen(NULL, -1, pfr->saddr, pfr->sport,
  876. mgr->cl, conf, &pfr->local,
  877. pfr->addressfamily);
  878. logeventf(mgr->cl->logctx,
  879. "Local %sport %s SOCKS dynamic forwarding%s%s",
  880. pfr->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  881. pfr->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  882. sportdesc,
  883. err ? " failed: " : "", err ? err : "");
  884. if (err)
  885. sfree(err);
  886. } else {
  887. const char *shost;
  888. if (pfr->saddr) {
  889. shost = pfr->saddr;
  890. } else if (conf_get_bool(conf, CONF_rport_acceptall)) {
  891. shost = "";
  892. } else {
  893. shost = "localhost";
  894. }
  895. pfr->remote = ssh_rportfwd_alloc(
  896. mgr->cl, shost, pfr->sport, pfr->daddr, pfr->dport,
  897. pfr->addressfamily, sportdesc, pfr, NULL);
  898. if (!pfr->remote) {
  899. logeventf(mgr->cl->logctx,
  900. "Duplicate remote port forwarding to %s:%d",
  901. pfr->daddr, pfr->dport);
  902. pfr_free(pfr);
  903. } else {
  904. logeventf(mgr->cl->logctx, "Requesting remote port %s"
  905. " forward to %s", sportdesc, dportdesc);
  906. }
  907. }
  908. sfree(sportdesc);
  909. sfree(dportdesc);
  910. }
  911. }
  912. }
  913. bool portfwdmgr_listen(PortFwdManager *mgr, const char *host, int port,
  914. const char *keyhost, int keyport, Conf *conf)
  915. {
  916. PortFwdRecord *pfr;
  917. pfr = snew(PortFwdRecord);
  918. pfr->type = 'L';
  919. pfr->saddr = host ? dupstr(host) : NULL;
  920. pfr->daddr = keyhost ? dupstr(keyhost) : NULL;
  921. pfr->sserv = pfr->dserv = NULL;
  922. pfr->sport = port;
  923. pfr->dport = keyport;
  924. pfr->local = NULL;
  925. pfr->remote = NULL;
  926. pfr->addressfamily = ADDRTYPE_UNSPEC;
  927. PortFwdRecord *existing = add234(mgr->forwardings, pfr);
  928. if (existing != pfr) {
  929. /*
  930. * We had this record already. Return failure.
  931. */
  932. pfr_free(pfr);
  933. return false;
  934. }
  935. char *err = pfl_listen(keyhost, keyport, host, port,
  936. mgr->cl, conf, &pfr->local, pfr->addressfamily);
  937. logeventf(mgr->cl->logctx,
  938. "%s on port %s:%d to forward to client%s%s",
  939. err ? "Failed to listen" : "Listening", host, port,
  940. err ? ": " : "", err ? err : "");
  941. if (err) {
  942. sfree(err);
  943. del234(mgr->forwardings, pfr);
  944. pfr_free(pfr);
  945. return false;
  946. }
  947. return true;
  948. }
  949. bool portfwdmgr_unlisten(PortFwdManager *mgr, const char *host, int port)
  950. {
  951. PortFwdRecord pfr_key;
  952. pfr_key.type = 'L';
  953. /* Safe to cast the const away here, because it will only be used
  954. * by pfr_cmp, which won't write to the string */
  955. pfr_key.saddr = pfr_key.daddr = (char *)host;
  956. pfr_key.sserv = pfr_key.dserv = NULL;
  957. pfr_key.sport = pfr_key.dport = port;
  958. pfr_key.local = NULL;
  959. pfr_key.remote = NULL;
  960. pfr_key.addressfamily = ADDRTYPE_UNSPEC;
  961. PortFwdRecord *pfr = del234(mgr->forwardings, &pfr_key);
  962. if (!pfr)
  963. return false;
  964. logeventf(mgr->cl->logctx, "Closing listening port %s:%d", host, port);
  965. pfr_free(pfr);
  966. return true;
  967. }
  968. /*
  969. * Called when receiving a PORT OPEN from the server to make a
  970. * connection to a destination host.
  971. *
  972. * On success, returns NULL and fills in *pf_ret. On error, returns a
  973. * dynamically allocated error message string.
  974. */
  975. char *portfwdmgr_connect(PortFwdManager *mgr, Channel **chan_ret,
  976. char *hostname, int port, SshChannel *c,
  977. int addressfamily)
  978. {
  979. SockAddr *addr;
  980. const char *err;
  981. char *dummy_realhost = NULL;
  982. struct PortForwarding *pf;
  983. /*
  984. * Try to find host.
  985. */
  986. addr = name_lookup(hostname, port, &dummy_realhost, mgr->conf,
  987. addressfamily, NULL, NULL);
  988. if ((err = sk_addr_error(addr)) != NULL) {
  989. char *err_ret = dupstr(err);
  990. sk_addr_free(addr);
  991. sfree(dummy_realhost);
  992. return err_ret;
  993. }
  994. /*
  995. * Open socket.
  996. */
  997. pf = new_portfwd_state();
  998. *chan_ret = &pf->chan;
  999. pf->plug.vt = &PortForwarding_plugvt;
  1000. pf->chan.initial_fixed_window_size = 0;
  1001. pf->chan.vt = &PortForwarding_channelvt;
  1002. pf->input_wanted = true;
  1003. pf->ready = true;
  1004. pf->c = c;
  1005. pf->cl = mgr->cl;
  1006. pf->socks_state = SOCKS_NONE;
  1007. pf->s = new_connection(addr, dummy_realhost, port,
  1008. false, true, false, false, &pf->plug, mgr->conf,
  1009. NULL);
  1010. sfree(dummy_realhost);
  1011. if ((err = sk_socket_error(pf->s)) != NULL) {
  1012. char *err_ret = dupstr(err);
  1013. sk_close(pf->s);
  1014. free_portfwd_state(pf);
  1015. *chan_ret = NULL;
  1016. return err_ret;
  1017. }
  1018. return NULL;
  1019. }