x11fwd.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. /*
  2. * Platform-independent bits of X11 forwarding.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <time.h>
  8. #include "putty.h"
  9. #include "ssh.h"
  10. #include "tree234.h"
  11. #define GET_16BIT(endian, cp) \
  12. (endian=='B' ? GET_16BIT_MSB_FIRST(cp) : GET_16BIT_LSB_FIRST(cp))
  13. #define PUT_16BIT(endian, cp, val) \
  14. (endian=='B' ? PUT_16BIT_MSB_FIRST(cp, val) : PUT_16BIT_LSB_FIRST(cp, val))
  15. const char *const x11_authnames[] = {
  16. "", "MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"
  17. };
  18. struct XDMSeen {
  19. unsigned int time;
  20. unsigned char clientid[6];
  21. };
  22. struct X11Connection {
  23. const struct plug_function_table *fn;
  24. /* the above variable absolutely *must* be the first in this structure */
  25. unsigned char firstpkt[12]; /* first X data packet */
  26. tree234 *authtree;
  27. struct X11Display *disp;
  28. char *auth_protocol;
  29. unsigned char *auth_data;
  30. int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;
  31. int verified;
  32. int throttled, throttle_override;
  33. int no_data_sent_to_x_client;
  34. char *peer_addr;
  35. int peer_port;
  36. struct ssh_channel *c; /* channel structure held by ssh.c */
  37. Socket s;
  38. };
  39. static int xdmseen_cmp(void *a, void *b)
  40. {
  41. struct XDMSeen *sa = a, *sb = b;
  42. return sa->time > sb->time ? 1 :
  43. sa->time < sb->time ? -1 :
  44. memcmp(sa->clientid, sb->clientid, sizeof(sa->clientid));
  45. }
  46. /* Do-nothing "plug" implementation, used by x11_setup_display() when it
  47. * creates a trial connection (and then immediately closes it).
  48. * XXX: bit out of place here, could in principle live in a platform-
  49. * independent network.c or something */
  50. static void dummy_plug_log(Plug p, int type, SockAddr addr, int port,
  51. const char *error_msg, int error_code) { }
  52. static void dummy_plug_closing
  53. (Plug p, const char *error_msg, int error_code, int calling_back) { }
  54. static void dummy_plug_receive(Plug p, int urgent, char *data, int len) { }
  55. static void dummy_plug_sent(Plug p, int bufsize) { }
  56. static int dummy_plug_accepting(Plug p, accept_fn_t constructor, accept_ctx_t ctx) { return 1; }
  57. static const struct plug_function_table dummy_plug = {
  58. dummy_plug_log, dummy_plug_closing, dummy_plug_receive,
  59. dummy_plug_sent, dummy_plug_accepting
  60. };
  61. struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype)
  62. {
  63. struct X11FakeAuth *auth = snew(struct X11FakeAuth);
  64. int i;
  65. /*
  66. * This function has the job of inventing a set of X11 fake auth
  67. * data, and adding it to 'authtree'. We must preserve the
  68. * property that for any given actual authorisation attempt, _at
  69. * most one_ thing in the tree can possibly match it.
  70. *
  71. * For MIT-MAGIC-COOKIE-1, that's not too difficult: the match
  72. * criterion is simply that the entire cookie is correct, so we
  73. * just have to make sure we don't make up two cookies the same.
  74. * (Vanishingly unlikely, but we check anyway to be sure, and go
  75. * round again inventing a new cookie if add234 tells us the one
  76. * we thought of is already in use.)
  77. *
  78. * For XDM-AUTHORIZATION-1, it's a little more fiddly. The setup
  79. * with XA1 is that half the cookie is used as a DES key with
  80. * which to CBC-encrypt an assortment of stuff. Happily, the stuff
  81. * encrypted _begins_ with the other half of the cookie, and the
  82. * IV is always zero, which means that any valid XA1 authorisation
  83. * attempt for a given cookie must begin with the same cipher
  84. * block, consisting of the DES ECB encryption of the first half
  85. * of the cookie using the second half as a key. So we compute
  86. * that cipher block here and now, and use it as the sorting key
  87. * for distinguishing XA1 entries in the tree.
  88. */
  89. if (authtype == X11_MIT) {
  90. auth->proto = X11_MIT;
  91. /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
  92. auth->datalen = 16;
  93. auth->data = snewn(auth->datalen, unsigned char);
  94. auth->xa1_firstblock = NULL;
  95. while (1) {
  96. for (i = 0; i < auth->datalen; i++)
  97. auth->data[i] = random_byte();
  98. if (add234(authtree, auth) == auth)
  99. break;
  100. }
  101. auth->xdmseen = NULL;
  102. } else {
  103. assert(authtype == X11_XDM);
  104. auth->proto = X11_XDM;
  105. /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */
  106. auth->datalen = 16;
  107. auth->data = snewn(auth->datalen, unsigned char);
  108. auth->xa1_firstblock = snewn(8, unsigned char);
  109. memset(auth->xa1_firstblock, 0, 8);
  110. while (1) {
  111. for (i = 0; i < auth->datalen; i++)
  112. auth->data[i] = (i == 8 ? 0 : random_byte());
  113. memcpy(auth->xa1_firstblock, auth->data, 8);
  114. des_encrypt_xdmauth(auth->data + 9, auth->xa1_firstblock, 8);
  115. if (add234(authtree, auth) == auth)
  116. break;
  117. }
  118. auth->xdmseen = newtree234(xdmseen_cmp);
  119. }
  120. auth->protoname = dupstr(x11_authnames[auth->proto]);
  121. auth->datastring = snewn(auth->datalen * 2 + 1, char);
  122. for (i = 0; i < auth->datalen; i++)
  123. sprintf(auth->datastring + i*2, "%02x",
  124. auth->data[i]);
  125. auth->disp = NULL;
  126. auth->share_cs = auth->share_chan = NULL;
  127. return auth;
  128. }
  129. void x11_free_fake_auth(struct X11FakeAuth *auth)
  130. {
  131. if (auth->data)
  132. smemclr(auth->data, auth->datalen);
  133. sfree(auth->data);
  134. sfree(auth->protoname);
  135. sfree(auth->datastring);
  136. sfree(auth->xa1_firstblock);
  137. if (auth->xdmseen != NULL) {
  138. struct XDMSeen *seen;
  139. while ((seen = delpos234(auth->xdmseen, 0)) != NULL)
  140. sfree(seen);
  141. freetree234(auth->xdmseen);
  142. }
  143. sfree(auth);
  144. }
  145. int x11_authcmp(void *av, void *bv)
  146. {
  147. struct X11FakeAuth *a = (struct X11FakeAuth *)av;
  148. struct X11FakeAuth *b = (struct X11FakeAuth *)bv;
  149. if (a->proto < b->proto)
  150. return -1;
  151. else if (a->proto > b->proto)
  152. return +1;
  153. if (a->proto == X11_MIT) {
  154. if (a->datalen < b->datalen)
  155. return -1;
  156. else if (a->datalen > b->datalen)
  157. return +1;
  158. return memcmp(a->data, b->data, a->datalen);
  159. } else {
  160. assert(a->proto == X11_XDM);
  161. return memcmp(a->xa1_firstblock, b->xa1_firstblock, 8);
  162. }
  163. }
  164. struct X11Display *x11_setup_display(const char *display, Conf *conf)
  165. {
  166. struct X11Display *disp = snew(struct X11Display);
  167. char *localcopy;
  168. if (!display || !*display) {
  169. localcopy = platform_get_x_display();
  170. if (!localcopy || !*localcopy) {
  171. sfree(localcopy);
  172. localcopy = dupstr(":0"); /* plausible default for any platform */
  173. }
  174. } else
  175. localcopy = dupstr(display);
  176. /*
  177. * Parse the display name.
  178. *
  179. * We expect this to have one of the following forms:
  180. *
  181. * - the standard X format which looks like
  182. * [ [ protocol '/' ] host ] ':' displaynumber [ '.' screennumber ]
  183. * (X11 also permits a double colon to indicate DECnet, but
  184. * that's not our problem, thankfully!)
  185. *
  186. * - only seen in the wild on MacOS (so far): a pathname to a
  187. * Unix-domain socket, which will typically and confusingly
  188. * end in ":0", and which I'm currently distinguishing from
  189. * the standard scheme by noting that it starts with '/'.
  190. */
  191. if (localcopy[0] == '/') {
  192. disp->unixsocketpath = localcopy;
  193. disp->unixdomain = TRUE;
  194. disp->hostname = NULL;
  195. disp->displaynum = -1;
  196. disp->screennum = 0;
  197. disp->addr = NULL;
  198. } else {
  199. char *colon, *dot, *slash;
  200. char *protocol, *hostname;
  201. colon = host_strrchr(localcopy, ':');
  202. if (!colon) {
  203. sfree(disp);
  204. sfree(localcopy);
  205. return NULL; /* FIXME: report a specific error? */
  206. }
  207. *colon++ = '\0';
  208. dot = strchr(colon, '.');
  209. if (dot)
  210. *dot++ = '\0';
  211. disp->displaynum = atoi(colon);
  212. if (dot)
  213. disp->screennum = atoi(dot);
  214. else
  215. disp->screennum = 0;
  216. protocol = NULL;
  217. hostname = localcopy;
  218. if (colon > localcopy) {
  219. slash = strchr(localcopy, '/');
  220. if (slash) {
  221. *slash++ = '\0';
  222. protocol = localcopy;
  223. hostname = slash;
  224. }
  225. }
  226. disp->hostname = *hostname ? dupstr(hostname) : NULL;
  227. if (protocol)
  228. disp->unixdomain = (!strcmp(protocol, "local") ||
  229. !strcmp(protocol, "unix"));
  230. else if (!*hostname || !strcmp(hostname, "unix"))
  231. disp->unixdomain = platform_uses_x11_unix_by_default;
  232. else
  233. disp->unixdomain = FALSE;
  234. if (!disp->hostname && !disp->unixdomain)
  235. disp->hostname = dupstr("localhost");
  236. disp->unixsocketpath = NULL;
  237. disp->addr = NULL;
  238. sfree(localcopy);
  239. }
  240. /*
  241. * Look up the display hostname, if we need to.
  242. */
  243. if (!disp->unixdomain) {
  244. const char *err;
  245. disp->port = 6000 + disp->displaynum;
  246. disp->addr = name_lookup(disp->hostname, disp->port,
  247. &disp->realhost, conf, ADDRTYPE_UNSPEC,
  248. NULL, NULL);
  249. if ((err = sk_addr_error(disp->addr)) != NULL) {
  250. sk_addr_free(disp->addr);
  251. sfree(disp->hostname);
  252. sfree(disp->unixsocketpath);
  253. sfree(disp);
  254. return NULL; /* FIXME: report an error */
  255. }
  256. }
  257. /*
  258. * Try upgrading an IP-style localhost display to a Unix-socket
  259. * display (as the standard X connection libraries do).
  260. */
  261. if (!disp->unixdomain && sk_address_is_local(disp->addr)) {
  262. SockAddr ux = platform_get_x11_unix_address(NULL, disp->displaynum);
  263. const char *err = sk_addr_error(ux);
  264. if (!err) {
  265. /* Create trial connection to see if there is a useful Unix-domain
  266. * socket */
  267. const struct plug_function_table *dummy = &dummy_plug;
  268. Socket s = sk_new(sk_addr_dup(ux), 0, 0, 0, 0, 0, (Plug)&dummy,
  269. #ifdef MPEXT
  270. 0, 0
  271. #endif
  272. );
  273. err = sk_socket_error(s);
  274. sk_close(s);
  275. }
  276. if (err) {
  277. sk_addr_free(ux);
  278. } else {
  279. sk_addr_free(disp->addr);
  280. disp->unixdomain = TRUE;
  281. disp->addr = ux;
  282. /* Fill in the rest in a moment */
  283. }
  284. }
  285. if (disp->unixdomain) {
  286. if (!disp->addr)
  287. disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
  288. disp->displaynum);
  289. if (disp->unixsocketpath)
  290. disp->realhost = dupstr(disp->unixsocketpath);
  291. else
  292. disp->realhost = dupprintf("unix:%d", disp->displaynum);
  293. disp->port = 0;
  294. }
  295. /*
  296. * Fetch the local authorisation details.
  297. */
  298. disp->localauthproto = X11_NO_AUTH;
  299. disp->localauthdata = NULL;
  300. disp->localauthdatalen = 0;
  301. platform_get_x11_auth(disp, conf);
  302. return disp;
  303. }
  304. void x11_free_display(struct X11Display *disp)
  305. {
  306. sfree(disp->hostname);
  307. sfree(disp->unixsocketpath);
  308. if (disp->localauthdata)
  309. smemclr(disp->localauthdata, disp->localauthdatalen);
  310. sfree(disp->localauthdata);
  311. sk_addr_free(disp->addr);
  312. sfree(disp);
  313. }
  314. #define XDM_MAXSKEW 20*60 /* 20 minute clock skew should be OK */
  315. static const char *x11_verify(unsigned long peer_ip, int peer_port,
  316. tree234 *authtree, char *proto,
  317. unsigned char *data, int dlen,
  318. struct X11FakeAuth **auth_ret)
  319. {
  320. struct X11FakeAuth match_dummy; /* for passing to find234 */
  321. struct X11FakeAuth *auth;
  322. /*
  323. * First, do a lookup in our tree to find the only authorisation
  324. * record that _might_ match.
  325. */
  326. if (!strcmp(proto, x11_authnames[X11_MIT])) {
  327. /*
  328. * Just look up the whole cookie that was presented to us,
  329. * which x11_authcmp will compare against the cookies we
  330. * currently believe in.
  331. */
  332. match_dummy.proto = X11_MIT;
  333. match_dummy.datalen = dlen;
  334. match_dummy.data = data;
  335. } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
  336. /*
  337. * Look up the first cipher block, against the stored first
  338. * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
  339. * currently know. (See comment in x11_invent_fake_auth.)
  340. */
  341. match_dummy.proto = X11_XDM;
  342. match_dummy.xa1_firstblock = data;
  343. } else {
  344. return "Unsupported authorisation protocol";
  345. }
  346. if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
  347. return "Authorisation not recognised";
  348. /*
  349. * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
  350. * we're doing XDM-AUTHORIZATION-1, though, we have to check the
  351. * rest of the auth data.
  352. */
  353. if (auth->proto == X11_XDM) {
  354. unsigned long t;
  355. time_t tim;
  356. int i;
  357. struct XDMSeen *seen, *ret;
  358. if (dlen != 24)
  359. return "XDM-AUTHORIZATION-1 data was wrong length";
  360. if (peer_port == -1)
  361. return "cannot do XDM-AUTHORIZATION-1 without remote address data";
  362. des_decrypt_xdmauth(auth->data+9, data, 24);
  363. if (memcmp(auth->data, data, 8) != 0)
  364. return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
  365. if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
  366. return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */
  367. if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
  368. return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */
  369. t = GET_32BIT_MSB_FIRST(data+14);
  370. for (i = 18; i < 24; i++)
  371. if (data[i] != 0) /* zero padding wrong */
  372. return "XDM-AUTHORIZATION-1 data failed check";
  373. tim = time(NULL);
  374. if (((unsigned long)t - (unsigned long)tim
  375. + XDM_MAXSKEW) > 2*XDM_MAXSKEW)
  376. return "XDM-AUTHORIZATION-1 time stamp was too far out";
  377. seen = snew(struct XDMSeen);
  378. seen->time = t;
  379. memcpy(seen->clientid, data+8, 6);
  380. assert(auth->xdmseen != NULL);
  381. ret = add234(auth->xdmseen, seen);
  382. if (ret != seen) {
  383. sfree(seen);
  384. return "XDM-AUTHORIZATION-1 data replayed";
  385. }
  386. /* While we're here, purge entries too old to be replayed. */
  387. for (;;) {
  388. seen = index234(auth->xdmseen, 0);
  389. assert(seen != NULL);
  390. if (t - seen->time <= XDM_MAXSKEW)
  391. break;
  392. sfree(delpos234(auth->xdmseen, 0));
  393. }
  394. }
  395. /* implement other protocols here if ever required */
  396. *auth_ret = auth;
  397. return NULL;
  398. }
  399. void x11_get_auth_from_authfile(struct X11Display *disp,
  400. const char *authfilename)
  401. {
  402. FILE *authfp;
  403. char *buf, *ptr, *str[4];
  404. int len[4];
  405. int family, protocol;
  406. int ideal_match = FALSE;
  407. char *ourhostname;
  408. /*
  409. * Normally we should look for precisely the details specified in
  410. * `disp'. However, there's an oddity when the display is local:
  411. * displays like "localhost:0" usually have their details stored
  412. * in a Unix-domain-socket record (even if there isn't actually a
  413. * real Unix-domain socket available, as with OpenSSH's proxy X11
  414. * server).
  415. *
  416. * This is apparently a fudge to get round the meaninglessness of
  417. * "localhost" in a shared-home-directory context -- xauth entries
  418. * for Unix-domain sockets already disambiguate this by storing
  419. * the *local* hostname in the conveniently-blank hostname field,
  420. * but IP "localhost" records couldn't do this. So, typically, an
  421. * IP "localhost" entry in the auth database isn't present and if
  422. * it were it would be ignored.
  423. *
  424. * However, we don't entirely trust that (say) Windows X servers
  425. * won't rely on a straight "localhost" entry, bad idea though
  426. * that is; so if we can't find a Unix-domain-socket entry we'll
  427. * fall back to an IP-based entry if we can find one.
  428. */
  429. int localhost = !disp->unixdomain && sk_address_is_local(disp->addr);
  430. authfp = fopen(authfilename, "rb");
  431. if (!authfp)
  432. return;
  433. ourhostname = get_hostname();
  434. /* Records in .Xauthority contain four strings of up to 64K each */
  435. buf = snewn(65537 * 4, char);
  436. while (!ideal_match) {
  437. int c, i, j, match = FALSE;
  438. #define GET do { c = fgetc(authfp); if (c == EOF) goto done; c = (unsigned char)c; } while (0)
  439. /* Expect a big-endian 2-byte number giving address family */
  440. GET; family = c;
  441. GET; family = (family << 8) | c;
  442. /* Then expect four strings, each composed of a big-endian 2-byte
  443. * length field followed by that many bytes of data */
  444. ptr = buf;
  445. for (i = 0; i < 4; i++) {
  446. GET; len[i] = c;
  447. GET; len[i] = (len[i] << 8) | c;
  448. str[i] = ptr;
  449. for (j = 0; j < len[i]; j++) {
  450. GET; *ptr++ = c;
  451. }
  452. *ptr++ = '\0';
  453. }
  454. #undef GET
  455. /*
  456. * Now we have a full X authority record in memory. See
  457. * whether it matches the display we're trying to
  458. * authenticate to.
  459. *
  460. * The details we've just read should be interpreted as
  461. * follows:
  462. *
  463. * - 'family' is the network address family used to
  464. * connect to the display. 0 means IPv4; 6 means IPv6;
  465. * 256 means Unix-domain sockets.
  466. *
  467. * - str[0] is the network address itself. For IPv4 and
  468. * IPv6, this is a string of binary data of the
  469. * appropriate length (respectively 4 and 16 bytes)
  470. * representing the address in big-endian format, e.g.
  471. * 7F 00 00 01 means IPv4 localhost. For Unix-domain
  472. * sockets, this is the host name of the machine on
  473. * which the Unix-domain display resides (so that an
  474. * .Xauthority file on a shared file system can contain
  475. * authority entries for Unix-domain displays on
  476. * several machines without them clashing).
  477. *
  478. * - str[1] is the display number. I've no idea why
  479. * .Xauthority stores this as a string when it has a
  480. * perfectly good integer format, but there we go.
  481. *
  482. * - str[2] is the authorisation method, encoded as its
  483. * canonical string name (i.e. "MIT-MAGIC-COOKIE-1",
  484. * "XDM-AUTHORIZATION-1" or something we don't
  485. * recognise).
  486. *
  487. * - str[3] is the actual authorisation data, stored in
  488. * binary form.
  489. */
  490. if (disp->displaynum < 0 || disp->displaynum != atoi(str[1]))
  491. continue; /* not the one */
  492. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  493. if (!strcmp(str[2], x11_authnames[protocol]))
  494. break;
  495. if (protocol == lenof(x11_authnames))
  496. continue; /* don't recognise this protocol, look for another */
  497. switch (family) {
  498. case 0: /* IPv4 */
  499. if (!disp->unixdomain &&
  500. sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {
  501. char buf[4];
  502. sk_addrcopy(disp->addr, buf);
  503. if (len[0] == 4 && !memcmp(str[0], buf, 4)) {
  504. match = TRUE;
  505. /* If this is a "localhost" entry, note it down
  506. * but carry on looking for a Unix-domain entry. */
  507. ideal_match = !localhost;
  508. }
  509. }
  510. break;
  511. case 6: /* IPv6 */
  512. if (!disp->unixdomain &&
  513. sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {
  514. char buf[16];
  515. sk_addrcopy(disp->addr, buf);
  516. if (len[0] == 16 && !memcmp(str[0], buf, 16)) {
  517. match = TRUE;
  518. ideal_match = !localhost;
  519. }
  520. }
  521. break;
  522. case 256: /* Unix-domain / localhost */
  523. if ((disp->unixdomain || localhost)
  524. && ourhostname && !strcmp(ourhostname, str[0]))
  525. /* A matching Unix-domain socket is always the best
  526. * match. */
  527. match = ideal_match = TRUE;
  528. break;
  529. }
  530. if (match) {
  531. /* Current best guess -- may be overridden if !ideal_match */
  532. disp->localauthproto = protocol;
  533. sfree(disp->localauthdata); /* free previous guess, if any */
  534. disp->localauthdata = snewn(len[3], unsigned char);
  535. memcpy(disp->localauthdata, str[3], len[3]);
  536. disp->localauthdatalen = len[3];
  537. }
  538. }
  539. done:
  540. fclose(authfp);
  541. smemclr(buf, 65537 * 4);
  542. sfree(buf);
  543. sfree(ourhostname);
  544. }
  545. static void x11_log(Plug p, int type, SockAddr addr, int port,
  546. const char *error_msg, int error_code)
  547. {
  548. /* We have no interface to the logging module here, so we drop these. */
  549. }
  550. static void x11_send_init_error(struct X11Connection *conn,
  551. const char *err_message);
  552. static void x11_closing(Plug plug, const char *error_msg, int error_code,
  553. int calling_back)
  554. {
  555. struct X11Connection *xconn = (struct X11Connection *) plug;
  556. if (error_msg) {
  557. /*
  558. * Socket error. If we're still at the connection setup stage,
  559. * construct an X11 error packet passing on the problem.
  560. */
  561. if (xconn->no_data_sent_to_x_client) {
  562. char *err_message = dupprintf("unable to connect to forwarded "
  563. "X server: %s", error_msg);
  564. x11_send_init_error(xconn, err_message);
  565. sfree(err_message);
  566. }
  567. /*
  568. * Whether we did that or not, now we slam the connection
  569. * shut.
  570. */
  571. sshfwd_unclean_close(xconn->c, error_msg);
  572. } else {
  573. /*
  574. * Ordinary EOF received on socket. Send an EOF on the SSH
  575. * channel.
  576. */
  577. if (xconn->c)
  578. sshfwd_write_eof(xconn->c);
  579. }
  580. }
  581. static void x11_receive(Plug plug, int urgent, char *data, int len)
  582. {
  583. struct X11Connection *xconn = (struct X11Connection *) plug;
  584. if (sshfwd_write(xconn->c, data, len) > 0) {
  585. xconn->throttled = 1;
  586. xconn->no_data_sent_to_x_client = FALSE;
  587. sk_set_frozen(xconn->s, 1);
  588. }
  589. }
  590. static void x11_sent(Plug plug, int bufsize)
  591. {
  592. struct X11Connection *xconn = (struct X11Connection *) plug;
  593. sshfwd_unthrottle(xconn->c, bufsize);
  594. }
  595. /*
  596. * When setting up X forwarding, we should send the screen number
  597. * from the specified local display. This function extracts it from
  598. * the display string.
  599. */
  600. int x11_get_screen_number(char *display)
  601. {
  602. int n;
  603. n = host_strcspn(display, ":");
  604. if (!display[n])
  605. return 0;
  606. n = strcspn(display, ".");
  607. if (!display[n])
  608. return 0;
  609. return atoi(display + n + 1);
  610. }
  611. /*
  612. * Called to set up the X11Connection structure, though this does not
  613. * yet connect to an actual server.
  614. */
  615. struct X11Connection *x11_init(tree234 *authtree, void *c,
  616. const char *peeraddr, int peerport)
  617. {
  618. static const struct plug_function_table fn_table = {
  619. x11_log,
  620. x11_closing,
  621. x11_receive,
  622. x11_sent,
  623. NULL
  624. };
  625. struct X11Connection *xconn;
  626. /*
  627. * Open socket.
  628. */
  629. xconn = snew(struct X11Connection);
  630. xconn->fn = &fn_table;
  631. xconn->auth_protocol = NULL;
  632. xconn->authtree = authtree;
  633. xconn->verified = 0;
  634. xconn->data_read = 0;
  635. xconn->throttled = xconn->throttle_override = 0;
  636. xconn->no_data_sent_to_x_client = TRUE;
  637. xconn->c = c;
  638. /*
  639. * We don't actually open a local socket to the X server just yet,
  640. * because we don't know which one it is. Instead, we'll wait
  641. * until we see the incoming authentication data, which may tell
  642. * us what display to connect to, or whether we have to divert
  643. * this X forwarding channel to a connection-sharing downstream
  644. * rather than handling it ourself.
  645. */
  646. xconn->disp = NULL;
  647. xconn->s = NULL;
  648. /*
  649. * Stash the peer address we were given in its original text form.
  650. */
  651. xconn->peer_addr = peeraddr ? dupstr(peeraddr) : NULL;
  652. xconn->peer_port = peerport;
  653. return xconn;
  654. }
  655. void x11_close(struct X11Connection *xconn)
  656. {
  657. if (!xconn)
  658. return;
  659. if (xconn->auth_protocol) {
  660. sfree(xconn->auth_protocol);
  661. sfree(xconn->auth_data);
  662. }
  663. if (xconn->s)
  664. sk_close(xconn->s);
  665. sfree(xconn->peer_addr);
  666. sfree(xconn);
  667. }
  668. void x11_unthrottle(struct X11Connection *xconn)
  669. {
  670. if (!xconn)
  671. return;
  672. xconn->throttled = 0;
  673. if (xconn->s)
  674. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  675. }
  676. void x11_override_throttle(struct X11Connection *xconn, int enable)
  677. {
  678. if (!xconn)
  679. return;
  680. xconn->throttle_override = enable;
  681. if (xconn->s)
  682. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  683. }
  684. static void x11_send_init_error(struct X11Connection *xconn,
  685. const char *err_message)
  686. {
  687. char *full_message;
  688. int msglen, msgsize;
  689. unsigned char *reply;
  690. full_message = dupprintf("%s X11 proxy: %s\n", appname, err_message);
  691. msglen = strlen(full_message);
  692. reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
  693. msgsize = (msglen + 3) & ~3;
  694. reply[0] = 0; /* failure */
  695. reply[1] = msglen; /* length of reason string */
  696. memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */
  697. PUT_16BIT(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
  698. memset(reply + 8, 0, msgsize);
  699. memcpy(reply + 8, full_message, msglen);
  700. sshfwd_write(xconn->c, (char *)reply, 8 + msgsize);
  701. sshfwd_write_eof(xconn->c);
  702. xconn->no_data_sent_to_x_client = FALSE;
  703. sfree(reply);
  704. sfree(full_message);
  705. }
  706. static int x11_parse_ip(const char *addr_string, unsigned long *ip)
  707. {
  708. /*
  709. * See if we can make sense of this string as an IPv4 address, for
  710. * XDM-AUTHORIZATION-1 purposes.
  711. */
  712. int i[4];
  713. if (addr_string &&
  714. 4 == sscanf(addr_string, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
  715. *ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
  716. return TRUE;
  717. } else {
  718. return FALSE;
  719. }
  720. }
  721. /*
  722. * Called to send data down the raw connection.
  723. */
  724. int x11_send(struct X11Connection *xconn, char *data, int len)
  725. {
  726. if (!xconn)
  727. return 0;
  728. /*
  729. * Read the first packet.
  730. */
  731. while (len > 0 && xconn->data_read < 12)
  732. xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++);
  733. if (xconn->data_read < 12)
  734. return 0;
  735. /*
  736. * If we have not allocated the auth_protocol and auth_data
  737. * strings, do so now.
  738. */
  739. if (!xconn->auth_protocol) {
  740. xconn->auth_plen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 6);
  741. xconn->auth_dlen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 8);
  742. xconn->auth_psize = (xconn->auth_plen + 3) & ~3;
  743. xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3;
  744. /* Leave room for a terminating zero, to make our lives easier. */
  745. xconn->auth_protocol = snewn(xconn->auth_psize + 1, char);
  746. xconn->auth_data = snewn(xconn->auth_dsize, unsigned char);
  747. }
  748. /*
  749. * Read the auth_protocol and auth_data strings.
  750. */
  751. while (len > 0 &&
  752. xconn->data_read < 12 + xconn->auth_psize)
  753. xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++);
  754. while (len > 0 &&
  755. xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  756. xconn->auth_data[xconn->data_read++ - 12 -
  757. xconn->auth_psize] = (unsigned char) (len--, *data++);
  758. if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  759. return 0;
  760. /*
  761. * If we haven't verified the authorisation, do so now.
  762. */
  763. if (!xconn->verified) {
  764. const char *err;
  765. struct X11FakeAuth *auth_matched = NULL;
  766. unsigned long peer_ip;
  767. int peer_port;
  768. int protomajor, protominor;
  769. void *greeting;
  770. int greeting_len;
  771. unsigned char *socketdata;
  772. int socketdatalen;
  773. char new_peer_addr[32];
  774. int new_peer_port;
  775. protomajor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 2);
  776. protominor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 4);
  777. assert(!xconn->s);
  778. xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */
  779. peer_ip = 0; /* placate optimiser */
  780. if (x11_parse_ip(xconn->peer_addr, &peer_ip))
  781. peer_port = xconn->peer_port;
  782. else
  783. peer_port = -1; /* signal no peer address data available */
  784. err = x11_verify(peer_ip, peer_port,
  785. xconn->authtree, xconn->auth_protocol,
  786. xconn->auth_data, xconn->auth_dlen, &auth_matched);
  787. if (err) {
  788. x11_send_init_error(xconn, err);
  789. return 0;
  790. }
  791. assert(auth_matched);
  792. /*
  793. * If this auth points to a connection-sharing downstream
  794. * rather than an X display we know how to connect to
  795. * directly, pass it off to the sharing module now.
  796. */
  797. if (auth_matched->share_cs) {
  798. sshfwd_x11_sharing_handover(xconn->c, auth_matched->share_cs,
  799. auth_matched->share_chan,
  800. xconn->peer_addr, xconn->peer_port,
  801. xconn->firstpkt[0],
  802. protomajor, protominor, data, len);
  803. return 0;
  804. }
  805. /*
  806. * Now we know we're going to accept the connection, and what
  807. * X display to connect to. Actually connect to it.
  808. */
  809. sshfwd_x11_is_local(xconn->c);
  810. xconn->disp = auth_matched->disp;
  811. xconn->s = new_connection(sk_addr_dup(xconn->disp->addr),
  812. xconn->disp->realhost, xconn->disp->port,
  813. 0, 1, 0, 0, (Plug) xconn,
  814. sshfwd_get_conf(xconn->c));
  815. if ((err = sk_socket_error(xconn->s)) != NULL) {
  816. char *err_message = dupprintf("unable to connect to"
  817. " forwarded X server: %s", err);
  818. x11_send_init_error(xconn, err_message);
  819. sfree(err_message);
  820. return 0;
  821. }
  822. /*
  823. * Write a new connection header containing our replacement
  824. * auth data.
  825. */
  826. socketdatalen = 0; /* placate compiler warning */
  827. #ifdef MPEXT
  828. // placate compiler warning
  829. socketdatalen = 0;
  830. #endif
  831. socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
  832. if (socketdata && socketdatalen==6) {
  833. sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
  834. socketdata[1], socketdata[2], socketdata[3]);
  835. new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
  836. } else {
  837. strcpy(new_peer_addr, "0.0.0.0");
  838. new_peer_port = 0;
  839. }
  840. greeting = x11_make_greeting(xconn->firstpkt[0],
  841. protomajor, protominor,
  842. xconn->disp->localauthproto,
  843. xconn->disp->localauthdata,
  844. xconn->disp->localauthdatalen,
  845. new_peer_addr, new_peer_port,
  846. &greeting_len);
  847. sk_write(xconn->s, greeting, greeting_len);
  848. smemclr(greeting, greeting_len);
  849. sfree(greeting);
  850. /*
  851. * Now we're done.
  852. */
  853. xconn->verified = 1;
  854. }
  855. /*
  856. * After initialisation, just copy data simply.
  857. */
  858. return sk_write(xconn->s, data, len);
  859. }
  860. void x11_send_eof(struct X11Connection *xconn)
  861. {
  862. if (xconn->s) {
  863. sk_write_eof(xconn->s);
  864. } else {
  865. /*
  866. * If EOF is received from the X client before we've got to
  867. * the point of actually connecting to an X server, then we
  868. * should send an EOF back to the client so that the
  869. * forwarded channel will be terminated.
  870. */
  871. if (xconn->c)
  872. sshfwd_write_eof(xconn->c);
  873. }
  874. }
  875. /*
  876. * Utility functions used by connection sharing to convert textual
  877. * representations of an X11 auth protocol name + hex cookie into our
  878. * usual integer protocol id and binary auth data.
  879. */
  880. int x11_identify_auth_proto(const char *protoname)
  881. {
  882. int protocol;
  883. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  884. if (!strcmp(protoname, x11_authnames[protocol]))
  885. return protocol;
  886. return -1;
  887. }
  888. void *x11_dehexify(const char *hex, int *outlen)
  889. {
  890. int len, i;
  891. unsigned char *ret;
  892. len = strlen(hex) / 2;
  893. ret = snewn(len, unsigned char);
  894. for (i = 0; i < len; i++) {
  895. char bytestr[3];
  896. unsigned val = 0;
  897. bytestr[0] = hex[2*i];
  898. bytestr[1] = hex[2*i+1];
  899. bytestr[2] = '\0';
  900. sscanf(bytestr, "%x", &val);
  901. ret[i] = val;
  902. }
  903. *outlen = len;
  904. return ret;
  905. }
  906. /*
  907. * Construct an X11 greeting packet, including making up the right
  908. * authorisation data.
  909. */
  910. void *x11_make_greeting(int endian, int protomajor, int protominor,
  911. int auth_proto, const void *auth_data, int auth_len,
  912. const char *peer_addr, int peer_port,
  913. int *outlen)
  914. {
  915. unsigned char *greeting;
  916. unsigned char realauthdata[64];
  917. const char *authname;
  918. const unsigned char *authdata;
  919. int authnamelen, authnamelen_pad;
  920. int authdatalen, authdatalen_pad;
  921. int greeting_len;
  922. authname = x11_authnames[auth_proto];
  923. authnamelen = strlen(authname);
  924. authnamelen_pad = (authnamelen + 3) & ~3;
  925. if (auth_proto == X11_MIT) {
  926. authdata = auth_data;
  927. authdatalen = auth_len;
  928. } else if (auth_proto == X11_XDM && auth_len == 16) {
  929. time_t t;
  930. unsigned long peer_ip = 0;
  931. x11_parse_ip(peer_addr, &peer_ip);
  932. authdata = realauthdata;
  933. authdatalen = 24;
  934. memset(realauthdata, 0, authdatalen);
  935. memcpy(realauthdata, auth_data, 8);
  936. PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
  937. PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
  938. t = time(NULL);
  939. PUT_32BIT_MSB_FIRST(realauthdata+14, t);
  940. des_encrypt_xdmauth((const unsigned char *)auth_data + 9,
  941. realauthdata, authdatalen);
  942. } else {
  943. authdata = realauthdata;
  944. authdatalen = 0;
  945. }
  946. authdatalen_pad = (authdatalen + 3) & ~3;
  947. greeting_len = 12 + authnamelen_pad + authdatalen_pad;
  948. greeting = snewn(greeting_len, unsigned char);
  949. memset(greeting, 0, greeting_len);
  950. greeting[0] = endian;
  951. PUT_16BIT(endian, greeting+2, protomajor);
  952. PUT_16BIT(endian, greeting+4, protominor);
  953. PUT_16BIT(endian, greeting+6, authnamelen);
  954. PUT_16BIT(endian, greeting+8, authdatalen);
  955. memcpy(greeting+12, authname, authnamelen);
  956. memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
  957. smemclr(realauthdata, sizeof(realauthdata));
  958. *outlen = greeting_len;
  959. return greeting;
  960. }