x11fwd.c 38 KB

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