x11fwd.c 34 KB

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