sshshare.c 76 KB

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