x11fwd.c 38 KB

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