x11fwd.c 40 KB

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