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.

CertificateManager.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.tls;
  18. import com.dmdirc.config.provider.AggregateConfigProvider;
  19. import com.dmdirc.config.provider.ConfigProvider;
  20. import com.dmdirc.events.ServerCertificateProblemEncounteredEvent;
  21. import com.dmdirc.events.ServerCertificateProblemResolvedEvent;
  22. import com.dmdirc.events.eventbus.EventBus;
  23. import com.dmdirc.interfaces.Connection;
  24. import java.io.FileInputStream;
  25. import java.io.FileNotFoundException;
  26. import java.io.IOException;
  27. import java.security.GeneralSecurityException;
  28. import java.security.InvalidAlgorithmParameterException;
  29. import java.security.KeyStore;
  30. import java.security.KeyStoreException;
  31. import java.security.cert.CertificateException;
  32. import java.security.cert.PKIXParameters;
  33. import java.security.cert.TrustAnchor;
  34. import java.security.cert.X509Certificate;
  35. import java.util.ArrayList;
  36. import java.util.Arrays;
  37. import java.util.Base64;
  38. import java.util.Collection;
  39. import java.util.HashMap;
  40. import java.util.HashSet;
  41. import java.util.List;
  42. import java.util.Map;
  43. import java.util.Set;
  44. import java.util.concurrent.Semaphore;
  45. import java.util.stream.Collectors;
  46. import javax.naming.InvalidNameException;
  47. import javax.naming.ldap.LdapName;
  48. import javax.naming.ldap.Rdn;
  49. import javax.net.ssl.KeyManager;
  50. import javax.net.ssl.KeyManagerFactory;
  51. import javax.net.ssl.X509TrustManager;
  52. import org.slf4j.Logger;
  53. import org.slf4j.LoggerFactory;
  54. import static com.dmdirc.util.LogUtils.USER_ERROR;
  55. /**
  56. * Manages storage and validation of certificates used when connecting to SSL servers.
  57. *
  58. * @since 0.6.3m1
  59. */
  60. public class CertificateManager implements X509TrustManager {
  61. private static final Logger LOG = LoggerFactory.getLogger(CertificateManager.class);
  62. /** Connection that owns this manager. */
  63. private final Connection connection;
  64. /** The server name the user is trying to connect to. */
  65. private final String serverName;
  66. /** The configuration manager to use for settings. */
  67. private final AggregateConfigProvider config;
  68. /** The set of CAs from the global cacert file. */
  69. private final Set<X509Certificate> globalTrustedCAs = new HashSet<>();
  70. /** Used to synchronise the manager with the certificate dialog. */
  71. private final Semaphore actionSem = new Semaphore(0);
  72. /** The event bus to post errors to. */
  73. private final EventBus eventBus;
  74. /** The action to perform. */
  75. private CertificateAction action;
  76. /** A list of problems encountered most recently. */
  77. private final List<CertificateException> problems = new ArrayList<>();
  78. /** The chain of certificates currently being validated. */
  79. private X509Certificate[] chain;
  80. /** The user settings to write to. */
  81. private final ConfigProvider userSettings;
  82. /** Locator to use to find a system keystore. */
  83. private final KeyStoreLocator keyStoreLocator;
  84. /** Checker to use for hostnames. */
  85. private final CertificateHostChecker hostChecker;
  86. /**
  87. * Creates a new certificate manager for a client connecting to the specified server.
  88. *
  89. * @param serverName The name the user used to connect to the server
  90. * @param config The configuration manager to use
  91. * @param userSettings The user settings to write to.
  92. * @param eventBus The event bus to post errors to
  93. */
  94. public CertificateManager(
  95. final Connection connection,
  96. final String serverName,
  97. final AggregateConfigProvider config,
  98. final ConfigProvider userSettings,
  99. final EventBus eventBus) {
  100. this.connection = connection;
  101. this.serverName = serverName;
  102. this.config = config;
  103. this.userSettings = userSettings;
  104. this.eventBus = eventBus;
  105. this.keyStoreLocator = new KeyStoreLocator();
  106. this.hostChecker = new CertificateHostChecker();
  107. loadTrustedCAs();
  108. }
  109. /**
  110. * Loads the trusted CA certificates from the Java cacerts store.
  111. */
  112. private void loadTrustedCAs() {
  113. try {
  114. final KeyStore keyStore = keyStoreLocator.getKeyStore();
  115. if (keyStore != null) {
  116. final PKIXParameters params = new PKIXParameters(keyStore);
  117. globalTrustedCAs.addAll(params.getTrustAnchors().stream()
  118. .map(TrustAnchor::getTrustedCert)
  119. .collect(Collectors.toList()));
  120. }
  121. } catch (InvalidAlgorithmParameterException | KeyStoreException ex) {
  122. LOG.warn(USER_ERROR, "Unable to load trusted certificates", ex);
  123. }
  124. }
  125. /**
  126. * Retrieves a KeyManager[] for the client certificate specified in the configuration, if there
  127. * is one.
  128. *
  129. * @return A KeyManager to use for the SSL connection
  130. */
  131. public KeyManager[] getKeyManager() {
  132. if (config.hasOptionString("ssl", "clientcert.file")) {
  133. try (FileInputStream fis = new FileInputStream(config.getOption("ssl",
  134. "clientcert.file"))) {
  135. final char[] pass;
  136. if (config.hasOptionString("ssl", "clientcert.pass")) {
  137. pass = config.getOption("ssl", "clientcert.pass").toCharArray();
  138. } else {
  139. pass = null;
  140. }
  141. final KeyStore ks = KeyStore.getInstance("pkcs12");
  142. ks.load(fis, pass);
  143. final KeyManagerFactory kmf = KeyManagerFactory.getInstance(
  144. KeyManagerFactory.getDefaultAlgorithm());
  145. kmf.init(ks, pass);
  146. return kmf.getKeyManagers();
  147. } catch (FileNotFoundException ex) {
  148. LOG.warn(USER_ERROR, "Certificate file not found", ex);
  149. } catch (GeneralSecurityException | IOException ex) {
  150. LOG.warn(USER_ERROR, "Unable to get key manager", ex);
  151. }
  152. }
  153. return null;
  154. }
  155. @Override
  156. public void checkClientTrusted(final X509Certificate[] chain, final String authType)
  157. throws CertificateException {
  158. throw new CertificateException("Not supported.");
  159. }
  160. /**
  161. * Determines if the specified certificate is trusted by the user.
  162. *
  163. * @param certificate The certificate to be checked
  164. *
  165. * @return True if the certificate matches one in the trusted certificate store, or if the
  166. * certificate's details are marked as trusted in the DMDirc configuration file.
  167. */
  168. public TrustResult isTrusted(final X509Certificate certificate) {
  169. try {
  170. final String sig = Base64.getEncoder().encodeToString(certificate.getSignature());
  171. if (config.hasOptionString("ssl", "trusted") && config.getOptionList("ssl",
  172. "trusted").contains(sig)) {
  173. return TrustResult.TRUSTED_MANUALLY;
  174. } else {
  175. for (X509Certificate trustedCert : globalTrustedCAs) {
  176. if (Arrays.equals(certificate.getSignature(), trustedCert.getSignature())
  177. && certificate.getIssuerDN().getName()
  178. .equals(trustedCert.getIssuerDN().getName())) {
  179. certificate.verify(trustedCert.getPublicKey());
  180. return TrustResult.TRUSTED_CA;
  181. }
  182. }
  183. }
  184. } catch (GeneralSecurityException ex) {
  185. return TrustResult.UNTRUSTED_EXCEPTION;
  186. }
  187. return TrustResult.UNTRUSTED_GENERAL;
  188. }
  189. @Override
  190. public void checkServerTrusted(final X509Certificate[] chain, final String authType)
  191. throws CertificateException {
  192. this.chain = Arrays.copyOf(chain, chain.length);
  193. problems.clear();
  194. if (!hostChecker.isValidFor(chain[0], serverName)) {
  195. problems.add(new CertificateDoesntMatchHostException(
  196. "Certificate was not issued to " + serverName));
  197. }
  198. if (checkIssuer(chain)) {
  199. problems.clear();
  200. }
  201. if (!problems.isEmpty()) {
  202. eventBus.publishAsync(new ServerCertificateProblemEncounteredEvent(connection, this,
  203. Arrays.asList(chain), problems));
  204. try {
  205. actionSem.acquire();
  206. } catch (InterruptedException ie) {
  207. throw new CertificateException("Thread aborted", ie);
  208. } finally {
  209. problems.clear();
  210. eventBus.publishAsync(new ServerCertificateProblemResolvedEvent(connection, this));
  211. }
  212. switch (action) {
  213. case DISCONNECT:
  214. throw new CertificateException("Not trusted");
  215. case IGNORE_PERMANENTLY:
  216. final List<String> list = new ArrayList<>(config
  217. .getOptionList("ssl", "trusted"));
  218. list.add(Base64.getEncoder().encodeToString(chain[0].getSignature()));
  219. userSettings.setOption("ssl", "trusted", list);
  220. break;
  221. case IGNORE_TEMPORARILY:
  222. // Do nothing, continue connecting
  223. break;
  224. }
  225. }
  226. }
  227. /**
  228. * Checks that some issuer in the certificate chain is trusted, either by the global CA list,
  229. * or manually by the user.
  230. *
  231. * @param chain The chain of certificates to check.
  232. * @return True if the certificate is trusted manually, false otherwise (i.e., trusted globally
  233. * OR untrusted).
  234. */
  235. private boolean checkIssuer(final X509Certificate... chain) {
  236. boolean manual = false;
  237. boolean verified = false;
  238. for (X509Certificate cert : chain) {
  239. final TrustResult trustResult = isTrusted(cert);
  240. // Check that the certificate is in-date
  241. try {
  242. cert.checkValidity();
  243. } catch (CertificateException ex) {
  244. problems.add(ex);
  245. }
  246. // Check that we trust an issuer
  247. verified |= trustResult.isTrusted();
  248. if (trustResult == TrustResult.TRUSTED_MANUALLY) {
  249. manual = true;
  250. }
  251. }
  252. if (!verified) {
  253. problems.add(new CertificateNotTrustedException("Issuer is not trusted"));
  254. }
  255. return manual;
  256. }
  257. /**
  258. * Gets the chain of certificates currently being validated, if any.
  259. *
  260. * @return The chain of certificates being validated
  261. */
  262. public X509Certificate[] getChain() {
  263. return chain;
  264. }
  265. /**
  266. * Gets the set of problems that were encountered with the last certificate.
  267. *
  268. * @return The set of problems encountered, or any empty collection if there is no current
  269. * validation attempt ongoing.
  270. */
  271. public Collection<CertificateException> getProblems() {
  272. return problems;
  273. }
  274. /**
  275. * Sets the action to perform for the request that's in progress.
  276. *
  277. * @param action The action that's been selected
  278. */
  279. public void setAction(final CertificateAction action) {
  280. this.action = action;
  281. actionSem.release();
  282. }
  283. /**
  284. * Retrieves the name of the server to which the user is trying to connect.
  285. *
  286. * @return The name of the server that the user is trying to connect to
  287. */
  288. public String getServerName() {
  289. return serverName;
  290. }
  291. /**
  292. * Reads the fields from the subject's designated name in the specified certificate.
  293. *
  294. * @param cert The certificate to read
  295. *
  296. * @return A map of the fields in the certificate's subject's designated name
  297. */
  298. public static Map<String, String> getDNFieldsFromCert(final X509Certificate cert) {
  299. final Map<String, String> res = new HashMap<>();
  300. try {
  301. final LdapName name = new LdapName(cert.getSubjectX500Principal().getName());
  302. for (Rdn rdn : name.getRdns()) {
  303. res.put(rdn.getType(), rdn.getValue().toString());
  304. }
  305. } catch (InvalidNameException ex) {
  306. // Don't care
  307. }
  308. return res;
  309. }
  310. @Override
  311. public X509Certificate[] getAcceptedIssuers() {
  312. return globalTrustedCAs.toArray(new X509Certificate[globalTrustedCAs.size()]);
  313. }
  314. }