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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. public boolean processMsg(CConnection cc) {
  98. is = (FdInStream)cc.getInStream();
  99. os = (FdOutStream)cc.getOutStream();
  100. client = cc;
  101. initGlobal();
  102. if (manager == null) {
  103. if (!is.checkNoWait(1))
  104. return false;
  105. if (is.readU8() == 0) {
  106. int result = is.readU32();
  107. String reason;
  108. if (result == Security.secResultFailed ||
  109. result == Security.secResultTooMany)
  110. reason = is.readString();
  111. else
  112. reason = new String("Authentication failure (protocol error)");
  113. throw new AuthFailureException(reason);
  114. }
  115. setParam();
  116. }
  117. try {
  118. manager = new SSLEngineManager(engine, is, os);
  119. manager.doHandshake();
  120. } catch(java.lang.Exception e) {
  121. throw new SystemException(e.toString());
  122. }
  123. cc.setStreams(new TLSInStream(is, manager),
  124. new TLSOutStream(os, manager));
  125. return true;
  126. }
  127. private void setParam() {
  128. if (anon) {
  129. try {
  130. ctx.init(null, null, null);
  131. } catch(KeyManagementException e) {
  132. throw new AuthFailureException(e.toString());
  133. }
  134. } else {
  135. try {
  136. TrustManager[] myTM = new TrustManager[] {
  137. new MyX509TrustManager()
  138. };
  139. ctx.init (null, myTM, null);
  140. } catch (java.security.GeneralSecurityException e) {
  141. throw new AuthFailureException(e.toString());
  142. }
  143. }
  144. SSLSocketFactory sslfactory = ctx.getSocketFactory();
  145. engine = ctx.createSSLEngine(client.getServerName(),
  146. client.getServerPort());
  147. engine.setUseClientMode(true);
  148. String[] supported = engine.getSupportedProtocols();
  149. ArrayList<String> enabled = new ArrayList<String>();
  150. for (int i = 0; i < supported.length; i++)
  151. if (supported[i].matches("TLS.*"))
  152. enabled.add(supported[i]);
  153. engine.setEnabledProtocols(enabled.toArray(new String[0]));
  154. if (anon) {
  155. supported = engine.getSupportedCipherSuites();
  156. enabled = new ArrayList<String>();
  157. // prefer ECDH over DHE
  158. for (int i = 0; i < supported.length; i++)
  159. if (supported[i].matches("TLS_ECDH_anon.*"))
  160. enabled.add(supported[i]);
  161. for (int i = 0; i < supported.length; i++)
  162. if (supported[i].matches("TLS_DH_anon.*"))
  163. enabled.add(supported[i]);
  164. engine.setEnabledCipherSuites(enabled.toArray(new String[0]));
  165. } else {
  166. engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
  167. }
  168. }
  169. class MyX509TrustManager implements X509TrustManager
  170. {
  171. X509TrustManager tm;
  172. MyX509TrustManager() throws java.security.GeneralSecurityException
  173. {
  174. KeyStore ks = KeyStore.getInstance("JKS");
  175. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  176. try {
  177. ks.load(null, null);
  178. String a = TrustManagerFactory.getDefaultAlgorithm();
  179. TrustManagerFactory tmf = TrustManagerFactory.getInstance(a);
  180. tmf.init((KeyStore)null);
  181. for (TrustManager m : tmf.getTrustManagers())
  182. if (m instanceof X509TrustManager)
  183. for (X509Certificate c : ((X509TrustManager)m).getAcceptedIssuers())
  184. ks.setCertificateEntry(getThumbprint((X509Certificate)c), c);
  185. File cacert = new File(cafile);
  186. if (cacert.exists() && cacert.canRead()) {
  187. InputStream caStream = new MyFileInputStream(cacert);
  188. Collection<? extends Certificate> cacerts =
  189. cf.generateCertificates(caStream);
  190. for (Certificate cert : cacerts) {
  191. String thumbprint = getThumbprint((X509Certificate)cert);
  192. ks.setCertificateEntry(thumbprint, (X509Certificate)cert);
  193. }
  194. }
  195. PKIXBuilderParameters params =
  196. new PKIXBuilderParameters(ks, new X509CertSelector());
  197. File crlcert = new File(crlfile);
  198. if (!crlcert.exists() || !crlcert.canRead()) {
  199. params.setRevocationEnabled(false);
  200. } else {
  201. InputStream crlStream = new FileInputStream(crlfile);
  202. Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
  203. CertStoreParameters csp = new CollectionCertStoreParameters(crls);
  204. CertStore store = CertStore.getInstance("Collection", csp);
  205. params.addCertStore(store);
  206. params.setRevocationEnabled(true);
  207. }
  208. tmf = TrustManagerFactory.getInstance("PKIX");
  209. tmf.init(new CertPathTrustManagerParameters(params));
  210. tm = (X509TrustManager)tmf.getTrustManagers()[0];
  211. } catch (java.lang.Exception e) {
  212. throw new Exception(e.getMessage());
  213. }
  214. }
  215. public void checkClientTrusted(X509Certificate[] chain, String authType)
  216. throws CertificateException
  217. {
  218. tm.checkClientTrusted(chain, authType);
  219. }
  220. private final char[] hexCode = "0123456789ABCDEF".toCharArray();
  221. private String printHexBinary(byte[] data)
  222. {
  223. StringBuilder r = new StringBuilder(data.length*2);
  224. for (byte b : data) {
  225. r.append(hexCode[(b >> 4) & 0xF]);
  226. r.append(hexCode[(b & 0xF)]);
  227. }
  228. return r.toString();
  229. }
  230. public void checkServerTrusted(X509Certificate[] chain, String authType)
  231. throws CertificateException
  232. {
  233. Collection<? extends Certificate> certs = null;
  234. X509Certificate cert = chain[0];
  235. String pk =
  236. Base64.getEncoder().encodeToString(cert.getPublicKey().getEncoded());
  237. try {
  238. cert.checkValidity();
  239. verifyHostname(cert);
  240. } catch(CertificateParsingException e) {
  241. throw new SystemException(e.getMessage());
  242. } catch(CertificateNotYetValidException e) {
  243. throw new AuthFailureException("server certificate has not been activated");
  244. } catch(CertificateExpiredException e) {
  245. if (!msg.showMsgBox(YES_NO_OPTION, "certificate has expired",
  246. "The certificate of the server has expired, "+
  247. "do you want to continue?"))
  248. throw new AuthFailureException("server certificate has expired");
  249. }
  250. File vncDir = new File(FileUtils.getVncHomeDir());
  251. if (!vncDir.exists()) {
  252. try {
  253. vncDir.mkdir();
  254. } catch(SecurityException e) {
  255. throw new AuthFailureException("Could not obtain VNC home directory "+
  256. "path for known hosts storage");
  257. }
  258. }
  259. File dbPath = new File(vncDir, "x509_known_hosts");
  260. String info =
  261. " Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
  262. " Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
  263. " Serial Number: "+cert.getSerialNumber()+"\n"+
  264. " Version: "+cert.getVersion()+"\n"+
  265. " Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
  266. " Not Valid Before: "+cert.getNotBefore()+"\n"+
  267. " Not Valid After: "+cert.getNotAfter()+"\n"+
  268. " SHA-1 Fingerprint: "+getThumbprint(cert)+"\n";
  269. try {
  270. if (dbPath.exists()) {
  271. FileReader db = new FileReader(dbPath);
  272. BufferedReader dbBuf = new BufferedReader(db);
  273. String line;
  274. String server = client.getServerName().toLowerCase();
  275. while ((line = dbBuf.readLine())!=null) {
  276. String fields[] = line.split("\\|");
  277. if (fields.length==6) {
  278. if (server.equals(fields[2]) && pk.equals(fields[5])) {
  279. vlog.debug("Server certificate found in known hosts file");
  280. dbBuf.close();
  281. return;
  282. } else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||
  283. !server.equals(fields[2]) && pk.equals(fields[5])) {
  284. throw new CertStoreException();
  285. }
  286. }
  287. }
  288. dbBuf.close();
  289. }
  290. tm.checkServerTrusted(chain, authType);
  291. } catch (IOException e) {
  292. throw new AuthFailureException("Could not load known hosts database");
  293. } catch (CertStoreException e) {
  294. vlog.debug("Server host key mismatch");
  295. vlog.debug(info);
  296. String text =
  297. "This host is previously known with a different "+
  298. "certificate, and the new certificate has been "+
  299. "signed by an unknown authority\n"+
  300. "\n"+info+"\n"+
  301. "Someone could be trying to impersonate the site and you should not continue.\n"+
  302. "\n"+
  303. "Do you want to make an exception for this server?";
  304. if (!msg.showMsgBox(YES_NO_OPTION, "Unexpected certificate issuer", text))
  305. throw new AuthFailureException("Unexpected certificate issuer");
  306. store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
  307. } catch (java.lang.Exception e) {
  308. if (e.getCause() instanceof CertPathBuilderException) {
  309. vlog.debug("Server host not previously known");
  310. vlog.debug(info);
  311. String text =
  312. "This certificate has been signed by an unknown authority\n"+
  313. "\n"+info+"\n"+
  314. "Someone could be trying to impersonate the site and you should not continue.\n"+
  315. "\n"+
  316. "Do you want to make an exception for this server?";
  317. if (!msg.showMsgBox(YES_NO_OPTION, "Unknown certificate issuer", text))
  318. throw new AuthFailureException("Unknown certificate issuer");
  319. store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
  320. } else {
  321. throw new SystemException(e.getMessage());
  322. }
  323. }
  324. }
  325. private void store_pubkey(File dbPath, String serverName, String pk)
  326. {
  327. ArrayList<String> lines = new ArrayList<String>();
  328. File vncDir = new File(FileUtils.getVncHomeDir());
  329. try {
  330. if (dbPath.exists()) {
  331. FileReader db = new FileReader(dbPath);
  332. BufferedReader dbBuf = new BufferedReader(db);
  333. String line;
  334. while ((line = dbBuf.readLine())!=null) {
  335. String fields[] = line.split("\\|");
  336. if (fields.length==6)
  337. if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))
  338. lines.add(line);
  339. }
  340. dbBuf.close();
  341. }
  342. } catch (IOException e) {
  343. throw new AuthFailureException("Could not load known hosts database");
  344. }
  345. try {
  346. if (!dbPath.exists())
  347. dbPath.createNewFile();
  348. FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);
  349. Iterator i = lines.iterator();
  350. while (i.hasNext())
  351. fw.write((String)i.next()+"\n");
  352. fw.write("|g0|"+serverName+"|*|0|"+pk+"\n");
  353. fw.close();
  354. } catch (IOException e) {
  355. vlog.error("Failed to store server certificate to known hosts database");
  356. }
  357. }
  358. public X509Certificate[] getAcceptedIssuers ()
  359. {
  360. return tm.getAcceptedIssuers();
  361. }
  362. private String getThumbprint(X509Certificate cert)
  363. {
  364. String thumbprint = null;
  365. try {
  366. MessageDigest md = MessageDigest.getInstance("SHA-1");
  367. md.update(cert.getEncoded());
  368. thumbprint = printHexBinary(md.digest());
  369. thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
  370. } catch(CertificateEncodingException e) {
  371. throw new SystemException(e.getMessage());
  372. } catch(NoSuchAlgorithmException e) {
  373. throw new SystemException(e.getMessage());
  374. }
  375. return thumbprint;
  376. }
  377. private void verifyHostname(X509Certificate cert)
  378. throws CertificateParsingException
  379. {
  380. try {
  381. Collection sans = cert.getSubjectAlternativeNames();
  382. if (sans == null) {
  383. String dn = cert.getSubjectX500Principal().getName();
  384. LdapName ln = new LdapName(dn);
  385. for (Rdn rdn : ln.getRdns()) {
  386. if (rdn.getType().equalsIgnoreCase("CN")) {
  387. String peer = client.getServerName().toLowerCase();
  388. if (peer.equals(((String)rdn.getValue()).toLowerCase()))
  389. return;
  390. }
  391. }
  392. } else {
  393. Iterator i = sans.iterator();
  394. while (i.hasNext()) {
  395. List nxt = (List)i.next();
  396. if (((Integer)nxt.get(0)).intValue() == 2) {
  397. String peer = client.getServerName().toLowerCase();
  398. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  399. return;
  400. } else if (((Integer)nxt.get(0)).intValue() == 7) {
  401. String peer = ((CConn)client).getSocket().getPeerAddress();
  402. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  403. return;
  404. }
  405. }
  406. }
  407. Object[] answer = {"YES", "NO"};
  408. int ret = JOptionPane.showOptionDialog(null,
  409. "Hostname ("+client.getServerName()+") does not match the"+
  410. " server certificate, do you want to continue?",
  411. "Certificate hostname mismatch",
  412. JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
  413. null, answer, answer[0]);
  414. if (ret != JOptionPane.YES_OPTION)
  415. throw new WarningException("Certificate hostname mismatch.");
  416. } catch (CertificateParsingException e) {
  417. throw new SystemException(e.getMessage());
  418. } catch (InvalidNameException e) {
  419. throw new SystemException(e.getMessage());
  420. }
  421. }
  422. private class MyFileInputStream extends InputStream {
  423. // Blank lines in a certificate file will cause Java 6 to throw a
  424. // "DerInputStream.getLength(): lengthTag=127, too big" exception.
  425. ByteBuffer buf;
  426. public MyFileInputStream(String name) {
  427. this(new File(name));
  428. }
  429. public MyFileInputStream(File file) {
  430. StringBuffer sb = new StringBuffer();
  431. BufferedReader reader = null;
  432. try {
  433. reader = new BufferedReader(new FileReader(file));
  434. String l;
  435. while ((l = reader.readLine()) != null) {
  436. if (l.trim().length() > 0 )
  437. sb.append(l+"\n");
  438. }
  439. } catch (java.lang.Exception e) {
  440. throw new Exception(e.toString());
  441. } finally {
  442. try {
  443. if (reader != null)
  444. reader.close();
  445. } catch(IOException ioe) {
  446. throw new Exception(ioe.getMessage());
  447. }
  448. }
  449. Charset utf8 = Charset.forName("UTF-8");
  450. buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
  451. buf.limit(buf.capacity());
  452. }
  453. @Override
  454. public int read(byte[] b) throws IOException {
  455. return this.read(b, 0, b.length);
  456. }
  457. @Override
  458. public int read(byte[] b, int off, int len) throws IOException {
  459. if (!buf.hasRemaining())
  460. return -1;
  461. len = Math.min(len, buf.remaining());
  462. buf.get(b, off, len);
  463. return len;
  464. }
  465. @Override
  466. public int read() throws IOException {
  467. if (!buf.hasRemaining())
  468. return -1;
  469. return buf.get() & 0xFF;
  470. }
  471. }
  472. }
  473. public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
  474. public final String description()
  475. { return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
  476. public boolean isSecure() { return !anon; }
  477. protected CConnection client;
  478. private SSLContext ctx;
  479. private SSLEngine engine;
  480. private SSLEngineManager manager;
  481. private boolean anon;
  482. private String cafile, crlfile;
  483. private FdInStream is;
  484. private FdOutStream os;
  485. static LogWriter vlog = new LogWriter("CSecurityTLS");
  486. }