x11fwd.c 36 KB

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