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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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), clientClipboard(NULL), hasLocalClipboard(false),
  56. unsolicitedClipboardAttempt(false)
  57. {
  58. defaultMajorVersion = 3;
  59. defaultMinorVersion = 8;
  60. if (rfb::Server::protocol3_3)
  61. defaultMinorVersion = 3;
  62. client.setVersion(defaultMajorVersion, defaultMinorVersion);
  63. }
  64. SConnection::~SConnection()
  65. {
  66. cleanup();
  67. }
  68. void SConnection::setStreams(rdr::InStream* is_, rdr::OutStream* os_)
  69. {
  70. is = is_;
  71. os = os_;
  72. }
  73. void SConnection::initialiseProtocol()
  74. {
  75. char str[13];
  76. sprintf(str, "RFB %03d.%03d\n", defaultMajorVersion, defaultMinorVersion);
  77. os->writeBytes(str, 12);
  78. os->flush();
  79. state_ = RFBSTATE_PROTOCOL_VERSION;
  80. }
  81. bool SConnection::processMsg()
  82. {
  83. switch (state_) {
  84. case RFBSTATE_PROTOCOL_VERSION: return processVersionMsg(); break;
  85. case RFBSTATE_SECURITY_TYPE: return processSecurityTypeMsg(); break;
  86. case RFBSTATE_SECURITY: return processSecurityMsg(); break;
  87. case RFBSTATE_SECURITY_FAILURE: return processSecurityFailure(); break;
  88. case RFBSTATE_INITIALISATION: return processInitMsg(); break;
  89. case RFBSTATE_NORMAL: return reader_->readMsg(); break;
  90. case RFBSTATE_QUERYING:
  91. throw Exception("SConnection::processMsg: bogus data from client while "
  92. "querying");
  93. case RFBSTATE_CLOSING:
  94. throw Exception("SConnection::processMsg: called while closing");
  95. case RFBSTATE_UNINITIALISED:
  96. throw Exception("SConnection::processMsg: not initialised yet?");
  97. default:
  98. throw Exception("SConnection::processMsg: invalid state");
  99. }
  100. }
  101. bool SConnection::processVersionMsg()
  102. {
  103. char verStr[13];
  104. int majorVersion;
  105. int minorVersion;
  106. vlog.debug("reading protocol version");
  107. if (!is->hasData(12))
  108. return false;
  109. is->readBytes(verStr, 12);
  110. verStr[12] = '\0';
  111. if (sscanf(verStr, "RFB %03d.%03d\n",
  112. &majorVersion, &minorVersion) != 2) {
  113. state_ = RFBSTATE_INVALID;
  114. throw Exception("reading version failed: not an RFB client?");
  115. }
  116. client.setVersion(majorVersion, minorVersion);
  117. vlog.info("Client needs protocol version %d.%d",
  118. client.majorVersion, client.minorVersion);
  119. if (client.majorVersion != 3) {
  120. // unknown protocol version
  121. throwConnFailedException("Client needs protocol version %d.%d, server has %d.%d",
  122. client.majorVersion, client.minorVersion,
  123. defaultMajorVersion, defaultMinorVersion);
  124. }
  125. if (client.minorVersion != 3 && client.minorVersion != 7 && client.minorVersion != 8) {
  126. vlog.error("Client uses unofficial protocol version %d.%d",
  127. client.majorVersion,client.minorVersion);
  128. if (client.minorVersion >= 8)
  129. client.minorVersion = 8;
  130. else if (client.minorVersion == 7)
  131. client.minorVersion = 7;
  132. else
  133. client.minorVersion = 3;
  134. vlog.error("Assuming compatibility with version %d.%d",
  135. client.majorVersion,client.minorVersion);
  136. }
  137. versionReceived();
  138. std::list<rdr::U8> secTypes;
  139. std::list<rdr::U8>::iterator i;
  140. secTypes = security.GetEnabledSecTypes();
  141. if (client.isVersion(3,3)) {
  142. // cope with legacy 3.3 client only if "no authentication" or "vnc
  143. // authentication" is supported.
  144. for (i=secTypes.begin(); i!=secTypes.end(); i++) {
  145. if (*i == secTypeNone || *i == secTypeVncAuth) break;
  146. }
  147. if (i == secTypes.end()) {
  148. throwConnFailedException("No supported security type for %d.%d client",
  149. client.majorVersion, client.minorVersion);
  150. }
  151. os->writeU32(*i);
  152. if (*i == secTypeNone) os->flush();
  153. state_ = RFBSTATE_SECURITY;
  154. ssecurity = security.GetSSecurity(this, *i);
  155. return true;
  156. }
  157. // list supported security types for >=3.7 clients
  158. if (secTypes.empty())
  159. throwConnFailedException("No supported security types");
  160. os->writeU8(secTypes.size());
  161. for (i=secTypes.begin(); i!=secTypes.end(); i++)
  162. os->writeU8(*i);
  163. os->flush();
  164. state_ = RFBSTATE_SECURITY_TYPE;
  165. return true;
  166. }
  167. bool SConnection::processSecurityTypeMsg()
  168. {
  169. vlog.debug("processing security type message");
  170. if (!is->hasData(1))
  171. return false;
  172. int secType = is->readU8();
  173. processSecurityType(secType);
  174. return true;
  175. }
  176. void SConnection::processSecurityType(int secType)
  177. {
  178. // Verify that the requested security type should be offered
  179. std::list<rdr::U8> secTypes;
  180. std::list<rdr::U8>::iterator i;
  181. secTypes = security.GetEnabledSecTypes();
  182. for (i=secTypes.begin(); i!=secTypes.end(); i++)
  183. if (*i == secType) break;
  184. if (i == secTypes.end())
  185. throw Exception("Requested security type not available");
  186. vlog.info("Client requests security type %s(%d)",
  187. secTypeName(secType),secType);
  188. try {
  189. state_ = RFBSTATE_SECURITY;
  190. ssecurity = security.GetSSecurity(this, secType);
  191. } catch (rdr::Exception& e) {
  192. throwConnFailedException("%s", e.str());
  193. }
  194. }
  195. bool SConnection::processSecurityMsg()
  196. {
  197. vlog.debug("processing security message");
  198. try {
  199. if (!ssecurity->processMsg())
  200. return false;
  201. } catch (AuthFailureException& e) {
  202. vlog.error("AuthFailureException: %s", e.str());
  203. state_ = RFBSTATE_SECURITY_FAILURE;
  204. // Introduce a slight delay of the authentication failure response
  205. // to make it difficult to brute force a password
  206. authFailureMsg.replaceBuf(strDup(e.str()));
  207. authFailureTimer.start(100);
  208. return true;
  209. }
  210. state_ = RFBSTATE_QUERYING;
  211. setAccessRights(ssecurity->getAccessRights());
  212. queryConnection(ssecurity->getUserName());
  213. // If the connection got approved right away then we can continue
  214. if (state_ == RFBSTATE_INITIALISATION)
  215. return true;
  216. // Otherwise we need to wait for the result
  217. // (or give up if if was rejected)
  218. return false;
  219. }
  220. bool SConnection::processSecurityFailure()
  221. {
  222. // Silently drop any data if we are currently delaying an
  223. // authentication failure response as otherwise we would close
  224. // the connection on unexpected data, and an attacker could use
  225. // that to detect our delayed state.
  226. if (!is->hasData(1))
  227. return false;
  228. is->skip(is->avail());
  229. return true;
  230. }
  231. bool SConnection::processInitMsg()
  232. {
  233. vlog.debug("reading client initialisation");
  234. return reader_->readClientInit();
  235. }
  236. bool SConnection::handleAuthFailureTimeout(Timer* /*t*/)
  237. {
  238. if (state_ != RFBSTATE_SECURITY_FAILURE) {
  239. close("SConnection::handleAuthFailureTimeout: invalid state");
  240. return false;
  241. }
  242. try {
  243. os->writeU32(secResultFailed);
  244. if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
  245. const char* reason = authFailureMsg.buf;
  246. os->writeU32(strlen(reason));
  247. os->writeBytes(reason, strlen(reason));
  248. }
  249. os->flush();
  250. } catch (rdr::Exception& e) {
  251. close(e.str());
  252. return false;
  253. }
  254. close(authFailureMsg.buf);
  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 rdr::S32* 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. rdr::U32 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. strFree(clientClipboard);
  315. clientClipboard = NULL;
  316. clientClipboard = latin1ToUTF8(str);
  317. handleClipboardAnnounce(true);
  318. }
  319. void SConnection::handleClipboardRequest(rdr::U32 flags)
  320. {
  321. if (!(flags & rfb::clipboardUTF8)) {
  322. vlog.debug("Ignoring clipboard request for unsupported formats 0x%x", flags);
  323. return;
  324. }
  325. if (!hasLocalClipboard) {
  326. vlog.debug("Ignoring unexpected clipboard request");
  327. return;
  328. }
  329. handleClipboardRequest();
  330. }
  331. void SConnection::handleClipboardPeek()
  332. {
  333. if (client.clipboardFlags() & rfb::clipboardNotify)
  334. writer()->writeClipboardNotify(hasLocalClipboard ? rfb::clipboardUTF8 : 0);
  335. }
  336. void SConnection::handleClipboardNotify(rdr::U32 flags)
  337. {
  338. strFree(clientClipboard);
  339. clientClipboard = NULL;
  340. if (flags & rfb::clipboardUTF8) {
  341. hasLocalClipboard = false;
  342. handleClipboardAnnounce(true);
  343. } else {
  344. handleClipboardAnnounce(false);
  345. }
  346. }
  347. void SConnection::handleClipboardProvide(rdr::U32 flags,
  348. const size_t* lengths,
  349. const rdr::U8* const* data)
  350. {
  351. if (!(flags & rfb::clipboardUTF8)) {
  352. vlog.debug("Ignoring clipboard provide with unsupported formats 0x%x", flags);
  353. return;
  354. }
  355. strFree(clientClipboard);
  356. clientClipboard = NULL;
  357. clientClipboard = convertLF((const char*)data[0], lengths[0]);
  358. // FIXME: Should probably verify that this data was actually requested
  359. handleClipboardData(clientClipboard);
  360. }
  361. void SConnection::supportsQEMUKeyEvent()
  362. {
  363. writer()->writeQEMUKeyEvent();
  364. }
  365. void SConnection::versionReceived()
  366. {
  367. }
  368. void SConnection::authSuccess()
  369. {
  370. }
  371. void SConnection::queryConnection(const char* /*userName*/)
  372. {
  373. approveConnection(true);
  374. }
  375. void SConnection::approveConnection(bool accept, const char* reason)
  376. {
  377. if (state_ != RFBSTATE_QUERYING)
  378. throw Exception("SConnection::approveConnection: invalid state");
  379. if (!client.beforeVersion(3,8) || ssecurity->getType() != secTypeNone) {
  380. if (accept) {
  381. os->writeU32(secResultOK);
  382. } else {
  383. os->writeU32(secResultFailed);
  384. if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
  385. if (!reason)
  386. reason = "Authentication failure";
  387. os->writeU32(strlen(reason));
  388. os->writeBytes(reason, strlen(reason));
  389. }
  390. }
  391. os->flush();
  392. }
  393. if (accept) {
  394. state_ = RFBSTATE_INITIALISATION;
  395. reader_ = new SMsgReader(this, is);
  396. writer_ = new SMsgWriter(&client, os);
  397. authSuccess();
  398. } else {
  399. state_ = RFBSTATE_INVALID;
  400. if (reason)
  401. throw AuthFailureException(reason);
  402. else
  403. throw AuthFailureException();
  404. }
  405. }
  406. void SConnection::clientInit(bool /*shared*/)
  407. {
  408. writer_->writeServerInit(client.width(), client.height(),
  409. client.pf(), client.name());
  410. state_ = RFBSTATE_NORMAL;
  411. }
  412. void SConnection::close(const char* /*reason*/)
  413. {
  414. state_ = RFBSTATE_CLOSING;
  415. cleanup();
  416. }
  417. void SConnection::setPixelFormat(const PixelFormat& pf)
  418. {
  419. SMsgHandler::setPixelFormat(pf);
  420. readyForSetColourMapEntries = true;
  421. if (!pf.trueColour)
  422. writeFakeColourMap();
  423. }
  424. void SConnection::framebufferUpdateRequest(const Rect& /*r*/,
  425. bool /*incremental*/)
  426. {
  427. if (!readyForSetColourMapEntries) {
  428. readyForSetColourMapEntries = true;
  429. if (!client.pf().trueColour) {
  430. writeFakeColourMap();
  431. }
  432. }
  433. }
  434. void SConnection::fence(rdr::U32 flags, unsigned len, const char 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 (clientClipboard != NULL) {
  459. handleClipboardData(clientClipboard);
  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. CharArray filtered(convertCRLF(data));
  493. size_t sizes[1] = { strlen(filtered.buf) + 1 };
  494. const rdr::U8* data[1] = { (const rdr::U8*)filtered.buf };
  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. CharArray latin1(utf8ToLatin1(data));
  507. writer()->writeServerCutText(latin1.buf);
  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. strFree(clientClipboard);
  519. clientClipboard = NULL;
  520. }
  521. void SConnection::writeFakeColourMap(void)
  522. {
  523. int i;
  524. rdr::U16 red[256], green[256], blue[256];
  525. for (i = 0;i < 256;i++)
  526. client.pf().rgbFromPixel(i, &red[i], &green[i], &blue[i]);
  527. writer()->writeSetColourMapEntries(0, 256, red, green, blue);
  528. }