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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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->checkNoWait(1))
  130. return false;
  131. if (is->readU8() == 0) {
  132. rdr::U32 result = is->readU32();
  133. CharArray reason;
  134. if (result == secResultFailed || result == secResultTooMany)
  135. reason.buf = is->readString();
  136. else
  137. reason.buf = strDup("protocol error");
  138. throw AuthFailureException(reason.buf);
  139. }
  140. if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS)
  141. throw AuthFailureException("gnutls_init failed");
  142. if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)
  143. throw AuthFailureException("gnutls_set_default_priority failed");
  144. setParam();
  145. // Create these early as they set up the push/pull functions
  146. // for GnuTLS
  147. tlsis = new rdr::TLSInStream(is, session);
  148. tlsos = new rdr::TLSOutStream(os, session);
  149. rawis = is;
  150. rawos = os;
  151. }
  152. int err;
  153. err = gnutls_handshake(session);
  154. if (err != GNUTLS_E_SUCCESS) {
  155. if (!gnutls_error_is_fatal(err))
  156. return false;
  157. vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err));
  158. shutdown(false);
  159. throw AuthFailureException("TLS Handshake failed");
  160. }
  161. vlog.debug("TLS handshake completed with %s",
  162. gnutls_session_get_desc(session));
  163. checkSession();
  164. cc->setStreams(tlsis, tlsos);
  165. return true;
  166. }
  167. void CSecurityTLS::setParam()
  168. {
  169. static const char kx_anon_priority[] = ":+ANON-ECDH:+ANON-DH";
  170. int ret;
  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. if (anon) {
  188. if (gnutls_anon_allocate_client_credentials(&anon_cred) != GNUTLS_E_SUCCESS)
  189. throw AuthFailureException("gnutls_anon_allocate_client_credentials failed");
  190. if (gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred) != GNUTLS_E_SUCCESS)
  191. throw AuthFailureException("gnutls_credentials_set failed");
  192. vlog.debug("Anonymous session has been set");
  193. } else {
  194. if (gnutls_certificate_allocate_credentials(&cert_cred) != GNUTLS_E_SUCCESS)
  195. throw AuthFailureException("gnutls_certificate_allocate_credentials failed");
  196. if (gnutls_certificate_set_x509_system_trust(cert_cred) != GNUTLS_E_SUCCESS)
  197. vlog.error("Could not load system certificate trust store");
  198. if (*cafile && gnutls_certificate_set_x509_trust_file(cert_cred,cafile,GNUTLS_X509_FMT_PEM) < 0)
  199. throw AuthFailureException("load of CA cert failed");
  200. if (*crlfile && gnutls_certificate_set_x509_crl_file(cert_cred,crlfile,GNUTLS_X509_FMT_PEM) < 0)
  201. throw AuthFailureException("load of CRL failed");
  202. if (gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred) != GNUTLS_E_SUCCESS)
  203. throw AuthFailureException("gnutls_credentials_set failed");
  204. if (gnutls_server_name_set(session, GNUTLS_NAME_DNS,
  205. client->getServerName(),
  206. strlen(client->getServerName())) != GNUTLS_E_SUCCESS)
  207. vlog.error("Failed to configure the server name for TLS handshake");
  208. vlog.debug("X509 session has been set");
  209. }
  210. }
  211. void CSecurityTLS::checkSession()
  212. {
  213. const unsigned allowed_errors = GNUTLS_CERT_INVALID |
  214. GNUTLS_CERT_SIGNER_NOT_FOUND |
  215. GNUTLS_CERT_SIGNER_NOT_CA;
  216. unsigned int status;
  217. const gnutls_datum_t *cert_list;
  218. unsigned int cert_list_size = 0;
  219. int err;
  220. char *homeDir;
  221. gnutls_datum_t info;
  222. size_t len;
  223. if (anon)
  224. return;
  225. if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
  226. throw AuthFailureException("unsupported certificate type");
  227. err = gnutls_certificate_verify_peers2(session, &status);
  228. if (err != 0) {
  229. vlog.error("server certificate verification failed: %s", gnutls_strerror(err));
  230. throw AuthFailureException("server certificate verification failed");
  231. }
  232. if (status & GNUTLS_CERT_REVOKED)
  233. throw AuthFailureException("server certificate has been revoked");
  234. #ifndef WITHOUT_X509_TIMES
  235. if (status & GNUTLS_CERT_NOT_ACTIVATED)
  236. throw AuthFailureException("server certificate has not been activated");
  237. if (status & GNUTLS_CERT_EXPIRED) {
  238. vlog.debug("server certificate has expired");
  239. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate has expired",
  240. "The certificate of the server has expired, "
  241. "do you want to continue?"))
  242. throw AuthFailureException("server certificate has expired");
  243. }
  244. #endif
  245. /* Process other errors later */
  246. cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
  247. if (!cert_list_size)
  248. throw AuthFailureException("empty certificate chain");
  249. /* Process only server's certificate, not issuer's certificate */
  250. gnutls_x509_crt_t crt;
  251. gnutls_x509_crt_init(&crt);
  252. if (gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER) < 0)
  253. throw AuthFailureException("decoding of certificate failed");
  254. if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) {
  255. CharArray text;
  256. vlog.debug("hostname mismatch");
  257. text.format("Hostname (%s) does not match the server certificate, "
  258. "do you want to continue?", client->getServerName());
  259. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  260. "Certificate hostname mismatch", text.buf))
  261. throw AuthFailureException("Certificate hostname mismatch");
  262. }
  263. if (status == 0) {
  264. /* Everything is fine (hostname + verification) */
  265. gnutls_x509_crt_deinit(crt);
  266. return;
  267. }
  268. if (status & GNUTLS_CERT_INVALID)
  269. vlog.debug("server certificate invalid");
  270. if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  271. vlog.debug("server cert signer not found");
  272. if (status & GNUTLS_CERT_SIGNER_NOT_CA)
  273. vlog.debug("server cert signer not CA");
  274. if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
  275. throw AuthFailureException("The server certificate uses an insecure algorithm");
  276. if ((status & (~allowed_errors)) != 0) {
  277. /* No other errors are allowed */
  278. vlog.debug("GNUTLS status of certificate verification: %u", status);
  279. throw AuthFailureException("Invalid status of server certificate verification");
  280. }
  281. /* Certificate is fine, except we don't know the issuer, so TOFU time */
  282. homeDir = NULL;
  283. if (getvnchomedir(&homeDir) == -1) {
  284. throw AuthFailureException("Could not obtain VNC home directory "
  285. "path for known hosts storage");
  286. }
  287. CharArray dbPath(strlen(homeDir) + 16 + 1);
  288. sprintf(dbPath.buf, "%sx509_known_hosts", homeDir);
  289. delete [] homeDir;
  290. err = gnutls_verify_stored_pubkey(dbPath.buf, NULL,
  291. client->getServerName(), NULL,
  292. GNUTLS_CRT_X509, &cert_list[0], 0);
  293. /* Previously known? */
  294. if (err == GNUTLS_E_SUCCESS) {
  295. vlog.debug("Server certificate found in known hosts file");
  296. gnutls_x509_crt_deinit(crt);
  297. return;
  298. }
  299. if ((err != GNUTLS_E_NO_CERTIFICATE_FOUND) &&
  300. (err != GNUTLS_E_CERTIFICATE_KEY_MISMATCH)) {
  301. throw AuthFailureException("Could not load known hosts database");
  302. }
  303. if (gnutls_x509_crt_print(crt, GNUTLS_CRT_PRINT_ONELINE, &info))
  304. throw AuthFailureException("Could not find certificate to display");
  305. len = strlen((char*)info.data);
  306. for (size_t i = 0; i < len - 1; i++) {
  307. if (info.data[i] == ',' && info.data[i + 1] == ' ')
  308. info.data[i] = '\n';
  309. }
  310. /* New host */
  311. if (err == GNUTLS_E_NO_CERTIFICATE_FOUND) {
  312. CharArray text;
  313. vlog.debug("Server host not previously known");
  314. vlog.debug("%s", info.data);
  315. text.format("This certificate has been signed by an unknown "
  316. "authority:\n\n%s\n\nSomeone could be trying to "
  317. "impersonate the site and you should not "
  318. "continue.\n\nDo you want to make an exception "
  319. "for this server?", info.data);
  320. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  321. "Unknown certificate issuer",
  322. text.buf))
  323. throw AuthFailureException("Unknown certificate issuer");
  324. } else if (err == GNUTLS_E_CERTIFICATE_KEY_MISMATCH) {
  325. CharArray text;
  326. vlog.debug("Server host key mismatch");
  327. vlog.debug("%s", info.data);
  328. text.format("This host is previously known with a different "
  329. "certificate, and the new certificate has been "
  330. "signed by an unknown authority:\n\n%s\n\nSomeone "
  331. "could be trying to impersonate the site and you "
  332. "should not continue.\n\nDo you want to make an "
  333. "exception for this server?", info.data);
  334. if (!msg->showMsgBox(UserMsgBox::M_YESNO,
  335. "Unexpected server certificate",
  336. text.buf))
  337. throw AuthFailureException("Unexpected server certificate");
  338. }
  339. if (gnutls_store_pubkey(dbPath.buf, NULL, client->getServerName(),
  340. NULL, GNUTLS_CRT_X509, &cert_list[0], 0, 0))
  341. vlog.error("Failed to store server certificate to known hosts database");
  342. gnutls_x509_crt_deinit(crt);
  343. /*
  344. * GNUTLS doesn't correctly export gnutls_free symbol which is
  345. * a function pointer. Linking with Visual Studio 2008 Express will
  346. * fail when you call gnutls_free().
  347. */
  348. #if WIN32
  349. free(info.data);
  350. #else
  351. gnutls_free(info.data);
  352. #endif
  353. }