x11fwd.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. err = sk_socket_error(s);
  270. sk_close(s);
  271. }
  272. if (err) {
  273. sk_addr_free(ux);
  274. } else {
  275. sk_addr_free(disp->addr);
  276. disp->unixdomain = TRUE;
  277. disp->addr = ux;
  278. /* Fill in the rest in a moment */
  279. }
  280. }
  281. if (disp->unixdomain) {
  282. if (!disp->addr)
  283. disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
  284. disp->displaynum);
  285. if (disp->unixsocketpath)
  286. disp->realhost = dupstr(disp->unixsocketpath);
  287. else
  288. disp->realhost = dupprintf("unix:%d", disp->displaynum);
  289. disp->port = 0;
  290. }
  291. /*
  292. * Fetch the local authorisation details.
  293. */
  294. disp->localauthproto = X11_NO_AUTH;
  295. disp->localauthdata = NULL;
  296. disp->localauthdatalen = 0;
  297. platform_get_x11_auth(disp, conf);
  298. return disp;
  299. }
  300. void x11_free_display(struct X11Display *disp)
  301. {
  302. sfree(disp->hostname);
  303. sfree(disp->unixsocketpath);
  304. if (disp->localauthdata)
  305. smemclr(disp->localauthdata, disp->localauthdatalen);
  306. sfree(disp->localauthdata);
  307. sk_addr_free(disp->addr);
  308. sfree(disp);
  309. }
  310. #define XDM_MAXSKEW 20*60 /* 20 minute clock skew should be OK */
  311. static const char *x11_verify(unsigned long peer_ip, int peer_port,
  312. tree234 *authtree, char *proto,
  313. unsigned char *data, int dlen,
  314. struct X11FakeAuth **auth_ret)
  315. {
  316. struct X11FakeAuth match_dummy; /* for passing to find234 */
  317. struct X11FakeAuth *auth;
  318. /*
  319. * First, do a lookup in our tree to find the only authorisation
  320. * record that _might_ match.
  321. */
  322. if (!strcmp(proto, x11_authnames[X11_MIT])) {
  323. /*
  324. * Just look up the whole cookie that was presented to us,
  325. * which x11_authcmp will compare against the cookies we
  326. * currently believe in.
  327. */
  328. match_dummy.proto = X11_MIT;
  329. match_dummy.datalen = dlen;
  330. match_dummy.data = data;
  331. } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
  332. /*
  333. * Look up the first cipher block, against the stored first
  334. * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
  335. * currently know. (See comment in x11_invent_fake_auth.)
  336. */
  337. match_dummy.proto = X11_XDM;
  338. match_dummy.xa1_firstblock = data;
  339. } else {
  340. return "Unsupported authorisation protocol";
  341. }
  342. if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
  343. return "Authorisation not recognised";
  344. /*
  345. * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
  346. * we're doing XDM-AUTHORIZATION-1, though, we have to check the
  347. * rest of the auth data.
  348. */
  349. if (auth->proto == X11_XDM) {
  350. unsigned long t;
  351. time_t tim;
  352. int i;
  353. struct XDMSeen *seen, *ret;
  354. if (dlen != 24)
  355. return "XDM-AUTHORIZATION-1 data was wrong length";
  356. if (peer_port == -1)
  357. return "cannot do XDM-AUTHORIZATION-1 without remote address data";
  358. des_decrypt_xdmauth(auth->data+9, data, 24);
  359. if (memcmp(auth->data, data, 8) != 0)
  360. return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
  361. if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
  362. return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */
  363. if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
  364. return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */
  365. t = GET_32BIT_MSB_FIRST(data+14);
  366. for (i = 18; i < 24; i++)
  367. if (data[i] != 0) /* zero padding wrong */
  368. return "XDM-AUTHORIZATION-1 data failed check";
  369. tim = time(NULL);
  370. if (((unsigned long)t - (unsigned long)tim
  371. + XDM_MAXSKEW) > 2*XDM_MAXSKEW)
  372. return "XDM-AUTHORIZATION-1 time stamp was too far out";
  373. seen = snew(struct XDMSeen);
  374. seen->time = t;
  375. memcpy(seen->clientid, data+8, 6);
  376. assert(auth->xdmseen != NULL);
  377. ret = add234(auth->xdmseen, seen);
  378. if (ret != seen) {
  379. sfree(seen);
  380. return "XDM-AUTHORIZATION-1 data replayed";
  381. }
  382. /* While we're here, purge entries too old to be replayed. */
  383. for (;;) {
  384. seen = index234(auth->xdmseen, 0);
  385. assert(seen != NULL);
  386. if (t - seen->time <= XDM_MAXSKEW)
  387. break;
  388. sfree(delpos234(auth->xdmseen, 0));
  389. }
  390. }
  391. /* implement other protocols here if ever required */
  392. *auth_ret = auth;
  393. return NULL;
  394. }
  395. void x11_get_auth_from_authfile(struct X11Display *disp,
  396. const char *authfilename)
  397. {
  398. FILE *authfp;
  399. char *buf, *ptr, *str[4];
  400. int len[4];
  401. int family, protocol;
  402. int ideal_match = FALSE;
  403. char *ourhostname;
  404. /*
  405. * Normally we should look for precisely the details specified in
  406. * `disp'. However, there's an oddity when the display is local:
  407. * displays like "localhost:0" usually have their details stored
  408. * in a Unix-domain-socket record (even if there isn't actually a
  409. * real Unix-domain socket available, as with OpenSSH's proxy X11
  410. * server).
  411. *
  412. * This is apparently a fudge to get round the meaninglessness of
  413. * "localhost" in a shared-home-directory context -- xauth entries
  414. * for Unix-domain sockets already disambiguate this by storing
  415. * the *local* hostname in the conveniently-blank hostname field,
  416. * but IP "localhost" records couldn't do this. So, typically, an
  417. * IP "localhost" entry in the auth database isn't present and if
  418. * it were it would be ignored.
  419. *
  420. * However, we don't entirely trust that (say) Windows X servers
  421. * won't rely on a straight "localhost" entry, bad idea though
  422. * that is; so if we can't find a Unix-domain-socket entry we'll
  423. * fall back to an IP-based entry if we can find one.
  424. */
  425. int localhost = !disp->unixdomain && sk_address_is_local(disp->addr);
  426. authfp = fopen(authfilename, "rb");
  427. if (!authfp)
  428. return;
  429. ourhostname = get_hostname();
  430. /* Records in .Xauthority contain four strings of up to 64K each */
  431. buf = snewn(65537 * 4, char);
  432. while (!ideal_match) {
  433. int c, i, j, match = FALSE;
  434. #define GET do { c = fgetc(authfp); if (c == EOF) goto done; c = (unsigned char)c; } while (0)
  435. /* Expect a big-endian 2-byte number giving address family */
  436. GET; family = c;
  437. GET; family = (family << 8) | c;
  438. /* Then expect four strings, each composed of a big-endian 2-byte
  439. * length field followed by that many bytes of data */
  440. ptr = buf;
  441. for (i = 0; i < 4; i++) {
  442. GET; len[i] = c;
  443. GET; len[i] = (len[i] << 8) | c;
  444. str[i] = ptr;
  445. for (j = 0; j < len[i]; j++) {
  446. GET; *ptr++ = c;
  447. }
  448. *ptr++ = '\0';
  449. }
  450. #undef GET
  451. /*
  452. * Now we have a full X authority record in memory. See
  453. * whether it matches the display we're trying to
  454. * authenticate to.
  455. *
  456. * The details we've just read should be interpreted as
  457. * follows:
  458. *
  459. * - 'family' is the network address family used to
  460. * connect to the display. 0 means IPv4; 6 means IPv6;
  461. * 256 means Unix-domain sockets.
  462. *
  463. * - str[0] is the network address itself. For IPv4 and
  464. * IPv6, this is a string of binary data of the
  465. * appropriate length (respectively 4 and 16 bytes)
  466. * representing the address in big-endian format, e.g.
  467. * 7F 00 00 01 means IPv4 localhost. For Unix-domain
  468. * sockets, this is the host name of the machine on
  469. * which the Unix-domain display resides (so that an
  470. * .Xauthority file on a shared file system can contain
  471. * authority entries for Unix-domain displays on
  472. * several machines without them clashing).
  473. *
  474. * - str[1] is the display number. I've no idea why
  475. * .Xauthority stores this as a string when it has a
  476. * perfectly good integer format, but there we go.
  477. *
  478. * - str[2] is the authorisation method, encoded as its
  479. * canonical string name (i.e. "MIT-MAGIC-COOKIE-1",
  480. * "XDM-AUTHORIZATION-1" or something we don't
  481. * recognise).
  482. *
  483. * - str[3] is the actual authorisation data, stored in
  484. * binary form.
  485. */
  486. if (disp->displaynum < 0 || disp->displaynum != atoi(str[1]))
  487. continue; /* not the one */
  488. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  489. if (!strcmp(str[2], x11_authnames[protocol]))
  490. break;
  491. if (protocol == lenof(x11_authnames))
  492. continue; /* don't recognise this protocol, look for another */
  493. switch (family) {
  494. case 0: /* IPv4 */
  495. if (!disp->unixdomain &&
  496. sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {
  497. char buf[4];
  498. sk_addrcopy(disp->addr, buf);
  499. if (len[0] == 4 && !memcmp(str[0], buf, 4)) {
  500. match = TRUE;
  501. /* If this is a "localhost" entry, note it down
  502. * but carry on looking for a Unix-domain entry. */
  503. ideal_match = !localhost;
  504. }
  505. }
  506. break;
  507. case 6: /* IPv6 */
  508. if (!disp->unixdomain &&
  509. sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {
  510. char buf[16];
  511. sk_addrcopy(disp->addr, buf);
  512. if (len[0] == 16 && !memcmp(str[0], buf, 16)) {
  513. match = TRUE;
  514. ideal_match = !localhost;
  515. }
  516. }
  517. break;
  518. case 256: /* Unix-domain / localhost */
  519. if ((disp->unixdomain || localhost)
  520. && ourhostname && !strcmp(ourhostname, str[0]))
  521. /* A matching Unix-domain socket is always the best
  522. * match. */
  523. match = ideal_match = TRUE;
  524. break;
  525. }
  526. if (match) {
  527. /* Current best guess -- may be overridden if !ideal_match */
  528. disp->localauthproto = protocol;
  529. sfree(disp->localauthdata); /* free previous guess, if any */
  530. disp->localauthdata = snewn(len[3], unsigned char);
  531. memcpy(disp->localauthdata, str[3], len[3]);
  532. disp->localauthdatalen = len[3];
  533. }
  534. }
  535. done:
  536. fclose(authfp);
  537. smemclr(buf, 65537 * 4);
  538. sfree(buf);
  539. sfree(ourhostname);
  540. }
  541. static void x11_log(Plug p, int type, SockAddr addr, int port,
  542. const char *error_msg, int error_code)
  543. {
  544. /* We have no interface to the logging module here, so we drop these. */
  545. }
  546. static void x11_send_init_error(struct X11Connection *conn,
  547. const char *err_message);
  548. static void x11_closing(Plug plug, const char *error_msg, int error_code,
  549. int calling_back)
  550. {
  551. struct X11Connection *xconn = (struct X11Connection *) plug;
  552. if (error_msg) {
  553. /*
  554. * Socket error. If we're still at the connection setup stage,
  555. * construct an X11 error packet passing on the problem.
  556. */
  557. if (xconn->no_data_sent_to_x_client) {
  558. char *err_message = dupprintf("unable to connect to forwarded "
  559. "X server: %s", error_msg);
  560. x11_send_init_error(xconn, err_message);
  561. sfree(err_message);
  562. }
  563. /*
  564. * Whether we did that or not, now we slam the connection
  565. * shut.
  566. */
  567. sshfwd_unclean_close(xconn->c, error_msg);
  568. } else {
  569. /*
  570. * Ordinary EOF received on socket. Send an EOF on the SSH
  571. * channel.
  572. */
  573. if (xconn->c)
  574. sshfwd_write_eof(xconn->c);
  575. }
  576. }
  577. static void x11_receive(Plug plug, int urgent, char *data, int len)
  578. {
  579. struct X11Connection *xconn = (struct X11Connection *) plug;
  580. if (sshfwd_write(xconn->c, data, len) > 0) {
  581. xconn->throttled = 1;
  582. xconn->no_data_sent_to_x_client = FALSE;
  583. sk_set_frozen(xconn->s, 1);
  584. }
  585. }
  586. static void x11_sent(Plug plug, int bufsize)
  587. {
  588. struct X11Connection *xconn = (struct X11Connection *) plug;
  589. sshfwd_unthrottle(xconn->c, bufsize);
  590. }
  591. /*
  592. * When setting up X forwarding, we should send the screen number
  593. * from the specified local display. This function extracts it from
  594. * the display string.
  595. */
  596. int x11_get_screen_number(char *display)
  597. {
  598. int n;
  599. n = host_strcspn(display, ":");
  600. if (!display[n])
  601. return 0;
  602. n = strcspn(display, ".");
  603. if (!display[n])
  604. return 0;
  605. return atoi(display + n + 1);
  606. }
  607. /*
  608. * Called to set up the X11Connection structure, though this does not
  609. * yet connect to an actual server.
  610. */
  611. struct X11Connection *x11_init(tree234 *authtree, void *c,
  612. const char *peeraddr, int peerport)
  613. {
  614. static const struct plug_function_table fn_table = {
  615. x11_log,
  616. x11_closing,
  617. x11_receive,
  618. x11_sent,
  619. NULL
  620. };
  621. struct X11Connection *xconn;
  622. /*
  623. * Open socket.
  624. */
  625. xconn = snew(struct X11Connection);
  626. xconn->fn = &fn_table;
  627. xconn->auth_protocol = NULL;
  628. xconn->authtree = authtree;
  629. xconn->verified = 0;
  630. xconn->data_read = 0;
  631. xconn->throttled = xconn->throttle_override = 0;
  632. xconn->no_data_sent_to_x_client = TRUE;
  633. xconn->c = c;
  634. /*
  635. * We don't actually open a local socket to the X server just yet,
  636. * because we don't know which one it is. Instead, we'll wait
  637. * until we see the incoming authentication data, which may tell
  638. * us what display to connect to, or whether we have to divert
  639. * this X forwarding channel to a connection-sharing downstream
  640. * rather than handling it ourself.
  641. */
  642. xconn->disp = NULL;
  643. xconn->s = NULL;
  644. /*
  645. * Stash the peer address we were given in its original text form.
  646. */
  647. xconn->peer_addr = peeraddr ? dupstr(peeraddr) : NULL;
  648. xconn->peer_port = peerport;
  649. return xconn;
  650. }
  651. void x11_close(struct X11Connection *xconn)
  652. {
  653. if (!xconn)
  654. return;
  655. if (xconn->auth_protocol) {
  656. sfree(xconn->auth_protocol);
  657. sfree(xconn->auth_data);
  658. }
  659. if (xconn->s)
  660. sk_close(xconn->s);
  661. sfree(xconn->peer_addr);
  662. sfree(xconn);
  663. }
  664. void x11_unthrottle(struct X11Connection *xconn)
  665. {
  666. if (!xconn)
  667. return;
  668. xconn->throttled = 0;
  669. if (xconn->s)
  670. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  671. }
  672. void x11_override_throttle(struct X11Connection *xconn, int enable)
  673. {
  674. if (!xconn)
  675. return;
  676. xconn->throttle_override = enable;
  677. if (xconn->s)
  678. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  679. }
  680. static void x11_send_init_error(struct X11Connection *xconn,
  681. const char *err_message)
  682. {
  683. char *full_message;
  684. int msglen, msgsize;
  685. unsigned char *reply;
  686. full_message = dupprintf("%s X11 proxy: %s\n", appname, err_message);
  687. msglen = strlen(full_message);
  688. reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
  689. msgsize = (msglen + 3) & ~3;
  690. reply[0] = 0; /* failure */
  691. reply[1] = msglen; /* length of reason string */
  692. memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */
  693. PUT_16BIT(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
  694. memset(reply + 8, 0, msgsize);
  695. memcpy(reply + 8, full_message, msglen);
  696. sshfwd_write(xconn->c, (char *)reply, 8 + msgsize);
  697. sshfwd_write_eof(xconn->c);
  698. xconn->no_data_sent_to_x_client = FALSE;
  699. sfree(reply);
  700. sfree(full_message);
  701. }
  702. static int x11_parse_ip(const char *addr_string, unsigned long *ip)
  703. {
  704. /*
  705. * See if we can make sense of this string as an IPv4 address, for
  706. * XDM-AUTHORIZATION-1 purposes.
  707. */
  708. int i[4];
  709. if (addr_string &&
  710. 4 == sscanf(addr_string, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
  711. *ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
  712. return TRUE;
  713. } else {
  714. return FALSE;
  715. }
  716. }
  717. /*
  718. * Called to send data down the raw connection.
  719. */
  720. int x11_send(struct X11Connection *xconn, char *data, int len)
  721. {
  722. if (!xconn)
  723. return 0;
  724. /*
  725. * Read the first packet.
  726. */
  727. while (len > 0 && xconn->data_read < 12)
  728. xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++);
  729. if (xconn->data_read < 12)
  730. return 0;
  731. /*
  732. * If we have not allocated the auth_protocol and auth_data
  733. * strings, do so now.
  734. */
  735. if (!xconn->auth_protocol) {
  736. xconn->auth_plen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 6);
  737. xconn->auth_dlen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 8);
  738. xconn->auth_psize = (xconn->auth_plen + 3) & ~3;
  739. xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3;
  740. /* Leave room for a terminating zero, to make our lives easier. */
  741. xconn->auth_protocol = snewn(xconn->auth_psize + 1, char);
  742. xconn->auth_data = snewn(xconn->auth_dsize, unsigned char);
  743. }
  744. /*
  745. * Read the auth_protocol and auth_data strings.
  746. */
  747. while (len > 0 &&
  748. xconn->data_read < 12 + xconn->auth_psize)
  749. xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++);
  750. while (len > 0 &&
  751. xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  752. xconn->auth_data[xconn->data_read++ - 12 -
  753. xconn->auth_psize] = (unsigned char) (len--, *data++);
  754. if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  755. return 0;
  756. /*
  757. * If we haven't verified the authorisation, do so now.
  758. */
  759. if (!xconn->verified) {
  760. const char *err;
  761. struct X11FakeAuth *auth_matched = NULL;
  762. unsigned long peer_ip;
  763. int peer_port;
  764. int protomajor, protominor;
  765. void *greeting;
  766. int greeting_len;
  767. unsigned char *socketdata;
  768. int socketdatalen;
  769. char new_peer_addr[32];
  770. int new_peer_port;
  771. protomajor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 2);
  772. protominor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 4);
  773. assert(!xconn->s);
  774. xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */
  775. peer_ip = 0; /* placate optimiser */
  776. if (x11_parse_ip(xconn->peer_addr, &peer_ip))
  777. peer_port = xconn->peer_port;
  778. else
  779. peer_port = -1; /* signal no peer address data available */
  780. err = x11_verify(peer_ip, peer_port,
  781. xconn->authtree, xconn->auth_protocol,
  782. xconn->auth_data, xconn->auth_dlen, &auth_matched);
  783. if (err) {
  784. x11_send_init_error(xconn, err);
  785. return 0;
  786. }
  787. assert(auth_matched);
  788. /*
  789. * If this auth points to a connection-sharing downstream
  790. * rather than an X display we know how to connect to
  791. * directly, pass it off to the sharing module now.
  792. */
  793. if (auth_matched->share_cs) {
  794. sshfwd_x11_sharing_handover(xconn->c, auth_matched->share_cs,
  795. auth_matched->share_chan,
  796. xconn->peer_addr, xconn->peer_port,
  797. xconn->firstpkt[0],
  798. protomajor, protominor, data, len);
  799. return 0;
  800. }
  801. /*
  802. * Now we know we're going to accept the connection, and what
  803. * X display to connect to. Actually connect to it.
  804. */
  805. sshfwd_x11_is_local(xconn->c);
  806. xconn->disp = auth_matched->disp;
  807. xconn->s = new_connection(sk_addr_dup(xconn->disp->addr),
  808. xconn->disp->realhost, xconn->disp->port,
  809. 0, 1, 0, 0, (Plug) xconn,
  810. sshfwd_get_conf(xconn->c));
  811. if ((err = sk_socket_error(xconn->s)) != NULL) {
  812. char *err_message = dupprintf("unable to connect to"
  813. " forwarded X server: %s", err);
  814. x11_send_init_error(xconn, err_message);
  815. sfree(err_message);
  816. return 0;
  817. }
  818. /*
  819. * Write a new connection header containing our replacement
  820. * auth data.
  821. */
  822. socketdatalen = 0; /* placate compiler warning */
  823. socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
  824. if (socketdata && socketdatalen==6) {
  825. sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
  826. socketdata[1], socketdata[2], socketdata[3]);
  827. new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
  828. } else {
  829. strcpy(new_peer_addr, "0.0.0.0");
  830. new_peer_port = 0;
  831. }
  832. greeting = x11_make_greeting(xconn->firstpkt[0],
  833. protomajor, protominor,
  834. xconn->disp->localauthproto,
  835. xconn->disp->localauthdata,
  836. xconn->disp->localauthdatalen,
  837. new_peer_addr, new_peer_port,
  838. &greeting_len);
  839. sk_write(xconn->s, greeting, greeting_len);
  840. smemclr(greeting, greeting_len);
  841. sfree(greeting);
  842. /*
  843. * Now we're done.
  844. */
  845. xconn->verified = 1;
  846. }
  847. /*
  848. * After initialisation, just copy data simply.
  849. */
  850. return sk_write(xconn->s, data, len);
  851. }
  852. void x11_send_eof(struct X11Connection *xconn)
  853. {
  854. if (xconn->s) {
  855. sk_write_eof(xconn->s);
  856. } else {
  857. /*
  858. * If EOF is received from the X client before we've got to
  859. * the point of actually connecting to an X server, then we
  860. * should send an EOF back to the client so that the
  861. * forwarded channel will be terminated.
  862. */
  863. if (xconn->c)
  864. sshfwd_write_eof(xconn->c);
  865. }
  866. }
  867. /*
  868. * Utility functions used by connection sharing to convert textual
  869. * representations of an X11 auth protocol name + hex cookie into our
  870. * usual integer protocol id and binary auth data.
  871. */
  872. int x11_identify_auth_proto(const char *protoname)
  873. {
  874. int protocol;
  875. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  876. if (!strcmp(protoname, x11_authnames[protocol]))
  877. return protocol;
  878. return -1;
  879. }
  880. void *x11_dehexify(const char *hex, int *outlen)
  881. {
  882. int len, i;
  883. unsigned char *ret;
  884. len = strlen(hex) / 2;
  885. ret = snewn(len, unsigned char);
  886. for (i = 0; i < len; i++) {
  887. char bytestr[3];
  888. unsigned val = 0;
  889. bytestr[0] = hex[2*i];
  890. bytestr[1] = hex[2*i+1];
  891. bytestr[2] = '\0';
  892. sscanf(bytestr, "%x", &val);
  893. ret[i] = val;
  894. }
  895. *outlen = len;
  896. return ret;
  897. }
  898. /*
  899. * Construct an X11 greeting packet, including making up the right
  900. * authorisation data.
  901. */
  902. void *x11_make_greeting(int endian, int protomajor, int protominor,
  903. int auth_proto, const void *auth_data, int auth_len,
  904. const char *peer_addr, int peer_port,
  905. int *outlen)
  906. {
  907. unsigned char *greeting;
  908. unsigned char realauthdata[64];
  909. const char *authname;
  910. const unsigned char *authdata;
  911. int authnamelen, authnamelen_pad;
  912. int authdatalen, authdatalen_pad;
  913. int greeting_len;
  914. authname = x11_authnames[auth_proto];
  915. authnamelen = strlen(authname);
  916. authnamelen_pad = (authnamelen + 3) & ~3;
  917. if (auth_proto == X11_MIT) {
  918. authdata = auth_data;
  919. authdatalen = auth_len;
  920. } else if (auth_proto == X11_XDM && auth_len == 16) {
  921. time_t t;
  922. unsigned long peer_ip = 0;
  923. x11_parse_ip(peer_addr, &peer_ip);
  924. authdata = realauthdata;
  925. authdatalen = 24;
  926. memset(realauthdata, 0, authdatalen);
  927. memcpy(realauthdata, auth_data, 8);
  928. PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
  929. PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
  930. t = time(NULL);
  931. PUT_32BIT_MSB_FIRST(realauthdata+14, t);
  932. des_encrypt_xdmauth((const unsigned char *)auth_data + 9,
  933. realauthdata, authdatalen);
  934. } else {
  935. authdata = realauthdata;
  936. authdatalen = 0;
  937. }
  938. authdatalen_pad = (authdatalen + 3) & ~3;
  939. greeting_len = 12 + authnamelen_pad + authdatalen_pad;
  940. greeting = snewn(greeting_len, unsigned char);
  941. memset(greeting, 0, greeting_len);
  942. greeting[0] = endian;
  943. PUT_16BIT(endian, greeting+2, protomajor);
  944. PUT_16BIT(endian, greeting+4, protominor);
  945. PUT_16BIT(endian, greeting+6, authnamelen);
  946. PUT_16BIT(endian, greeting+8, authdatalen);
  947. memcpy(greeting+12, authname, authnamelen);
  948. memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
  949. smemclr(realauthdata, sizeof(realauthdata));
  950. *outlen = greeting_len;
  951. return greeting;
  952. }