sshshare.c 80 KB

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