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.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * Copyright (C) 2004 Red Hat Inc.
  3. * Copyright (C) 2005 Martin Koegler
  4. * Copyright (C) 2010 m-privacy GmbH
  5. * Copyright (C) 2010 TigerVNC Team
  6. * Copyright (C) 2011-2019 Brian P. Hinz
  7. * Copyright (C) 2015 D. R. Commander. All Rights Reserved.
  8. *
  9. * This is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This software is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this software; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  22. * USA.
  23. */
  24. package com.tigervnc.rfb;
  25. import javax.net.ssl.*;
  26. import java.security.KeyManagementException;
  27. import java.security.KeyStore;
  28. import java.security.NoSuchAlgorithmException;
  29. import java.security.MessageDigest;
  30. import java.security.cert.*;
  31. import java.io.BufferedReader;
  32. import java.io.File;
  33. import java.io.FileInputStream;
  34. import java.io.FileNotFoundException;
  35. import java.io.FileReader;
  36. import java.io.FileWriter;
  37. import java.io.InputStream;
  38. import java.io.IOException;
  39. import java.nio.ByteBuffer;
  40. import java.nio.charset.Charset;
  41. import java.util.ArrayList;
  42. import java.util.Base64;
  43. import java.util.Collection;
  44. import java.util.Collections;
  45. import java.util.Iterator;
  46. import java.util.List;
  47. import javax.naming.InvalidNameException;
  48. import javax.naming.ldap.LdapName;
  49. import javax.naming.ldap.Rdn;
  50. import javax.net.ssl.HostnameVerifier;
  51. import javax.swing.JOptionPane;
  52. import com.tigervnc.rdr.*;
  53. import com.tigervnc.network.*;
  54. import com.tigervnc.vncviewer.*;
  55. import static javax.swing.JOptionPane.*;
  56. public class CSecurityTLS extends CSecurity {
  57. public static StringParameter X509CA
  58. = new StringParameter("X509CA",
  59. "X509 CA certificate", "", Configuration.ConfigurationObject.ConfViewer);
  60. public static StringParameter X509CRL
  61. = new StringParameter("X509CRL",
  62. "X509 CRL file", "", Configuration.ConfigurationObject.ConfViewer);
  63. public static UserMsgBox msg;
  64. private void initGlobal()
  65. {
  66. try {
  67. ctx = SSLContext.getInstance("TLS");
  68. } catch(NoSuchAlgorithmException e) {
  69. throw new Exception(e.toString());
  70. }
  71. }
  72. public CSecurityTLS(boolean _anon)
  73. {
  74. anon = _anon;
  75. manager = null;
  76. setDefaults();
  77. cafile = X509CA.getData();
  78. crlfile = X509CRL.getData();
  79. }
  80. public static String getDefaultCA() {
  81. if (UserPreferences.get("viewer", "x509ca") != null)
  82. return UserPreferences.get("viewer", "x509ca");
  83. return FileUtils.getVncHomeDir()+"x509_ca.pem";
  84. }
  85. public static String getDefaultCRL() {
  86. if (UserPreferences.get("viewer", "x509crl") != null)
  87. return UserPreferences.get("viewer", "x509crl");
  88. return FileUtils.getVncHomeDir()+"x509_crl.pem";
  89. }
  90. public static void setDefaults()
  91. {
  92. if (new File(getDefaultCA()).exists())
  93. X509CA.setDefaultStr(getDefaultCA());
  94. if (new File(getDefaultCRL()).exists())
  95. X509CRL.setDefaultStr(getDefaultCRL());
  96. }
  97. // FIXME:
  98. // Need to shutdown the connection cleanly
  99. // FIXME?
  100. // add a finalizer method that calls shutdown
  101. public boolean processMsg(CConnection cc) {
  102. is = (FdInStream)cc.getInStream();
  103. os = (FdOutStream)cc.getOutStream();
  104. client = cc;
  105. initGlobal();
  106. if (manager == null) {
  107. if (!is.checkNoWait(1))
  108. return false;
  109. if (is.readU8() == 0) {
  110. int result = is.readU32();
  111. String reason;
  112. if (result == Security.secResultFailed ||
  113. result == Security.secResultTooMany)
  114. reason = is.readString();
  115. else
  116. reason = new String("Authentication failure (protocol error)");
  117. throw new AuthFailureException(reason);
  118. }
  119. setParam();
  120. }
  121. try {
  122. manager = new SSLEngineManager(engine, is, os);
  123. manager.doHandshake();
  124. } catch(java.lang.Exception e) {
  125. throw new SystemException(e.toString());
  126. }
  127. cc.setStreams(new TLSInStream(is, manager),
  128. new TLSOutStream(os, manager));
  129. return true;
  130. }
  131. private void setParam() {
  132. if (anon) {
  133. try {
  134. ctx.init(null, null, null);
  135. } catch(KeyManagementException e) {
  136. throw new AuthFailureException(e.toString());
  137. }
  138. } else {
  139. try {
  140. TrustManager[] myTM = new TrustManager[] {
  141. new MyX509TrustManager()
  142. };
  143. ctx.init (null, myTM, null);
  144. } catch (java.security.GeneralSecurityException e) {
  145. throw new AuthFailureException(e.toString());
  146. }
  147. }
  148. SSLSocketFactory sslfactory = ctx.getSocketFactory();
  149. engine = ctx.createSSLEngine(client.getServerName(),
  150. client.getServerPort());
  151. engine.setUseClientMode(true);
  152. String[] supported = engine.getSupportedProtocols();
  153. ArrayList<String> enabled = new ArrayList<String>();
  154. for (int i = 0; i < supported.length; i++)
  155. if (supported[i].matches("TLS.*"))
  156. enabled.add(supported[i]);
  157. engine.setEnabledProtocols(enabled.toArray(new String[0]));
  158. if (anon) {
  159. supported = engine.getSupportedCipherSuites();
  160. enabled = new ArrayList<String>();
  161. // prefer ECDH over DHE
  162. for (int i = 0; i < supported.length; i++)
  163. if (supported[i].matches("TLS_ECDH_anon.*"))
  164. enabled.add(supported[i]);
  165. for (int i = 0; i < supported.length; i++)
  166. if (supported[i].matches("TLS_DH_anon.*"))
  167. enabled.add(supported[i]);
  168. engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
  169. } else {
  170. engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
  171. }
  172. }
  173. class MyX509TrustManager implements X509TrustManager
  174. {
  175. X509TrustManager tm;
  176. MyX509TrustManager() throws java.security.GeneralSecurityException
  177. {
  178. KeyStore ks = KeyStore.getInstance("JKS");
  179. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  180. try {
  181. ks.load(null, null);
  182. String a = TrustManagerFactory.getDefaultAlgorithm();
  183. TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
  184. tmf.init((KeyStore)null);
  185. for (TrustManager m : tmf.getTrustManagers())
  186. if (m instanceof X509TrustManager)
  187. for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
  188. ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
  189. File cacert = new File(cafile);
  190. if (cacert.exists() && cacert.canRead()) {
  191. InputStream caStream = new MyFileInputStream(cacert);
  192. Collection<? extends Certificate> cacerts =
  193. cf.generateCertificates(caStream);
  194. for (Certificate cert : cacerts) {
  195. String thumbprint = getThumbprint((X509Certificate)cert);
  196. ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
  197. }
  198. }
  199. PKIXBuilderParameters params =
  200. new PKIXBuilderParameters(ks, new X509CertSelector());
  201. File crlcert = new File(crlfile);
  202. if (!crlcert.exists() || !crlcert.canRead()) {
  203. params.setRevocationEnabled(false);
  204. } else {
  205. InputStream crlStream = new FileInputStream(crlfile);
  206. Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
  207. CertStoreParameters csp = new CollectionCertStoreParameters(crls);
  208. CertStore store = CertStore.getInstance("Collection", csp);
  209. params.addCertStore(store);
  210. params.setRevocationEnabled(true);
  211. }
  212. tmf = TrustManagerFactory.getInstance("PKIX");
  213. tmf.init(new CertPathTrustManagerParameters(params));
  214. tm = (X509TrustManager)tmf.getTrustManagers()[0];
  215. } catch (java.lang.Exception e) {
  216. throw new Exception(e.getMessage());
  217. }
  218. }
  219. public void checkClientTrusted(X509Certificate[] chain, String authType)
  220. throws CertificateException
  221. {
  222. tm.checkClientTrusted(chain, authType);
  223. }
  224. private final char[] hexCode = "0123456789ABCDEF".toCharArray();
  225. private String printHexBinary(byte[] data)
  226. {
  227. StringBuilder r = new StringBuilder(data.length*2);
  228. for (byte b : data) {
  229. r.append(hexCode[(b >> 4) & 0xF]);
  230. r.append(hexCode[(b & 0xF)]);
  231. }
  232. return r.toString();
  233. }
  234. public void checkServerTrusted(X509Certificate[] chain, String authType)
  235. throws CertificateException
  236. {
  237. Collection<? extends Certificate> certs = null;
  238. X509Certificate cert = chain[0];
  239. try {
  240. cert.checkValidity();
  241. } catch(CertificateNotYetValidException e) {
  242. throw new AuthFailureException("server certificate has not been activated");
  243. } catch(CertificateExpiredException e) {
  244. if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
  245. "The certificate of the server has expired, "+
  246. "do you want to continue?"))
  247. throw new AuthFailureException("server certificate has expired");
  248. }
  249. String thumbprint = getThumbprint(cert);
  250. File vncDir = new File(FileUtils.getVncHomeDir());
  251. File certFile = new File(vncDir, "x509_savedcerts.pem");
  252. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  253. if (vncDir.exists() && certFile.exists() && certFile.canRead()) {
  254. InputStream certStream = new MyFileInputStream(certFile);
  255. certs = cf.generateCertificates(certStream);
  256. for (Certificate c : certs)
  257. if (thumbprint.equals(getThumbprint((X509Certificate)c)))
  258. return;
  259. }
  260. try {
  261. verifyHostname(cert);
  262. tm.checkServerTrusted(chain, authType);
  263. } catch (java.lang.Exception e) {
  264. if (e.getCause() instanceof CertPathBuilderException) {
  265. String certinfo =
  266. "This certificate has been signed by an unknown authority\n"+
  267. "\n"+
  268. " Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
  269. " Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
  270. " Serial Number: "+cert.getSerialNumber()+"\n"+
  271. " Version: "+cert.getVersion()+"\n"+
  272. " Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
  273. " Not Valid Before: "+cert.getNotBefore()+"\n"+
  274. " Not Valid After: "+cert.getNotAfter()+"\n"+
  275. " SHA1 Fingerprint: "+getThumbprint(cert)+"\n"+
  276. "\n"+
  277. "Do you want to save it and continue?";
  278. if (!msg.showMsgBox(YES_NO_OPTION, "certificate issuer unknown",
  279. certinfo)) {
  280. throw new AuthFailureException("certificate issuer unknown");
  281. }
  282. if (certs == null || !certs.contains(cert)) {
  283. byte[] der = cert.getEncoded();
  284. String pem = Base64.getEncoder().encodeToString(der);
  285. pem = pem.replaceAll("(.{64})", "$1\n");
  286. FileWriter fw = null;
  287. try {
  288. if (!vncDir.exists())
  289. vncDir.mkdir();
  290. if (!certFile.exists() && !certFile.createNewFile()) {
  291. vlog.error("Certificate save failed.");
  292. } else {
  293. fw = new FileWriter(certFile.getAbsolutePath(), true);
  294. fw.write("-----BEGIN CERTIFICATE-----\n");
  295. fw.write(pem+"\n");
  296. fw.write("-----END CERTIFICATE-----\n");
  297. }
  298. } catch (IOException ioe) {
  299. msg.showMsgBox(OK_OPTION, "certificate save failed",
  300. "Could not save the certificate");
  301. } finally {
  302. try {
  303. if (fw != null)
  304. fw.close();
  305. } catch(IOException ioe2) {
  306. throw new Exception(ioe2.getMessage());
  307. }
  308. }
  309. }
  310. } else {
  311. throw new SystemException(e.getMessage());
  312. }
  313. }
  314. }
  315. public X509Certificate[] getAcceptedIssuers ()
  316. {
  317. return tm.getAcceptedIssuers();
  318. }
  319. private String getThumbprint(X509Certificate cert)
  320. {
  321. String thumbprint = null;
  322. try {
  323. MessageDigest md = MessageDigest.getInstance("SHA-1");
  324. md.update(cert.getEncoded());
  325. thumbprint = printHexBinary(md.digest());
  326. thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
  327. } catch(CertificateEncodingException e) {
  328. throw new SystemException(e.getMessage());
  329. } catch(NoSuchAlgorithmException e) {
  330. throw new SystemException(e.getMessage());
  331. }
  332. return thumbprint;
  333. }
  334. private void verifyHostname(X509Certificate cert)
  335. throws CertificateParsingException
  336. {
  337. try {
  338. Collection sans = cert.getSubjectAlternativeNames();
  339. if (sans == null) {
  340. String dn = cert.getSubjectX500Principal().getName();
  341. LdapName ln = new LdapName(dn);
  342. for (Rdn rdn : ln.getRdns()) {
  343. if (rdn.getType().equalsIgnoreCase("CN")) {
  344. String peer =
  345. ((CConn)client).getSocket().getPeerName().toLowerCase();
  346. if (peer.equals(((String)rdn.getValue()).toLowerCase()))
  347. return;
  348. }
  349. }
  350. } else {
  351. Iterator i = sans.iterator();
  352. while (i.hasNext()) {
  353. List nxt = (List)i.next();
  354. if (((Integer)nxt.get(0)).intValue() == 2) {
  355. String peer =
  356. ((CConn)client).getSocket().getPeerName().toLowerCase();
  357. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  358. return;
  359. } else if (((Integer)nxt.get(0)).intValue() == 7) {
  360. String peer = ((CConn)client).getSocket().getPeerAddress();
  361. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  362. return;
  363. }
  364. }
  365. }
  366. Object[] answer = {"YES", "NO"};
  367. int ret = JOptionPane.showOptionDialog(null,
  368. "Hostname verification failed. Do you want to continue?",
  369. "Hostname Verification Failure",
  370. JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
  371. null, answer, answer[0]);
  372. if (ret != JOptionPane.YES_OPTION)
  373. throw new WarningException("Hostname verification failed.");
  374. } catch (CertificateParsingException e) {
  375. throw new SystemException(e.getMessage());
  376. } catch (InvalidNameException e) {
  377. throw new SystemException(e.getMessage());
  378. }
  379. }
  380. private class MyFileInputStream extends InputStream {
  381. // Blank lines in a certificate file will cause Java 6 to throw a
  382. // "DerInputStream.getLength(): lengthTag=127, too big" exception.
  383. ByteBuffer buf;
  384. public MyFileInputStream(String name) {
  385. this(new File(name));
  386. }
  387. public MyFileInputStream(File file) {
  388. StringBuffer sb = new StringBuffer();
  389. BufferedReader reader = null;
  390. try {
  391. reader = new BufferedReader(new FileReader(file));
  392. String l;
  393. while ((l = reader.readLine()) != null) {
  394. if (l.trim().length() > 0 )
  395. sb.append(l+"\n");
  396. }
  397. } catch (java.lang.Exception e) {
  398. throw new Exception(e.toString());
  399. } finally {
  400. try {
  401. if (reader != null)
  402. reader.close();
  403. } catch(IOException ioe) {
  404. throw new Exception(ioe.getMessage());
  405. }
  406. }
  407. Charset utf8 = Charset.forName("UTF-8");
  408. buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
  409. buf.limit(buf.capacity());
  410. }
  411. @Override
  412. public int read(byte[] b) throws IOException {
  413. return this.read(b, 0, b.length);
  414. }
  415. @Override
  416. public int read(byte[] b, int off, int len) throws IOException {
  417. if (!buf.hasRemaining())
  418. return -1;
  419. len = Math.min(len, buf.remaining());
  420. buf.get(b, off, len);
  421. return len;
  422. }
  423. @Override
  424. public int read() throws IOException {
  425. if (!buf.hasRemaining())
  426. return -1;
  427. return buf.get() & 0xFF;
  428. }
  429. }
  430. }
  431. public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
  432. public final String description()
  433. { return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
  434. public boolean isSecure() { return !anon; }
  435. protected CConnection client;
  436. private SSLContext ctx;
  437. private SSLEngine engine;
  438. private SSLEngineManager manager;
  439. private boolean anon;
  440. private String cafile, crlfile;
  441. private FdInStream is;
  442. private FdOutStream os;
  443. static LogWriter vlog = new LogWriter("CSecurityTLS");
  444. }