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

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