Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

CSecurityTLS.cxx 13KB

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