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

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