sshshare.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. /*
  2. * Support for SSH connection sharing, i.e. permitting one PuTTY to
  3. * open its own channels over the SSH session being run by another.
  4. */
  5. /*
  6. * Discussion and technical documentation
  7. * ======================================
  8. *
  9. * The basic strategy for PuTTY's implementation of SSH connection
  10. * sharing is to have a single 'upstream' PuTTY process, which manages
  11. * the real SSH connection and all the cryptography, and then zero or
  12. * more 'downstream' PuTTYs, which never talk to the real host but
  13. * only talk to the upstream through local IPC (Unix-domain sockets or
  14. * Windows named pipes).
  15. *
  16. * The downstreams communicate with the upstream using a protocol
  17. * derived from SSH itself, which I'll document in detail below. In
  18. * brief, though: the downstream->upstream protocol uses a trivial
  19. * binary packet protocol (just length/type/data) to encapsulate
  20. * unencrypted SSH messages, and downstreams talk to the upstream more
  21. * or less as if it was an SSH server itself. (So downstreams can
  22. * themselves open multiple SSH channels, for example, by sending
  23. * multiple SSH2_MSG_CHANNEL_OPENs; they can send CHANNEL_REQUESTs of
  24. * their choice within each channel, and they handle their own
  25. * WINDOW_ADJUST messages.)
  26. *
  27. * The upstream would ideally handle these downstreams by just putting
  28. * their messages into the queue for proper SSH-2 encapsulation and
  29. * encryption and sending them straight on to the server. However,
  30. * that's not quite feasible as written, because client-side channel
  31. * IDs could easily conflict (between multiple downstreams, or between
  32. * a downstream and the upstream). To protect against that, the
  33. * upstream rewrites the client-side channel IDs in messages it passes
  34. * on to the server, so that it's performing what you might describe
  35. * as 'channel-number NAT'. Then the upstream remembers which of its
  36. * own channel IDs are channels it's managing itself, and which are
  37. * placeholders associated with a particular downstream, so that when
  38. * replies come in from the server they can be sent on to the relevant
  39. * downstream (after un-NATting the channel number, of course).
  40. *
  41. * Global requests from downstreams are only accepted if the upstream
  42. * knows what to do about them; currently the only such requests are
  43. * the ones having to do with remote-to-local port forwarding (in
  44. * which, again, the upstream remembers that some of the forwardings
  45. * it's asked the server to set up were on behalf of particular
  46. * downstreams, and sends the incoming CHANNEL_OPENs to those
  47. * downstreams when connections come in).
  48. *
  49. * Other fiddly pieces of this mechanism are X forwarding and
  50. * (OpenSSH-style) agent forwarding. Both of these have a fundamental
  51. * problem arising from the protocol design: that the CHANNEL_OPEN
  52. * from the server introducing a forwarded connection does not carry
  53. * any indication of which session channel gave rise to it; so if
  54. * session channels from multiple downstreams enable those forwarding
  55. * methods, it's hard for the upstream to know which downstream to
  56. * send the resulting connections back to.
  57. *
  58. * For X forwarding, we can work around this in a really painful way
  59. * by using the fake X11 authorisation data sent to the server as part
  60. * of the forwarding setup: upstream ensures that every X forwarding
  61. * request carries distinguishable fake auth data, and then when X
  62. * connections come in it waits to see the auth data in the X11 setup
  63. * message before it decides which downstream to pass the connection
  64. * on to.
  65. *
  66. * For agent forwarding, that workaround is unavailable. As a result,
  67. * this system (and, as far as I can think of, any other system too)
  68. * has the fundamental constraint that it can only forward one SSH
  69. * agent - it can't forward two agents to different session channels.
  70. * So downstreams can request agent forwarding if they like, but if
  71. * they do, they'll get whatever SSH agent is known to the upstream
  72. * (if any) forwarded to their sessions.
  73. *
  74. * Downstream-to-upstream protocol
  75. * -------------------------------
  76. *
  77. * Here I document in detail the protocol spoken between PuTTY
  78. * downstreams and upstreams over local IPC. The IPC mechanism can
  79. * vary between host platforms, but the protocol is the same.
  80. *
  81. * The protocol commences with a version exchange which is exactly
  82. * like the SSH-2 one, in that each side sends a single line of text
  83. * of the form
  84. *
  85. * <protocol>-<version>-<softwareversion> [comments] \r\n
  86. *
  87. * The only difference is that in real SSH-2, <protocol> is the string
  88. * "SSH", whereas in this protocol the string is
  89. * "[email protected]".
  90. *
  91. * (The SSH RFCs allow many protocol-level identifier namespaces to be
  92. * extended by implementors without central standardisation as long as
  93. * they suffix "@" and a domain name they control to their new ids.
  94. * RFC 4253 does not define this particular name to be changeable at
  95. * all, but I like to think this is obviously how it would have done
  96. * so if the working group had foreseen the need :-)
  97. *
  98. * Thereafter, all data exchanged consists of a sequence of binary
  99. * packets concatenated end-to-end, each of which is of the form
  100. *
  101. * uint32 length of packet, N
  102. * byte[N] N bytes of packet data
  103. *
  104. * and, since these are SSH-2 messages, the first data byte is taken
  105. * to be the packet type code.
  106. *
  107. * These messages are interpreted as those of an SSH connection, after
  108. * userauth completes, and without any repeat key exchange.
  109. * Specifically, any message from the SSH Connection Protocol is
  110. * permitted, and also SSH_MSG_IGNORE, SSH_MSG_DEBUG,
  111. * SSH_MSG_DISCONNECT and SSH_MSG_UNIMPLEMENTED from the SSH Transport
  112. * Protocol.
  113. *
  114. * This protocol imposes a few additional requirements, over and above
  115. * those of the standard SSH Connection Protocol:
  116. *
  117. * Message sizes are not permitted to exceed 0x4010 (16400) bytes,
  118. * including their length header.
  119. *
  120. * When the server (i.e. really the PuTTY upstream) sends
  121. * SSH_MSG_CHANNEL_OPEN with channel type "x11", and the client
  122. * (downstream) responds with SSH_MSG_CHANNEL_OPEN_CONFIRMATION, that
  123. * confirmation message MUST include an initial window size of at
  124. * least 256. (Rationale: this is a bit of a fudge which makes it
  125. * easier, by eliminating the possibility of nasty edge cases, for an
  126. * upstream to arrange not to pass the CHANNEL_OPEN on to downstream
  127. * until after it's seen the X11 auth data to decide which downstream
  128. * it needs to go to.)
  129. */
  130. #include <stdio.h>
  131. #include <stdlib.h>
  132. #include <assert.h>
  133. #include <limits.h>
  134. #include <errno.h>
  135. #include "putty.h"
  136. #include "tree234.h"
  137. #include "ssh.h"
  138. struct ssh_sharing_state {
  139. char *sockname; /* the socket name, kept for cleanup */
  140. Socket listensock; /* the master listening Socket */
  141. tree234 *connections; /* holds ssh_sharing_connstates */
  142. unsigned nextid; /* preferred id for next connstate */
  143. Ssh ssh; /* instance of the ssh backend */
  144. char *server_verstring; /* server version string after "SSH-" */
  145. const Plug_vtable *plugvt;
  146. };
  147. struct share_globreq;
  148. struct ssh_sharing_connstate {
  149. unsigned id; /* used to identify this downstream in log messages */
  150. Socket sock; /* the Socket for this connection */
  151. struct ssh_sharing_state *parent;
  152. int crLine; /* coroutine state for share_receive */
  153. int sent_verstring, got_verstring, curr_packetlen;
  154. unsigned char recvbuf[0x4010];
  155. int recvlen;
  156. /*
  157. * Assorted state we have to remember about this downstream, so
  158. * that we can clean it up appropriately when the downstream goes
  159. * away.
  160. */
  161. /* Channels which don't have a downstream id, i.e. we've passed a
  162. * CHANNEL_OPEN down from the server but not had an
  163. * OPEN_CONFIRMATION or OPEN_FAILURE back. If downstream goes
  164. * away, we respond to all of these with OPEN_FAILURE. */
  165. tree234 *halfchannels; /* stores 'struct share_halfchannel' */
  166. /* Channels which do have a downstream id. We need to index these
  167. * by both server id and upstream id, so we can find a channel
  168. * when handling either an upward or a downward message referring
  169. * to it. */
  170. tree234 *channels_by_us; /* stores 'struct share_channel' */
  171. tree234 *channels_by_server; /* stores 'struct share_channel' */
  172. /* Another class of channel which doesn't have a downstream id.
  173. * The difference between these and halfchannels is that xchannels
  174. * do have an *upstream* id, because upstream has already accepted
  175. * the channel request from the server. This arises in the case of
  176. * X forwarding, where we have to accept the request and read the
  177. * X authorisation data before we know whether the channel needs
  178. * to be forwarded to a downstream. */
  179. tree234 *xchannels_by_us; /* stores 'struct share_xchannel' */
  180. tree234 *xchannels_by_server; /* stores 'struct share_xchannel' */
  181. /* Remote port forwarding requests in force. */
  182. tree234 *forwardings; /* stores 'struct share_forwarding' */
  183. /* Global requests we've sent on to the server, pending replies. */
  184. struct share_globreq *globreq_head, *globreq_tail;
  185. const Plug_vtable *plugvt;
  186. };
  187. struct share_halfchannel {
  188. unsigned server_id;
  189. };
  190. /* States of a share_channel. */
  191. enum {
  192. OPEN,
  193. SENT_CLOSE,
  194. RCVD_CLOSE,
  195. /* Downstream has sent CHANNEL_OPEN but server hasn't replied yet.
  196. * If downstream goes away when a channel is in this state, we
  197. * must wait for the server's response before starting to send
  198. * CLOSE. Channels in this state are also not held in
  199. * channels_by_server, because their server_id field is
  200. * meaningless. */
  201. UNACKNOWLEDGED
  202. };
  203. struct share_channel {
  204. unsigned downstream_id, upstream_id, server_id;
  205. int downstream_maxpkt;
  206. int state;
  207. /*
  208. * Some channels (specifically, channels on which downstream has
  209. * sent "x11-req") have the additional function of storing a set
  210. * of downstream X authorisation data and a handle to an upstream
  211. * fake set.
  212. */
  213. struct X11FakeAuth *x11_auth_upstream;
  214. int x11_auth_proto;
  215. char *x11_auth_data;
  216. int x11_auth_datalen;
  217. int x11_one_shot;
  218. };
  219. struct share_forwarding {
  220. char *host;
  221. int port;
  222. int active; /* has the server sent REQUEST_SUCCESS? */
  223. };
  224. struct share_xchannel_message {
  225. struct share_xchannel_message *next;
  226. int type;
  227. unsigned char *data;
  228. int datalen;
  229. };
  230. struct share_xchannel {
  231. unsigned upstream_id, server_id;
  232. /*
  233. * xchannels come in two flavours: live and dead. Live ones are
  234. * waiting for an OPEN_CONFIRMATION or OPEN_FAILURE from
  235. * downstream; dead ones have had an OPEN_FAILURE, so they only
  236. * exist as a means of letting us conveniently respond to further
  237. * channel messages from the server until such time as the server
  238. * sends us CHANNEL_CLOSE.
  239. */
  240. int live;
  241. /*
  242. * When we receive OPEN_CONFIRMATION, we will need to send a
  243. * WINDOW_ADJUST to the server to synchronise the windows. For
  244. * this purpose we need to know what window we have so far offered
  245. * the server. We record this as exactly the value in the
  246. * OPEN_CONFIRMATION that upstream sent us, adjusted by the amount
  247. * by which the two X greetings differed in length.
  248. */
  249. int window;
  250. /*
  251. * Linked list of SSH messages from the server relating to this
  252. * channel, which we queue up until downstream sends us an
  253. * OPEN_CONFIRMATION and we can belatedly send them all on.
  254. */
  255. struct share_xchannel_message *msghead, *msgtail;
  256. };
  257. enum {
  258. GLOBREQ_TCPIP_FORWARD,
  259. GLOBREQ_CANCEL_TCPIP_FORWARD
  260. };
  261. struct share_globreq {
  262. struct share_globreq *next;
  263. int type;
  264. int want_reply;
  265. struct share_forwarding *fwd;
  266. };
  267. static int share_connstate_cmp(void *av, void *bv)
  268. {
  269. const struct ssh_sharing_connstate *a =
  270. (const struct ssh_sharing_connstate *)av;
  271. const struct ssh_sharing_connstate *b =
  272. (const struct ssh_sharing_connstate *)bv;
  273. if (a->id < b->id)
  274. return -1;
  275. else if (a->id > b->id)
  276. return +1;
  277. else
  278. return 0;
  279. }
  280. static unsigned share_find_unused_id
  281. (struct ssh_sharing_state *sharestate, unsigned first)
  282. {
  283. int low_orig, low, mid, high, high_orig;
  284. struct ssh_sharing_connstate *cs;
  285. unsigned ret;
  286. /*
  287. * Find the lowest unused downstream ID greater or equal to
  288. * 'first'.
  289. *
  290. * Begin by seeing if 'first' itself is available. If it is, we'll
  291. * just return it; if it's already in the tree, we'll find the
  292. * tree index where it appears and use that for the next stage.
  293. */
  294. {
  295. struct ssh_sharing_connstate dummy;
  296. dummy.id = first;
  297. cs = findrelpos234(sharestate->connections, &dummy, NULL,
  298. REL234_GE, &low_orig);
  299. if (!cs)
  300. return first;
  301. }
  302. /*
  303. * Now binary-search using the counted B-tree, to find the largest
  304. * ID which is in a contiguous sequence from the beginning of that
  305. * range.
  306. */
  307. low = low_orig;
  308. high = high_orig = count234(sharestate->connections);
  309. while (high - low > 1) {
  310. mid = (high + low) / 2;
  311. cs = index234(sharestate->connections, mid);
  312. if (cs->id == first + (mid - low_orig))
  313. low = mid; /* this one is still in the sequence */
  314. else
  315. high = mid; /* this one is past the end */
  316. }
  317. /*
  318. * Now low is the tree index of the largest ID in the initial
  319. * sequence. So the return value is one more than low's id, and we
  320. * know low's id is given by the formula in the binary search loop
  321. * above.
  322. *
  323. * (If an SSH connection went on for _enormously_ long, we might
  324. * reach a point where all ids from 'first' to UINT_MAX were in
  325. * use. In that situation the formula below would wrap round by
  326. * one and return zero, which is conveniently the right way to
  327. * signal 'no id available' from this function.)
  328. */
  329. ret = first + (low - low_orig) + 1;
  330. {
  331. struct ssh_sharing_connstate dummy;
  332. dummy.id = ret;
  333. assert(NULL == find234(sharestate->connections, &dummy, NULL));
  334. }
  335. return ret;
  336. }
  337. static int share_halfchannel_cmp(void *av, void *bv)
  338. {
  339. const struct share_halfchannel *a = (const struct share_halfchannel *)av;
  340. const struct share_halfchannel *b = (const struct share_halfchannel *)bv;
  341. if (a->server_id < b->server_id)
  342. return -1;
  343. else if (a->server_id > b->server_id)
  344. return +1;
  345. else
  346. return 0;
  347. }
  348. static int share_channel_us_cmp(void *av, void *bv)
  349. {
  350. const struct share_channel *a = (const struct share_channel *)av;
  351. const struct share_channel *b = (const struct share_channel *)bv;
  352. if (a->upstream_id < b->upstream_id)
  353. return -1;
  354. else if (a->upstream_id > b->upstream_id)
  355. return +1;
  356. else
  357. return 0;
  358. }
  359. static int share_channel_server_cmp(void *av, void *bv)
  360. {
  361. const struct share_channel *a = (const struct share_channel *)av;
  362. const struct share_channel *b = (const struct share_channel *)bv;
  363. if (a->server_id < b->server_id)
  364. return -1;
  365. else if (a->server_id > b->server_id)
  366. return +1;
  367. else
  368. return 0;
  369. }
  370. static int share_xchannel_us_cmp(void *av, void *bv)
  371. {
  372. const struct share_xchannel *a = (const struct share_xchannel *)av;
  373. const struct share_xchannel *b = (const struct share_xchannel *)bv;
  374. if (a->upstream_id < b->upstream_id)
  375. return -1;
  376. else if (a->upstream_id > b->upstream_id)
  377. return +1;
  378. else
  379. return 0;
  380. }
  381. static int share_xchannel_server_cmp(void *av, void *bv)
  382. {
  383. const struct share_xchannel *a = (const struct share_xchannel *)av;
  384. const struct share_xchannel *b = (const struct share_xchannel *)bv;
  385. if (a->server_id < b->server_id)
  386. return -1;
  387. else if (a->server_id > b->server_id)
  388. return +1;
  389. else
  390. return 0;
  391. }
  392. static int share_forwarding_cmp(void *av, void *bv)
  393. {
  394. const struct share_forwarding *a = (const struct share_forwarding *)av;
  395. const struct share_forwarding *b = (const struct share_forwarding *)bv;
  396. int i;
  397. if ((i = strcmp(a->host, b->host)) != 0)
  398. return i;
  399. else if (a->port < b->port)
  400. return -1;
  401. else if (a->port > b->port)
  402. return +1;
  403. else
  404. return 0;
  405. }
  406. static void share_xchannel_free(struct share_xchannel *xc)
  407. {
  408. while (xc->msghead) {
  409. struct share_xchannel_message *tmp = xc->msghead;
  410. xc->msghead = tmp->next;
  411. sfree(tmp);
  412. }
  413. sfree(xc);
  414. }
  415. static void share_connstate_free(struct ssh_sharing_connstate *cs)
  416. {
  417. struct share_halfchannel *hc;
  418. struct share_xchannel *xc;
  419. struct share_channel *chan;
  420. struct share_forwarding *fwd;
  421. while ((hc = (struct share_halfchannel *)
  422. delpos234(cs->halfchannels, 0)) != NULL)
  423. sfree(hc);
  424. freetree234(cs->halfchannels);
  425. /* All channels live in 'channels_by_us' but only some in
  426. * 'channels_by_server', so we use the former to find the list of
  427. * ones to free */
  428. freetree234(cs->channels_by_server);
  429. while ((chan = (struct share_channel *)
  430. delpos234(cs->channels_by_us, 0)) != NULL)
  431. sfree(chan);
  432. freetree234(cs->channels_by_us);
  433. /* But every xchannel is in both trees, so it doesn't matter which
  434. * we use to free them. */
  435. while ((xc = (struct share_xchannel *)
  436. delpos234(cs->xchannels_by_us, 0)) != NULL)
  437. share_xchannel_free(xc);
  438. freetree234(cs->xchannels_by_us);
  439. freetree234(cs->xchannels_by_server);
  440. while ((fwd = (struct share_forwarding *)
  441. delpos234(cs->forwardings, 0)) != NULL)
  442. sfree(fwd);
  443. freetree234(cs->forwardings);
  444. while (cs->globreq_head) {
  445. struct share_globreq *globreq = cs->globreq_head;
  446. cs->globreq_head = cs->globreq_head->next;
  447. sfree(globreq);
  448. }
  449. if (cs->sock)
  450. sk_close(cs->sock);
  451. sfree(cs);
  452. }
  453. void sharestate_free(ssh_sharing_state *sharestate)
  454. {
  455. struct ssh_sharing_connstate *cs;
  456. platform_ssh_share_cleanup(sharestate->sockname);
  457. while ((cs = (struct ssh_sharing_connstate *)
  458. delpos234(sharestate->connections, 0)) != NULL) {
  459. share_connstate_free(cs);
  460. }
  461. freetree234(sharestate->connections);
  462. if (sharestate->listensock) {
  463. sk_close(sharestate->listensock);
  464. sharestate->listensock = NULL;
  465. }
  466. sfree(sharestate->server_verstring);
  467. sfree(sharestate->sockname);
  468. sfree(sharestate);
  469. }
  470. static struct share_halfchannel *share_add_halfchannel
  471. (struct ssh_sharing_connstate *cs, unsigned server_id)
  472. {
  473. struct share_halfchannel *hc = snew(struct share_halfchannel);
  474. hc->server_id = server_id;
  475. if (add234(cs->halfchannels, hc) != hc) {
  476. /* Duplicate?! */
  477. sfree(hc);
  478. return NULL;
  479. } else {
  480. return hc;
  481. }
  482. }
  483. static struct share_halfchannel *share_find_halfchannel
  484. (struct ssh_sharing_connstate *cs, unsigned server_id)
  485. {
  486. struct share_halfchannel dummyhc;
  487. dummyhc.server_id = server_id;
  488. return find234(cs->halfchannels, &dummyhc, NULL);
  489. }
  490. static void share_remove_halfchannel(struct ssh_sharing_connstate *cs,
  491. struct share_halfchannel *hc)
  492. {
  493. del234(cs->halfchannels, hc);
  494. sfree(hc);
  495. }
  496. static struct share_channel *share_add_channel
  497. (struct ssh_sharing_connstate *cs, unsigned downstream_id,
  498. unsigned upstream_id, unsigned server_id, int state, int maxpkt)
  499. {
  500. struct share_channel *chan = snew(struct share_channel);
  501. chan->downstream_id = downstream_id;
  502. chan->upstream_id = upstream_id;
  503. chan->server_id = server_id;
  504. chan->state = state;
  505. chan->downstream_maxpkt = maxpkt;
  506. chan->x11_auth_upstream = NULL;
  507. chan->x11_auth_data = NULL;
  508. chan->x11_auth_proto = -1;
  509. chan->x11_auth_datalen = 0;
  510. chan->x11_one_shot = 0;
  511. if (add234(cs->channels_by_us, chan) != chan) {
  512. sfree(chan);
  513. return NULL;
  514. }
  515. if (chan->state != UNACKNOWLEDGED) {
  516. if (add234(cs->channels_by_server, chan) != chan) {
  517. del234(cs->channels_by_us, chan);
  518. sfree(chan);
  519. return NULL;
  520. }
  521. }
  522. return chan;
  523. }
  524. static void share_channel_set_server_id(struct ssh_sharing_connstate *cs,
  525. struct share_channel *chan,
  526. unsigned server_id, int newstate)
  527. {
  528. chan->server_id = server_id;
  529. chan->state = newstate;
  530. assert(newstate != UNACKNOWLEDGED);
  531. add234(cs->channels_by_server, chan);
  532. }
  533. static struct share_channel *share_find_channel_by_upstream
  534. (struct ssh_sharing_connstate *cs, unsigned upstream_id)
  535. {
  536. struct share_channel dummychan;
  537. dummychan.upstream_id = upstream_id;
  538. return find234(cs->channels_by_us, &dummychan, NULL);
  539. }
  540. static struct share_channel *share_find_channel_by_server
  541. (struct ssh_sharing_connstate *cs, unsigned server_id)
  542. {
  543. struct share_channel dummychan;
  544. dummychan.server_id = server_id;
  545. return find234(cs->channels_by_server, &dummychan, NULL);
  546. }
  547. static void share_remove_channel(struct ssh_sharing_connstate *cs,
  548. struct share_channel *chan)
  549. {
  550. del234(cs->channels_by_us, chan);
  551. del234(cs->channels_by_server, chan);
  552. if (chan->x11_auth_upstream)
  553. ssh_sharing_remove_x11_display(cs->parent->ssh,
  554. chan->x11_auth_upstream);
  555. sfree(chan->x11_auth_data);
  556. sfree(chan);
  557. }
  558. static struct share_xchannel *share_add_xchannel
  559. (struct ssh_sharing_connstate *cs,
  560. unsigned upstream_id, unsigned server_id)
  561. {
  562. struct share_xchannel *xc = snew(struct share_xchannel);
  563. xc->upstream_id = upstream_id;
  564. xc->server_id = server_id;
  565. xc->live = TRUE;
  566. xc->msghead = xc->msgtail = NULL;
  567. if (add234(cs->xchannels_by_us, xc) != xc) {
  568. sfree(xc);
  569. return NULL;
  570. }
  571. if (add234(cs->xchannels_by_server, xc) != xc) {
  572. del234(cs->xchannels_by_us, xc);
  573. sfree(xc);
  574. return NULL;
  575. }
  576. return xc;
  577. }
  578. static struct share_xchannel *share_find_xchannel_by_upstream
  579. (struct ssh_sharing_connstate *cs, unsigned upstream_id)
  580. {
  581. struct share_xchannel dummyxc;
  582. dummyxc.upstream_id = upstream_id;
  583. return find234(cs->xchannels_by_us, &dummyxc, NULL);
  584. }
  585. static struct share_xchannel *share_find_xchannel_by_server
  586. (struct ssh_sharing_connstate *cs, unsigned server_id)
  587. {
  588. struct share_xchannel dummyxc;
  589. dummyxc.server_id = server_id;
  590. return find234(cs->xchannels_by_server, &dummyxc, NULL);
  591. }
  592. static void share_remove_xchannel(struct ssh_sharing_connstate *cs,
  593. struct share_xchannel *xc)
  594. {
  595. del234(cs->xchannels_by_us, xc);
  596. del234(cs->xchannels_by_server, xc);
  597. share_xchannel_free(xc);
  598. }
  599. static struct share_forwarding *share_add_forwarding
  600. (struct ssh_sharing_connstate *cs,
  601. const char *host, int port)
  602. {
  603. struct share_forwarding *fwd = snew(struct share_forwarding);
  604. fwd->host = dupstr(host);
  605. fwd->port = port;
  606. fwd->active = FALSE;
  607. if (add234(cs->forwardings, fwd) != fwd) {
  608. /* Duplicate?! */
  609. sfree(fwd);
  610. return NULL;
  611. }
  612. return fwd;
  613. }
  614. static struct share_forwarding *share_find_forwarding
  615. (struct ssh_sharing_connstate *cs, const char *host, int port)
  616. {
  617. struct share_forwarding dummyfwd, *ret;
  618. dummyfwd.host = dupstr(host);
  619. dummyfwd.port = port;
  620. ret = find234(cs->forwardings, &dummyfwd, NULL);
  621. sfree(dummyfwd.host);
  622. return ret;
  623. }
  624. static void share_remove_forwarding(struct ssh_sharing_connstate *cs,
  625. struct share_forwarding *fwd)
  626. {
  627. del234(cs->forwardings, fwd);
  628. sfree(fwd);
  629. }
  630. static void send_packet_to_downstream(struct ssh_sharing_connstate *cs,
  631. int type, const void *pkt, int pktlen,
  632. struct share_channel *chan)
  633. {
  634. strbuf *packet;
  635. if (!cs->sock) /* throw away all packets destined for a dead downstream */
  636. return;
  637. if (type == SSH2_MSG_CHANNEL_DATA) {
  638. /*
  639. * Special case which we take care of at a low level, so as to
  640. * be sure to apply it in all cases. On rare occasions we
  641. * might find that we have a channel for which the
  642. * downstream's maximum packet size exceeds the max packet
  643. * size we presented to the server on its behalf. (This can
  644. * occur in X11 forwarding, where we have to send _our_
  645. * CHANNEL_OPEN_CONFIRMATION before we discover which if any
  646. * downstream the channel is destined for, so if that
  647. * downstream turns out to present a smaller max packet size
  648. * then we're in this situation.)
  649. *
  650. * If that happens, we just chop up the packet into pieces and
  651. * send them as separate CHANNEL_DATA packets.
  652. */
  653. BinarySource src[1];
  654. unsigned channel;
  655. ptrlen data;
  656. BinarySource_BARE_INIT(src, pkt, pktlen);
  657. channel = get_uint32(src);
  658. data = get_string(src);
  659. do {
  660. int this_len = (data.len > chan->downstream_maxpkt ?
  661. chan->downstream_maxpkt : data.len);
  662. packet = strbuf_new();
  663. put_uint32(packet, 0); /* placeholder for length field */
  664. put_byte(packet, type);
  665. put_uint32(packet, channel);
  666. put_uint32(packet, this_len);
  667. put_data(packet, data.ptr, this_len);
  668. data.ptr = (const char *)data.ptr + this_len;
  669. data.len -= this_len;
  670. PUT_32BIT(packet->s, packet->len-4);
  671. sk_write(cs->sock, packet->s, packet->len);
  672. strbuf_free(packet);
  673. } while (data.len > 0);
  674. } else {
  675. /*
  676. * Just do the obvious thing.
  677. */
  678. packet = strbuf_new();
  679. put_uint32(packet, 0); /* placeholder for length field */
  680. put_byte(packet, type);
  681. put_data(packet, pkt, pktlen);
  682. PUT_32BIT(packet->s, packet->len-4);
  683. sk_write(cs->sock, packet->s, packet->len);
  684. strbuf_free(packet);
  685. }
  686. }
  687. static void share_try_cleanup(struct ssh_sharing_connstate *cs)
  688. {
  689. int i;
  690. struct share_halfchannel *hc;
  691. struct share_channel *chan;
  692. struct share_forwarding *fwd;
  693. /*
  694. * Any half-open channels, i.e. those for which we'd received
  695. * CHANNEL_OPEN from the server but not passed back a response
  696. * from downstream, should be responded to with OPEN_FAILURE.
  697. */
  698. while ((hc = (struct share_halfchannel *)
  699. index234(cs->halfchannels, 0)) != NULL) {
  700. static const char reason[] = "PuTTY downstream no longer available";
  701. static const char lang[] = "en";
  702. strbuf *packet;
  703. packet = strbuf_new();
  704. put_uint32(packet, hc->server_id);
  705. put_uint32(packet, SSH2_OPEN_CONNECT_FAILED);
  706. put_stringz(packet, reason);
  707. put_stringz(packet, lang);
  708. ssh_send_packet_from_downstream(
  709. cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_OPEN_FAILURE,
  710. packet->s, packet->len,
  711. "cleanup after downstream went away");
  712. strbuf_free(packet);
  713. share_remove_halfchannel(cs, hc);
  714. }
  715. /*
  716. * Any actually open channels should have a CHANNEL_CLOSE sent for
  717. * them, unless we've already done so. We won't be able to
  718. * actually clean them up until CHANNEL_CLOSE comes back from the
  719. * server, though (unless the server happens to have sent a CLOSE
  720. * already).
  721. *
  722. * Another annoying exception is UNACKNOWLEDGED channels, i.e.
  723. * we've _sent_ a CHANNEL_OPEN to the server but not received an
  724. * OPEN_CONFIRMATION or OPEN_FAILURE. We must wait for a reply
  725. * before closing the channel, because until we see that reply we
  726. * won't have the server's channel id to put in the close message.
  727. */
  728. for (i = 0; (chan = (struct share_channel *)
  729. index234(cs->channels_by_us, i)) != NULL; i++) {
  730. strbuf *packet;
  731. if (chan->state != SENT_CLOSE && chan->state != UNACKNOWLEDGED) {
  732. packet = strbuf_new();
  733. put_uint32(packet, chan->server_id);
  734. ssh_send_packet_from_downstream(
  735. cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_CLOSE,
  736. packet->s, packet->len,
  737. "cleanup after downstream went away");
  738. strbuf_free(packet);
  739. if (chan->state != RCVD_CLOSE) {
  740. chan->state = SENT_CLOSE;
  741. } else {
  742. /* In this case, we _can_ clear up the channel now. */
  743. ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
  744. share_remove_channel(cs, chan);
  745. i--; /* don't accidentally skip one as a result */
  746. }
  747. }
  748. }
  749. /*
  750. * Any remote port forwardings we're managing on behalf of this
  751. * downstream should be cancelled. Again, we must defer those for
  752. * which we haven't yet seen REQUEST_SUCCESS/FAILURE.
  753. *
  754. * We take a fire-and-forget approach during cleanup, not
  755. * bothering to set want_reply.
  756. */
  757. for (i = 0; (fwd = (struct share_forwarding *)
  758. index234(cs->forwardings, i)) != NULL; i++) {
  759. if (fwd->active) {
  760. strbuf *packet = strbuf_new();
  761. put_stringz(packet, "cancel-tcpip-forward");
  762. put_bool(packet, FALSE); /* !want_reply */
  763. put_stringz(packet, fwd->host);
  764. put_uint32(packet, fwd->port);
  765. ssh_send_packet_from_downstream(
  766. cs->parent->ssh, cs->id, SSH2_MSG_GLOBAL_REQUEST,
  767. packet->s, packet->len,
  768. "cleanup after downstream went away");
  769. strbuf_free(packet);
  770. ssh_remove_sharing_rportfwd(cs->parent->ssh,
  771. fwd->host, fwd->port, cs);
  772. share_remove_forwarding(cs, fwd);
  773. i--; /* don't accidentally skip one as a result */
  774. }
  775. }
  776. if (count234(cs->halfchannels) == 0 &&
  777. count234(cs->channels_by_us) == 0 &&
  778. count234(cs->forwardings) == 0) {
  779. /*
  780. * Now we're _really_ done, so we can get rid of cs completely.
  781. */
  782. del234(cs->parent->connections, cs);
  783. ssh_sharing_downstream_disconnected(cs->parent->ssh, cs->id);
  784. share_connstate_free(cs);
  785. }
  786. }
  787. static void share_begin_cleanup(struct ssh_sharing_connstate *cs)
  788. {
  789. sk_close(cs->sock);
  790. cs->sock = NULL;
  791. share_try_cleanup(cs);
  792. }
  793. static void share_disconnect(struct ssh_sharing_connstate *cs,
  794. const char *message)
  795. {
  796. strbuf *packet = strbuf_new();
  797. put_uint32(packet, SSH2_DISCONNECT_PROTOCOL_ERROR);
  798. put_stringz(packet, message);
  799. put_stringz(packet, "en"); /* language */
  800. send_packet_to_downstream(cs, SSH2_MSG_DISCONNECT,
  801. packet->s, packet->len, NULL);
  802. strbuf_free(packet);
  803. share_begin_cleanup(cs);
  804. }
  805. static void share_closing(Plug plug, const char *error_msg, int error_code,
  806. int calling_back)
  807. {
  808. struct ssh_sharing_connstate *cs = FROMFIELD(
  809. plug, struct ssh_sharing_connstate, plugvt);
  810. if (error_msg) {
  811. #ifdef BROKEN_PIPE_ERROR_CODE
  812. /*
  813. * Most of the time, we log what went wrong when a downstream
  814. * disappears with a socket error. One exception, though, is
  815. * receiving EPIPE when we haven't received a protocol version
  816. * string from the downstream, because that can happen as a result
  817. * of plink -shareexists (opening the connection and instantly
  818. * closing it again without bothering to read our version string).
  819. * So that one case is not treated as a log-worthy error.
  820. */
  821. if (error_code == BROKEN_PIPE_ERROR_CODE && !cs->got_verstring)
  822. /* do nothing */;
  823. else
  824. #endif
  825. ssh_sharing_logf(cs->parent->ssh, cs->id,
  826. "Socket error: %s", error_msg);
  827. }
  828. share_begin_cleanup(cs);
  829. }
  830. /*
  831. * Append a message to the end of an xchannel's queue.
  832. */
  833. static void share_xchannel_add_message(
  834. struct share_xchannel *xc, int type, const void *data, int len)
  835. {
  836. struct share_xchannel_message *msg;
  837. /*
  838. * Allocate the 'struct share_xchannel_message' and the actual
  839. * data in one unit.
  840. */
  841. msg = snew_plus(struct share_xchannel_message, len);
  842. msg->data = snew_plus_get_aux(msg);
  843. msg->datalen = len;
  844. msg->type = type;
  845. memcpy(msg->data, data, len);
  846. /*
  847. * Queue it in the xchannel.
  848. */
  849. if (xc->msgtail)
  850. xc->msgtail->next = msg;
  851. else
  852. xc->msghead = msg;
  853. msg->next = NULL;
  854. xc->msgtail = msg;
  855. }
  856. void share_dead_xchannel_respond(struct ssh_sharing_connstate *cs,
  857. struct share_xchannel *xc)
  858. {
  859. /*
  860. * Handle queued incoming messages from the server destined for an
  861. * xchannel which is dead (i.e. downstream sent OPEN_FAILURE).
  862. */
  863. int delete = FALSE;
  864. while (xc->msghead) {
  865. struct share_xchannel_message *msg = xc->msghead;
  866. xc->msghead = msg->next;
  867. if (msg->type == SSH2_MSG_CHANNEL_REQUEST && msg->datalen > 4) {
  868. /*
  869. * A CHANNEL_REQUEST is responded to by sending
  870. * CHANNEL_FAILURE, if it has want_reply set.
  871. */
  872. BinarySource src[1];
  873. BinarySource_BARE_INIT(src, msg->data, msg->datalen);
  874. get_uint32(src); /* skip channel id */
  875. get_string(src); /* skip request type */
  876. if (get_bool(src)) {
  877. strbuf *packet = strbuf_new();
  878. put_uint32(packet, xc->server_id);
  879. ssh_send_packet_from_downstream
  880. (cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_FAILURE,
  881. packet->s, packet->len,
  882. "downstream refused X channel open");
  883. strbuf_free(packet);
  884. }
  885. } else if (msg->type == SSH2_MSG_CHANNEL_CLOSE) {
  886. /*
  887. * On CHANNEL_CLOSE we can discard the channel completely.
  888. */
  889. delete = TRUE;
  890. }
  891. sfree(msg);
  892. }
  893. xc->msgtail = NULL;
  894. if (delete) {
  895. ssh_delete_sharing_channel(cs->parent->ssh, xc->upstream_id);
  896. share_remove_xchannel(cs, xc);
  897. }
  898. }
  899. void share_xchannel_confirmation(struct ssh_sharing_connstate *cs,
  900. struct share_xchannel *xc,
  901. struct share_channel *chan,
  902. unsigned downstream_window)
  903. {
  904. strbuf *packet;
  905. /*
  906. * Send all the queued messages downstream.
  907. */
  908. while (xc->msghead) {
  909. struct share_xchannel_message *msg = xc->msghead;
  910. xc->msghead = msg->next;
  911. if (msg->datalen >= 4)
  912. PUT_32BIT(msg->data, chan->downstream_id);
  913. send_packet_to_downstream(cs, msg->type,
  914. msg->data, msg->datalen, chan);
  915. sfree(msg);
  916. }
  917. /*
  918. * Send a WINDOW_ADJUST back upstream, to synchronise the window
  919. * size downstream thinks it's presented with the one we've
  920. * actually presented.
  921. */
  922. packet = strbuf_new();
  923. put_uint32(packet, xc->server_id);
  924. put_uint32(packet, downstream_window - xc->window);
  925. ssh_send_packet_from_downstream(
  926. cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_WINDOW_ADJUST,
  927. packet->s, packet->len,
  928. "window adjustment after downstream accepted X channel");
  929. strbuf_free(packet);
  930. }
  931. void share_xchannel_failure(struct ssh_sharing_connstate *cs,
  932. struct share_xchannel *xc)
  933. {
  934. /*
  935. * If downstream refuses to open our X channel at all for some
  936. * reason, we must respond by sending an emergency CLOSE upstream.
  937. */
  938. strbuf *packet = strbuf_new();
  939. put_uint32(packet, xc->server_id);
  940. ssh_send_packet_from_downstream(
  941. cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_CLOSE,
  942. packet->s, packet->len,
  943. "downstream refused X channel open");
  944. strbuf_free(packet);
  945. /*
  946. * Now mark the xchannel as dead, and respond to anything sent on
  947. * it until we see CLOSE for it in turn.
  948. */
  949. xc->live = FALSE;
  950. share_dead_xchannel_respond(cs, xc);
  951. }
  952. void share_setup_x11_channel(ssh_sharing_connstate *cs, share_channel *chan,
  953. unsigned upstream_id, unsigned server_id,
  954. unsigned server_currwin, unsigned server_maxpkt,
  955. unsigned client_adjusted_window,
  956. const char *peer_addr, int peer_port, int endian,
  957. int protomajor, int protominor,
  958. const void *initial_data, int initial_len)
  959. {
  960. struct share_xchannel *xc;
  961. void *greeting;
  962. int greeting_len;
  963. strbuf *packet;
  964. /*
  965. * Create an xchannel containing data we've already received from
  966. * the X client, and preload it with a CHANNEL_DATA message
  967. * containing our own made-up authorisation greeting and any
  968. * additional data sent from the server so far.
  969. */
  970. xc = share_add_xchannel(cs, upstream_id, server_id);
  971. greeting = x11_make_greeting(endian, protomajor, protominor,
  972. chan->x11_auth_proto,
  973. chan->x11_auth_data, chan->x11_auth_datalen,
  974. peer_addr, peer_port, &greeting_len);
  975. packet = strbuf_new();
  976. put_uint32(packet, 0); /* leave the channel id field unfilled - we
  977. * don't know the downstream id yet */
  978. put_uint32(packet, greeting_len + initial_len);
  979. put_data(packet, greeting, greeting_len);
  980. put_data(packet, initial_data, initial_len);
  981. sfree(greeting);
  982. share_xchannel_add_message(xc, SSH2_MSG_CHANNEL_DATA,
  983. packet->s, packet->len);
  984. strbuf_free(packet);
  985. xc->window = client_adjusted_window + greeting_len;
  986. /*
  987. * Send on a CHANNEL_OPEN to downstream.
  988. */
  989. packet = strbuf_new();
  990. put_stringz(packet, "x11");
  991. put_uint32(packet, server_id);
  992. put_uint32(packet, server_currwin);
  993. put_uint32(packet, server_maxpkt);
  994. put_stringz(packet, peer_addr);
  995. put_uint32(packet, peer_port);
  996. send_packet_to_downstream(cs, SSH2_MSG_CHANNEL_OPEN,
  997. packet->s, packet->len, NULL);
  998. strbuf_free(packet);
  999. /*
  1000. * If this was a once-only X forwarding, clean it up now.
  1001. */
  1002. if (chan->x11_one_shot) {
  1003. ssh_sharing_remove_x11_display(cs->parent->ssh,
  1004. chan->x11_auth_upstream);
  1005. chan->x11_auth_upstream = NULL;
  1006. sfree(chan->x11_auth_data);
  1007. chan->x11_auth_proto = -1;
  1008. chan->x11_auth_datalen = 0;
  1009. chan->x11_one_shot = 0;
  1010. }
  1011. }
  1012. void share_got_pkt_from_server(ssh_sharing_connstate *cs, int type,
  1013. const void *vpkt, int pktlen)
  1014. {
  1015. const unsigned char *pkt = (const unsigned char *)vpkt;
  1016. struct share_globreq *globreq;
  1017. size_t id_pos;
  1018. unsigned upstream_id, server_id;
  1019. struct share_channel *chan;
  1020. struct share_xchannel *xc;
  1021. BinarySource src[1];
  1022. BinarySource_BARE_INIT(src, pkt, pktlen);
  1023. switch (type) {
  1024. case SSH2_MSG_REQUEST_SUCCESS:
  1025. case SSH2_MSG_REQUEST_FAILURE:
  1026. globreq = cs->globreq_head;
  1027. assert(globreq); /* should match the queue in ssh.c */
  1028. if (globreq->type == GLOBREQ_TCPIP_FORWARD) {
  1029. if (type == SSH2_MSG_REQUEST_FAILURE) {
  1030. share_remove_forwarding(cs, globreq->fwd);
  1031. } else {
  1032. globreq->fwd->active = TRUE;
  1033. }
  1034. } else if (globreq->type == GLOBREQ_CANCEL_TCPIP_FORWARD) {
  1035. if (type == SSH2_MSG_REQUEST_SUCCESS) {
  1036. share_remove_forwarding(cs, globreq->fwd);
  1037. }
  1038. }
  1039. if (globreq->want_reply) {
  1040. send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
  1041. }
  1042. cs->globreq_head = globreq->next;
  1043. sfree(globreq);
  1044. if (cs->globreq_head == NULL)
  1045. cs->globreq_tail = NULL;
  1046. if (!cs->sock) {
  1047. /* Retry cleaning up this connection, in case that reply
  1048. * was the last thing we were waiting for. */
  1049. share_try_cleanup(cs);
  1050. }
  1051. break;
  1052. case SSH2_MSG_CHANNEL_OPEN:
  1053. get_string(src);
  1054. server_id = get_uint32(src);
  1055. assert(!get_err(src));
  1056. share_add_halfchannel(cs, server_id);
  1057. send_packet_to_downstream(cs, type, pkt, pktlen, NULL);
  1058. break;
  1059. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  1060. case SSH2_MSG_CHANNEL_OPEN_FAILURE:
  1061. case SSH2_MSG_CHANNEL_CLOSE:
  1062. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  1063. case SSH2_MSG_CHANNEL_DATA:
  1064. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  1065. case SSH2_MSG_CHANNEL_EOF:
  1066. case SSH2_MSG_CHANNEL_REQUEST:
  1067. case SSH2_MSG_CHANNEL_SUCCESS:
  1068. case SSH2_MSG_CHANNEL_FAILURE:
  1069. /*
  1070. * All these messages have the recipient channel id as the
  1071. * first uint32 field in the packet. Substitute the downstream
  1072. * channel id for our one and pass the packet downstream.
  1073. */
  1074. id_pos = src->pos;
  1075. upstream_id = get_uint32(src);
  1076. if ((chan = share_find_channel_by_upstream(cs, upstream_id)) != NULL) {
  1077. /*
  1078. * The normal case: this id refers to an open channel.
  1079. */
  1080. unsigned char *rewritten = snewn(pktlen, unsigned char);
  1081. memcpy(rewritten, pkt, pktlen);
  1082. PUT_32BIT(rewritten + id_pos, chan->downstream_id);
  1083. send_packet_to_downstream(cs, type, rewritten, pktlen, chan);
  1084. sfree(rewritten);
  1085. /*
  1086. * Update the channel state, for messages that need it.
  1087. */
  1088. if (type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
  1089. if (chan->state == UNACKNOWLEDGED && pktlen >= 8) {
  1090. share_channel_set_server_id(cs, chan, GET_32BIT(pkt+4),
  1091. OPEN);
  1092. if (!cs->sock) {
  1093. /* Retry cleaning up this connection, so that we
  1094. * can send an immediate CLOSE on this channel for
  1095. * which we now know the server id. */
  1096. share_try_cleanup(cs);
  1097. }
  1098. }
  1099. } else if (type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  1100. ssh_delete_sharing_channel(cs->parent->ssh, chan->upstream_id);
  1101. share_remove_channel(cs, chan);
  1102. } else if (type == SSH2_MSG_CHANNEL_CLOSE) {
  1103. if (chan->state == SENT_CLOSE) {
  1104. ssh_delete_sharing_channel(cs->parent->ssh,
  1105. chan->upstream_id);
  1106. share_remove_channel(cs, chan);
  1107. if (!cs->sock) {
  1108. /* Retry cleaning up this connection, in case this
  1109. * channel closure was the last thing we were
  1110. * waiting for. */
  1111. share_try_cleanup(cs);
  1112. }
  1113. } else {
  1114. chan->state = RCVD_CLOSE;
  1115. }
  1116. }
  1117. } else if ((xc = share_find_xchannel_by_upstream(cs, upstream_id))
  1118. != NULL) {
  1119. /*
  1120. * The unusual case: this id refers to an xchannel. Add it
  1121. * to the xchannel's queue.
  1122. */
  1123. share_xchannel_add_message(xc, type, pkt, pktlen);
  1124. /* If the xchannel is dead, then also respond to it (which
  1125. * may involve deleting the channel). */
  1126. if (!xc->live)
  1127. share_dead_xchannel_respond(cs, xc);
  1128. }
  1129. break;
  1130. default:
  1131. assert(!"This packet type should never have come from ssh.c");
  1132. break;
  1133. }
  1134. }
  1135. static void share_got_pkt_from_downstream(struct ssh_sharing_connstate *cs,
  1136. int type,
  1137. unsigned char *pkt, int pktlen)
  1138. {
  1139. ptrlen request_name;
  1140. struct share_forwarding *fwd;
  1141. size_t id_pos;
  1142. unsigned maxpkt;
  1143. unsigned old_id, new_id, server_id;
  1144. struct share_globreq *globreq;
  1145. struct share_channel *chan;
  1146. struct share_halfchannel *hc;
  1147. struct share_xchannel *xc;
  1148. strbuf *packet;
  1149. char *err = NULL;
  1150. BinarySource src[1];
  1151. size_t wantreplypos;
  1152. int orig_wantreply;
  1153. BinarySource_BARE_INIT(src, pkt, pktlen);
  1154. switch (type) {
  1155. case SSH2_MSG_DISCONNECT:
  1156. /*
  1157. * This message stops here: if downstream is disconnecting
  1158. * from us, that doesn't mean we want to disconnect from the
  1159. * SSH server. Close the downstream connection and start
  1160. * cleanup.
  1161. */
  1162. share_begin_cleanup(cs);
  1163. break;
  1164. case SSH2_MSG_GLOBAL_REQUEST:
  1165. /*
  1166. * The only global requests we understand are "tcpip-forward"
  1167. * and "cancel-tcpip-forward". Since those require us to
  1168. * maintain state, we must assume that other global requests
  1169. * will probably require that too, and so we don't forward on
  1170. * any request we don't understand.
  1171. */
  1172. request_name = get_string(src);
  1173. wantreplypos = src->pos;
  1174. orig_wantreply = get_bool(src);
  1175. if (ptrlen_eq_string(request_name, "tcpip-forward")) {
  1176. ptrlen hostpl;
  1177. char *host;
  1178. int port, ret;
  1179. /*
  1180. * Pick the packet apart to find the want_reply field and
  1181. * the host/port we're going to ask to listen on.
  1182. */
  1183. hostpl = get_string(src);
  1184. port = toint(get_uint32(src));
  1185. if (get_err(src)) {
  1186. err = dupprintf("Truncated GLOBAL_REQUEST packet");
  1187. goto confused;
  1188. }
  1189. host = mkstr(hostpl);
  1190. /*
  1191. * See if we can allocate space in ssh.c's tree of remote
  1192. * port forwardings. If we can't, it's because another
  1193. * client sharing this connection has already allocated
  1194. * the identical port forwarding, so we take it on
  1195. * ourselves to manufacture a failure packet and send it
  1196. * back to downstream.
  1197. */
  1198. ret = ssh_alloc_sharing_rportfwd(cs->parent->ssh, host, port, cs);
  1199. if (!ret) {
  1200. if (orig_wantreply) {
  1201. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1202. "", 0, NULL);
  1203. }
  1204. } else {
  1205. /*
  1206. * We've managed to make space for this forwarding
  1207. * locally. Pass the request on to the SSH server, but
  1208. * set want_reply even if it wasn't originally set, so
  1209. * that we know whether this forwarding needs to be
  1210. * cleaned up if downstream goes away.
  1211. */
  1212. pkt[wantreplypos] = 1;
  1213. ssh_send_packet_from_downstream
  1214. (cs->parent->ssh, cs->id, type, pkt, pktlen,
  1215. orig_wantreply ? NULL : "upstream added want_reply flag");
  1216. fwd = share_add_forwarding(cs, host, port);
  1217. ssh_sharing_queue_global_request(cs->parent->ssh, cs);
  1218. if (fwd) {
  1219. globreq = snew(struct share_globreq);
  1220. globreq->next = NULL;
  1221. if (cs->globreq_tail)
  1222. cs->globreq_tail->next = globreq;
  1223. else
  1224. cs->globreq_head = globreq;
  1225. globreq->fwd = fwd;
  1226. globreq->want_reply = orig_wantreply;
  1227. globreq->type = GLOBREQ_TCPIP_FORWARD;
  1228. }
  1229. }
  1230. sfree(host);
  1231. } else if (ptrlen_eq_string(request_name, "cancel-tcpip-forward")) {
  1232. ptrlen hostpl;
  1233. char *host;
  1234. int port;
  1235. struct share_forwarding *fwd;
  1236. /*
  1237. * Pick the packet apart to find the want_reply field and
  1238. * the host/port we're going to ask to listen on.
  1239. */
  1240. hostpl = get_string(src);
  1241. port = toint(get_uint32(src));
  1242. if (get_err(src)) {
  1243. err = dupprintf("Truncated GLOBAL_REQUEST packet");
  1244. goto confused;
  1245. }
  1246. host = mkstr(hostpl);
  1247. /*
  1248. * Look up the existing forwarding with these details.
  1249. */
  1250. fwd = share_find_forwarding(cs, host, port);
  1251. if (!fwd) {
  1252. if (orig_wantreply) {
  1253. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1254. "", 0, NULL);
  1255. }
  1256. } else {
  1257. /*
  1258. * Tell ssh.c to stop sending us channel-opens for
  1259. * this forwarding.
  1260. */
  1261. ssh_remove_sharing_rportfwd(cs->parent->ssh, host, port, cs);
  1262. /*
  1263. * Pass the cancel request on to the SSH server, but
  1264. * set want_reply even if it wasn't originally set, so
  1265. * that _we_ know whether the forwarding has been
  1266. * deleted even if downstream doesn't want to know.
  1267. */
  1268. pkt[wantreplypos] = 1;
  1269. ssh_send_packet_from_downstream
  1270. (cs->parent->ssh, cs->id, type, pkt, pktlen,
  1271. orig_wantreply ? NULL : "upstream added want_reply flag");
  1272. ssh_sharing_queue_global_request(cs->parent->ssh, cs);
  1273. /*
  1274. * And queue a globreq so that when the reply comes
  1275. * back we know to cancel it.
  1276. */
  1277. globreq = snew(struct share_globreq);
  1278. globreq->next = NULL;
  1279. if (cs->globreq_tail)
  1280. cs->globreq_tail->next = globreq;
  1281. else
  1282. cs->globreq_head = globreq;
  1283. globreq->fwd = fwd;
  1284. globreq->want_reply = orig_wantreply;
  1285. globreq->type = GLOBREQ_CANCEL_TCPIP_FORWARD;
  1286. }
  1287. sfree(host);
  1288. } else {
  1289. /*
  1290. * Request we don't understand. Manufacture a failure
  1291. * message if an answer was required.
  1292. */
  1293. if (orig_wantreply)
  1294. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1295. "", 0, NULL);
  1296. }
  1297. break;
  1298. case SSH2_MSG_CHANNEL_OPEN:
  1299. /* Sender channel id comes after the channel type string */
  1300. get_string(src);
  1301. id_pos = src->pos;
  1302. old_id = get_uint32(src);
  1303. new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
  1304. get_uint32(src); /* skip initial window size */
  1305. maxpkt = get_uint32(src);
  1306. if (get_err(src)) {
  1307. err = dupprintf("Truncated CHANNEL_OPEN packet");
  1308. goto confused;
  1309. }
  1310. share_add_channel(cs, old_id, new_id, 0, UNACKNOWLEDGED, maxpkt);
  1311. PUT_32BIT(pkt + id_pos, new_id);
  1312. ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
  1313. type, pkt, pktlen, NULL);
  1314. break;
  1315. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  1316. if (pktlen < 16) {
  1317. err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
  1318. goto confused;
  1319. }
  1320. server_id = get_uint32(src);
  1321. id_pos = src->pos;
  1322. old_id = get_uint32(src);
  1323. get_uint32(src); /* skip initial window size */
  1324. maxpkt = get_uint32(src);
  1325. if (get_err(src)) {
  1326. err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
  1327. goto confused;
  1328. }
  1329. /* This server id may refer to either a halfchannel or an xchannel. */
  1330. hc = NULL, xc = NULL; /* placate optimiser */
  1331. if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
  1332. new_id = ssh_alloc_sharing_channel(cs->parent->ssh, cs);
  1333. } else if ((xc = share_find_xchannel_by_server(cs, server_id))
  1334. != NULL) {
  1335. new_id = xc->upstream_id;
  1336. } else {
  1337. err = dupprintf("CHANNEL_OPEN_CONFIRMATION packet cited unknown channel %u", (unsigned)server_id);
  1338. goto confused;
  1339. }
  1340. PUT_32BIT(pkt + id_pos, new_id);
  1341. chan = share_add_channel(cs, old_id, new_id, server_id, OPEN, maxpkt);
  1342. if (hc) {
  1343. ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
  1344. type, pkt, pktlen, NULL);
  1345. share_remove_halfchannel(cs, hc);
  1346. } else if (xc) {
  1347. unsigned downstream_window = GET_32BIT(pkt + 8);
  1348. if (downstream_window < 256) {
  1349. err = dupprintf("Initial window size for x11 channel must be at least 256 (got %u)", downstream_window);
  1350. goto confused;
  1351. }
  1352. share_xchannel_confirmation(cs, xc, chan, downstream_window);
  1353. share_remove_xchannel(cs, xc);
  1354. }
  1355. break;
  1356. case SSH2_MSG_CHANNEL_OPEN_FAILURE:
  1357. server_id = get_uint32(src);
  1358. if (get_err(src)) {
  1359. err = dupprintf("Truncated CHANNEL_OPEN_FAILURE packet");
  1360. goto confused;
  1361. }
  1362. /* This server id may refer to either a halfchannel or an xchannel. */
  1363. if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
  1364. ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
  1365. type, pkt, pktlen, NULL);
  1366. share_remove_halfchannel(cs, hc);
  1367. } else if ((xc = share_find_xchannel_by_server(cs, server_id))
  1368. != NULL) {
  1369. share_xchannel_failure(cs, xc);
  1370. } else {
  1371. err = dupprintf("CHANNEL_OPEN_FAILURE packet cited unknown channel %u", (unsigned)server_id);
  1372. goto confused;
  1373. }
  1374. break;
  1375. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  1376. case SSH2_MSG_CHANNEL_DATA:
  1377. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  1378. case SSH2_MSG_CHANNEL_EOF:
  1379. case SSH2_MSG_CHANNEL_CLOSE:
  1380. case SSH2_MSG_CHANNEL_REQUEST:
  1381. case SSH2_MSG_CHANNEL_SUCCESS:
  1382. case SSH2_MSG_CHANNEL_FAILURE:
  1383. case SSH2_MSG_IGNORE:
  1384. case SSH2_MSG_DEBUG:
  1385. server_id = get_uint32(src);
  1386. if (type == SSH2_MSG_CHANNEL_REQUEST) {
  1387. request_name = get_string(src);
  1388. /*
  1389. * Agent forwarding requests from downstream are treated
  1390. * specially. Because OpenSSHD doesn't let us enable agent
  1391. * forwarding independently per session channel, and in
  1392. * particular because the OpenSSH-defined agent forwarding
  1393. * protocol does not mark agent-channel requests with the
  1394. * id of the session channel they originate from, the only
  1395. * way we can implement agent forwarding in a
  1396. * connection-shared PuTTY is to forward the _upstream_
  1397. * agent. Hence, we unilaterally deny agent forwarding
  1398. * requests from downstreams if we aren't prepared to
  1399. * forward an agent ourselves.
  1400. *
  1401. * (If we are, then we dutifully pass agent forwarding
  1402. * requests upstream. OpenSSHD has the curious behaviour
  1403. * that all but the first such request will be rejected,
  1404. * but all session channels opened after the first request
  1405. * get agent forwarding enabled whether they ask for it or
  1406. * not; but that's not our concern, since other SSH
  1407. * servers supporting the same piece of protocol might in
  1408. * principle at least manage to enable agent forwarding on
  1409. * precisely the channels that requested it, even if the
  1410. * subsequent CHANNEL_OPENs still can't be associated with
  1411. * a parent session channel.)
  1412. */
  1413. if (ptrlen_eq_string(request_name, "[email protected]") &&
  1414. !ssh_agent_forwarding_permitted(cs->parent->ssh)) {
  1415. chan = share_find_channel_by_server(cs, server_id);
  1416. if (chan) {
  1417. packet = strbuf_new();
  1418. put_uint32(packet, chan->downstream_id);
  1419. send_packet_to_downstream(
  1420. cs, SSH2_MSG_CHANNEL_FAILURE,
  1421. packet->s, packet->len, NULL);
  1422. strbuf_free(packet);
  1423. } else {
  1424. char *buf = dupprintf("Agent forwarding request for "
  1425. "unrecognised channel %u", server_id);
  1426. share_disconnect(cs, buf);
  1427. sfree(buf);
  1428. return;
  1429. }
  1430. break;
  1431. }
  1432. /*
  1433. * Another thing we treat specially is X11 forwarding
  1434. * requests. For these, we have to make up another set of
  1435. * X11 auth data, and enter it into our SSH connection's
  1436. * list of possible X11 authorisation credentials so that
  1437. * when we see an X11 channel open request we can know
  1438. * whether it's one to handle locally or one to pass on to
  1439. * a downstream, and if the latter, which one.
  1440. */
  1441. if (ptrlen_eq_string(request_name, "x11-req")) {
  1442. int want_reply, single_connection, screen;
  1443. ptrlen auth_data;
  1444. int auth_proto;
  1445. chan = share_find_channel_by_server(cs, server_id);
  1446. if (!chan) {
  1447. char *buf = dupprintf("X11 forwarding request for "
  1448. "unrecognised channel %u", server_id);
  1449. share_disconnect(cs, buf);
  1450. sfree(buf);
  1451. return;
  1452. }
  1453. /*
  1454. * Pick apart the whole message to find the downstream
  1455. * auth details.
  1456. */
  1457. want_reply = get_bool(src);
  1458. single_connection = get_bool(src);
  1459. auth_proto = x11_identify_auth_proto(get_string(src));
  1460. auth_data = get_string(src);
  1461. screen = toint(get_uint32(src));
  1462. if (get_err(src)) {
  1463. err = dupprintf("Truncated CHANNEL_REQUEST(\"x11-req\")"
  1464. " packet");
  1465. goto confused;
  1466. }
  1467. if (auth_proto < 0) {
  1468. /* Reject due to not understanding downstream's
  1469. * requested authorisation method. */
  1470. packet = strbuf_new();
  1471. put_uint32(packet, chan->downstream_id);
  1472. send_packet_to_downstream(
  1473. cs, SSH2_MSG_CHANNEL_FAILURE,
  1474. packet->s, packet->len, NULL);
  1475. strbuf_free(packet);
  1476. break;
  1477. }
  1478. chan->x11_auth_proto = auth_proto;
  1479. chan->x11_auth_data = x11_dehexify(auth_data,
  1480. &chan->x11_auth_datalen);
  1481. chan->x11_auth_upstream =
  1482. ssh_sharing_add_x11_display(cs->parent->ssh, auth_proto,
  1483. cs, chan);
  1484. chan->x11_one_shot = single_connection;
  1485. /*
  1486. * Now construct a replacement X forwarding request,
  1487. * containing our own auth data, and send that to the
  1488. * server.
  1489. */
  1490. packet = strbuf_new();
  1491. put_uint32(packet, server_id);
  1492. put_stringz(packet, "x11-req");
  1493. put_bool(packet, want_reply);
  1494. put_bool(packet, single_connection);
  1495. put_stringz(packet, chan->x11_auth_upstream->protoname);
  1496. put_stringz(packet, chan->x11_auth_upstream->datastring);
  1497. put_uint32(packet, screen);
  1498. ssh_send_packet_from_downstream(
  1499. cs->parent->ssh, cs->id, SSH2_MSG_CHANNEL_REQUEST,
  1500. packet->s, packet->len, NULL);
  1501. strbuf_free(packet);
  1502. break;
  1503. }
  1504. }
  1505. ssh_send_packet_from_downstream(cs->parent->ssh, cs->id,
  1506. type, pkt, pktlen, NULL);
  1507. if (type == SSH2_MSG_CHANNEL_CLOSE && pktlen >= 4) {
  1508. chan = share_find_channel_by_server(cs, server_id);
  1509. if (chan) {
  1510. if (chan->state == RCVD_CLOSE) {
  1511. ssh_delete_sharing_channel(cs->parent->ssh,
  1512. chan->upstream_id);
  1513. share_remove_channel(cs, chan);
  1514. } else {
  1515. chan->state = SENT_CLOSE;
  1516. }
  1517. }
  1518. }
  1519. break;
  1520. default:
  1521. err = dupprintf("Unexpected packet type %d\n", type);
  1522. goto confused;
  1523. /*
  1524. * Any other packet type is unexpected. In particular, we
  1525. * never pass GLOBAL_REQUESTs downstream, so we never expect
  1526. * to see SSH2_MSG_REQUEST_{SUCCESS,FAILURE}.
  1527. */
  1528. confused:
  1529. assert(err != NULL);
  1530. share_disconnect(cs, err);
  1531. sfree(err);
  1532. break;
  1533. }
  1534. }
  1535. /*
  1536. * Coroutine macros similar to, but simplified from, those in ssh.c.
  1537. */
  1538. #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
  1539. #define crFinishV } *crLine = 0; return; }
  1540. #define crGetChar(c) do \
  1541. { \
  1542. while (len == 0) { \
  1543. *crLine =__LINE__; return; case __LINE__:; \
  1544. } \
  1545. len--; \
  1546. (c) = (unsigned char)*data++; \
  1547. } while (0)
  1548. static void share_receive(Plug plug, int urgent, char *data, int len)
  1549. {
  1550. ssh_sharing_connstate *cs = FROMFIELD(
  1551. plug, ssh_sharing_connstate, plugvt);
  1552. static const char expected_verstring_prefix[] =
  1553. "[email protected]";
  1554. unsigned char c;
  1555. crBegin(cs->crLine);
  1556. /*
  1557. * First read the version string from downstream.
  1558. */
  1559. cs->recvlen = 0;
  1560. while (1) {
  1561. crGetChar(c);
  1562. if (c == '\012')
  1563. break;
  1564. if (cs->recvlen >= sizeof(cs->recvbuf)) {
  1565. char *buf = dupprintf("Version string far too long\n");
  1566. share_disconnect(cs, buf);
  1567. sfree(buf);
  1568. goto dead;
  1569. }
  1570. cs->recvbuf[cs->recvlen++] = c;
  1571. }
  1572. /*
  1573. * Now parse the version string to make sure it's at least vaguely
  1574. * sensible, and log it.
  1575. */
  1576. if (cs->recvlen < sizeof(expected_verstring_prefix)-1 ||
  1577. memcmp(cs->recvbuf, expected_verstring_prefix,
  1578. sizeof(expected_verstring_prefix) - 1)) {
  1579. char *buf = dupprintf("Version string did not have expected prefix\n");
  1580. share_disconnect(cs, buf);
  1581. sfree(buf);
  1582. goto dead;
  1583. }
  1584. if (cs->recvlen > 0 && cs->recvbuf[cs->recvlen-1] == '\015')
  1585. cs->recvlen--; /* trim off \r before \n */
  1586. ssh_sharing_logf(cs->parent->ssh, cs->id,
  1587. "Downstream version string: %.*s",
  1588. cs->recvlen, cs->recvbuf);
  1589. cs->got_verstring = TRUE;
  1590. /*
  1591. * Loop round reading packets.
  1592. */
  1593. while (1) {
  1594. cs->recvlen = 0;
  1595. while (cs->recvlen < 4) {
  1596. crGetChar(c);
  1597. cs->recvbuf[cs->recvlen++] = c;
  1598. }
  1599. cs->curr_packetlen = toint(GET_32BIT(cs->recvbuf) + 4);
  1600. if (cs->curr_packetlen < 5 ||
  1601. cs->curr_packetlen > sizeof(cs->recvbuf)) {
  1602. char *buf = dupprintf("Bad packet length %u\n",
  1603. (unsigned)cs->curr_packetlen);
  1604. share_disconnect(cs, buf);
  1605. sfree(buf);
  1606. goto dead;
  1607. }
  1608. while (cs->recvlen < cs->curr_packetlen) {
  1609. crGetChar(c);
  1610. cs->recvbuf[cs->recvlen++] = c;
  1611. }
  1612. share_got_pkt_from_downstream(cs, cs->recvbuf[4],
  1613. cs->recvbuf + 5, cs->recvlen - 5);
  1614. }
  1615. dead:;
  1616. crFinishV;
  1617. }
  1618. static void share_sent(Plug plug, int bufsize)
  1619. {
  1620. /* ssh_sharing_connstate *cs = FROMFIELD(
  1621. plug, ssh_sharing_connstate, plugvt); */
  1622. /*
  1623. * We do nothing here, because we expect that there won't be a
  1624. * need to throttle and unthrottle the connection to a downstream.
  1625. * It should automatically throttle itself: if the SSH server
  1626. * sends huge amounts of data on all channels then it'll run out
  1627. * of window until our downstream sends it back some
  1628. * WINDOW_ADJUSTs.
  1629. */
  1630. }
  1631. static void share_listen_closing(Plug plug, const char *error_msg,
  1632. int error_code, int calling_back)
  1633. {
  1634. ssh_sharing_state *sharestate = FROMFIELD(plug, ssh_sharing_state, plugvt);
  1635. if (error_msg)
  1636. ssh_sharing_logf(sharestate->ssh, 0,
  1637. "listening socket: %s", error_msg);
  1638. sk_close(sharestate->listensock);
  1639. sharestate->listensock = NULL;
  1640. }
  1641. static void share_send_verstring(ssh_sharing_connstate *cs)
  1642. {
  1643. char *fullstring = dupcat("[email protected]",
  1644. cs->parent->server_verstring, "\015\012", NULL);
  1645. sk_write(cs->sock, fullstring, strlen(fullstring));
  1646. sfree(fullstring);
  1647. cs->sent_verstring = TRUE;
  1648. }
  1649. int share_ndownstreams(ssh_sharing_state *sharestate)
  1650. {
  1651. return count234(sharestate->connections);
  1652. }
  1653. void share_activate(ssh_sharing_state *sharestate,
  1654. const char *server_verstring)
  1655. {
  1656. /*
  1657. * Indication from ssh.c that we are now ready to begin serving
  1658. * any downstreams that have already connected to us.
  1659. */
  1660. struct ssh_sharing_connstate *cs;
  1661. int i;
  1662. /*
  1663. * Trim the server's version string down to just the software
  1664. * version component, removing "SSH-2.0-" or whatever at the
  1665. * front.
  1666. */
  1667. for (i = 0; i < 2; i++) {
  1668. server_verstring += strcspn(server_verstring, "-");
  1669. if (*server_verstring)
  1670. server_verstring++;
  1671. }
  1672. sharestate->server_verstring = dupstr(server_verstring);
  1673. for (i = 0; (cs = (struct ssh_sharing_connstate *)
  1674. index234(sharestate->connections, i)) != NULL; i++) {
  1675. assert(!cs->sent_verstring);
  1676. share_send_verstring(cs);
  1677. }
  1678. }
  1679. static const Plug_vtable ssh_sharing_conn_plugvt = {
  1680. NULL, /* no log function, because that's for outgoing connections */
  1681. share_closing,
  1682. share_receive,
  1683. share_sent,
  1684. NULL /* no accepting function, because we've already done it */
  1685. };
  1686. static int share_listen_accepting(Plug plug,
  1687. accept_fn_t constructor, accept_ctx_t ctx)
  1688. {
  1689. struct ssh_sharing_state *sharestate = FROMFIELD(
  1690. plug, struct ssh_sharing_state, plugvt);
  1691. struct ssh_sharing_connstate *cs;
  1692. const char *err;
  1693. char *peerinfo;
  1694. /*
  1695. * A new downstream has connected to us.
  1696. */
  1697. cs = snew(struct ssh_sharing_connstate);
  1698. cs->plugvt = &ssh_sharing_conn_plugvt;
  1699. cs->parent = sharestate;
  1700. if ((cs->id = share_find_unused_id(sharestate, sharestate->nextid)) == 0 &&
  1701. (cs->id = share_find_unused_id(sharestate, 1)) == 0) {
  1702. sfree(cs);
  1703. return 1;
  1704. }
  1705. sharestate->nextid = cs->id + 1;
  1706. if (sharestate->nextid == 0)
  1707. sharestate->nextid++; /* only happens in VERY long-running upstreams */
  1708. cs->sock = constructor(ctx, &cs->plugvt);
  1709. if ((err = sk_socket_error(cs->sock)) != NULL) {
  1710. sfree(cs);
  1711. return err != NULL;
  1712. }
  1713. sk_set_frozen(cs->sock, 0);
  1714. add234(cs->parent->connections, cs);
  1715. cs->sent_verstring = FALSE;
  1716. if (sharestate->server_verstring)
  1717. share_send_verstring(cs);
  1718. cs->got_verstring = FALSE;
  1719. cs->recvlen = 0;
  1720. cs->crLine = 0;
  1721. cs->halfchannels = newtree234(share_halfchannel_cmp);
  1722. cs->channels_by_us = newtree234(share_channel_us_cmp);
  1723. cs->channels_by_server = newtree234(share_channel_server_cmp);
  1724. cs->xchannels_by_us = newtree234(share_xchannel_us_cmp);
  1725. cs->xchannels_by_server = newtree234(share_xchannel_server_cmp);
  1726. cs->forwardings = newtree234(share_forwarding_cmp);
  1727. cs->globreq_head = cs->globreq_tail = NULL;
  1728. peerinfo = sk_peer_info(cs->sock);
  1729. ssh_sharing_downstream_connected(sharestate->ssh, cs->id, peerinfo);
  1730. sfree(peerinfo);
  1731. return 0;
  1732. }
  1733. /* Per-application overrides for what roles we can take (e.g. pscp
  1734. * will never be an upstream) */
  1735. extern const int share_can_be_downstream;
  1736. extern const int share_can_be_upstream;
  1737. /*
  1738. * Decide on the string used to identify the connection point between
  1739. * upstream and downstream (be it a Windows named pipe or a
  1740. * Unix-domain socket or whatever else).
  1741. *
  1742. * I wondered about making this a SHA hash of all sorts of pieces of
  1743. * the PuTTY configuration - essentially everything PuTTY uses to know
  1744. * where and how to make a connection, including all the proxy details
  1745. * (or rather, all the _relevant_ ones - only including settings that
  1746. * other settings didn't prevent from having any effect), plus the
  1747. * username. However, I think it's better to keep it really simple:
  1748. * the connection point identifier is derived from the hostname and
  1749. * port used to index the host-key cache (not necessarily where we
  1750. * _physically_ connected to, in cases involving proxies or
  1751. * CONF_loghost), plus the username if one is specified.
  1752. *
  1753. * The per-platform code will quite likely hash or obfuscate this name
  1754. * in turn, for privacy from other users; failing that, it might
  1755. * transform it to avoid dangerous filename characters and so on. But
  1756. * that doesn't matter to us: for us, the point is that two session
  1757. * configurations which return the same string from this function will
  1758. * be treated as potentially shareable with each other.
  1759. */
  1760. char *ssh_share_sockname(const char *host, int port, Conf *conf)
  1761. {
  1762. char *username = get_remote_username(conf);
  1763. char *sockname;
  1764. if (port == 22) {
  1765. if (username)
  1766. sockname = dupprintf("%s@%s", username, host);
  1767. else
  1768. sockname = dupprintf("%s", host);
  1769. } else {
  1770. if (username)
  1771. sockname = dupprintf("%s@%s:%d", username, host, port);
  1772. else
  1773. sockname = dupprintf("%s:%d", host, port);
  1774. }
  1775. sfree(username);
  1776. return sockname;
  1777. }
  1778. int ssh_share_test_for_upstream(const char *host, int port, Conf *conf)
  1779. {
  1780. char *sockname, *logtext, *ds_err, *us_err;
  1781. int result;
  1782. Socket sock;
  1783. sockname = ssh_share_sockname(host, port, conf);
  1784. sock = NULL;
  1785. logtext = ds_err = us_err = NULL;
  1786. result = platform_ssh_share(sockname, conf, nullplug, (Plug)NULL, &sock,
  1787. &logtext, &ds_err, &us_err, FALSE, TRUE);
  1788. sfree(logtext);
  1789. sfree(ds_err);
  1790. sfree(us_err);
  1791. sfree(sockname);
  1792. if (result == SHARE_NONE) {
  1793. assert(sock == NULL);
  1794. return FALSE;
  1795. } else {
  1796. assert(result == SHARE_DOWNSTREAM);
  1797. sk_close(sock);
  1798. return TRUE;
  1799. }
  1800. }
  1801. static const Plug_vtable ssh_sharing_listen_plugvt = {
  1802. NULL, /* no log function, because that's for outgoing connections */
  1803. share_listen_closing,
  1804. NULL, /* no receive function on a listening socket */
  1805. NULL, /* no sent function on a listening socket */
  1806. share_listen_accepting
  1807. };
  1808. /*
  1809. * Init function for connection sharing. We either open a listening
  1810. * socket and become an upstream, or connect to an existing one and
  1811. * become a downstream, or do neither. We are responsible for deciding
  1812. * which of these to do (including checking the Conf to see if
  1813. * connection sharing is even enabled in the first place). If we
  1814. * become a downstream, we return the Socket with which we connected
  1815. * to the upstream; otherwise (whether or not we have established an
  1816. * upstream) we return NULL.
  1817. */
  1818. Socket ssh_connection_sharing_init(const char *host, int port,
  1819. Conf *conf, Ssh ssh, Plug sshplug,
  1820. ssh_sharing_state **state)
  1821. {
  1822. int result, can_upstream, can_downstream;
  1823. char *logtext, *ds_err, *us_err;
  1824. char *sockname;
  1825. Socket sock;
  1826. struct ssh_sharing_state *sharestate;
  1827. if (!conf_get_int(conf, CONF_ssh_connection_sharing))
  1828. return NULL; /* do not share anything */
  1829. can_upstream = share_can_be_upstream &&
  1830. conf_get_int(conf, CONF_ssh_connection_sharing_upstream);
  1831. can_downstream = share_can_be_downstream &&
  1832. conf_get_int(conf, CONF_ssh_connection_sharing_downstream);
  1833. if (!can_upstream && !can_downstream)
  1834. return NULL;
  1835. sockname = ssh_share_sockname(host, port, conf);
  1836. /*
  1837. * Create a data structure for the listening plug if we turn out
  1838. * to be an upstream.
  1839. */
  1840. sharestate = snew(struct ssh_sharing_state);
  1841. sharestate->plugvt = &ssh_sharing_listen_plugvt;
  1842. sharestate->listensock = NULL;
  1843. /*
  1844. * Now hand off to a per-platform routine that either connects to
  1845. * an existing upstream (using 'ssh' as the plug), establishes our
  1846. * own upstream (using 'sharestate' as the plug), or forks off a
  1847. * separate upstream and then connects to that. It will return a
  1848. * code telling us which kind of socket it put in 'sock'.
  1849. */
  1850. sock = NULL;
  1851. logtext = ds_err = us_err = NULL;
  1852. result = platform_ssh_share(
  1853. sockname, conf, sshplug, &sharestate->plugvt, &sock, &logtext,
  1854. &ds_err, &us_err, can_upstream, can_downstream);
  1855. ssh_connshare_log(ssh, result, logtext, ds_err, us_err);
  1856. sfree(logtext);
  1857. sfree(ds_err);
  1858. sfree(us_err);
  1859. switch (result) {
  1860. case SHARE_NONE:
  1861. /*
  1862. * We aren't sharing our connection at all (e.g. something
  1863. * went wrong setting the socket up). Free the upstream
  1864. * structure and return NULL.
  1865. */
  1866. assert(sock == NULL);
  1867. *state = NULL;
  1868. sfree(sharestate);
  1869. sfree(sockname);
  1870. return NULL;
  1871. case SHARE_DOWNSTREAM:
  1872. /*
  1873. * We are downstream, so free sharestate which it turns out we
  1874. * don't need after all, and return the downstream socket as a
  1875. * replacement for an ordinary SSH connection.
  1876. */
  1877. *state = NULL;
  1878. sfree(sharestate);
  1879. sfree(sockname);
  1880. return sock;
  1881. case SHARE_UPSTREAM:
  1882. /*
  1883. * We are upstream. Set up sharestate properly and pass a copy
  1884. * to the caller; return NULL, to tell ssh.c that it has to
  1885. * make an ordinary connection after all.
  1886. */
  1887. *state = sharestate;
  1888. sharestate->listensock = sock;
  1889. sharestate->connections = newtree234(share_connstate_cmp);
  1890. sharestate->ssh = ssh;
  1891. sharestate->server_verstring = NULL;
  1892. sharestate->sockname = sockname;
  1893. sharestate->nextid = 1;
  1894. return NULL;
  1895. }
  1896. return NULL;
  1897. }