x11fwd.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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(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. if ((err = sk_addr_error(disp->addr)) != NULL) {
  251. sk_addr_free(disp->addr);
  252. sfree(disp->hostname);
  253. sfree(disp->unixsocketpath);
  254. sfree(disp);
  255. return NULL; /* FIXME: report an error */
  256. }
  257. }
  258. /*
  259. * Try upgrading an IP-style localhost display to a Unix-socket
  260. * display (as the standard X connection libraries do).
  261. */
  262. if (!disp->unixdomain && sk_address_is_local(disp->addr)) {
  263. SockAddr ux = platform_get_x11_unix_address(NULL, disp->displaynum);
  264. const char *err = sk_addr_error(ux);
  265. if (!err) {
  266. /* Create trial connection to see if there is a useful Unix-domain
  267. * socket */
  268. const struct plug_function_table *dummy = &dummy_plug;
  269. Socket s = sk_new(sk_addr_dup(ux), 0, 0, 0, 0, 0, (Plug)&dummy,
  270. #ifdef MPEXT
  271. 0, 0
  272. #endif
  273. );
  274. err = sk_socket_error(s);
  275. sk_close(s);
  276. }
  277. if (err) {
  278. sk_addr_free(ux);
  279. } else {
  280. sk_addr_free(disp->addr);
  281. disp->unixdomain = TRUE;
  282. disp->addr = ux;
  283. /* Fill in the rest in a moment */
  284. }
  285. }
  286. if (disp->unixdomain) {
  287. if (!disp->addr)
  288. disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
  289. disp->displaynum);
  290. if (disp->unixsocketpath)
  291. disp->realhost = dupstr(disp->unixsocketpath);
  292. else
  293. disp->realhost = dupprintf("unix:%d", disp->displaynum);
  294. disp->port = 0;
  295. }
  296. /*
  297. * Fetch the local authorisation details.
  298. */
  299. disp->localauthproto = X11_NO_AUTH;
  300. disp->localauthdata = NULL;
  301. disp->localauthdatalen = 0;
  302. platform_get_x11_auth(disp, conf);
  303. return disp;
  304. }
  305. void x11_free_display(struct X11Display *disp)
  306. {
  307. sfree(disp->hostname);
  308. sfree(disp->unixsocketpath);
  309. if (disp->localauthdata)
  310. smemclr(disp->localauthdata, disp->localauthdatalen);
  311. sfree(disp->localauthdata);
  312. sk_addr_free(disp->addr);
  313. sfree(disp);
  314. }
  315. #define XDM_MAXSKEW 20*60 /* 20 minute clock skew should be OK */
  316. static char *x11_verify(unsigned long peer_ip, int peer_port,
  317. tree234 *authtree, char *proto,
  318. unsigned char *data, int dlen,
  319. struct X11FakeAuth **auth_ret)
  320. {
  321. struct X11FakeAuth match_dummy; /* for passing to find234 */
  322. struct X11FakeAuth *auth;
  323. /*
  324. * First, do a lookup in our tree to find the only authorisation
  325. * record that _might_ match.
  326. */
  327. if (!strcmp(proto, x11_authnames[X11_MIT])) {
  328. /*
  329. * Just look up the whole cookie that was presented to us,
  330. * which x11_authcmp will compare against the cookies we
  331. * currently believe in.
  332. */
  333. match_dummy.proto = X11_MIT;
  334. match_dummy.datalen = dlen;
  335. match_dummy.data = data;
  336. } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
  337. /*
  338. * Look up the first cipher block, against the stored first
  339. * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
  340. * currently know. (See comment in x11_invent_fake_auth.)
  341. */
  342. match_dummy.proto = X11_XDM;
  343. match_dummy.xa1_firstblock = data;
  344. } else {
  345. return "Unsupported authorisation protocol";
  346. }
  347. if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
  348. return "Authorisation not recognised";
  349. /*
  350. * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
  351. * we're doing XDM-AUTHORIZATION-1, though, we have to check the
  352. * rest of the auth data.
  353. */
  354. if (auth->proto == X11_XDM) {
  355. unsigned long t;
  356. time_t tim;
  357. int i;
  358. struct XDMSeen *seen, *ret;
  359. if (dlen != 24)
  360. return "XDM-AUTHORIZATION-1 data was wrong length";
  361. if (peer_port == -1)
  362. return "cannot do XDM-AUTHORIZATION-1 without remote address data";
  363. des_decrypt_xdmauth(auth->data+9, data, 24);
  364. if (memcmp(auth->data, data, 8) != 0)
  365. return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
  366. if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
  367. return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */
  368. if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
  369. return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */
  370. t = GET_32BIT_MSB_FIRST(data+14);
  371. for (i = 18; i < 24; i++)
  372. if (data[i] != 0) /* zero padding wrong */
  373. return "XDM-AUTHORIZATION-1 data failed check";
  374. tim = time(NULL);
  375. if (abs(t - tim) > 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 int 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. return 1;
  581. }
  582. static int x11_receive(Plug plug, int urgent, char *data, int len)
  583. {
  584. struct X11Connection *xconn = (struct X11Connection *) plug;
  585. if (sshfwd_write(xconn->c, data, len) > 0) {
  586. xconn->throttled = 1;
  587. xconn->no_data_sent_to_x_client = FALSE;
  588. sk_set_frozen(xconn->s, 1);
  589. }
  590. return 1;
  591. }
  592. static void x11_sent(Plug plug, int bufsize)
  593. {
  594. struct X11Connection *xconn = (struct X11Connection *) plug;
  595. sshfwd_unthrottle(xconn->c, bufsize);
  596. }
  597. /*
  598. * When setting up X forwarding, we should send the screen number
  599. * from the specified local display. This function extracts it from
  600. * the display string.
  601. */
  602. int x11_get_screen_number(char *display)
  603. {
  604. int n;
  605. n = host_strcspn(display, ":");
  606. if (!display[n])
  607. return 0;
  608. n = strcspn(display, ".");
  609. if (!display[n])
  610. return 0;
  611. return atoi(display + n + 1);
  612. }
  613. /*
  614. * Called to set up the X11Connection structure, though this does not
  615. * yet connect to an actual server.
  616. */
  617. struct X11Connection *x11_init(tree234 *authtree, void *c,
  618. const char *peeraddr, int peerport)
  619. {
  620. static const struct plug_function_table fn_table = {
  621. x11_log,
  622. x11_closing,
  623. x11_receive,
  624. x11_sent,
  625. NULL
  626. };
  627. struct X11Connection *xconn;
  628. /*
  629. * Open socket.
  630. */
  631. xconn = snew(struct X11Connection);
  632. xconn->fn = &fn_table;
  633. xconn->auth_protocol = NULL;
  634. xconn->authtree = authtree;
  635. xconn->verified = 0;
  636. xconn->data_read = 0;
  637. xconn->throttled = xconn->throttle_override = 0;
  638. xconn->no_data_sent_to_x_client = TRUE;
  639. xconn->c = c;
  640. /*
  641. * We don't actually open a local socket to the X server just yet,
  642. * because we don't know which one it is. Instead, we'll wait
  643. * until we see the incoming authentication data, which may tell
  644. * us what display to connect to, or whether we have to divert
  645. * this X forwarding channel to a connection-sharing downstream
  646. * rather than handling it ourself.
  647. */
  648. xconn->disp = NULL;
  649. xconn->s = NULL;
  650. /*
  651. * Stash the peer address we were given in its original text form.
  652. */
  653. xconn->peer_addr = peeraddr ? dupstr(peeraddr) : NULL;
  654. xconn->peer_port = peerport;
  655. return xconn;
  656. }
  657. void x11_close(struct X11Connection *xconn)
  658. {
  659. if (!xconn)
  660. return;
  661. if (xconn->auth_protocol) {
  662. sfree(xconn->auth_protocol);
  663. sfree(xconn->auth_data);
  664. }
  665. if (xconn->s)
  666. sk_close(xconn->s);
  667. sfree(xconn->peer_addr);
  668. sfree(xconn);
  669. }
  670. void x11_unthrottle(struct X11Connection *xconn)
  671. {
  672. if (!xconn)
  673. return;
  674. xconn->throttled = 0;
  675. if (xconn->s)
  676. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  677. }
  678. void x11_override_throttle(struct X11Connection *xconn, int enable)
  679. {
  680. if (!xconn)
  681. return;
  682. xconn->throttle_override = enable;
  683. if (xconn->s)
  684. sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
  685. }
  686. static void x11_send_init_error(struct X11Connection *xconn,
  687. const char *err_message)
  688. {
  689. char *full_message;
  690. int msglen, msgsize;
  691. unsigned char *reply;
  692. full_message = dupprintf("%s X11 proxy: %s\n", appname, err_message);
  693. msglen = strlen(full_message);
  694. reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
  695. msgsize = (msglen + 3) & ~3;
  696. reply[0] = 0; /* failure */
  697. reply[1] = msglen; /* length of reason string */
  698. memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */
  699. PUT_16BIT(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
  700. memset(reply + 8, 0, msgsize);
  701. memcpy(reply + 8, full_message, msglen);
  702. sshfwd_write(xconn->c, (char *)reply, 8 + msgsize);
  703. sshfwd_write_eof(xconn->c);
  704. xconn->no_data_sent_to_x_client = FALSE;
  705. sfree(reply);
  706. sfree(full_message);
  707. }
  708. static int x11_parse_ip(const char *addr_string, unsigned long *ip)
  709. {
  710. /*
  711. * See if we can make sense of this string as an IPv4 address, for
  712. * XDM-AUTHORIZATION-1 purposes.
  713. */
  714. int i[4];
  715. if (addr_string &&
  716. 4 == sscanf(addr_string, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
  717. *ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
  718. return TRUE;
  719. } else {
  720. return FALSE;
  721. }
  722. }
  723. /*
  724. * Called to send data down the raw connection.
  725. */
  726. int x11_send(struct X11Connection *xconn, char *data, int len)
  727. {
  728. if (!xconn)
  729. return 0;
  730. /*
  731. * Read the first packet.
  732. */
  733. while (len > 0 && xconn->data_read < 12)
  734. xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++);
  735. if (xconn->data_read < 12)
  736. return 0;
  737. /*
  738. * If we have not allocated the auth_protocol and auth_data
  739. * strings, do so now.
  740. */
  741. if (!xconn->auth_protocol) {
  742. xconn->auth_plen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 6);
  743. xconn->auth_dlen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 8);
  744. xconn->auth_psize = (xconn->auth_plen + 3) & ~3;
  745. xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3;
  746. /* Leave room for a terminating zero, to make our lives easier. */
  747. xconn->auth_protocol = snewn(xconn->auth_psize + 1, char);
  748. xconn->auth_data = snewn(xconn->auth_dsize, unsigned char);
  749. }
  750. /*
  751. * Read the auth_protocol and auth_data strings.
  752. */
  753. while (len > 0 &&
  754. xconn->data_read < 12 + xconn->auth_psize)
  755. xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++);
  756. while (len > 0 &&
  757. xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  758. xconn->auth_data[xconn->data_read++ - 12 -
  759. xconn->auth_psize] = (unsigned char) (len--, *data++);
  760. if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
  761. return 0;
  762. /*
  763. * If we haven't verified the authorisation, do so now.
  764. */
  765. if (!xconn->verified) {
  766. const char *err;
  767. struct X11FakeAuth *auth_matched = NULL;
  768. unsigned long peer_ip;
  769. int peer_port;
  770. int protomajor, protominor;
  771. void *greeting;
  772. int greeting_len;
  773. unsigned char *socketdata;
  774. int socketdatalen;
  775. char new_peer_addr[32];
  776. int new_peer_port;
  777. protomajor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 2);
  778. protominor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 4);
  779. assert(!xconn->s);
  780. xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */
  781. peer_ip = 0; /* placate optimiser */
  782. if (x11_parse_ip(xconn->peer_addr, &peer_ip))
  783. peer_port = xconn->peer_port;
  784. else
  785. peer_port = -1; /* signal no peer address data available */
  786. err = x11_verify(peer_ip, peer_port,
  787. xconn->authtree, xconn->auth_protocol,
  788. xconn->auth_data, xconn->auth_dlen, &auth_matched);
  789. if (err) {
  790. x11_send_init_error(xconn, err);
  791. return 0;
  792. }
  793. assert(auth_matched);
  794. /*
  795. * If this auth points to a connection-sharing downstream
  796. * rather than an X display we know how to connect to
  797. * directly, pass it off to the sharing module now.
  798. */
  799. if (auth_matched->share_cs) {
  800. sshfwd_x11_sharing_handover(xconn->c, auth_matched->share_cs,
  801. auth_matched->share_chan,
  802. xconn->peer_addr, xconn->peer_port,
  803. xconn->firstpkt[0],
  804. protomajor, protominor, data, len);
  805. return 0;
  806. }
  807. /*
  808. * Now we know we're going to accept the connection, and what
  809. * X display to connect to. Actually connect to it.
  810. */
  811. sshfwd_x11_is_local(xconn->c);
  812. xconn->disp = auth_matched->disp;
  813. xconn->s = new_connection(sk_addr_dup(xconn->disp->addr),
  814. xconn->disp->realhost, xconn->disp->port,
  815. 0, 1, 0, 0, (Plug) xconn,
  816. sshfwd_get_conf(xconn->c));
  817. if ((err = sk_socket_error(xconn->s)) != NULL) {
  818. char *err_message = dupprintf("unable to connect to"
  819. " forwarded X server: %s", err);
  820. x11_send_init_error(xconn, err_message);
  821. sfree(err_message);
  822. return 0;
  823. }
  824. /*
  825. * Write a new connection header containing our replacement
  826. * auth data.
  827. */
  828. #ifdef MPEXT
  829. // placate compiler warning
  830. socketdatalen = 0;
  831. #endif
  832. socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
  833. if (socketdata && socketdatalen==6) {
  834. sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
  835. socketdata[1], socketdata[2], socketdata[3]);
  836. new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
  837. } else {
  838. strcpy(new_peer_addr, "0.0.0.0");
  839. new_peer_port = 0;
  840. }
  841. greeting = x11_make_greeting(xconn->firstpkt[0],
  842. protomajor, protominor,
  843. xconn->disp->localauthproto,
  844. xconn->disp->localauthdata,
  845. xconn->disp->localauthdatalen,
  846. new_peer_addr, new_peer_port,
  847. &greeting_len);
  848. sk_write(xconn->s, greeting, greeting_len);
  849. smemclr(greeting, greeting_len);
  850. sfree(greeting);
  851. /*
  852. * Now we're done.
  853. */
  854. xconn->verified = 1;
  855. }
  856. /*
  857. * After initialisation, just copy data simply.
  858. */
  859. return sk_write(xconn->s, data, len);
  860. }
  861. void x11_send_eof(struct X11Connection *xconn)
  862. {
  863. if (xconn->s) {
  864. sk_write_eof(xconn->s);
  865. } else {
  866. /*
  867. * If EOF is received from the X client before we've got to
  868. * the point of actually connecting to an X server, then we
  869. * should send an EOF back to the client so that the
  870. * forwarded channel will be terminated.
  871. */
  872. if (xconn->c)
  873. sshfwd_write_eof(xconn->c);
  874. }
  875. }
  876. /*
  877. * Utility functions used by connection sharing to convert textual
  878. * representations of an X11 auth protocol name + hex cookie into our
  879. * usual integer protocol id and binary auth data.
  880. */
  881. int x11_identify_auth_proto(const char *protoname)
  882. {
  883. int protocol;
  884. for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
  885. if (!strcmp(protoname, x11_authnames[protocol]))
  886. return protocol;
  887. return -1;
  888. }
  889. void *x11_dehexify(const char *hex, int *outlen)
  890. {
  891. int len, i;
  892. unsigned char *ret;
  893. len = strlen(hex) / 2;
  894. ret = snewn(len, unsigned char);
  895. for (i = 0; i < len; i++) {
  896. char bytestr[3];
  897. unsigned val = 0;
  898. bytestr[0] = hex[2*i];
  899. bytestr[1] = hex[2*i+1];
  900. bytestr[2] = '\0';
  901. sscanf(bytestr, "%x", &val);
  902. ret[i] = val;
  903. }
  904. *outlen = len;
  905. return ret;
  906. }
  907. /*
  908. * Construct an X11 greeting packet, including making up the right
  909. * authorisation data.
  910. */
  911. void *x11_make_greeting(int endian, int protomajor, int protominor,
  912. int auth_proto, const void *auth_data, int auth_len,
  913. const char *peer_addr, int peer_port,
  914. int *outlen)
  915. {
  916. unsigned char *greeting;
  917. unsigned char realauthdata[64];
  918. const char *authname;
  919. const unsigned char *authdata;
  920. int authnamelen, authnamelen_pad;
  921. int authdatalen, authdatalen_pad;
  922. int greeting_len;
  923. authname = x11_authnames[auth_proto];
  924. authnamelen = strlen(authname);
  925. authnamelen_pad = (authnamelen + 3) & ~3;
  926. if (auth_proto == X11_MIT) {
  927. authdata = auth_data;
  928. authdatalen = auth_len;
  929. } else if (auth_proto == X11_XDM && auth_len == 16) {
  930. time_t t;
  931. unsigned long peer_ip = 0;
  932. x11_parse_ip(peer_addr, &peer_ip);
  933. authdata = realauthdata;
  934. authdatalen = 24;
  935. memset(realauthdata, 0, authdatalen);
  936. memcpy(realauthdata, auth_data, 8);
  937. PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
  938. PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
  939. t = time(NULL);
  940. PUT_32BIT_MSB_FIRST(realauthdata+14, t);
  941. des_encrypt_xdmauth((const unsigned char *)auth_data + 9,
  942. realauthdata, authdatalen);
  943. } else {
  944. authdata = realauthdata;
  945. authdatalen = 0;
  946. }
  947. authdatalen_pad = (authdatalen + 3) & ~3;
  948. greeting_len = 12 + authnamelen_pad + authdatalen_pad;
  949. greeting = snewn(greeting_len, unsigned char);
  950. memset(greeting, 0, greeting_len);
  951. greeting[0] = endian;
  952. PUT_16BIT(endian, greeting+2, protomajor);
  953. PUT_16BIT(endian, greeting+4, protominor);
  954. PUT_16BIT(endian, greeting+6, authnamelen);
  955. PUT_16BIT(endian, greeting+8, authdatalen);
  956. memcpy(greeting+12, authname, authnamelen);
  957. memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
  958. smemclr(realauthdata, sizeof(realauthdata));
  959. *outlen = greeting_len;
  960. return greeting;
  961. }