x11fwd.c 38 KB

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