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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 <assert.h>
  25. #include <rfb/Exception.h>
  26. #include <rfb/Security.h>
  27. #include <rfb/clipboardTypes.h>
  28. #include <rfb/msgTypes.h>
  29. #include <rfb/fenceTypes.h>
  30. #include <rfb/SMsgReader.h>
  31. #include <rfb/SMsgWriter.h>
  32. #include <rfb/SConnection.h>
  33. #include <rfb/ServerCore.h>
  34. #include <rfb/encodings.h>
  35. #include <rfb/EncodeManager.h>
  36. #include <rfb/SSecurity.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(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(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(authFailureMsg.data(), authFailureMsg.size());
  248. }
  249. os->flush();
  250. } catch (rdr::Exception& e) {
  251. close(e.str());
  252. return false;
  253. }
  254. close(authFailureMsg.c_str());
  255. return false;
  256. }
  257. void SConnection::throwConnFailedException(const char* format, ...)
  258. {
  259. va_list ap;
  260. char str[256];
  261. va_start(ap, format);
  262. (void) vsnprintf(str, sizeof(str), format, ap);
  263. va_end(ap);
  264. vlog.info("Connection failed: %s", str);
  265. if (state_ == RFBSTATE_PROTOCOL_VERSION) {
  266. if (client.majorVersion == 3 && client.minorVersion == 3) {
  267. os->writeU32(0);
  268. os->writeU32(strlen(str));
  269. os->writeBytes(str, strlen(str));
  270. os->flush();
  271. } else {
  272. os->writeU8(0);
  273. os->writeU32(strlen(str));
  274. os->writeBytes(str, strlen(str));
  275. os->flush();
  276. }
  277. }
  278. state_ = RFBSTATE_INVALID;
  279. throw ConnFailedException(str);
  280. }
  281. void SConnection::setAccessRights(AccessRights ar)
  282. {
  283. accessRights = ar;
  284. }
  285. bool SConnection::accessCheck(AccessRights ar) const
  286. {
  287. assert(state_ >= RFBSTATE_QUERYING);
  288. return (accessRights & ar) == ar;
  289. }
  290. void SConnection::setEncodings(int nEncodings, const int32_t* encodings)
  291. {
  292. int i;
  293. preferredEncoding = encodingRaw;
  294. for (i = 0;i < nEncodings;i++) {
  295. if (EncodeManager::supported(encodings[i])) {
  296. preferredEncoding = encodings[i];
  297. break;
  298. }
  299. }
  300. SMsgHandler::setEncodings(nEncodings, encodings);
  301. if (client.supportsEncoding(pseudoEncodingExtendedClipboard)) {
  302. uint32_t sizes[] = { 0 };
  303. writer()->writeClipboardCaps(rfb::clipboardUTF8 |
  304. rfb::clipboardRequest |
  305. rfb::clipboardPeek |
  306. rfb::clipboardNotify |
  307. rfb::clipboardProvide,
  308. sizes);
  309. }
  310. }
  311. void SConnection::clientCutText(const char* str)
  312. {
  313. hasLocalClipboard = false;
  314. clientClipboard = latin1ToUTF8(str);
  315. hasRemoteClipboard = true;
  316. handleClipboardAnnounce(true);
  317. }
  318. void SConnection::handleClipboardRequest(uint32_t flags)
  319. {
  320. if (!(flags & rfb::clipboardUTF8)) {
  321. vlog.debug("Ignoring clipboard request for unsupported formats 0x%x", flags);
  322. return;
  323. }
  324. if (!hasLocalClipboard) {
  325. vlog.debug("Ignoring unexpected clipboard request");
  326. return;
  327. }
  328. handleClipboardRequest();
  329. }
  330. void SConnection::handleClipboardPeek()
  331. {
  332. if (client.clipboardFlags() & rfb::clipboardNotify)
  333. writer()->writeClipboardNotify(hasLocalClipboard ? rfb::clipboardUTF8 : 0);
  334. }
  335. void SConnection::handleClipboardNotify(uint32_t flags)
  336. {
  337. hasRemoteClipboard = false;
  338. if (flags & rfb::clipboardUTF8) {
  339. hasLocalClipboard = false;
  340. handleClipboardAnnounce(true);
  341. } else {
  342. handleClipboardAnnounce(false);
  343. }
  344. }
  345. void SConnection::handleClipboardProvide(uint32_t flags,
  346. const size_t* lengths,
  347. const uint8_t* const* data)
  348. {
  349. if (!(flags & rfb::clipboardUTF8)) {
  350. vlog.debug("Ignoring clipboard provide with unsupported formats 0x%x", flags);
  351. return;
  352. }
  353. clientClipboard = convertLF((const char*)data[0], lengths[0]);
  354. hasRemoteClipboard = true;
  355. // FIXME: Should probably verify that this data was actually requested
  356. handleClipboardData(clientClipboard.c_str());
  357. }
  358. void SConnection::supportsQEMUKeyEvent()
  359. {
  360. writer()->writeQEMUKeyEvent();
  361. }
  362. void SConnection::versionReceived()
  363. {
  364. }
  365. void SConnection::authSuccess()
  366. {
  367. }
  368. void SConnection::queryConnection(const char* /*userName*/)
  369. {
  370. approveConnection(true);
  371. }
  372. void SConnection::approveConnection(bool accept, const char* reason)
  373. {
  374. if (state_ != RFBSTATE_QUERYING)
  375. throw Exception("SConnection::approveConnection: invalid state");
  376. if (!client.beforeVersion(3,8) || ssecurity->getType() != secTypeNone) {
  377. if (accept) {
  378. os->writeU32(secResultOK);
  379. } else {
  380. os->writeU32(secResultFailed);
  381. if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
  382. if (!reason)
  383. reason = "Authentication failure";
  384. os->writeU32(strlen(reason));
  385. os->writeBytes(reason, strlen(reason));
  386. }
  387. }
  388. os->flush();
  389. }
  390. if (accept) {
  391. state_ = RFBSTATE_INITIALISATION;
  392. reader_ = new SMsgReader(this, is);
  393. writer_ = new SMsgWriter(&client, os);
  394. authSuccess();
  395. } else {
  396. state_ = RFBSTATE_INVALID;
  397. if (reason)
  398. throw AuthFailureException(reason);
  399. else
  400. throw AuthFailureException();
  401. }
  402. }
  403. void SConnection::clientInit(bool /*shared*/)
  404. {
  405. writer_->writeServerInit(client.width(), client.height(),
  406. client.pf(), client.name());
  407. state_ = RFBSTATE_NORMAL;
  408. }
  409. void SConnection::close(const char* /*reason*/)
  410. {
  411. state_ = RFBSTATE_CLOSING;
  412. cleanup();
  413. }
  414. void SConnection::setPixelFormat(const PixelFormat& pf)
  415. {
  416. SMsgHandler::setPixelFormat(pf);
  417. readyForSetColourMapEntries = true;
  418. if (!pf.trueColour)
  419. writeFakeColourMap();
  420. }
  421. void SConnection::framebufferUpdateRequest(const Rect& /*r*/,
  422. bool /*incremental*/)
  423. {
  424. if (!readyForSetColourMapEntries) {
  425. readyForSetColourMapEntries = true;
  426. if (!client.pf().trueColour) {
  427. writeFakeColourMap();
  428. }
  429. }
  430. }
  431. void SConnection::fence(uint32_t 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*/,
  441. int /*w*/, int /*h*/)
  442. {
  443. }
  444. void SConnection::handleClipboardRequest()
  445. {
  446. }
  447. void SConnection::handleClipboardAnnounce(bool /*available*/)
  448. {
  449. }
  450. void SConnection::handleClipboardData(const char* /*data*/)
  451. {
  452. }
  453. void SConnection::requestClipboard()
  454. {
  455. if (hasRemoteClipboard) {
  456. handleClipboardData(clientClipboard.c_str());
  457. return;
  458. }
  459. if (client.supportsEncoding(pseudoEncodingExtendedClipboard) &&
  460. (client.clipboardFlags() & rfb::clipboardRequest))
  461. writer()->writeClipboardRequest(rfb::clipboardUTF8);
  462. }
  463. void SConnection::announceClipboard(bool available)
  464. {
  465. hasLocalClipboard = available;
  466. unsolicitedClipboardAttempt = false;
  467. if (client.supportsEncoding(pseudoEncodingExtendedClipboard)) {
  468. // Attempt an unsolicited transfer?
  469. if (available &&
  470. (client.clipboardSize(rfb::clipboardUTF8) > 0) &&
  471. (client.clipboardFlags() & rfb::clipboardProvide)) {
  472. vlog.debug("Attempting unsolicited clipboard transfer...");
  473. unsolicitedClipboardAttempt = true;
  474. handleClipboardRequest();
  475. return;
  476. }
  477. if (client.clipboardFlags() & rfb::clipboardNotify) {
  478. writer()->writeClipboardNotify(available ? rfb::clipboardUTF8 : 0);
  479. return;
  480. }
  481. }
  482. if (available)
  483. handleClipboardRequest();
  484. }
  485. void SConnection::sendClipboardData(const char* data)
  486. {
  487. if (client.supportsEncoding(pseudoEncodingExtendedClipboard) &&
  488. (client.clipboardFlags() & rfb::clipboardProvide)) {
  489. std::string filtered(convertCRLF(data));
  490. size_t sizes[1] = { filtered.size() + 1 };
  491. const uint8_t* data[1] = { (const uint8_t*)filtered.c_str() };
  492. if (unsolicitedClipboardAttempt) {
  493. unsolicitedClipboardAttempt = false;
  494. if (sizes[0] > client.clipboardSize(rfb::clipboardUTF8)) {
  495. vlog.debug("Clipboard was too large for unsolicited clipboard transfer");
  496. if (client.clipboardFlags() & rfb::clipboardNotify)
  497. writer()->writeClipboardNotify(rfb::clipboardUTF8);
  498. return;
  499. }
  500. }
  501. writer()->writeClipboardProvide(rfb::clipboardUTF8, sizes, data);
  502. } else {
  503. std::string latin1(utf8ToLatin1(data));
  504. writer()->writeServerCutText(latin1.c_str());
  505. }
  506. }
  507. void SConnection::cleanup()
  508. {
  509. delete ssecurity;
  510. ssecurity = NULL;
  511. delete reader_;
  512. reader_ = NULL;
  513. delete writer_;
  514. writer_ = NULL;
  515. }
  516. void SConnection::writeFakeColourMap(void)
  517. {
  518. int i;
  519. uint16_t red[256], green[256], blue[256];
  520. for (i = 0;i < 256;i++)
  521. client.pf().rgbFromPixel(i, &red[i], &green[i], &blue[i]);
  522. writer()->writeSetColourMapEntries(0, 256, red, green, blue);
  523. }