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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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/SSecurityVeNCrypt.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. StringParameter CSecurityTLS::X509CA("X509CA", "X509 CA certificate", "", ConfViewer);
  57. StringParameter CSecurityTLS::X509CRL("X509CRL", "X509 CRL file", "", ConfViewer);
  58. static LogWriter vlog("TLS");
  59. CSecurityTLS::CSecurityTLS(CConnection* cc, bool _anon)
  60. : CSecurity(cc), session(NULL), anon_cred(NULL), cert_cred(NULL),
  61. anon(_anon), tlsis(NULL), tlsos(NULL), rawis(NULL), rawos(NULL)
  62. {
  63. cafile = X509CA.getData();
  64. crlfile = X509CRL.getData();
  65. if (gnutls_global_init() != GNUTLS_E_SUCCESS)
  66. throw AuthFailureException("gnutls_global_init failed");
  67. }
  68. void CSecurityTLS::setDefaults()
  69. {
  70. char* homeDir = NULL;
  71. if (getvnchomedir(&homeDir) == -1) {
  72. vlog.error("Could not obtain VNC home directory path");
  73. return;
  74. }
  75. int len = strlen(homeDir) + 1;
  76. CharArray caDefault(len + 11);
  77. CharArray crlDefault(len + 12);
  78. sprintf(caDefault.buf, "%sx509_ca.pem", homeDir);
  79. sprintf(crlDefault.buf, "%s509_crl.pem", homeDir);
  80. delete [] homeDir;
  81. if (!fileexists(caDefault.buf))
  82. X509CA.setDefaultStr(strdup(caDefault.buf));
  83. if (!fileexists(crlDefault.buf))
  84. X509CRL.setDefaultStr(strdup(crlDefault.buf));
  85. }
  86. void CSecurityTLS::shutdown(bool needbye)
  87. {
  88. if (session && needbye)
  89. if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS)
  90. vlog.error("gnutls_bye failed");
  91. if (anon_cred) {
  92. gnutls_anon_free_client_credentials(anon_cred);
  93. anon_cred = 0;
  94. }
  95. if (cert_cred) {
  96. gnutls_certificate_free_credentials(cert_cred);
  97. cert_cred = 0;
  98. }
  99. if (rawis && rawos) {
  100. cc->setStreams(rawis, rawos);
  101. rawis = NULL;
  102. rawos = NULL;
  103. }
  104. if (tlsis) {
  105. delete tlsis;
  106. tlsis = NULL;
  107. }
  108. if (tlsos) {
  109. delete tlsos;
  110. tlsos = NULL;
  111. }
  112. if (session) {
  113. gnutls_deinit(session);
  114. session = 0;
  115. }
  116. }
  117. CSecurityTLS::~CSecurityTLS()
  118. {
  119. shutdown(true);
  120. delete[] cafile;
  121. delete[] crlfile;
  122. gnutls_global_deinit();
  123. }
  124. bool CSecurityTLS::processMsg()
  125. {
  126. rdr::InStream* is = cc->getInStream();
  127. rdr::OutStream* os = cc->getOutStream();
  128. client = cc;
  129. if (!session) {
  130. if (!is->checkNoWait(1))
  131. return false;
  132. if (is->readU8() == 0) {
  133. rdr::U32 result = is->readU32();
  134. CharArray reason;
  135. if (result == secResultFailed || result == secResultTooMany)
  136. reason.buf = is->readString();
  137. else
  138. reason.buf = strDup("protocol error");
  139. throw AuthFailureException(reason.buf);
  140. }
  141. if (gnutls_init(&session, GNUTLS_CLIENT) != GNUTLS_E_SUCCESS)
  142. throw AuthFailureException("gnutls_init failed");
  143. if (gnutls_set_default_priority(session) != GNUTLS_E_SUCCESS)
  144. throw AuthFailureException("gnutls_set_default_priority failed");
  145. setParam();
  146. // Create these early as they set up the push/pull functions
  147. // for GnuTLS
  148. tlsis = new rdr::TLSInStream(is, session);
  149. tlsos = new rdr::TLSOutStream(os, session);
  150. rawis = is;
  151. rawos = os;
  152. }
  153. int err;
  154. err = gnutls_handshake(session);
  155. if (err != GNUTLS_E_SUCCESS) {
  156. if (!gnutls_error_is_fatal(err))
  157. return false;
  158. vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err));
  159. shutdown(false);
  160. throw AuthFailureException("TLS Handshake failed");
  161. }
  162. vlog.debug("TLS handshake completed with %s",
  163. gnutls_session_get_desc(session));
  164. checkSession();
  165. cc->setStreams(tlsis, tlsos);
  166. return true;
  167. }
  168. void CSecurityTLS::setParam()
  169. {
  170. static const char kx_anon_priority[] = ":+ANON-ECDH:+ANON-DH";
  171. int ret;
  172. char *prio;
  173. const char *err;
  174. prio = (char*)malloc(strlen(Security::GnuTLSPriority) +
  175. strlen(kx_anon_priority) + 1);
  176. if (prio == NULL)
  177. throw AuthFailureException("Not enough memory for GnuTLS priority string");
  178. strcpy(prio, Security::GnuTLSPriority);
  179. if (anon)
  180. strcat(prio, kx_anon_priority);
  181. ret = gnutls_priority_set_direct(session, prio, &err);
  182. free(prio);
  183. if (ret != GNUTLS_E_SUCCESS) {
  184. if (ret == GNUTLS_E_INVALID_REQUEST)
  185. vlog.error("GnuTLS priority syntax error at: %s", err);
  186. throw AuthFailureException("gnutls_set_priority_direct failed");
  187. }
  188. if (anon) {
  189. if (gnutls_anon_allocate_client_credentials(&anon_cred) != GNUTLS_E_SUCCESS)
  190. throw AuthFailureException("gnutls_anon_allocate_client_credentials failed");
  191. if (gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred) != GNUTLS_E_SUCCESS)
  192. throw AuthFailureException("gnutls_credentials_set failed");
  193. vlog.debug("Anonymous session has been set");
  194. } else {
  195. if (gnutls_certificate_allocate_credentials(&cert_cred) != GNUTLS_E_SUCCESS)
  196. throw AuthFailureException("gnutls_certificate_allocate_credentials failed");
  197. if (gnutls_certificate_set_x509_system_trust(cert_cred) != GNUTLS_E_SUCCESS)
  198. vlog.error("Could not load system certificate trust store");
  199. if (*cafile && gnutls_certificate_set_x509_trust_file(cert_cred,cafile,GNUTLS_X509_FMT_PEM) < 0)
  200. throw AuthFailureException("load of CA cert failed");
  201. /* Load previously saved certs */
  202. char *homeDir = NULL;
  203. int err;
  204. if (getvnchomedir(&homeDir) == -1)
  205. vlog.error("Could not obtain VNC home directory path");
  206. else {
  207. CharArray caSave(strlen(homeDir) + 19 + 1);
  208. sprintf(caSave.buf, "%sx509_savedcerts.pem", homeDir);
  209. delete [] homeDir;
  210. err = gnutls_certificate_set_x509_trust_file(cert_cred, caSave.buf,
  211. GNUTLS_X509_FMT_PEM);
  212. if (err < 0)
  213. vlog.debug("Failed to load saved server certificates from %s", caSave.buf);
  214. }
  215. if (*crlfile && gnutls_certificate_set_x509_crl_file(cert_cred,crlfile,GNUTLS_X509_FMT_PEM) < 0)
  216. throw AuthFailureException("load of CRL failed");
  217. if (gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred) != GNUTLS_E_SUCCESS)
  218. throw AuthFailureException("gnutls_credentials_set failed");
  219. if (gnutls_server_name_set(session, GNUTLS_NAME_DNS,
  220. client->getServerName(),
  221. strlen(client->getServerName())) != GNUTLS_E_SUCCESS)
  222. vlog.error("Failed to configure the server name for TLS handshake");
  223. vlog.debug("X509 session has been set");
  224. }
  225. }
  226. void CSecurityTLS::checkSession()
  227. {
  228. const unsigned allowed_errors = GNUTLS_CERT_INVALID |
  229. GNUTLS_CERT_SIGNER_NOT_FOUND |
  230. GNUTLS_CERT_SIGNER_NOT_CA;
  231. unsigned int status;
  232. const gnutls_datum_t *cert_list;
  233. unsigned int cert_list_size = 0;
  234. int err;
  235. gnutls_datum_t info;
  236. if (anon)
  237. return;
  238. if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
  239. throw AuthFailureException("unsupported certificate type");
  240. err = gnutls_certificate_verify_peers2(session, &status);
  241. if (err != 0) {
  242. vlog.error("server certificate verification failed: %s", gnutls_strerror(err));
  243. throw AuthFailureException("server certificate verification failed");
  244. }
  245. if (status & GNUTLS_CERT_REVOKED)
  246. throw AuthFailureException("server certificate has been revoked");
  247. #ifndef WITHOUT_X509_TIMES
  248. if (status & GNUTLS_CERT_NOT_ACTIVATED)
  249. throw AuthFailureException("server certificate has not been activated");
  250. if (status & GNUTLS_CERT_EXPIRED) {
  251. vlog.debug("server certificate has expired");
  252. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate has expired",
  253. "The certificate of the server has expired, "
  254. "do you want to continue?"))
  255. throw AuthFailureException("server certificate has expired");
  256. }
  257. #endif
  258. /* Process other errors later */
  259. cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
  260. if (!cert_list_size)
  261. throw AuthFailureException("empty certificate chain");
  262. /* Process only server's certificate, not issuer's certificate */
  263. gnutls_x509_crt_t crt;
  264. gnutls_x509_crt_init(&crt);
  265. if (gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER) < 0)
  266. throw AuthFailureException("decoding of certificate failed");
  267. if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) {
  268. char buf[255];
  269. vlog.debug("hostname mismatch");
  270. snprintf(buf, sizeof(buf), "Hostname (%s) does not match any certificate, "
  271. "do you want to continue?", client->getServerName());
  272. buf[sizeof(buf) - 1] = '\0';
  273. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "hostname mismatch", buf))
  274. throw AuthFailureException("hostname mismatch");
  275. }
  276. if (status == 0) {
  277. /* Everything is fine (hostname + verification) */
  278. gnutls_x509_crt_deinit(crt);
  279. return;
  280. }
  281. if (status & GNUTLS_CERT_INVALID)
  282. vlog.debug("server certificate invalid");
  283. if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  284. vlog.debug("server cert signer not found");
  285. if (status & GNUTLS_CERT_SIGNER_NOT_CA)
  286. vlog.debug("server cert signer not CA");
  287. if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
  288. throw AuthFailureException("The server certificate uses an insecure algorithm");
  289. if ((status & (~allowed_errors)) != 0) {
  290. /* No other errors are allowed */
  291. vlog.debug("GNUTLS status of certificate verification: %u", status);
  292. throw AuthFailureException("Invalid status of server certificate verification");
  293. }
  294. vlog.debug("Saved server certificates don't match");
  295. if (gnutls_x509_crt_print(crt, GNUTLS_CRT_PRINT_ONELINE, &info)) {
  296. /*
  297. * GNUTLS doesn't correctly export gnutls_free symbol which is
  298. * a function pointer. Linking with Visual Studio 2008 Express will
  299. * fail when you call gnutls_free().
  300. */
  301. #if WIN32
  302. free(info.data);
  303. #else
  304. gnutls_free(info.data);
  305. #endif
  306. throw AuthFailureException("Could not find certificate to display");
  307. }
  308. size_t out_size = 0;
  309. char *out_buf = NULL;
  310. char *certinfo = NULL;
  311. int len = 0;
  312. vlog.debug("certificate issuer unknown");
  313. len = snprintf(NULL, 0, "This certificate has been signed by an unknown "
  314. "authority:\n\n%s\n\nDo you want to save it and "
  315. "continue?\n ", info.data);
  316. if (len < 0)
  317. AuthFailureException("certificate decoding error");
  318. vlog.debug("%s", info.data);
  319. certinfo = new char[len];
  320. if (certinfo == NULL)
  321. throw AuthFailureException("Out of memory");
  322. snprintf(certinfo, len, "This certificate has been signed by an unknown "
  323. "authority:\n\n%s\n\nDo you want to save it and "
  324. "continue? ", info.data);
  325. for (int i = 0; i < len - 1; i++)
  326. if (certinfo[i] == ',' && certinfo[i + 1] == ' ')
  327. certinfo[i] = '\n';
  328. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate issuer unknown",
  329. certinfo)) {
  330. delete [] certinfo;
  331. throw AuthFailureException("certificate issuer unknown");
  332. }
  333. delete [] certinfo;
  334. if (gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, NULL, &out_size)
  335. == GNUTLS_E_SHORT_MEMORY_BUFFER)
  336. AuthFailureException("Out of memory");
  337. // Save cert
  338. out_buf = new char[out_size];
  339. if (out_buf == NULL)
  340. AuthFailureException("Out of memory");
  341. if (gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, out_buf, &out_size) < 0)
  342. AuthFailureException("certificate issuer unknown, and certificate "
  343. "export failed");
  344. char *homeDir = NULL;
  345. if (getvnchomedir(&homeDir) == -1)
  346. vlog.error("Could not obtain VNC home directory path");
  347. else {
  348. FILE *f;
  349. CharArray caSave(strlen(homeDir) + 1 + 19);
  350. sprintf(caSave.buf, "%sx509_savedcerts.pem", homeDir);
  351. delete [] homeDir;
  352. f = fopen(caSave.buf, "a+");
  353. if (!f)
  354. msg->showMsgBox(UserMsgBox::M_OK, "certificate save failed",
  355. "Could not save the certificate");
  356. else {
  357. fprintf(f, "%s\n", out_buf);
  358. fclose(f);
  359. }
  360. }
  361. delete [] out_buf;
  362. gnutls_x509_crt_deinit(crt);
  363. /*
  364. * GNUTLS doesn't correctly export gnutls_free symbol which is
  365. * a function pointer. Linking with Visual Studio 2008 Express will
  366. * fail when you call gnutls_free().
  367. */
  368. #if WIN32
  369. free(info.data);
  370. #else
  371. gnutls_free(info.data);
  372. #endif
  373. }