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