You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SConnection.cxx 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2011-2019 Pierre Ossman for Cendio AB
  3. *
  4. * This is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this software; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  17. * USA.
  18. */
  19. #ifdef HAVE_CONFIG_H
  20. #include <config.h>
  21. #endif
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <rfb/Exception.h>
  25. #include <rfb/Security.h>
  26. #include <rfb/clipboardTypes.h>
  27. #include <rfb/msgTypes.h>
  28. #include <rfb/fenceTypes.h>
  29. #include <rfb/SMsgReader.h>
  30. #include <rfb/SMsgWriter.h>
  31. #include <rfb/SConnection.h>
  32. #include <rfb/ServerCore.h>
  33. #include <rfb/encodings.h>
  34. #include <rfb/EncodeManager.h>
  35. #include <rfb/SSecurity.h>
  36. #include <rfb/LogWriter.h>
  37. using namespace rfb;
  38. static LogWriter vlog("SConnection");
  39. // AccessRights values
  40. const SConnection::AccessRights SConnection::AccessView = 0x0001;
  41. const SConnection::AccessRights SConnection::AccessKeyEvents = 0x0002;
  42. const SConnection::AccessRights SConnection::AccessPtrEvents = 0x0004;
  43. const SConnection::AccessRights SConnection::AccessCutText = 0x0008;
  44. const SConnection::AccessRights SConnection::AccessSetDesktopSize = 0x0010;
  45. const SConnection::AccessRights SConnection::AccessNonShared = 0x0020;
  46. const SConnection::AccessRights SConnection::AccessDefault = 0x03ff;
  47. const SConnection::AccessRights SConnection::AccessNoQuery = 0x0400;
  48. const SConnection::AccessRights SConnection::AccessFull = 0xffff;
  49. SConnection::SConnection()
  50. : readyForSetColourMapEntries(false),
  51. is(0), os(0), reader_(0), writer_(0), ssecurity(0),
  52. authFailureTimer(this, &SConnection::handleAuthFailureTimeout),
  53. state_(RFBSTATE_UNINITIALISED), preferredEncoding(encodingRaw),
  54. clientClipboard(NULL), hasLocalClipboard(false),
  55. unsolicitedClipboardAttempt(false)
  56. {
  57. defaultMajorVersion = 3;
  58. defaultMinorVersion = 8;
  59. if (rfb::Server::protocol3_3)
  60. defaultMinorVersion = 3;
  61. client.setVersion(defaultMajorVersion, defaultMinorVersion);
  62. }
  63. SConnection::~SConnection()
  64. {
  65. cleanup();
  66. }
  67. void SConnection::setStreams(rdr::InStream* is_, rdr::OutStream* os_)
  68. {
  69. is = is_;
  70. os = os_;
  71. }
  72. void SConnection::initialiseProtocol()
  73. {
  74. char str[13];
  75. sprintf(str, "RFB %03d.%03d\n", defaultMajorVersion, defaultMinorVersion);
  76. os->writeBytes(str, 12);
  77. os->flush();
  78. state_ = RFBSTATE_PROTOCOL_VERSION;
  79. }
  80. bool SConnection::processMsg()
  81. {
  82. switch (state_) {
  83. case RFBSTATE_PROTOCOL_VERSION: return processVersionMsg(); break;
  84. case RFBSTATE_SECURITY_TYPE: return processSecurityTypeMsg(); break;
  85. case RFBSTATE_SECURITY: return processSecurityMsg(); break;
  86. case RFBSTATE_SECURITY_FAILURE: return processSecurityFailure(); break;
  87. case RFBSTATE_INITIALISATION: return processInitMsg(); break;
  88. case RFBSTATE_NORMAL: return reader_->readMsg(); break;
  89. case RFBSTATE_QUERYING:
  90. throw Exception("SConnection::processMsg: bogus data from client while "
  91. "querying");
  92. case RFBSTATE_CLOSING:
  93. throw Exception("SConnection::processMsg: called while closing");
  94. case RFBSTATE_UNINITIALISED:
  95. throw Exception("SConnection::processMsg: not initialised yet?");
  96. default:
  97. throw Exception("SConnection::processMsg: invalid state");
  98. }
  99. }
  100. bool SConnection::processVersionMsg()
  101. {
  102. char verStr[13];
  103. int majorVersion;
  104. int minorVersion;
  105. vlog.debug("reading protocol version");
  106. if (!is->hasData(12))
  107. return false;
  108. is->readBytes(verStr, 12);
  109. verStr[12] = '\0';
  110. if (sscanf(verStr, "RFB %03d.%03d\n",
  111. &majorVersion, &minorVersion) != 2) {
  112. state_ = RFBSTATE_INVALID;
  113. throw Exception("reading version failed: not an RFB client?");
  114. }
  115. client.setVersion(majorVersion, minorVersion);
  116. vlog.info("Client needs protocol version %d.%d",
  117. client.majorVersion, client.minorVersion);
  118. if (client.majorVersion != 3) {
  119. // unknown protocol version
  120. throwConnFailedException("Client needs protocol version %d.%d, server has %d.%d",
  121. client.majorVersion, client.minorVersion,
  122. defaultMajorVersion, defaultMinorVersion);
  123. }
  124. if (client.minorVersion != 3 && client.minorVersion != 7 && client.minorVersion != 8) {
  125. vlog.error("Client uses unofficial protocol version %d.%d",
  126. client.majorVersion,client.minorVersion);
  127. if (client.minorVersion >= 8)
  128. client.minorVersion = 8;
  129. else if (client.minorVersion == 7)
  130. client.minorVersion = 7;
  131. else
  132. client.minorVersion = 3;
  133. vlog.error("Assuming compatibility with version %d.%d",
  134. client.majorVersion,client.minorVersion);
  135. }
  136. versionReceived();
  137. std::list<rdr::U8> secTypes;
  138. std::list<rdr::U8>::iterator i;
  139. secTypes = security.GetEnabledSecTypes();
  140. if (client.isVersion(3,3)) {
  141. // cope with legacy 3.3 client only if "no authentication" or "vnc
  142. // authentication" is supported.
  143. for (i=secTypes.begin(); i!=secTypes.end(); i++) {
  144. if (*i == secTypeNone || *i == secTypeVncAuth) break;
  145. }
  146. if (i == secTypes.end()) {
  147. throwConnFailedException("No supported security type for %d.%d client",
  148. client.majorVersion, client.minorVersion);
  149. }
  150. os->writeU32(*i);
  151. if (*i == secTypeNone) os->flush();
  152. state_ = RFBSTATE_SECURITY;
  153. ssecurity = security.GetSSecurity(this, *i);
  154. return true;
  155. }
  156. // list supported security types for >=3.7 clients
  157. if (secTypes.empty())
  158. throwConnFailedException("No supported security types");
  159. os->writeU8(secTypes.size());
  160. for (i=secTypes.begin(); i!=secTypes.end(); i++)
  161. os->writeU8(*i);
  162. os->flush();
  163. state_ = RFBSTATE_SECURITY_TYPE;
  164. return true;
  165. }
  166. bool SConnection::processSecurityTypeMsg()
  167. {
  168. vlog.debug("processing security type message");
  169. if (!is->hasData(1))
  170. return false;
  171. int secType = is->readU8();
  172. processSecurityType(secType);
  173. return true;
  174. }
  175. void SConnection::processSecurityType(int secType)
  176. {
  177. // Verify that the requested security type should be offered
  178. std::list<rdr::U8> secTypes;
  179. std::list<rdr::U8>::iterator i;
  180. secTypes = security.GetEnabledSecTypes();
  181. for (i=secTypes.begin(); i!=secTypes.end(); i++)
  182. if (*i == secType) break;
  183. if (i == secTypes.end())
  184. throw Exception("Requested security type not available");
  185. vlog.info("Client requests security type %s(%d)",
  186. secTypeName(secType),secType);
  187. try {
  188. state_ = RFBSTATE_SECURITY;
  189. ssecurity = security.GetSSecurity(this, secType);
  190. } catch (rdr::Exception& e) {
  191. throwConnFailedException("%s", e.str());
  192. }
  193. }
  194. bool SConnection::processSecurityMsg()
  195. {
  196. vlog.debug("processing security message");
  197. try {
  198. if (!ssecurity->processMsg())
  199. return false;
  200. } catch (AuthFailureException& e) {
  201. vlog.error("AuthFailureException: %s", e.str());
  202. state_ = RFBSTATE_SECURITY_FAILURE;
  203. // Introduce a slight delay of the authentication failure response
  204. // to make it difficult to brute force a password
  205. authFailureMsg.replaceBuf(strDup(e.str()));
  206. authFailureTimer.start(100);
  207. return true;
  208. }
  209. state_ = RFBSTATE_QUERYING;
  210. setAccessRights(ssecurity->getAccessRights());
  211. queryConnection(ssecurity->getUserName());
  212. // If the connection got approved right away then we can continue
  213. if (state_ == RFBSTATE_INITIALISATION)
  214. return true;
  215. // Otherwise we need to wait for the result
  216. // (or give up if if was rejected)
  217. return false;
  218. }
  219. bool SConnection::processSecurityFailure()
  220. {
  221. // Silently drop any data if we are currently delaying an
  222. // authentication failure response as otherwise we would close
  223. // the connection on unexpected data, and an attacker could use
  224. // that to detect our delayed state.
  225. if (!is->hasData(1))
  226. return false;
  227. is->skip(is->avail());
  228. return true;
  229. }
  230. bool SConnection::processInitMsg()
  231. {
  232. vlog.debug("reading client initialisation");
  233. return reader_->readClientInit();
  234. }
  235. bool SConnection::handleAuthFailureTimeout(Timer* t)
  236. {
  237. if (state_ != RFBSTATE_SECURITY_FAILURE) {
  238. close("SConnection::handleAuthFailureTimeout: invalid state");
  239. return false;
  240. }
  241. try {
  242. os->writeU32(secResultFailed);
  243. if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
  244. const char* reason = authFailureMsg.buf;
  245. os->writeU32(strlen(reason));
  246. os->writeBytes(reason, strlen(reason));
  247. }
  248. os->flush();
  249. } catch (rdr::Exception& e) {
  250. close(e.str());
  251. return false;
  252. }
  253. close(authFailureMsg.buf);
  254. return false;
  255. }
  256. void SConnection::throwConnFailedException(const char* format, ...)
  257. {
  258. va_list ap;
  259. char str[256];
  260. va_start(ap, format);
  261. (void) vsnprintf(str, sizeof(str), format, ap);
  262. va_end(ap);
  263. vlog.info("Connection failed: %s", str);
  264. if (state_ == RFBSTATE_PROTOCOL_VERSION) {
  265. if (client.majorVersion == 3 && client.minorVersion == 3) {
  266. os->writeU32(0);
  267. os->writeU32(strlen(str));
  268. os->writeBytes(str, strlen(str));
  269. os->flush();
  270. } else {
  271. os->writeU8(0);
  272. os->writeU32(strlen(str));
  273. os->writeBytes(str, strlen(str));
  274. os->flush();
  275. }
  276. }
  277. state_ = RFBSTATE_INVALID;
  278. throw ConnFailedException(str);
  279. }
  280. void SConnection::setAccessRights(AccessRights ar)
  281. {
  282. accessRights = ar;
  283. }
  284. bool SConnection::accessCheck(AccessRights ar) const
  285. {
  286. return (accessRights & ar) == ar;
  287. }
  288. void SConnection::setEncodings(int nEncodings, const rdr::S32* encodings)
  289. {
  290. int i;
  291. preferredEncoding = encodingRaw;
  292. for (i = 0;i < nEncodings;i++) {
  293. if (EncodeManager::supported(encodings[i])) {
  294. preferredEncoding = encodings[i];
  295. break;
  296. }
  297. }
  298. SMsgHandler::setEncodings(nEncodings, encodings);
  299. if (client.supportsEncoding(pseudoEncodingExtendedClipboard)) {
  300. rdr::U32 sizes[] = { 0 };
  301. writer()->writeClipboardCaps(rfb::clipboardUTF8 |
  302. rfb::clipboardRequest |
  303. rfb::clipboardPeek |
  304. rfb::clipboardNotify |
  305. rfb::clipboardProvide,
  306. sizes);
  307. }
  308. }
  309. void SConnection::clientCutText(const char* str)
  310. {
  311. hasLocalClipboard = false;
  312. strFree(clientClipboard);
  313. clientClipboard = NULL;
  314. clientClipboard = latin1ToUTF8(str);
  315. handleClipboardAnnounce(true);
  316. }
  317. void SConnection::handleClipboardRequest(rdr::U32 flags)
  318. {
  319. if (!(flags & rfb::clipboardUTF8)) {
  320. vlog.debug("Ignoring clipboard request for unsupported formats 0x%x", flags);
  321. return;
  322. }
  323. if (!hasLocalClipboard) {
  324. vlog.debug("Ignoring unexpected clipboard request");
  325. return;
  326. }
  327. handleClipboardRequest();
  328. }
  329. void SConnection::handleClipboardPeek(rdr::U32 flags)
  330. {
  331. if (client.clipboardFlags() & rfb::clipboardNotify)
  332. writer()->writeClipboardNotify(hasLocalClipboard ? rfb::clipboardUTF8 : 0);
  333. }
  334. void SConnection::handleClipboardNotify(rdr::U32 flags)
  335. {
  336. strFree(clientClipboard);
  337. clientClipboard = NULL;
  338. if (flags & rfb::clipboardUTF8) {
  339. hasLocalClipboard = false;
  340. handleClipboardAnnounce(true);
  341. } else {
  342. handleClipboardAnnounce(false);
  343. }
  344. }
  345. void SConnection::handleClipboardProvide(rdr::U32 flags,
  346. const size_t* lengths,
  347. const rdr::U8* const* data)
  348. {
  349. if (!(flags & rfb::clipboardUTF8)) {
  350. vlog.debug("Ignoring clipboard provide with unsupported formats 0x%x", flags);
  351. return;
  352. }
  353. strFree(clientClipboard);
  354. clientClipboard = NULL;
  355. clientClipboard = convertLF((const char*)data[0], lengths[0]);
  356. // FIXME: Should probably verify that this data was actually requested
  357. handleClipboardData(clientClipboard);
  358. }
  359. void SConnection::supportsQEMUKeyEvent()
  360. {
  361. writer()->writeQEMUKeyEvent();
  362. }
  363. void SConnection::versionReceived()
  364. {
  365. }
  366. void SConnection::authSuccess()
  367. {
  368. }
  369. void SConnection::queryConnection(const char* userName)
  370. {
  371. approveConnection(true);
  372. }
  373. void SConnection::approveConnection(bool accept, const char* reason)
  374. {
  375. if (state_ != RFBSTATE_QUERYING)
  376. throw Exception("SConnection::approveConnection: invalid state");
  377. if (!client.beforeVersion(3,8) || ssecurity->getType() != secTypeNone) {
  378. if (accept) {
  379. os->writeU32(secResultOK);
  380. } else {
  381. os->writeU32(secResultFailed);
  382. if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
  383. if (!reason)
  384. reason = "Authentication failure";
  385. os->writeU32(strlen(reason));
  386. os->writeBytes(reason, strlen(reason));
  387. }
  388. }
  389. os->flush();
  390. }
  391. if (accept) {
  392. state_ = RFBSTATE_INITIALISATION;
  393. reader_ = new SMsgReader(this, is);
  394. writer_ = new SMsgWriter(&client, os);
  395. authSuccess();
  396. } else {
  397. state_ = RFBSTATE_INVALID;
  398. if (reason)
  399. throw AuthFailureException(reason);
  400. else
  401. throw AuthFailureException();
  402. }
  403. }
  404. void SConnection::clientInit(bool shared)
  405. {
  406. writer_->writeServerInit(client.width(), client.height(),
  407. client.pf(), client.name());
  408. state_ = RFBSTATE_NORMAL;
  409. }
  410. void SConnection::close(const char* reason)
  411. {
  412. state_ = RFBSTATE_CLOSING;
  413. cleanup();
  414. }
  415. void SConnection::setPixelFormat(const PixelFormat& pf)
  416. {
  417. SMsgHandler::setPixelFormat(pf);
  418. readyForSetColourMapEntries = true;
  419. if (!pf.trueColour)
  420. writeFakeColourMap();
  421. }
  422. void SConnection::framebufferUpdateRequest(const Rect& r, bool incremental)
  423. {
  424. if (!readyForSetColourMapEntries) {
  425. readyForSetColourMapEntries = true;
  426. if (!client.pf().trueColour) {
  427. writeFakeColourMap();
  428. }
  429. }
  430. }
  431. void SConnection::fence(rdr::U32 flags, unsigned len, const char data[])
  432. {
  433. if (!(flags & fenceFlagRequest))
  434. return;
  435. // We cannot guarantee any synchronisation at this level
  436. flags = 0;
  437. writer()->writeFence(flags, len, data);
  438. }
  439. void SConnection::enableContinuousUpdates(bool enable,
  440. int x, int y, int w, int h)
  441. {
  442. }
  443. void SConnection::handleClipboardRequest()
  444. {
  445. }
  446. void SConnection::handleClipboardAnnounce(bool available)
  447. {
  448. }
  449. void SConnection::handleClipboardData(const char* data)
  450. {
  451. }
  452. void SConnection::requestClipboard()
  453. {
  454. if (clientClipboard != NULL) {
  455. handleClipboardData(clientClipboard);
  456. return;
  457. }
  458. if (client.supportsEncoding(pseudoEncodingExtendedClipboard) &&
  459. (client.clipboardFlags() & rfb::clipboardRequest))
  460. writer()->writeClipboardRequest(rfb::clipboardUTF8);
  461. }
  462. void SConnection::announceClipboard(bool available)
  463. {
  464. hasLocalClipboard = available;
  465. unsolicitedClipboardAttempt = false;
  466. if (client.supportsEncoding(pseudoEncodingExtendedClipboard)) {
  467. // Attempt an unsolicited transfer?
  468. if (available &&
  469. (client.clipboardSize(rfb::clipboardUTF8) > 0) &&
  470. (client.clipboardFlags() & rfb::clipboardProvide)) {
  471. vlog.debug("Attempting unsolicited clipboard transfer...");
  472. unsolicitedClipboardAttempt = true;
  473. handleClipboardRequest();
  474. return;
  475. }
  476. if (client.clipboardFlags() & rfb::clipboardNotify) {
  477. writer()->writeClipboardNotify(available ? rfb::clipboardUTF8 : 0);
  478. return;
  479. }
  480. }
  481. if (available)
  482. handleClipboardRequest();
  483. }
  484. void SConnection::sendClipboardData(const char* data)
  485. {
  486. if (client.supportsEncoding(pseudoEncodingExtendedClipboard) &&
  487. (client.clipboardFlags() & rfb::clipboardProvide)) {
  488. CharArray filtered(convertCRLF(data));
  489. size_t sizes[1] = { strlen(filtered.buf) + 1 };
  490. const rdr::U8* data[1] = { (const rdr::U8*)filtered.buf };
  491. if (unsolicitedClipboardAttempt) {
  492. unsolicitedClipboardAttempt = false;
  493. if (sizes[0] > client.clipboardSize(rfb::clipboardUTF8)) {
  494. vlog.debug("Clipboard was too large for unsolicited clipboard transfer");
  495. if (client.clipboardFlags() & rfb::clipboardNotify)
  496. writer()->writeClipboardNotify(rfb::clipboardUTF8);
  497. return;
  498. }
  499. }
  500. writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data);
  501. } else {
  502. CharArray latin1(utf8ToLatin1(data));
  503. writer()->writeServerCutText(latin1.buf);
  504. }
  505. }
  506. void SConnection::cleanup()
  507. {
  508. delete ssecurity;
  509. ssecurity = NULL;
  510. delete reader_;
  511. reader_ = NULL;
  512. delete writer_;
  513. writer_ = NULL;
  514. strFree(clientClipboard);
  515. clientClipboard = NULL;
  516. }
  517. void SConnection::writeFakeColourMap(void)
  518. {
  519. int i;
  520. rdr::U16 red[256], green[256], blue[256];
  521. for (i = 0;i < 256;i++)
  522. client.pf().rgbFromPixel(i, &red[i], &green[i], &blue[i]);
  523. writer()->writeSetColourMapEntries(0, 256, red, green, blue);
  524. }