sharing.c 76 KB

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