x11fwd.c 36 KB

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