sshshare.c 78 KB

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