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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. throw new AuthFailureException("Could not obtain VNC home directory "+
  253. "path for known hosts storage");
  254. File dbPath = new File(vncDir, "x509_known_hosts");
  255. String info =
  256. " Subject: "+cert.getSubjectX500Principal().getName()+"\n"+
  257. " Issuer: "+cert.getIssuerX500Principal().getName()+"\n"+
  258. " Serial Number: "+cert.getSerialNumber()+"\n"+
  259. " Version: "+cert.getVersion()+"\n"+
  260. " Signature Algorithm: "+cert.getPublicKey().getAlgorithm()+"\n"+
  261. " Not Valid Before: "+cert.getNotBefore()+"\n"+
  262. " Not Valid After: "+cert.getNotAfter()+"\n"+
  263. " SHA-1 Fingerprint: "+getThumbprint(cert)+"\n";
  264. try {
  265. if (dbPath.exists()) {
  266. FileReader db = new FileReader(dbPath);
  267. BufferedReader dbBuf = new BufferedReader(db);
  268. String line;
  269. String server = client.getServerName().toLowerCase();
  270. while ((line = dbBuf.readLine())!=null) {
  271. String fields[] = line.split("\\|");
  272. if (fields.length==6) {
  273. if (server.equals(fields[2]) && pk.equals(fields[5])) {
  274. vlog.debug("Server certificate found in known hosts file");
  275. dbBuf.close();
  276. return;
  277. } else if (server.equals(fields[2]) && !pk.equals(fields[5]) ||
  278. !server.equals(fields[2]) && pk.equals(fields[5])) {
  279. throw new CertStoreException();
  280. }
  281. }
  282. }
  283. dbBuf.close();
  284. }
  285. tm.checkServerTrusted(chain, authType);
  286. } catch (IOException e) {
  287. throw new AuthFailureException("Could not load known hosts database");
  288. } catch (CertStoreException e) {
  289. vlog.debug("Server host key mismatch");
  290. vlog.debug(info);
  291. String text =
  292. "This host is previously known with a different "+
  293. "certificate, and the new certificate has been "+
  294. "signed by an unknown authority\n"+
  295. "\n"+info+"\n"+
  296. "Someone could be trying to impersonate the site and you should not continue.\n"+
  297. "\n"+
  298. "Do you want to make an exception for this server?";
  299. if (!msg.showMsgBox(YES_NO_OPTION, "Unexpected certificate issuer", text))
  300. throw new AuthFailureException("Unexpected certificate issuer");
  301. store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
  302. } catch (java.lang.Exception e) {
  303. if (e.getCause() instanceof CertPathBuilderException) {
  304. vlog.debug("Server host not previously known");
  305. vlog.debug(info);
  306. String text =
  307. "This certificate has been signed by an unknown authority\n"+
  308. "\n"+info+"\n"+
  309. "Someone could be trying to impersonate the site and you should not continue.\n"+
  310. "\n"+
  311. "Do you want to make an exception for this server?";
  312. if (!msg.showMsgBox(YES_NO_OPTION, "Unknown certificate issuer", text))
  313. throw new AuthFailureException("Unknown certificate issuer");
  314. store_pubkey(dbPath, client.getServerName().toLowerCase(), pk);
  315. } else {
  316. throw new SystemException(e.getMessage());
  317. }
  318. }
  319. }
  320. private void store_pubkey(File dbPath, String serverName, String pk)
  321. {
  322. ArrayList<String> lines = new ArrayList<String>();
  323. File vncDir = new File(FileUtils.getVncHomeDir());
  324. try {
  325. if (dbPath.exists()) {
  326. FileReader db = new FileReader(dbPath);
  327. BufferedReader dbBuf = new BufferedReader(db);
  328. String line;
  329. while ((line = dbBuf.readLine())!=null) {
  330. String fields[] = line.split("\\|");
  331. if (fields.length==6)
  332. if (!serverName.equals(fields[2]) && !pk.equals(fields[5]))
  333. lines.add(line);
  334. }
  335. dbBuf.close();
  336. }
  337. } catch (IOException e) {
  338. throw new AuthFailureException("Could not load known hosts database");
  339. }
  340. try {
  341. if (!dbPath.exists())
  342. dbPath.createNewFile();
  343. FileWriter fw = new FileWriter(dbPath.getAbsolutePath(), false);
  344. Iterator i = lines.iterator();
  345. while (i.hasNext())
  346. fw.write((String)i.next()+"\n");
  347. fw.write("|g0|"+serverName+"|*|0|"+pk+"\n");
  348. fw.close();
  349. } catch (IOException e) {
  350. vlog.error("Failed to store server certificate to known hosts database");
  351. }
  352. }
  353. public X509Certificate[] getAcceptedIssuers ()
  354. {
  355. return tm.getAcceptedIssuers();
  356. }
  357. private String getThumbprint(X509Certificate cert)
  358. {
  359. String thumbprint = null;
  360. try {
  361. MessageDigest md = MessageDigest.getInstance("SHA-1");
  362. md.update(cert.getEncoded());
  363. thumbprint = printHexBinary(md.digest());
  364. thumbprint = thumbprint.replaceAll("..(?!$)", "$0 ");
  365. } catch(CertificateEncodingException e) {
  366. throw new SystemException(e.getMessage());
  367. } catch(NoSuchAlgorithmException e) {
  368. throw new SystemException(e.getMessage());
  369. }
  370. return thumbprint;
  371. }
  372. private void verifyHostname(X509Certificate cert)
  373. throws CertificateParsingException
  374. {
  375. try {
  376. Collection sans = cert.getSubjectAlternativeNames();
  377. if (sans == null) {
  378. String dn = cert.getSubjectX500Principal().getName();
  379. LdapName ln = new LdapName(dn);
  380. for (Rdn rdn : ln.getRdns()) {
  381. if (rdn.getType().equalsIgnoreCase("CN")) {
  382. String peer = client.getServerName().toLowerCase();
  383. if (peer.equals(((String)rdn.getValue()).toLowerCase()))
  384. return;
  385. }
  386. }
  387. } else {
  388. Iterator i = sans.iterator();
  389. while (i.hasNext()) {
  390. List nxt = (List)i.next();
  391. if (((Integer)nxt.get(0)).intValue() == 2) {
  392. String peer = client.getServerName().toLowerCase();
  393. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  394. return;
  395. } else if (((Integer)nxt.get(0)).intValue() == 7) {
  396. String peer = ((CConn)client).getSocket().getPeerAddress();
  397. if (peer.equals(((String)nxt.get(1)).toLowerCase()))
  398. return;
  399. }
  400. }
  401. }
  402. Object[] answer = {"YES", "NO"};
  403. int ret = JOptionPane.showOptionDialog(null,
  404. "Hostname ("+client.getServerName()+") does not match the"+
  405. " server certificate, do you want to continue?",
  406. "Certificate hostname mismatch",
  407. JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
  408. null, answer, answer[0]);
  409. if (ret != JOptionPane.YES_OPTION)
  410. throw new WarningException("Certificate hostname mismatch.");
  411. } catch (CertificateParsingException e) {
  412. throw new SystemException(e.getMessage());
  413. } catch (InvalidNameException e) {
  414. throw new SystemException(e.getMessage());
  415. }
  416. }
  417. private class MyFileInputStream extends InputStream {
  418. // Blank lines in a certificate file will cause Java 6 to throw a
  419. // "DerInputStream.getLength(): lengthTag=127, too big" exception.
  420. ByteBuffer buf;
  421. public MyFileInputStream(String name) {
  422. this(new File(name));
  423. }
  424. public MyFileInputStream(File file) {
  425. StringBuffer sb = new StringBuffer();
  426. BufferedReader reader = null;
  427. try {
  428. reader = new BufferedReader(new FileReader(file));
  429. String l;
  430. while ((l = reader.readLine()) != null) {
  431. if (l.trim().length() > 0 )
  432. sb.append(l+"\n");
  433. }
  434. } catch (java.lang.Exception e) {
  435. throw new Exception(e.toString());
  436. } finally {
  437. try {
  438. if (reader != null)
  439. reader.close();
  440. } catch(IOException ioe) {
  441. throw new Exception(ioe.getMessage());
  442. }
  443. }
  444. Charset utf8 = Charset.forName("UTF-8");
  445. buf = ByteBuffer.wrap(sb.toString().getBytes(utf8));
  446. buf.limit(buf.capacity());
  447. }
  448. @Override
  449. public int read(byte[] b) throws IOException {
  450. return this.read(b, 0, b.length);
  451. }
  452. @Override
  453. public int read(byte[] b, int off, int len) throws IOException {
  454. if (!buf.hasRemaining())
  455. return -1;
  456. len = Math.min(len, buf.remaining());
  457. buf.get(b, off, len);
  458. return len;
  459. }
  460. @Override
  461. public int read() throws IOException {
  462. if (!buf.hasRemaining())
  463. return -1;
  464. return buf.get() & 0xFF;
  465. }
  466. }
  467. }
  468. public final int getType() { return anon ? Security.secTypeTLSNone : Security.secTypeX509None; }
  469. public final String description()
  470. { return anon ? "TLS Encryption without VncAuth" : "X509 Encryption without VncAuth"; }
  471. public boolean isSecure() { return !anon; }
  472. protected CConnection client;
  473. private SSLContext ctx;
  474. private SSLEngine engine;
  475. private SSLEngineManager manager;
  476. private boolean anon;
  477. private String cafile, crlfile;
  478. private FdInStream is;
  479. private FdOutStream os;
  480. static LogWriter vlog = new LogWriter("CSecurityTLS");
  481. }