x11fwd.c 40 KB

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