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

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