sshshare.c 78 KB

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