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.

CSecurityTLS.cxx 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*
  2. * Copyright (C) 2004 Red Hat Inc.
  3. * Copyright (C) 2005 Martin Koegler
  4. * Copyright (C) 2010 TigerVNC Team
  5. * Copyright (C) 2010 m-privacy GmbH
  6. * Copyright (C) 2012-2021 Pierre Ossman for Cendio AB
  7. *
  8. * This is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This software is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this software; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  21. * USA.
  22. */
  23. #ifdef HAVE_CONFIG_H
  24. #include <config.h>
  25. #endif
  26. #ifndef HAVE_GNUTLS
  27. #error "This header should not be compiled without HAVE_GNUTLS defined"
  28. #endif
  29. #include <stdlib.h>
  30. #ifndef WIN32
  31. #include <unistd.h>
  32. #endif
  33. #include <rfb/CSecurityTLS.h>
  34. #include <rfb/CConnection.h>
  35. #include <rfb/LogWriter.h>
  36. #include <rfb/Exception.h>
  37. #include <rfb/UserMsgBox.h>
  38. #include <rdr/TLSInStream.h>
  39. #include <rdr/TLSOutStream.h>
  40. #include <os/os.h>
  41. #include <gnutls/x509.h>
  42. /*
  43. * GNUTLS 2.6.5 and older didn't have some variables defined so don't use them.
  44. * GNUTLS 1.X.X defined LIBGNUTLS_VERSION_NUMBER so treat it as "old" gnutls as
  45. * well
  46. */
  47. #if (defined(GNUTLS_VERSION_NUMBER) && GNUTLS_VERSION_NUMBER < 0x020606) || \
  48. defined(LIBGNUTLS_VERSION_NUMBER)
  49. #define WITHOUT_X509_TIMES
  50. #endif
  51. /* Ancient GNUTLS... */
  52. #if !defined(GNUTLS_VERSION_NUMBER) && !defined(LIBGNUTLS_VERSION_NUMBER)
  53. #define WITHOUT_X509_TIMES
  54. #endif
  55. using namespace rfb;
  56. static const char* homedirfn(const char* fn);
  57. StringParameter CSecurityTLS::X509CA("X509CA", "X509 CA certificate",
  58. homedirfn("x509_ca.pem"),
  59. ConfViewer);
  60. StringParameter CSecurityTLS::X509CRL("X509CRL", "X509 CRL file",
  61. homedirfn("x509_crl.pem"),
  62. ConfViewer);
  63. static LogWriter vlog("TLS");
  64. static const char* homedirfn(const char* fn)
  65. {
  66. static char full_path[PATH_MAX];
  67. char* homedir = NULL;
  68. if (getvnchomedir(&homedir) == -1)
  69. return "";
  70. snprintf(full_path, sizeof(full_path), "%s%s", homedir, fn);
  71. delete [] homedir;
  72. return full_path;
  73. }
  74. CSecurityTLS::CSecurityTLS(CConnection* cc, bool _anon)
  75. : CSecurity(cc), session(NULL), anon_cred(NULL), cert_cred(NULL),
  76. anon(_anon), tlsis(NULL), tlsos(NULL), rawis(NULL), rawos(NULL)
  77. {
  78. cafile = X509CA.getData();
  79. crlfile = X509CRL.getData();
  80. if (gnutls_global_init() != GNUTLS_E_SUCCESS)
  81. throw AuthFailureException("gnutls_global_init failed");
  82. }
  83. void CSecurityTLS::shutdown()
  84. {
  85. if (session) {
  86. int ret;
  87. // FIXME: We can't currently wait for the response, so we only send
  88. // our close and hope for the best
  89. ret = gnutls_bye(session, GNUTLS_SHUT_WR);
  90. if ((ret != GNUTLS_E_SUCCESS) && (ret != GNUTLS_E_INVALID_SESSION))
  91. vlog.error("TLS shutdown failed: %s", gnutls_strerror(ret));
  92. }
  93. if (anon_cred) {
  94. gnutls_anon_free_client_credentials(anon_cred);
  95. anon_cred = 0;
  96. }
  97. if (cert_cred) {
  98. gnutls_certificate_free_credentials(cert_cred);
  99. cert_cred = 0;
  100. }
  101. if (rawis && rawos) {
  102. cc->setStreams(rawis, rawos);
  103. rawis = NULL;
  104. rawos = NULL;
  105. }
  106. if (tlsis) {
  107. delete tlsis;
  108. tlsis = NULL;
  109. }
  110. if (tlsos) {
  111. delete tlsos;
  112. tlsos = NULL;
  113. }
  114. if (session) {
  115. gnutls_deinit(session);
  116. session = 0;
  117. }
  118. }
  119. CSecurityTLS::~CSecurityTLS()
  120. {
  121. shutdown();
  122. delete[] cafile;
  123. delete[] crlfile;
  124. gnutls_global_deinit();
  125. }
  126. bool CSecurityTLS::processMsg()
  127. {
  128. rdr::InStream* is = cc->getInStream();
  129. rdr::OutStream* os = cc->getOutStream();
  130. client = cc;
  131. if (!session) {
  132. if (!is->hasData(1))
  133. return false;
  134. if (is->readU8() == 0)
  135. throw AuthFailureException("Server failed to initialize TLS session");
  136. if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS)
  137. throw AuthFailureException("gnutls_init failed");
  138. if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)
  139. throw AuthFailureException("gnutls_set_default_priority failed");
  140. setParam();
  141. // Create these early as they set up the push/pull functions
  142. // for GnuTLS
  143. tlsis = new rdr::TLSInStream(is, session);
  144. tlsos = new rdr::TLSOutStream(os, session);
  145. rawis = is;
  146. rawos = os;
  147. }
  148. int err;
  149. err = gnutls_handshake(session);
  150. if (err != GNUTLS_E_SUCCESS) {
  151. if (!gnutls_error_is_fatal(err)) {
  152. vlog.debug("Deferring completion of TLS handshake: %s", gnutls_strerror(err));
  153. return false;
  154. }
  155. vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err));
  156. shutdown();
  157. throw AuthFailureException("TLS Handshake failed");
  158. }
  159. vlog.debug("TLS handshake completed with %s",
  160. gnutls_session_get_desc(session));
  161. checkSession();
  162. cc->setStreams(tlsis, tlsos);
  163. return true;
  164. }
  165. void CSecurityTLS::setParam()
  166. {
  167. static const char kx_anon_priority[] = ":+ANON-ECDH:+ANON-DH";
  168. int ret;
  169. // Custom priority string specified?
  170. if (strcmp(Security::GnuTLSPriority, "") != 0) {
  171. char *prio;
  172. const char *err;
  173. prio = (char*)malloc(strlen(Security::GnuTLSPriority) +
  174. strlen(kx_anon_priority) + 1);
  175. if (prio == NULL)
  176. throw AuthFailureException("Not enough memory for GnuTLS priority string");
  177. strcpy(prio, Security::GnuTLSPriority);
  178. if (anon)
  179. strcat(prio, kx_anon_priority);
  180. ret = gnutls_priority_set_direct(session, prio, &err);
  181. free(prio);
  182. if (ret != GNUTLS_E_SUCCESS) {
  183. if (ret == GNUTLS_E_INVALID_REQUEST)
  184. vlog.error("GnuTLS priority syntax error at: %s", err);
  185. throw AuthFailureException("gnutls_set_priority_direct failed");
  186. }
  187. } else if (anon) {
  188. const char *err;
  189. #if GNUTLS_VERSION_NUMBER >= 0x030603
  190. // gnutls_set_default_priority_appends() expects a normal priority string that
  191. // doesn't start with ":".
  192. ret = gnutls_set_default_priority_append(session, kx_anon_priority + 1, &err, 0);
  193. if (ret != GNUTLS_E_SUCCESS) {
  194. if (ret == GNUTLS_E_INVALID_REQUEST)
  195. vlog.error("GnuTLS priority syntax error at: %s", err);
  196. throw AuthFailureException("gnutls_set_default_priority_append failed");
  197. }
  198. #else
  199. // We don't know what the system default priority is, so we guess
  200. // it's what upstream GnuTLS has
  201. static const char gnutls_default_priority[] = "NORMAL";
  202. char *prio;
  203. prio = (char*)malloc(strlen(gnutls_default_priority) +
  204. strlen(kx_anon_priority) + 1);
  205. if (prio == NULL)
  206. throw AuthFailureException("Not enough memory for GnuTLS priority string");
  207. strcpy(prio, gnutls_default_priority);
  208. strcat(prio, kx_anon_priority);
  209. ret = gnutls_priority_set_direct(session, prio, &err);
  210. free(prio);
  211. if (ret != GNUTLS_E_SUCCESS) {
  212. if (ret == GNUTLS_E_INVALID_REQUEST)
  213. vlog.error("GnuTLS priority syntax error at: %s", err);
  214. throw AuthFailureException("gnutls_set_priority_direct failed");
  215. }
  216. #endif
  217. }
  218. if (anon) {
  219. if (gnutls_anon_allocate_client_credentials(&anon_cred) != GNUTLS_E_SUCCESS)
  220. throw AuthFailureException("gnutls_anon_allocate_client_credentials failed");
  221. if (gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred) != GNUTLS_E_SUCCESS)
  222. throw AuthFailureException("gnutls_credentials_set failed");
  223. vlog.debug("Anonymous session has been set");
  224. } else {
  225. if (gnutls_certificate_allocate_credentials(&cert_cred) != GNUTLS_E_SUCCESS)
  226. throw AuthFailureException("gnutls_certificate_allocate_credentials failed");
  227. if (gnutls_certificate_set_x509_system_trust(cert_cred) < 1)
  228. vlog.error("Could not load system certificate trust store");
  229. if (*cafile && gnutls_certificate_set_x509_trust_file(cert_cred,cafile,GNUTLS_X509_FMT_PEM) < 0)
  230. vlog.error("Could not load user specified certificate authority");
  231. if (*crlfile && gnutls_certificate_set_x509_crl_file(cert_cred,crlfile,GNUTLS_X509_FMT_PEM) < 0)
  232. vlog.error("Could not load user specified certificate revocation list");
  233. if (gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred) != GNUTLS_E_SUCCESS)
  234. throw AuthFailureException("gnutls_credentials_set failed");
  235. if (gnutls_server_name_set(session, GNUTLS_NAME_DNS,
  236. client->getServerName(),
  237. strlen(client->getServerName())) != GNUTLS_E_SUCCESS)
  238. vlog.error("Failed to configure the server name for TLS handshake");
  239. vlog.debug("X509 session has been set");
  240. }
  241. }
  242. void CSecurityTLS::checkSession()
  243. {
  244. const unsigned allowed_errors = GNUTLS_CERT_INVALID |
  245. GNUTLS_CERT_SIGNER_NOT_FOUND |
  246. GNUTLS_CERT_SIGNER_NOT_CA;
  247. unsigned int status;
  248. const gnutls_datum_t *cert_list;
  249. unsigned int cert_list_size = 0;
  250. int err;
  251. char *homeDir;
  252. gnutls_datum_t info;
  253. size_t len;
  254. if (anon)
  255. return;
  256. if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
  257. throw AuthFailureException("unsupported certificate type");
  258. err = gnutls_certificate_verify_peers2(session, &status);
  259. if (err != 0) {
  260. vlog.error("server certificate verification failed: %s", gnutls_strerror(err));
  261. throw AuthFailureException("server certificate verification failed");
  262. }
  263. if (status & GNUTLS_CERT_REVOKED)
  264. throw AuthFailureException("server certificate has been revoked");
  265. #ifndef WITHOUT_X509_TIMES
  266. if (status & GNUTLS_CERT_NOT_ACTIVATED)
  267. throw AuthFailureException("server certificate has not been activated");
  268. if (status & GNUTLS_CERT_EXPIRED) {
  269. vlog.debug("server certificate has expired");
  270. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate has expired",
  271. "The certificate of the server has expired, "
  272. "do you want to continue?"))
  273. throw AuthFailureException("server certificate has expired");
  274. }
  275. #endif
  276. /* Process other errors later */
  277. cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
  278. if (!cert_list_size)
  279. throw AuthFailureException("empty certificate chain");
  280. /* Process only server's certificate, not issuer's certificate */
  281. gnutls_x509_crt_t crt;
  282. gnutls_x509_crt_init(&crt);
  283. if (gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER) < 0)
  284. throw AuthFailureException("decoding of certificate failed");
  285. if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) {
  286. CharArray text;
  287. vlog.debug("hostname mismatch");
  288. text.format("Hostname (%s) does not match the server certificate, "
  289. "do you want to continue?", client->getServerName());
  290. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  291. "Certificate hostname mismatch", text.buf))
  292. throw AuthFailureException("Certificate hostname mismatch");
  293. }
  294. if (status == 0) {
  295. /* Everything is fine (hostname + verification) */
  296. gnutls_x509_crt_deinit(crt);
  297. return;
  298. }
  299. if (status & GNUTLS_CERT_INVALID)
  300. vlog.debug("server certificate invalid");
  301. if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  302. vlog.debug("server cert signer not found");
  303. if (status & GNUTLS_CERT_SIGNER_NOT_CA)
  304. vlog.debug("server cert signer not CA");
  305. if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
  306. throw AuthFailureException("The server certificate uses an insecure algorithm");
  307. if ((status & (~allowed_errors)) != 0) {
  308. /* No other errors are allowed */
  309. vlog.debug("GNUTLS status of certificate verification: %u", status);
  310. throw AuthFailureException("Invalid status of server certificate verification");
  311. }
  312. /* Certificate is fine, except we don't know the issuer, so TOFU time */
  313. homeDir = NULL;
  314. if (getvnchomedir(&homeDir) == -1) {
  315. throw AuthFailureException("Could not obtain VNC home directory "
  316. "path for known hosts storage");
  317. }
  318. CharArray dbPath(strlen(homeDir) + 16 + 1);
  319. sprintf(dbPath.buf, "%sx509_known_hosts", homeDir);
  320. delete [] homeDir;
  321. err = gnutls_verify_stored_pubkey(dbPath.buf, NULL,
  322. client->getServerName(), NULL,
  323. GNUTLS_CRT_X509, &cert_list[0], 0);
  324. /* Previously known? */
  325. if (err == GNUTLS_E_SUCCESS) {
  326. vlog.debug("Server certificate found in known hosts file");
  327. gnutls_x509_crt_deinit(crt);
  328. return;
  329. }
  330. if ((err != GNUTLS_E_NO_CERTIFICATE_FOUND) &&
  331. (err != GNUTLS_E_CERTIFICATE_KEY_MISMATCH)) {
  332. throw AuthFailureException("Could not load known hosts database");
  333. }
  334. if (gnutls_x509_crt_print(crt, GNUTLS_CRT_PRINT_ONELINE, &info))
  335. throw AuthFailureException("Could not find certificate to display");
  336. len = strlen((char*)info.data);
  337. for (size_t i = 0; i < len - 1; i++) {
  338. if (info.data[i] == ',' && info.data[i + 1] == ' ')
  339. info.data[i] = '\n';
  340. }
  341. /* New host */
  342. if (err == GNUTLS_E_NO_CERTIFICATE_FOUND) {
  343. CharArray text;
  344. vlog.debug("Server host not previously known");
  345. vlog.debug("%s", info.data);
  346. text.format("This certificate has been signed by an unknown "
  347. "authority:\n\n%s\n\nSomeone could be trying to "
  348. "impersonate the site and you should not "
  349. "continue.\n\nDo you want to make an exception "
  350. "for this server?", info.data);
  351. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  352. "Unknown certificate issuer",
  353. text.buf))
  354. throw AuthFailureException("Unknown certificate issuer");
  355. } else if (err == GNUTLS_E_CERTIFICATE_KEY_MISMATCH) {
  356. CharArray text;
  357. vlog.debug("Server host key mismatch");
  358. vlog.debug("%s", info.data);
  359. text.format("This host is previously known with a different "
  360. "certificate, and the new certificate has been "
  361. "signed by an unknown authority:\n\n%s\n\nSomeone "
  362. "could be trying to impersonate the site and you "
  363. "should not continue.\n\nDo you want to make an "
  364. "exception for this server?", info.data);
  365. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  366. "Unexpected server certificate",
  367. text.buf))
  368. throw AuthFailureException("Unexpected server certificate");
  369. }
  370. if (gnutls_store_pubkey(dbPath.buf, NULL, client->getServerName(),
  371. NULL, GNUTLS_CRT_X509, &cert_list[0], 0, 0))
  372. vlog.error("Failed to store server certificate to known hosts database");
  373. gnutls_x509_crt_deinit(crt);
  374. /*
  375. * GNUTLS doesn't correctly export gnutls_free symbol which is
  376. * a function pointer. Linking with Visual Studio 2008 Express will
  377. * fail when you call gnutls_free().
  378. */
  379. #if WIN32
  380. free(info.data);
  381. #else
  382. gnutls_free(info.data);
  383. #endif
  384. }