x11fwd.c 36 KB

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