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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. /* Load previously saved certs */
  201. char *homeDir = NULL;
  202. int err;
  203. if (getvnchomedir(&homeDir) == -1)
  204. vlog.error("Could not obtain VNC home directory path");
  205. else {
  206. CharArray caSave(strlen(homeDir) + 19 + 1);
  207. sprintf(caSave.buf, "%sx509_savedcerts.pem", homeDir);
  208. delete [] homeDir;
  209. err = gnutls_certificate_set_x509_trust_file(cert_cred, caSave.buf,
  210. GNUTLS_X509_FMT_PEM);
  211. if (err < 0)
  212. vlog.debug("Failed to load saved server certificates from %s", caSave.buf);
  213. }
  214. if (*crlfile && gnutls_certificate_set_x509_crl_file(cert_cred,crlfile,GNUTLS_X509_FMT_PEM) < 0)
  215. throw AuthFailureException("load of CRL failed");
  216. if (gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred) != GNUTLS_E_SUCCESS)
  217. throw AuthFailureException("gnutls_credentials_set failed");
  218. if (gnutls_server_name_set(session, GNUTLS_NAME_DNS,
  219. client->getServerName(),
  220. strlen(client->getServerName())) != GNUTLS_E_SUCCESS)
  221. vlog.error("Failed to configure the server name for TLS handshake");
  222. vlog.debug("X509 session has been set");
  223. }
  224. }
  225. void CSecurityTLS::checkSession()
  226. {
  227. const unsigned allowed_errors = GNUTLS_CERT_INVALID |
  228. GNUTLS_CERT_SIGNER_NOT_FOUND |
  229. GNUTLS_CERT_SIGNER_NOT_CA;
  230. unsigned int status;
  231. const gnutls_datum_t *cert_list;
  232. unsigned int cert_list_size = 0;
  233. int err;
  234. gnutls_datum_t info;
  235. if (anon)
  236. return;
  237. if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
  238. throw AuthFailureException("unsupported certificate type");
  239. err = gnutls_certificate_verify_peers2(session, &status);
  240. if (err != 0) {
  241. vlog.error("server certificate verification failed: %s", gnutls_strerror(err));
  242. throw AuthFailureException("server certificate verification failed");
  243. }
  244. if (status & GNUTLS_CERT_REVOKED)
  245. throw AuthFailureException("server certificate has been revoked");
  246. #ifndef WITHOUT_X509_TIMES
  247. if (status & GNUTLS_CERT_NOT_ACTIVATED)
  248. throw AuthFailureException("server certificate has not been activated");
  249. if (status & GNUTLS_CERT_EXPIRED) {
  250. vlog.debug("server certificate has expired");
  251. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate has expired",
  252. "The certificate of the server has expired, "
  253. "do you want to continue?"))
  254. throw AuthFailureException("server certificate has expired");
  255. }
  256. #endif
  257. /* Process other errors later */
  258. cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
  259. if (!cert_list_size)
  260. throw AuthFailureException("empty certificate chain");
  261. /* Process only server's certificate, not issuer's certificate */
  262. gnutls_x509_crt_t crt;
  263. gnutls_x509_crt_init(&crt);
  264. if (gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER) < 0)
  265. throw AuthFailureException("decoding of certificate failed");
  266. if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) {
  267. char buf[255];
  268. vlog.debug("hostname mismatch");
  269. snprintf(buf, sizeof(buf), "Hostname (%s) does not match any certificate, "
  270. "do you want to continue?", client->getServerName());
  271. buf[sizeof(buf) - 1] = '\0';
  272. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "hostname mismatch", buf))
  273. throw AuthFailureException("hostname mismatch");
  274. }
  275. if (status == 0) {
  276. /* Everything is fine (hostname + verification) */
  277. gnutls_x509_crt_deinit(crt);
  278. return;
  279. }
  280. if (status & GNUTLS_CERT_INVALID)
  281. vlog.debug("server certificate invalid");
  282. if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
  283. vlog.debug("server cert signer not found");
  284. if (status & GNUTLS_CERT_SIGNER_NOT_CA)
  285. vlog.debug("server cert signer not CA");
  286. if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
  287. throw AuthFailureException("The server certificate uses an insecure algorithm");
  288. if ((status & (~allowed_errors)) != 0) {
  289. /* No other errors are allowed */
  290. vlog.debug("GNUTLS status of certificate verification: %u", status);
  291. throw AuthFailureException("Invalid status of server certificate verification");
  292. }
  293. vlog.debug("Saved server certificates don't match");
  294. if (gnutls_x509_crt_print(crt, GNUTLS_CRT_PRINT_ONELINE, &info)) {
  295. /*
  296. * GNUTLS doesn't correctly export gnutls_free symbol which is
  297. * a function pointer. Linking with Visual Studio 2008 Express will
  298. * fail when you call gnutls_free().
  299. */
  300. #if WIN32
  301. free(info.data);
  302. #else
  303. gnutls_free(info.data);
  304. #endif
  305. throw AuthFailureException("Could not find certificate to display");
  306. }
  307. size_t out_size = 0;
  308. char *out_buf = NULL;
  309. char *certinfo = NULL;
  310. int len = 0;
  311. vlog.debug("certificate issuer unknown");
  312. len = snprintf(NULL, 0, "This certificate has been signed by an unknown "
  313. "authority:\n\n%s\n\nDo you want to save it and "
  314. "continue?\n ", info.data);
  315. if (len < 0)
  316. AuthFailureException("certificate decoding error");
  317. vlog.debug("%s", info.data);
  318. certinfo = new char[len];
  319. if (certinfo == NULL)
  320. throw AuthFailureException("Out of memory");
  321. snprintf(certinfo, len, "This certificate has been signed by an unknown "
  322. "authority:\n\n%s\n\nDo you want to save it and "
  323. "continue? ", info.data);
  324. for (int i = 0; i < len - 1; i++)
  325. if (certinfo[i] == ',' && certinfo[i + 1] == ' ')
  326. certinfo[i] = '\n';
  327. if (!msg->showMsgBox(UserMsgBox::M_YESNO, "certificate issuer unknown",
  328. certinfo)) {
  329. delete [] certinfo;
  330. throw AuthFailureException("certificate issuer unknown");
  331. }
  332. delete [] certinfo;
  333. if (gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, NULL, &out_size)
  334. == GNUTLS_E_SHORT_MEMORY_BUFFER)
  335. AuthFailureException("Out of memory");
  336. // Save cert
  337. out_buf = new char[out_size];
  338. if (out_buf == NULL)
  339. AuthFailureException("Out of memory");
  340. if (gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, out_buf, &out_size) < 0)
  341. AuthFailureException("certificate issuer unknown, and certificate "
  342. "export failed");
  343. char *homeDir = NULL;
  344. if (getvnchomedir(&homeDir) == -1)
  345. vlog.error("Could not obtain VNC home directory path");
  346. else {
  347. FILE *f;
  348. CharArray caSave(strlen(homeDir) + 1 + 19);
  349. sprintf(caSave.buf, "%sx509_savedcerts.pem", homeDir);
  350. delete [] homeDir;
  351. f = fopen(caSave.buf, "a+");
  352. if (!f)
  353. msg->showMsgBox(UserMsgBox::M_OK, "certificate save failed",
  354. "Could not save the certificate");
  355. else {
  356. fprintf(f, "%s\n", out_buf);
  357. fclose(f);
  358. }
  359. }
  360. delete [] out_buf;
  361. gnutls_x509_crt_deinit(crt);
  362. /*
  363. * GNUTLS doesn't correctly export gnutls_free symbol which is
  364. * a function pointer. Linking with Visual Studio 2008 Express will
  365. * fail when you call gnutls_free().
  366. */
  367. #if WIN32
  368. free(info.data);
  369. #else
  370. gnutls_free(info.data);
  371. #endif
  372. }