sshshare.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180
  1. /*
  2. * Support for SSH connection sharing, i.e. permitting one PuTTY to
  3. * open its own channels over the SSH session being run by another.
  4. */
  5. /*
  6. * Discussion and technical documentation
  7. * ======================================
  8. *
  9. * The basic strategy for PuTTY's implementation of SSH connection
  10. * sharing is to have a single 'upstream' PuTTY process, which manages
  11. * the real SSH connection and all the cryptography, and then zero or
  12. * more 'downstream' PuTTYs, which never talk to the real host but
  13. * only talk to the upstream through local IPC (Unix-domain sockets or
  14. * Windows named pipes).
  15. *
  16. * The downstreams communicate with the upstream using a protocol
  17. * derived from SSH itself, which I'll document in detail below. In
  18. * brief, though: the downstream->upstream protocol uses a trivial
  19. * binary packet protocol (just length/type/data) to encapsulate
  20. * unencrypted SSH messages, and downstreams talk to the upstream more
  21. * or less as if it was an SSH server itself. (So downstreams can
  22. * themselves open multiple SSH channels, for example, by sending
  23. * multiple SSH2_MSG_CHANNEL_OPENs; they can send CHANNEL_REQUESTs of
  24. * their choice within each channel, and they handle their own
  25. * WINDOW_ADJUST messages.)
  26. *
  27. * The upstream would ideally handle these downstreams by just putting
  28. * their messages into the queue for proper SSH-2 encapsulation and
  29. * encryption and sending them straight on to the server. However,
  30. * that's not quite feasible as written, because client-side channel
  31. * IDs could easily conflict (between multiple downstreams, or between
  32. * a downstream and the upstream). To protect against that, the
  33. * upstream rewrites the client-side channel IDs in messages it passes
  34. * on to the server, so that it's performing what you might describe
  35. * as 'channel-number NAT'. Then the upstream remembers which of its
  36. * own channel IDs are channels it's managing itself, and which are
  37. * placeholders associated with a particular downstream, so that when
  38. * replies come in from the server they can be sent on to the relevant
  39. * downstream (after un-NATting the channel number, of course).
  40. *
  41. * Global requests from downstreams are only accepted if the upstream
  42. * knows what to do about them; currently the only such requests are
  43. * the ones having to do with remote-to-local port forwarding (in
  44. * which, again, the upstream remembers that some of the forwardings
  45. * it's asked the server to set up were on behalf of particular
  46. * downstreams, and sends the incoming CHANNEL_OPENs to those
  47. * downstreams when connections come in).
  48. *
  49. * Other fiddly pieces of this mechanism are X forwarding and
  50. * (OpenSSH-style) agent forwarding. Both of these have a fundamental
  51. * problem arising from the protocol design: that the CHANNEL_OPEN
  52. * from the server introducing a forwarded connection does not carry
  53. * any indication of which session channel gave rise to it; so if
  54. * session channels from multiple downstreams enable those forwarding
  55. * methods, it's hard for the upstream to know which downstream to
  56. * send the resulting connections back to.
  57. *
  58. * For X forwarding, we can work around this in a really painful way
  59. * by using the fake X11 authorisation data sent to the server as part
  60. * of the forwarding setup: upstream ensures that every X forwarding
  61. * request carries distinguishable fake auth data, and then when X
  62. * connections come in it waits to see the auth data in the X11 setup
  63. * message before it decides which downstream to pass the connection
  64. * on to.
  65. *
  66. * For agent forwarding, that workaround is unavailable. As a result,
  67. * this system (and, as far as I can think of, any other system too)
  68. * has the fundamental constraint that it can only forward one SSH
  69. * agent - it can't forward two agents to different session channels.
  70. * So downstreams can request agent forwarding if they like, but if
  71. * they do, they'll get whatever SSH agent is known to the upstream
  72. * (if any) forwarded to their sessions.
  73. *
  74. * Downstream-to-upstream protocol
  75. * -------------------------------
  76. *
  77. * Here I document in detail the protocol spoken between PuTTY
  78. * downstreams and upstreams over local IPC. The IPC mechanism can
  79. * vary between host platforms, but the protocol is the same.
  80. *
  81. * The protocol commences with a version exchange which is exactly
  82. * like the SSH-2 one, in that each side sends a single line of text
  83. * of the form
  84. *
  85. * <protocol>-<version>-<softwareversion> [comments] \r\n
  86. *
  87. * The only difference is that in real SSH-2, <protocol> is the string
  88. * "SSH", whereas in this protocol the string is
  89. * "[email protected]".
  90. *
  91. * (The SSH RFCs allow many protocol-level identifier namespaces to be
  92. * extended by implementors without central standardisation as long as
  93. * they suffix "@" and a domain name they control to their new ids.
  94. * RFC 4253 does not define this particular name to be changeable at
  95. * all, but I like to think this is obviously how it would have done
  96. * so if the working group had foreseen the need :-)
  97. *
  98. * Thereafter, all data exchanged consists of a sequence of binary
  99. * packets concatenated end-to-end, each of which is of the form
  100. *
  101. * uint32 length of packet, N
  102. * byte[N] N bytes of packet data
  103. *
  104. * and, since these are SSH-2 messages, the first data byte is taken
  105. * to be the packet type code.
  106. *
  107. * These messages are interpreted as those of an SSH connection, after
  108. * userauth completes, and without any repeat key exchange.
  109. * Specifically, any message from the SSH Connection Protocol is
  110. * permitted, and also SSH_MSG_IGNORE, SSH_MSG_DEBUG,
  111. * SSH_MSG_DISCONNECT and SSH_MSG_UNIMPLEMENTED from the SSH Transport
  112. * Protocol.
  113. *
  114. * This protocol imposes a few additional requirements, over and above
  115. * those of the standard SSH Connection Protocol:
  116. *
  117. * Message sizes are not permitted to exceed 0x4010 (16400) bytes,
  118. * including their length header.
  119. *
  120. * When the server (i.e. really the PuTTY upstream) sends
  121. * SSH_MSG_CHANNEL_OPEN with channel type "x11", and the client
  122. * (downstream) responds with SSH_MSG_CHANNEL_OPEN_CONFIRMATION, that
  123. * confirmation message MUST include an initial window size of at
  124. * least 256. (Rationale: this is a bit of a fudge which makes it
  125. * easier, by eliminating the possibility of nasty edge cases, for an
  126. * upstream to arrange not to pass the CHANNEL_OPEN on to downstream
  127. * until after it's seen the X11 auth data to decide which downstream
  128. * it needs to go to.)
  129. */
  130. #include <stdio.h>
  131. #include <stdlib.h>
  132. #include <assert.h>
  133. #include <limits.h>
  134. #include <errno.h>
  135. #include "putty.h"
  136. #include "tree234.h"
  137. #include "ssh.h"
  138. #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 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 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. assert(!"This packet type should never have come from ssh.c");
  1164. break;
  1165. }
  1166. }
  1167. static void share_got_pkt_from_downstream(struct ssh_sharing_connstate *cs,
  1168. int type,
  1169. unsigned char *pkt, int pktlen)
  1170. {
  1171. ptrlen request_name;
  1172. struct share_forwarding *fwd;
  1173. size_t id_pos;
  1174. unsigned maxpkt;
  1175. unsigned old_id, new_id, server_id;
  1176. struct share_globreq *globreq;
  1177. struct share_channel *chan;
  1178. struct share_halfchannel *hc;
  1179. struct share_xchannel *xc;
  1180. strbuf *packet;
  1181. char *err = NULL;
  1182. BinarySource src[1];
  1183. size_t wantreplypos;
  1184. bool orig_wantreply;
  1185. BinarySource_BARE_INIT(src, pkt, pktlen);
  1186. switch (type) {
  1187. case SSH2_MSG_DISCONNECT:
  1188. /*
  1189. * This message stops here: if downstream is disconnecting
  1190. * from us, that doesn't mean we want to disconnect from the
  1191. * SSH server. Close the downstream connection and start
  1192. * cleanup.
  1193. */
  1194. share_begin_cleanup(cs);
  1195. break;
  1196. case SSH2_MSG_GLOBAL_REQUEST:
  1197. /*
  1198. * The only global requests we understand are "tcpip-forward"
  1199. * and "cancel-tcpip-forward". Since those require us to
  1200. * maintain state, we must assume that other global requests
  1201. * will probably require that too, and so we don't forward on
  1202. * any request we don't understand.
  1203. */
  1204. request_name = get_string(src);
  1205. wantreplypos = src->pos;
  1206. orig_wantreply = get_bool(src);
  1207. if (ptrlen_eq_string(request_name, "tcpip-forward")) {
  1208. ptrlen hostpl;
  1209. char *host;
  1210. int port;
  1211. struct ssh_rportfwd *rpf;
  1212. /*
  1213. * Pick the packet apart to find the want_reply field and
  1214. * the host/port we're going to ask to listen on.
  1215. */
  1216. hostpl = get_string(src);
  1217. port = toint(get_uint32(src));
  1218. if (get_err(src)) {
  1219. err = dupprintf("Truncated GLOBAL_REQUEST packet");
  1220. goto confused;
  1221. }
  1222. host = mkstr(hostpl);
  1223. /*
  1224. * See if we can allocate space in ssh.c's tree of remote
  1225. * port forwardings. If we can't, it's because another
  1226. * client sharing this connection has already allocated
  1227. * the identical port forwarding, so we take it on
  1228. * ourselves to manufacture a failure packet and send it
  1229. * back to downstream.
  1230. */
  1231. rpf = ssh_rportfwd_alloc(
  1232. cs->parent->cl, host, port, NULL, 0, 0, NULL, NULL, cs);
  1233. if (!rpf) {
  1234. if (orig_wantreply) {
  1235. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1236. "", 0, NULL);
  1237. }
  1238. } else {
  1239. /*
  1240. * We've managed to make space for this forwarding
  1241. * locally. Pass the request on to the SSH server, but
  1242. * set want_reply even if it wasn't originally set, so
  1243. * that we know whether this forwarding needs to be
  1244. * cleaned up if downstream goes away.
  1245. */
  1246. pkt[wantreplypos] = 1;
  1247. ssh_send_packet_from_downstream
  1248. (cs->parent->cl, cs->id, type, pkt, pktlen,
  1249. orig_wantreply ? NULL : "upstream added want_reply flag");
  1250. fwd = share_add_forwarding(cs, host, port);
  1251. ssh_sharing_queue_global_request(cs->parent->cl, cs);
  1252. if (fwd) {
  1253. globreq = snew(struct share_globreq);
  1254. globreq->next = NULL;
  1255. if (cs->globreq_tail)
  1256. cs->globreq_tail->next = globreq;
  1257. else
  1258. cs->globreq_head = globreq;
  1259. globreq->fwd = fwd;
  1260. globreq->want_reply = orig_wantreply;
  1261. globreq->type = GLOBREQ_TCPIP_FORWARD;
  1262. fwd->rpf = rpf;
  1263. }
  1264. }
  1265. sfree(host);
  1266. } else if (ptrlen_eq_string(request_name, "cancel-tcpip-forward")) {
  1267. ptrlen hostpl;
  1268. char *host;
  1269. int port;
  1270. struct share_forwarding *fwd;
  1271. /*
  1272. * Pick the packet apart to find the want_reply field and
  1273. * the host/port we're going to ask to listen on.
  1274. */
  1275. hostpl = get_string(src);
  1276. port = toint(get_uint32(src));
  1277. if (get_err(src)) {
  1278. err = dupprintf("Truncated GLOBAL_REQUEST packet");
  1279. goto confused;
  1280. }
  1281. host = mkstr(hostpl);
  1282. /*
  1283. * Look up the existing forwarding with these details.
  1284. */
  1285. fwd = share_find_forwarding(cs, host, port);
  1286. if (!fwd) {
  1287. if (orig_wantreply) {
  1288. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1289. "", 0, NULL);
  1290. }
  1291. } else {
  1292. /*
  1293. * Tell ssh.c to stop sending us channel-opens for
  1294. * this forwarding.
  1295. */
  1296. ssh_rportfwd_remove(cs->parent->cl, fwd->rpf);
  1297. /*
  1298. * Pass the cancel request on to the SSH server, but
  1299. * set want_reply even if it wasn't originally set, so
  1300. * that _we_ know whether the forwarding has been
  1301. * deleted even if downstream doesn't want to know.
  1302. */
  1303. pkt[wantreplypos] = 1;
  1304. ssh_send_packet_from_downstream
  1305. (cs->parent->cl, cs->id, type, pkt, pktlen,
  1306. orig_wantreply ? NULL : "upstream added want_reply flag");
  1307. ssh_sharing_queue_global_request(cs->parent->cl, cs);
  1308. /*
  1309. * And queue a globreq so that when the reply comes
  1310. * back we know to cancel it.
  1311. */
  1312. globreq = snew(struct share_globreq);
  1313. globreq->next = NULL;
  1314. if (cs->globreq_tail)
  1315. cs->globreq_tail->next = globreq;
  1316. else
  1317. cs->globreq_head = globreq;
  1318. globreq->fwd = fwd;
  1319. globreq->want_reply = orig_wantreply;
  1320. globreq->type = GLOBREQ_CANCEL_TCPIP_FORWARD;
  1321. }
  1322. sfree(host);
  1323. } else {
  1324. /*
  1325. * Request we don't understand. Manufacture a failure
  1326. * message if an answer was required.
  1327. */
  1328. if (orig_wantreply)
  1329. send_packet_to_downstream(cs, SSH2_MSG_REQUEST_FAILURE,
  1330. "", 0, NULL);
  1331. }
  1332. break;
  1333. case SSH2_MSG_CHANNEL_OPEN:
  1334. /* Sender channel id comes after the channel type string */
  1335. get_string(src);
  1336. id_pos = src->pos;
  1337. old_id = get_uint32(src);
  1338. new_id = ssh_alloc_sharing_channel(cs->parent->cl, cs);
  1339. get_uint32(src); /* skip initial window size */
  1340. maxpkt = get_uint32(src);
  1341. if (get_err(src)) {
  1342. err = dupprintf("Truncated CHANNEL_OPEN packet");
  1343. goto confused;
  1344. }
  1345. share_add_channel(cs, old_id, new_id, 0, UNACKNOWLEDGED, maxpkt);
  1346. PUT_32BIT_MSB_FIRST(pkt + id_pos, new_id);
  1347. ssh_send_packet_from_downstream(cs->parent->cl, cs->id,
  1348. type, pkt, pktlen, NULL);
  1349. break;
  1350. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  1351. if (pktlen < 16) {
  1352. err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
  1353. goto confused;
  1354. }
  1355. server_id = get_uint32(src);
  1356. id_pos = src->pos;
  1357. old_id = get_uint32(src);
  1358. get_uint32(src); /* skip initial window size */
  1359. maxpkt = get_uint32(src);
  1360. if (get_err(src)) {
  1361. err = dupprintf("Truncated CHANNEL_OPEN_CONFIRMATION packet");
  1362. goto confused;
  1363. }
  1364. /* This server id may refer to either a halfchannel or an xchannel. */
  1365. hc = NULL, xc = NULL; /* placate optimiser */
  1366. if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
  1367. new_id = ssh_alloc_sharing_channel(cs->parent->cl, cs);
  1368. } else if ((xc = share_find_xchannel_by_server(cs, server_id))
  1369. != NULL) {
  1370. new_id = xc->upstream_id;
  1371. } else {
  1372. err = dupprintf("CHANNEL_OPEN_CONFIRMATION packet cited unknown channel %u", (unsigned)server_id);
  1373. goto confused;
  1374. }
  1375. PUT_32BIT_MSB_FIRST(pkt + id_pos, new_id);
  1376. chan = share_add_channel(cs, old_id, new_id, server_id, OPEN, maxpkt);
  1377. if (hc) {
  1378. ssh_send_packet_from_downstream(cs->parent->cl, cs->id,
  1379. type, pkt, pktlen, NULL);
  1380. share_remove_halfchannel(cs, hc);
  1381. } else if (xc) {
  1382. unsigned downstream_window = GET_32BIT_MSB_FIRST(pkt + 8);
  1383. if (downstream_window < 256) {
  1384. err = dupprintf("Initial window size for x11 channel must be at least 256 (got %u)", downstream_window);
  1385. goto confused;
  1386. }
  1387. share_xchannel_confirmation(cs, xc, chan, downstream_window);
  1388. share_remove_xchannel(cs, xc);
  1389. }
  1390. break;
  1391. case SSH2_MSG_CHANNEL_OPEN_FAILURE:
  1392. server_id = get_uint32(src);
  1393. if (get_err(src)) {
  1394. err = dupprintf("Truncated CHANNEL_OPEN_FAILURE packet");
  1395. goto confused;
  1396. }
  1397. /* This server id may refer to either a halfchannel or an xchannel. */
  1398. if ((hc = share_find_halfchannel(cs, server_id)) != NULL) {
  1399. ssh_send_packet_from_downstream(cs->parent->cl, cs->id,
  1400. type, pkt, pktlen, NULL);
  1401. share_remove_halfchannel(cs, hc);
  1402. } else if ((xc = share_find_xchannel_by_server(cs, server_id))
  1403. != NULL) {
  1404. share_xchannel_failure(cs, xc);
  1405. } else {
  1406. err = dupprintf("CHANNEL_OPEN_FAILURE packet cited unknown channel %u", (unsigned)server_id);
  1407. goto confused;
  1408. }
  1409. break;
  1410. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  1411. case SSH2_MSG_CHANNEL_DATA:
  1412. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  1413. case SSH2_MSG_CHANNEL_EOF:
  1414. case SSH2_MSG_CHANNEL_CLOSE:
  1415. case SSH2_MSG_CHANNEL_REQUEST:
  1416. case SSH2_MSG_CHANNEL_SUCCESS:
  1417. case SSH2_MSG_CHANNEL_FAILURE:
  1418. case SSH2_MSG_IGNORE:
  1419. case SSH2_MSG_DEBUG:
  1420. server_id = get_uint32(src);
  1421. if (type == SSH2_MSG_CHANNEL_REQUEST) {
  1422. request_name = get_string(src);
  1423. /*
  1424. * Agent forwarding requests from downstream are treated
  1425. * specially. Because OpenSSHD doesn't let us enable agent
  1426. * forwarding independently per session channel, and in
  1427. * particular because the OpenSSH-defined agent forwarding
  1428. * protocol does not mark agent-channel requests with the
  1429. * id of the session channel they originate from, the only
  1430. * way we can implement agent forwarding in a
  1431. * connection-shared PuTTY is to forward the _upstream_
  1432. * agent. Hence, we unilaterally deny agent forwarding
  1433. * requests from downstreams if we aren't prepared to
  1434. * forward an agent ourselves.
  1435. *
  1436. * (If we are, then we dutifully pass agent forwarding
  1437. * requests upstream. OpenSSHD has the curious behaviour
  1438. * that all but the first such request will be rejected,
  1439. * but all session channels opened after the first request
  1440. * get agent forwarding enabled whether they ask for it or
  1441. * not; but that's not our concern, since other SSH
  1442. * servers supporting the same piece of protocol might in
  1443. * principle at least manage to enable agent forwarding on
  1444. * precisely the channels that requested it, even if the
  1445. * subsequent CHANNEL_OPENs still can't be associated with
  1446. * a parent session channel.)
  1447. */
  1448. if (ptrlen_eq_string(request_name, "[email protected]") &&
  1449. !ssh_agent_forwarding_permitted(cs->parent->cl)) {
  1450. chan = share_find_channel_by_server(cs, server_id);
  1451. if (chan) {
  1452. packet = strbuf_new();
  1453. put_uint32(packet, chan->downstream_id);
  1454. send_packet_to_downstream(
  1455. cs, SSH2_MSG_CHANNEL_FAILURE,
  1456. packet->s, packet->len, NULL);
  1457. strbuf_free(packet);
  1458. } else {
  1459. char *buf = dupprintf("Agent forwarding request for "
  1460. "unrecognised channel %u", server_id);
  1461. share_disconnect(cs, buf);
  1462. sfree(buf);
  1463. return;
  1464. }
  1465. break;
  1466. }
  1467. /*
  1468. * Another thing we treat specially is X11 forwarding
  1469. * requests. For these, we have to make up another set of
  1470. * X11 auth data, and enter it into our SSH connection's
  1471. * list of possible X11 authorisation credentials so that
  1472. * when we see an X11 channel open request we can know
  1473. * whether it's one to handle locally or one to pass on to
  1474. * a downstream, and if the latter, which one.
  1475. */
  1476. if (ptrlen_eq_string(request_name, "x11-req")) {
  1477. bool want_reply, single_connection;
  1478. int screen;
  1479. ptrlen auth_data;
  1480. int auth_proto;
  1481. chan = share_find_channel_by_server(cs, server_id);
  1482. if (!chan) {
  1483. char *buf = dupprintf("X11 forwarding request for "
  1484. "unrecognised channel %u", server_id);
  1485. share_disconnect(cs, buf);
  1486. sfree(buf);
  1487. return;
  1488. }
  1489. /*
  1490. * Pick apart the whole message to find the downstream
  1491. * auth details.
  1492. */
  1493. want_reply = get_bool(src);
  1494. single_connection = get_bool(src);
  1495. auth_proto = x11_identify_auth_proto(get_string(src));
  1496. auth_data = get_string(src);
  1497. screen = toint(get_uint32(src));
  1498. if (get_err(src)) {
  1499. err = dupprintf("Truncated CHANNEL_REQUEST(\"x11-req\")"
  1500. " packet");
  1501. goto confused;
  1502. }
  1503. if (auth_proto < 0) {
  1504. /* Reject due to not understanding downstream's
  1505. * requested authorisation method. */
  1506. packet = strbuf_new();
  1507. put_uint32(packet, chan->downstream_id);
  1508. send_packet_to_downstream(
  1509. cs, SSH2_MSG_CHANNEL_FAILURE,
  1510. packet->s, packet->len, NULL);
  1511. strbuf_free(packet);
  1512. break;
  1513. }
  1514. chan->x11_auth_proto = auth_proto;
  1515. chan->x11_auth_data = x11_dehexify(auth_data,
  1516. &chan->x11_auth_datalen);
  1517. chan->x11_auth_upstream =
  1518. ssh_add_sharing_x11_display(cs->parent->cl, auth_proto,
  1519. cs, chan);
  1520. chan->x11_one_shot = single_connection;
  1521. /*
  1522. * Now construct a replacement X forwarding request,
  1523. * containing our own auth data, and send that to the
  1524. * server.
  1525. */
  1526. packet = strbuf_new_nm();
  1527. put_uint32(packet, server_id);
  1528. put_stringz(packet, "x11-req");
  1529. put_bool(packet, want_reply);
  1530. put_bool(packet, single_connection);
  1531. put_stringz(packet, chan->x11_auth_upstream->protoname);
  1532. put_stringz(packet, chan->x11_auth_upstream->datastring);
  1533. put_uint32(packet, screen);
  1534. ssh_send_packet_from_downstream(
  1535. cs->parent->cl, cs->id, SSH2_MSG_CHANNEL_REQUEST,
  1536. packet->s, packet->len, NULL);
  1537. strbuf_free(packet);
  1538. break;
  1539. }
  1540. }
  1541. ssh_send_packet_from_downstream(cs->parent->cl, cs->id,
  1542. type, pkt, pktlen, NULL);
  1543. if (type == SSH2_MSG_CHANNEL_CLOSE && pktlen >= 4) {
  1544. chan = share_find_channel_by_server(cs, server_id);
  1545. if (chan) {
  1546. if (chan->state == RCVD_CLOSE) {
  1547. ssh_delete_sharing_channel(cs->parent->cl,
  1548. chan->upstream_id);
  1549. share_remove_channel(cs, chan);
  1550. } else {
  1551. chan->state = SENT_CLOSE;
  1552. }
  1553. }
  1554. }
  1555. break;
  1556. default:
  1557. err = dupprintf("Unexpected packet type %d\n", type);
  1558. goto confused;
  1559. /*
  1560. * Any other packet type is unexpected. In particular, we
  1561. * never pass GLOBAL_REQUESTs downstream, so we never expect
  1562. * to see SSH2_MSG_REQUEST_{SUCCESS,FAILURE}.
  1563. */
  1564. confused:
  1565. assert(err != NULL);
  1566. share_disconnect(cs, err);
  1567. sfree(err);
  1568. break;
  1569. }
  1570. }
  1571. /*
  1572. * An extra coroutine macro, specific to this code which is consuming
  1573. * 'const char *data'.
  1574. */
  1575. #define crGetChar(c) do \
  1576. { \
  1577. while (len == 0) { \
  1578. *crLine =__LINE__; return; case __LINE__:; \
  1579. } \
  1580. len--; \
  1581. (c) = (unsigned char)*data++; \
  1582. } while (0)
  1583. static void share_receive(Plug *plug, int urgent, const char *data, size_t len)
  1584. {
  1585. ssh_sharing_connstate *cs = container_of(
  1586. plug, ssh_sharing_connstate, plug);
  1587. static const char expected_verstring_prefix[] =
  1588. "[email protected]";
  1589. unsigned char c;
  1590. crBegin(cs->crLine);
  1591. /*
  1592. * First read the version string from downstream.
  1593. */
  1594. cs->recvlen = 0;
  1595. while (1) {
  1596. crGetChar(c);
  1597. if (c == '\012')
  1598. break;
  1599. if (cs->recvlen >= sizeof(cs->recvbuf)) {
  1600. char *buf = dupprintf("Version string far too long\n");
  1601. share_disconnect(cs, buf);
  1602. sfree(buf);
  1603. goto dead;
  1604. }
  1605. cs->recvbuf[cs->recvlen++] = c;
  1606. }
  1607. /*
  1608. * Now parse the version string to make sure it's at least vaguely
  1609. * sensible, and log it.
  1610. */
  1611. if (cs->recvlen < sizeof(expected_verstring_prefix)-1 ||
  1612. memcmp(cs->recvbuf, expected_verstring_prefix,
  1613. sizeof(expected_verstring_prefix) - 1)) {
  1614. char *buf = dupprintf("Version string did not have expected prefix\n");
  1615. share_disconnect(cs, buf);
  1616. sfree(buf);
  1617. goto dead;
  1618. }
  1619. if (cs->recvlen > 0 && cs->recvbuf[cs->recvlen-1] == '\015')
  1620. cs->recvlen--; /* trim off \r before \n */
  1621. log_downstream(cs, "Downstream version string: %.*s",
  1622. cs->recvlen, cs->recvbuf);
  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("[email protected]",
  1678. cs->parent->server_verstring, "\015\012", NULL);
  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. NULL, /* no log function, because that's for outgoing connections */
  1715. share_closing,
  1716. share_receive,
  1717. share_sent,
  1718. NULL /* no accepting function, because we've already done it */
  1719. };
  1720. static int share_listen_accepting(Plug *plug,
  1721. accept_fn_t constructor, accept_ctx_t ctx)
  1722. {
  1723. struct ssh_sharing_state *sharestate = container_of(
  1724. plug, struct ssh_sharing_state, plug);
  1725. struct ssh_sharing_connstate *cs;
  1726. const char *err;
  1727. SocketPeerInfo *peerinfo;
  1728. /*
  1729. * A new downstream has connected to us.
  1730. */
  1731. cs = snew(struct ssh_sharing_connstate);
  1732. cs->plug.vt = &ssh_sharing_conn_plugvt;
  1733. cs->parent = sharestate;
  1734. if ((cs->id = share_find_unused_id(sharestate, sharestate->nextid)) == 0 &&
  1735. (cs->id = share_find_unused_id(sharestate, 1)) == 0) {
  1736. sfree(cs);
  1737. return 1;
  1738. }
  1739. sharestate->nextid = cs->id + 1;
  1740. if (sharestate->nextid == 0)
  1741. sharestate->nextid++; /* only happens in VERY long-running upstreams */
  1742. cs->sock = constructor(ctx, &cs->plug);
  1743. if ((err = sk_socket_error(cs->sock)) != NULL) {
  1744. sfree(cs);
  1745. return err != NULL;
  1746. }
  1747. sk_set_frozen(cs->sock, 0);
  1748. add234(cs->parent->connections, cs);
  1749. cs->sent_verstring = false;
  1750. if (sharestate->server_verstring)
  1751. share_send_verstring(cs);
  1752. cs->got_verstring = false;
  1753. cs->recvlen = 0;
  1754. cs->crLine = 0;
  1755. cs->halfchannels = newtree234(share_halfchannel_cmp);
  1756. cs->channels_by_us = newtree234(share_channel_us_cmp);
  1757. cs->channels_by_server = newtree234(share_channel_server_cmp);
  1758. cs->xchannels_by_us = newtree234(share_xchannel_us_cmp);
  1759. cs->xchannels_by_server = newtree234(share_xchannel_server_cmp);
  1760. cs->forwardings = newtree234(share_forwarding_cmp);
  1761. cs->globreq_head = cs->globreq_tail = NULL;
  1762. peerinfo = sk_peer_info(cs->sock);
  1763. log_downstream(cs, "connected%s%s",
  1764. (peerinfo && peerinfo->log_text ? " from " : ""),
  1765. (peerinfo && peerinfo->log_text ? peerinfo->log_text : ""));
  1766. sk_free_peer_info(peerinfo);
  1767. return 0;
  1768. }
  1769. /*
  1770. * Decide on the string used to identify the connection point between
  1771. * upstream and downstream (be it a Windows named pipe or a
  1772. * Unix-domain socket or whatever else).
  1773. *
  1774. * I wondered about making this a SHA hash of all sorts of pieces of
  1775. * the PuTTY configuration - essentially everything PuTTY uses to know
  1776. * where and how to make a connection, including all the proxy details
  1777. * (or rather, all the _relevant_ ones - only including settings that
  1778. * other settings didn't prevent from having any effect), plus the
  1779. * username. However, I think it's better to keep it really simple:
  1780. * the connection point identifier is derived from the hostname and
  1781. * port used to index the host-key cache (not necessarily where we
  1782. * _physically_ connected to, in cases involving proxies or
  1783. * CONF_loghost), plus the username if one is specified.
  1784. *
  1785. * The per-platform code will quite likely hash or obfuscate this name
  1786. * in turn, for privacy from other users; failing that, it might
  1787. * transform it to avoid dangerous filename characters and so on. But
  1788. * that doesn't matter to us: for us, the point is that two session
  1789. * configurations which return the same string from this function will
  1790. * be treated as potentially shareable with each other.
  1791. */
  1792. char *ssh_share_sockname(const char *host, int port, Conf *conf)
  1793. {
  1794. char *username = get_remote_username(conf);
  1795. char *sockname;
  1796. if (port == 22) {
  1797. if (username)
  1798. sockname = dupprintf("%s@%s", username, host);
  1799. else
  1800. sockname = dupprintf("%s", host);
  1801. } else {
  1802. if (username)
  1803. sockname = dupprintf("%s@%s:%d", username, host, port);
  1804. else
  1805. sockname = dupprintf("%s:%d", host, port);
  1806. }
  1807. sfree(username);
  1808. return sockname;
  1809. }
  1810. bool ssh_share_test_for_upstream(const char *host, int port, Conf *conf)
  1811. {
  1812. char *sockname, *logtext, *ds_err, *us_err;
  1813. int result;
  1814. Socket *sock;
  1815. sockname = ssh_share_sockname(host, port, conf);
  1816. sock = NULL;
  1817. logtext = ds_err = us_err = NULL;
  1818. result = platform_ssh_share(sockname, conf, nullplug, (Plug *)NULL, &sock,
  1819. &logtext, &ds_err, &us_err, false, true);
  1820. sfree(logtext);
  1821. sfree(ds_err);
  1822. sfree(us_err);
  1823. sfree(sockname);
  1824. if (result == SHARE_NONE) {
  1825. assert(sock == NULL);
  1826. return false;
  1827. } else {
  1828. assert(result == SHARE_DOWNSTREAM);
  1829. sk_close(sock);
  1830. return true;
  1831. }
  1832. }
  1833. static const PlugVtable ssh_sharing_listen_plugvt = {
  1834. NULL, /* no log function, because that's for outgoing connections */
  1835. share_listen_closing,
  1836. NULL, /* no receive function on a listening socket */
  1837. NULL, /* no sent function on a listening socket */
  1838. share_listen_accepting
  1839. };
  1840. void ssh_connshare_provide_connlayer(ssh_sharing_state *sharestate,
  1841. ConnectionLayer *cl)
  1842. {
  1843. sharestate->cl = cl;
  1844. }
  1845. /*
  1846. * Init function for connection sharing. We either open a listening
  1847. * socket and become an upstream, or connect to an existing one and
  1848. * become a downstream, or do neither. We are responsible for deciding
  1849. * which of these to do (including checking the Conf to see if
  1850. * connection sharing is even enabled in the first place). If we
  1851. * become a downstream, we return the Socket with which we connected
  1852. * to the upstream; otherwise (whether or not we have established an
  1853. * upstream) we return NULL.
  1854. */
  1855. Socket *ssh_connection_sharing_init(
  1856. const char *host, int port, Conf *conf, LogContext *logctx,
  1857. Plug *sshplug, ssh_sharing_state **state)
  1858. {
  1859. int result;
  1860. bool can_upstream, can_downstream;
  1861. char *logtext, *ds_err, *us_err;
  1862. char *sockname;
  1863. Socket *sock, *toret = NULL;
  1864. struct ssh_sharing_state *sharestate;
  1865. if (!conf_get_bool(conf, CONF_ssh_connection_sharing))
  1866. return NULL; /* do not share anything */
  1867. can_upstream = share_can_be_upstream &&
  1868. conf_get_bool(conf, CONF_ssh_connection_sharing_upstream);
  1869. can_downstream = share_can_be_downstream &&
  1870. conf_get_bool(conf, CONF_ssh_connection_sharing_downstream);
  1871. if (!can_upstream && !can_downstream)
  1872. return NULL;
  1873. sockname = ssh_share_sockname(host, port, conf);
  1874. /*
  1875. * Create a data structure for the listening plug if we turn out
  1876. * to be an upstream.
  1877. */
  1878. sharestate = snew(struct ssh_sharing_state);
  1879. sharestate->plug.vt = &ssh_sharing_listen_plugvt;
  1880. sharestate->listensock = NULL;
  1881. sharestate->cl = NULL;
  1882. /*
  1883. * Now hand off to a per-platform routine that either connects to
  1884. * an existing upstream (using 'ssh' as the plug), establishes our
  1885. * own upstream (using 'sharestate' as the plug), or forks off a
  1886. * separate upstream and then connects to that. It will return a
  1887. * code telling us which kind of socket it put in 'sock'.
  1888. */
  1889. sock = NULL;
  1890. logtext = ds_err = us_err = NULL;
  1891. result = platform_ssh_share(
  1892. sockname, conf, sshplug, &sharestate->plug, &sock, &logtext,
  1893. &ds_err, &us_err, can_upstream, can_downstream);
  1894. switch (result) {
  1895. case SHARE_NONE:
  1896. /*
  1897. * We aren't sharing our connection at all (e.g. something
  1898. * went wrong setting the socket up). Free the upstream
  1899. * structure and return NULL.
  1900. */
  1901. if (logtext) {
  1902. /* For this result, if 'logtext' is not NULL then it is an
  1903. * error message indicating a reason why connection sharing
  1904. * couldn't be set up _at all_ */
  1905. logeventf(logctx,
  1906. "Could not set up connection sharing: %s", logtext);
  1907. } else {
  1908. /* Failing that, ds_err and us_err indicate why we
  1909. * couldn't be a downstream and an upstream respectively */
  1910. if (ds_err)
  1911. logeventf(logctx, "Could not set up connection sharing"
  1912. " as downstream: %s", ds_err);
  1913. if (us_err)
  1914. logeventf(logctx, "Could not set up connection sharing"
  1915. " as upstream: %s", us_err);
  1916. }
  1917. assert(sock == NULL);
  1918. *state = NULL;
  1919. sfree(sharestate);
  1920. sfree(sockname);
  1921. break;
  1922. case SHARE_DOWNSTREAM:
  1923. /*
  1924. * We are downstream, so free sharestate which it turns out we
  1925. * don't need after all, and return the downstream socket as a
  1926. * replacement for an ordinary SSH connection.
  1927. */
  1928. /* 'logtext' is a local endpoint address */
  1929. logeventf(logctx, "Using existing shared connection at %s", logtext);
  1930. *state = NULL;
  1931. sfree(sharestate);
  1932. sfree(sockname);
  1933. toret = sock;
  1934. break;
  1935. case SHARE_UPSTREAM:
  1936. /*
  1937. * We are upstream. Set up sharestate properly and pass a copy
  1938. * to the caller; return NULL, to tell ssh.c that it has to
  1939. * make an ordinary connection after all.
  1940. */
  1941. /* 'logtext' is a local endpoint address */
  1942. logeventf(logctx, "Sharing this connection at %s", logtext);
  1943. *state = sharestate;
  1944. sharestate->listensock = sock;
  1945. sharestate->connections = newtree234(share_connstate_cmp);
  1946. sharestate->server_verstring = NULL;
  1947. sharestate->sockname = sockname;
  1948. sharestate->nextid = 1;
  1949. break;
  1950. }
  1951. sfree(logtext);
  1952. sfree(ds_err);
  1953. sfree(us_err);
  1954. return toret;
  1955. }