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

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