x11fwd.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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 int dummy_plug_closing
  53. (Plug p, const char *error_msg, int error_code, int calling_back)
  54. { return 1; }
  55. static int dummy_plug_receive(Plug p, int urgent, char *data, int len)
  56. { return 1; }
  57. static void dummy_plug_sent(Plug p, int bufsize) { }
  58. static int dummy_plug_accepting(Plug p, accept_fn_t constructor, accept_ctx_t ctx) { return 1; }
  59. static const struct plug_function_table dummy_plug = {
  60. dummy_plug_log, dummy_plug_closing, dummy_plug_receive,
  61. dummy_plug_sent, dummy_plug_accepting
  62. };
  63. struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype)
  64. {
  65. struct X11FakeAuth *auth = snew(struct X11FakeAuth);
  66. int i;
  67. /*
  68. * This function has the job of inventing a set of X11 fake auth
  69. * data, and adding it to 'authtree'. We must preserve the
  70. * property that for any given actual authorisation attempt, _at
  71. * most one_ thing in the tree can possibly match it.
  72. *
  73. * For MIT-MAGIC-COOKIE-1, that's not too difficult: the match
  74. * criterion is simply that the entire cookie is correct, so we
  75. * just have to make sure we don't make up two cookies the same.
  76. * (Vanishingly unlikely, but we check anyway to be sure, and go
  77. * round again inventing a new cookie if add234 tells us the one
  78. * we thought of is already in use.)
  79. *
  80. * For XDM-AUTHORIZATION-1, it's a little more fiddly. The setup
  81. * with XA1 is that half the cookie is used as a DES key with
  82. * which to CBC-encrypt an assortment of stuff. Happily, the stuff
  83. * encrypted _begins_ with the other half of the cookie, and the
  84. * IV is always zero, which means that any valid XA1 authorisation
  85. * attempt for a given cookie must begin with the same cipher
  86. * block, consisting of the DES ECB encryption of the first half
  87. * of the cookie using the second half as a key. So we compute
  88. * that cipher block here and now, and use it as the sorting key
  89. * for distinguishing XA1 entries in the tree.
  90. */
  91. if (authtype == X11_MIT) {
  92. auth->proto = X11_MIT;
  93. /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
  94. auth->datalen = 16;
  95. auth->data = snewn(auth->datalen, unsigned char);
  96. auth->xa1_firstblock = NULL;
  97. while (1) {
  98. for (i = 0; i < auth->datalen; i++)
  99. auth->data[i] = random_byte();
  100. if (add234(authtree, auth) == auth)
  101. break;
  102. }
  103. auth->xdmseen = NULL;
  104. } else {
  105. assert(authtype == X11_XDM);
  106. auth->proto = X11_XDM;
  107. /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */
  108. auth->datalen = 16;
  109. auth->data = snewn(auth->datalen, unsigned char);
  110. auth->xa1_firstblock = snewn(8, unsigned char);
  111. memset(auth->xa1_firstblock, 0, 8);
  112. while (1) {
  113. for (i = 0; i < auth->datalen; i++)
  114. auth->data[i] = (i == 8 ? 0 : random_byte());
  115. memcpy(auth->xa1_firstblock, auth->data, 8);
  116. des_encrypt_xdmauth(auth->data + 9, auth->xa1_firstblock, 8);
  117. if (add234(authtree, auth) == auth)
  118. break;
  119. }
  120. auth->xdmseen = newtree234(xdmseen_cmp);
  121. }
  122. auth->protoname = dupstr(x11_authnames[auth->proto]);
  123. auth->datastring = snewn(auth->datalen * 2 + 1, char);
  124. for (i = 0; i < auth->datalen; i++)
  125. sprintf(auth->datastring + i*2, "%02x",
  126. auth->data[i]);
  127. auth->disp = NULL;
  128. auth->share_cs = auth->share_chan = NULL;
  129. return auth;
  130. }
  131. void x11_free_fake_auth(struct X11FakeAuth *auth)
  132. {
  133. if (auth->data)
  134. smemclr(auth->data, auth->datalen);
  135. sfree(auth->data);
  136. sfree(auth->protoname);
  137. sfree(auth->datastring);
  138. sfree(auth->xa1_firstblock);
  139. if (auth->xdmseen != NULL) {
  140. struct XDMSeen *seen;
  141. while ((seen = delpos234(auth->xdmseen, 0)) != NULL)
  142. sfree(seen);
  143. freetree234(auth->xdmseen);
  144. }
  145. sfree(auth);
  146. }
  147. int x11_authcmp(void *av, void *bv)
  148. {
  149. struct X11FakeAuth *a = (struct X11FakeAuth *)av;
  150. struct X11FakeAuth *b = (struct X11FakeAuth *)bv;
  151. if (a->proto < b->proto)
  152. return -1;
  153. else if (a->proto > b->proto)
  154. return +1;
  155. if (a->proto == X11_MIT) {
  156. if (a->datalen < b->datalen)
  157. return -1;
  158. else if (a->datalen > b->datalen)
  159. return +1;
  160. return memcmp(a->data, b->data, a->datalen);
  161. } else {
  162. assert(a->proto == X11_XDM);
  163. return memcmp(a->xa1_firstblock, b->xa1_firstblock, 8);
  164. }
  165. }
  166. struct X11Display *x11_setup_display(const char *display, Conf *conf)
  167. {
  168. struct X11Display *disp = snew(struct X11Display);
  169. char *localcopy;
  170. if (!display || !*display) {
  171. localcopy = platform_get_x_display();
  172. if (!localcopy || !*localcopy) {
  173. sfree(localcopy);
  174. localcopy = dupstr(":0"); /* plausible default for any platform */
  175. }
  176. } else
  177. localcopy = dupstr(display);
  178. /*
  179. * Parse the display name.
  180. *
  181. * We expect this to have one of the following forms:
  182. *
  183. * - the standard X format which looks like
  184. * [ [ protocol '/' ] host ] ':' displaynumber [ '.' screennumber ]
  185. * (X11 also permits a double colon to indicate DECnet, but
  186. * that's not our problem, thankfully!)
  187. *
  188. * - only seen in the wild on MacOS (so far): a pathname to a
  189. * Unix-domain socket, which will typically and confusingly
  190. * end in ":0", and which I'm currently distinguishing from
  191. * the standard scheme by noting that it starts with '/'.
  192. */
  193. if (localcopy[0] == '/') {
  194. disp->unixsocketpath = localcopy;
  195. disp->unixdomain = TRUE;
  196. disp->hostname = NULL;
  197. disp->displaynum = -1;
  198. disp->screennum = 0;
  199. disp->addr = NULL;
  200. } else {
  201. char *colon, *dot, *slash;
  202. char *protocol, *hostname;
  203. colon = host_strrchr(localcopy, ':');
  204. if (!colon) {
  205. sfree(disp);
  206. sfree(localcopy);
  207. return NULL; /* FIXME: report a specific error? */
  208. }
  209. *colon++ = '\0';
  210. dot = strchr(colon, '.');
  211. if (dot)
  212. *dot++ = '\0';
  213. disp->displaynum = atoi(colon);
  214. if (dot)
  215. disp->screennum = atoi(dot);
  216. else
  217. disp->screennum = 0;
  218. protocol = NULL;
  219. hostname = localcopy;
  220. if (colon > localcopy) {
  221. slash = strchr(localcopy, '/');
  222. if (slash) {
  223. *slash++ = '\0';
  224. protocol = localcopy;
  225. hostname = slash;
  226. }
  227. }
  228. disp->hostname = *hostname ? dupstr(hostname) : NULL;
  229. if (protocol)
  230. disp->unixdomain = (!strcmp(protocol, "local") ||
  231. !strcmp(protocol, "unix"));
  232. else if (!*hostname || !strcmp(hostname, "unix"))
  233. disp->unixdomain = platform_uses_x11_unix_by_default;
  234. else
  235. disp->unixdomain = FALSE;
  236. if (!disp->hostname && !disp->unixdomain)
  237. disp->hostname = dupstr("localhost");
  238. disp->unixsocketpath = NULL;
  239. disp->addr = NULL;
  240. sfree(localcopy);
  241. }
  242. /*
  243. * Look up the display hostname, if we need to.
  244. */
  245. if (!disp->unixdomain) {
  246. const char *err;
  247. disp->port = 6000 + disp->displaynum;
  248. disp->addr = name_lookup(disp->hostname, disp->port,
  249. &disp->realhost, conf, ADDRTYPE_UNSPEC,
  250. NULL, NULL);
  251. if ((err = sk_addr_error(disp->addr)) != NULL) {
  252. sk_addr_free(disp->addr);
  253. sfree(disp->hostname);
  254. sfree(disp->unixsocketpath);
  255. sfree(disp);
  256. return NULL; /* FIXME: report an error */
  257. }
  258. }
  259. /*
  260. * Try upgrading an IP-style localhost display to a Unix-socket
  261. * display (as the standard X connection libraries do).
  262. */
  263. if (!disp->unixdomain && sk_address_is_local(disp->addr)) {
  264. SockAddr ux = platform_get_x11_unix_address(NULL, disp->displaynum);
  265. const char *err = sk_addr_error(ux);
  266. if (!err) {
  267. /* Create trial connection to see if there is a useful Unix-domain
  268. * socket */
  269. const struct plug_function_table *dummy = &dummy_plug;
  270. Socket s = sk_new(sk_addr_dup(ux), 0, 0, 0, 0, 0, (Plug)&dummy);
  271. err = sk_socket_error(s);
  272. sk_close(s);
  273. }
  274. if (err) {
  275. sk_addr_free(ux);
  276. } else {
  277. sk_addr_free(disp->addr);
  278. disp->unixdomain = TRUE;
  279. disp->addr = ux;
  280. /* Fill in the rest in a moment */
  281. }
  282. }
  283. if (disp->unixdomain) {
  284. if (!disp->addr)
  285. disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
  286. disp->displaynum);
  287. if (disp->unixsocketpath)
  288. disp->realhost = dupstr(disp->unixsocketpath);
  289. else
  290. disp->realhost = dupprintf("unix:%d", disp->displaynum);
  291. disp->port = 0;
  292. }
  293. /*
  294. * Fetch the local authorisation details.
  295. */
  296. disp->localauthproto = X11_NO_AUTH;
  297. disp->localauthdata = NULL;
  298. disp->localauthdatalen = 0;
  299. platform_get_x11_auth(disp, conf);
  300. return disp;
  301. }
  302. void x11_free_display(struct X11Display *disp)
  303. {
  304. sfree(disp->hostname);
  305. sfree(disp->unixsocketpath);
  306. if (disp->localauthdata)
  307. smemclr(disp->localauthdata, disp->localauthdatalen);
  308. sfree(disp->localauthdata);
  309. sk_addr_free(disp->addr);
  310. sfree(disp);
  311. }
  312. #define XDM_MAXSKEW 20*60 /* 20 minute clock skew should be OK */
  313. static const char *x11_verify(unsigned long peer_ip, int peer_port,
  314. tree234 *authtree, char *proto,
  315. unsigned char *data, int dlen,
  316. struct X11FakeAuth **auth_ret)
  317. {
  318. struct X11FakeAuth match_dummy; /* for passing to find234 */
  319. struct X11FakeAuth *auth;
  320. /*
  321. * First, do a lookup in our tree to find the only authorisation
  322. * record that _might_ match.
  323. */
  324. if (!strcmp(proto, x11_authnames[X11_MIT])) {
  325. /*
  326. * Just look up the whole cookie that was presented to us,
  327. * which x11_authcmp will compare against the cookies we
  328. * currently believe in.
  329. */
  330. match_dummy.proto = X11_MIT;
  331. match_dummy.datalen = dlen;
  332. match_dummy.data = data;
  333. } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
  334. /*
  335. * Look up the first cipher block, against the stored first
  336. * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
  337. * currently know. (See comment in x11_invent_fake_auth.)
  338. */
  339. match_dummy.proto = X11_XDM;
  340. match_dummy.xa1_firstblock = data;
  341. } else {
  342. return "Unsupported authorisation protocol";
  343. }
  344. if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
  345. return "Authorisation not recognised";
  346. /*
  347. * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
  348. * we're doing XDM-AUTHORIZATION-1, though, we have to check the
  349. * rest of the auth data.
  350. */
  351. if (auth->proto == X11_XDM) {
  352. unsigned long t;
  353. time_t tim;
  354. int i;
  355. struct XDMSeen *seen, *ret;
  356. if (dlen != 24)
  357. return "XDM-AUTHORIZATION-1 data was wrong length";
  358. if (peer_port == -1)
  359. return "cannot do XDM-AUTHORIZATION-1 without remote address data";
  360. des_decrypt_xdmauth(auth->data+9, data, 24);
  361. if (memcmp(auth->data, data, 8) != 0)
  362. return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
  363. if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
  364. return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */
  365. if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
  366. return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */
  367. t = GET_32BIT_MSB_FIRST(data+14);
  368. for (i = 18; i < 24; i++)
  369. if (data[i] != 0) /* zero padding wrong */
  370. return "XDM-AUTHORIZATION-1 data failed check";
  371. tim = time(NULL);
  372. if (((unsigned long)t - (unsigned long)tim
  373. + XDM_MAXSKEW) > 2*XDM_MAXSKEW)
  374. return "XDM-AUTHORIZATION-1 time stamp was too far out";
  375. seen = snew(struct XDMSeen);
  376. seen->time = t;
  377. memcpy(seen->clientid, data+8, 6);
  378. assert(auth->xdmseen != NULL);
  379. ret = add234(auth->xdmseen, seen);
  380. if (ret != seen) {
  381. sfree(seen);
  382. return "XDM-AUTHORIZATION-1 data replayed";
  383. }
  384. /* While we're here, purge entries too old to be replayed. */
  385. for (;;) {
  386. seen = index234(auth->xdmseen, 0);
  387. assert(seen != NULL);
  388. if (t - seen->time <= XDM_MAXSKEW)
  389. break;
  390. sfree(delpos234(auth->xdmseen, 0));
  391. }
  392. }
  393. /* implement other protocols here if ever required */
  394. *auth_ret = auth;
  395. return NULL;
  396. }
  397. void x11_get_auth_from_authfile(struct X11Display *disp,
  398. const char *authfilename)
  399. {
  400. FILE *authfp;
  401. char *buf, *ptr, *str[4];
  402. int len[4];
  403. int family, protocol;
  404. int ideal_match = FALSE;
  405. char *ourhostname;
  406. /*
  407. * Normally we should look for precisely the details specified in
  408. * `disp'. However, there's an oddity when the display is local:
  409. * displays like "localhost:0" usually have their details stored
  410. * in a Unix-domain-socket record (even if there isn't actually a
  411. * real Unix-domain socket available, as with OpenSSH's proxy X11
  412. * server).
  413. *
  414. * This is apparently a fudge to get round the meaninglessness of
  415. * "localhost" in a shared-home-directory context -- xauth entries
  416. * for Unix-domain sockets already disambiguate this by storing
  417. * the *local* hostname in the conveniently-blank hostname field,
  418. * but IP "localhost" records couldn't do this. So, typically, an
  419. * IP "localhost" entry in the auth database isn't present and if
  420. * it were it would be ignored.
  421. *
  422. * However, we don't entirely trust that (say) Windows X servers
  423. * won't rely on a straight "localhost" entry, bad idea though
  424. * that is; so if we can't find a Unix-domain-socket entry we'll
  425. * fall back to an IP-based entry if we can find one.
  426. */
  427. int localhost = !disp->unixdomain && sk_address_is_local(disp->addr);
  428. authfp = fopen(authfilename, "rb");
  429. if (!authfp)
  430. return;
  431. ourhostname = get_hostname();
  432. /* Records in .Xauthority contain four strings of up to 64K each */
  433. buf = snewn(65537 * 4, char);
  434. while (!ideal_match) {
  435. int c, i, j, match = FALSE;
  436. #define GET do { c = fgetc(authfp); if (c == EOF) goto done; c = (unsigned char)c; } while (0)
  437. /* Expect a big-endian 2-byte number giving address family */
  438. GET; family = c;
  439. GET; family = (family << 8) | c;
  440. /* Then expect four strings, each composed of a big-endian 2-byte
  441. * length field followed by that many bytes of data */
  442. ptr = buf;
  443. for (i = 0; i < 4; i++) {
  444. GET; len[i] = c;
  445. GET; len[i] = (len[i] << 8) | c;
  446. str[i] = ptr;
  447. for (j = 0; j < len[i]; j++) {
  448. GET; *ptr++ = c;
  449. }
  450. *ptr++ = '\0';
  451. }
  452. #undef GET
  453. /*
  454. * Now we have a full X authority record in memory. See
  455. * whether it matches the display we're trying to
  456. * authenticate to.
  457. *
  458. * The details we've just read should be interpreted as
  459. * follows:
  460. *
  461. * - 'family' is the network address family used to
  462. * connect to the display. 0 means IPv4; 6 means IPv6;
  463. * 256 means Unix-domain sockets.
  464. *
  465. * - str[0] is the network address itself. For IPv4 and
  466. * IPv6, this is a string of binary data of the
  467. * appropriate length (respectively 4 and 16 bytes)
  468. * representing the address in big-endian format, e.g.
  469. * 7F 00 00 01 means IPv4 localhost. For Unix-domain
  470. * sockets, this is the host name of the machine on
  471. * which the Unix-domain display resides (so that an
  472. * .Xauthority file on a shared file system can contain
  473. * authority entries for Unix-domain displays on
  474. * several machines without them clashing).
  475. *
  476. * - str[1] is the display number. I've no idea why
  477. * .Xauthority stores this as a string when it has a
  478. * perfectly good integer format, but there we go.
  479. *
  480. * - str[2] is the authorisation method, encoded as its
  481. * canonical string name (i.e. "MIT-MAGIC-COOKIE-1",
  482. * "XDM-AUTHORIZATION-1" or something we don't
  483. * recognise).
  484. *
  485. * - str[3] is the actual authorisation data, stored in
  486. * binary form.
  487. */
  488. if (disp->displaynum < 0 || disp->displaynum != atoi(str[1]))
  489. continue; /* not the one */
  490. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  491. if (!strcmp(str[2], x11_authnames[protocol]))
  492. break;
  493. if (protocol == lenof(x11_authnames))
  494. continue; /* don't recognise this protocol, look for another */
  495. switch (family) {
  496. case 0: /* IPv4 */
  497. if (!disp->unixdomain &&
  498. sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {
  499. char buf[4];
  500. sk_addrcopy(disp->addr, buf);
  501. if (len[0] == 4 && !memcmp(str[0], buf, 4)) {
  502. match = TRUE;
  503. /* If this is a "localhost" entry, note it down
  504. * but carry on looking for a Unix-domain entry. */
  505. ideal_match = !localhost;
  506. }
  507. }
  508. break;
  509. case 6: /* IPv6 */
  510. if (!disp->unixdomain &&
  511. sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {
  512. char buf[16];
  513. sk_addrcopy(disp->addr, buf);
  514. if (len[0] == 16 && !memcmp(str[0], buf, 16)) {
  515. match = TRUE;
  516. ideal_match = !localhost;
  517. }
  518. }
  519. break;
  520. case 256: /* Unix-domain / localhost */
  521. if ((disp->unixdomain || localhost)
  522. && ourhostname && !strcmp(ourhostname, str[0]))
  523. /* A matching Unix-domain socket is always the best
  524. * match. */
  525. match = ideal_match = TRUE;
  526. break;
  527. }
  528. if (match) {
  529. /* Current best guess -- may be overridden if !ideal_match */
  530. disp->localauthproto = protocol;
  531. sfree(disp->localauthdata); /* free previous guess, if any */
  532. disp->localauthdata = snewn(len[3], unsigned char);
  533. memcpy(disp->localauthdata, str[3], len[3]);
  534. disp->localauthdatalen = len[3];
  535. }
  536. }
  537. done:
  538. fclose(authfp);
  539. smemclr(buf, 65537 * 4);
  540. sfree(buf);
  541. sfree(ourhostname);
  542. }
  543. static void x11_log(Plug p, int type, SockAddr addr, int port,
  544. const char *error_msg, int error_code)
  545. {
  546. /* We have no interface to the logging module here, so we drop these. */
  547. }
  548. static void x11_send_init_error(struct X11Connection *conn,
  549. const char *err_message);
  550. static int x11_closing(Plug plug, const char *error_msg, int error_code,
  551. int calling_back)
  552. {
  553. struct X11Connection *xconn = (struct X11Connection *) plug;
  554. if (error_msg) {
  555. /*
  556. * Socket error. If we're still at the connection setup stage,
  557. * construct an X11 error packet passing on the problem.
  558. */
  559. if (xconn->no_data_sent_to_x_client) {
  560. char *err_message = dupprintf("unable to connect to forwarded "
  561. "X server: %s", error_msg);
  562. x11_send_init_error(xconn, err_message);
  563. sfree(err_message);
  564. }
  565. /*
  566. * Whether we did that or not, now we slam the connection
  567. * shut.
  568. */
  569. sshfwd_unclean_close(xconn->c, error_msg);
  570. } else {
  571. /*
  572. * Ordinary EOF received on socket. Send an EOF on the SSH
  573. * channel.
  574. */
  575. if (xconn->c)
  576. sshfwd_write_eof(xconn->c);
  577. }
  578. return 1;
  579. }
  580. static int x11_receive(Plug plug, int urgent, char *data, int len)
  581. {
  582. struct X11Connection *xconn = (struct X11Connection *) plug;
  583. if (sshfwd_write(xconn->c, data, len) > 0) {
  584. xconn->throttled = 1;
  585. xconn->no_data_sent_to_x_client = FALSE;
  586. sk_set_frozen(xconn->s, 1);
  587. }
  588. return 1;
  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. socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
  827. if (socketdata && socketdatalen==6) {
  828. sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
  829. socketdata[1], socketdata[2], socketdata[3]);
  830. new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
  831. } else {
  832. strcpy(new_peer_addr, "0.0.0.0");
  833. new_peer_port = 0;
  834. }
  835. greeting = x11_make_greeting(xconn->firstpkt[0],
  836. protomajor, protominor,
  837. xconn->disp->localauthproto,
  838. xconn->disp->localauthdata,
  839. xconn->disp->localauthdatalen,
  840. new_peer_addr, new_peer_port,
  841. &greeting_len);
  842. sk_write(xconn->s, greeting, greeting_len);
  843. smemclr(greeting, greeting_len);
  844. sfree(greeting);
  845. /*
  846. * Now we're done.
  847. */
  848. xconn->verified = 1;
  849. }
  850. /*
  851. * After initialisation, just copy data simply.
  852. */
  853. return sk_write(xconn->s, data, len);
  854. }
  855. void x11_send_eof(struct X11Connection *xconn)
  856. {
  857. if (xconn->s) {
  858. sk_write_eof(xconn->s);
  859. } else {
  860. /*
  861. * If EOF is received from the X client before we've got to
  862. * the point of actually connecting to an X server, then we
  863. * should send an EOF back to the client so that the
  864. * forwarded channel will be terminated.
  865. */
  866. if (xconn->c)
  867. sshfwd_write_eof(xconn->c);
  868. }
  869. }
  870. /*
  871. * Utility functions used by connection sharing to convert textual
  872. * representations of an X11 auth protocol name + hex cookie into our
  873. * usual integer protocol id and binary auth data.
  874. */
  875. int x11_identify_auth_proto(const char *protoname)
  876. {
  877. int protocol;
  878. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  879. if (!strcmp(protoname, x11_authnames[protocol]))
  880. return protocol;
  881. return -1;
  882. }
  883. void *x11_dehexify(const char *hex, int *outlen)
  884. {
  885. int len, i;
  886. unsigned char *ret;
  887. len = strlen(hex) / 2;
  888. ret = snewn(len, unsigned char);
  889. for (i = 0; i < len; i++) {
  890. char bytestr[3];
  891. unsigned val = 0;
  892. bytestr[0] = hex[2*i];
  893. bytestr[1] = hex[2*i+1];
  894. bytestr[2] = '\0';
  895. sscanf(bytestr, "%x", &val);
  896. ret[i] = val;
  897. }
  898. *outlen = len;
  899. return ret;
  900. }
  901. /*
  902. * Construct an X11 greeting packet, including making up the right
  903. * authorisation data.
  904. */
  905. void *x11_make_greeting(int endian, int protomajor, int protominor,
  906. int auth_proto, const void *auth_data, int auth_len,
  907. const char *peer_addr, int peer_port,
  908. int *outlen)
  909. {
  910. unsigned char *greeting;
  911. unsigned char realauthdata[64];
  912. const char *authname;
  913. const unsigned char *authdata;
  914. int authnamelen, authnamelen_pad;
  915. int authdatalen, authdatalen_pad;
  916. int greeting_len;
  917. authname = x11_authnames[auth_proto];
  918. authnamelen = strlen(authname);
  919. authnamelen_pad = (authnamelen + 3) & ~3;
  920. if (auth_proto == X11_MIT) {
  921. authdata = auth_data;
  922. authdatalen = auth_len;
  923. } else if (auth_proto == X11_XDM && auth_len == 16) {
  924. time_t t;
  925. unsigned long peer_ip = 0;
  926. x11_parse_ip(peer_addr, &peer_ip);
  927. authdata = realauthdata;
  928. authdatalen = 24;
  929. memset(realauthdata, 0, authdatalen);
  930. memcpy(realauthdata, auth_data, 8);
  931. PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
  932. PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
  933. t = time(NULL);
  934. PUT_32BIT_MSB_FIRST(realauthdata+14, t);
  935. des_encrypt_xdmauth((const unsigned char *)auth_data + 9,
  936. realauthdata, authdatalen);
  937. } else {
  938. authdata = realauthdata;
  939. authdatalen = 0;
  940. }
  941. authdatalen_pad = (authdatalen + 3) & ~3;
  942. greeting_len = 12 + authnamelen_pad + authdatalen_pad;
  943. greeting = snewn(greeting_len, unsigned char);
  944. memset(greeting, 0, greeting_len);
  945. greeting[0] = endian;
  946. PUT_16BIT(endian, greeting+2, protomajor);
  947. PUT_16BIT(endian, greeting+4, protominor);
  948. PUT_16BIT(endian, greeting+6, authnamelen);
  949. PUT_16BIT(endian, greeting+8, authdatalen);
  950. memcpy(greeting+12, authname, authnamelen);
  951. memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
  952. smemclr(realauthdata, sizeof(realauthdata));
  953. *outlen = greeting_len;
  954. return greeting;
  955. }