Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

CertificateManager.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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.events.ServerCertificateProblemEncounteredEvent;
  19. import com.dmdirc.events.ServerCertificateProblemResolvedEvent;
  20. import com.dmdirc.interfaces.Connection;
  21. import com.dmdirc.events.eventbus.EventBus;
  22. import com.dmdirc.config.provider.AggregateConfigProvider;
  23. import com.dmdirc.config.provider.ConfigProvider;
  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.CertificateParsingException;
  33. import java.security.cert.PKIXParameters;
  34. import java.security.cert.TrustAnchor;
  35. import java.security.cert.X509Certificate;
  36. import java.util.ArrayList;
  37. import java.util.Arrays;
  38. import java.util.Base64;
  39. import java.util.Collection;
  40. import java.util.HashMap;
  41. import java.util.HashSet;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.Set;
  45. import java.util.concurrent.Semaphore;
  46. import java.util.stream.Collectors;
  47. import javax.naming.InvalidNameException;
  48. import javax.naming.ldap.LdapName;
  49. import javax.naming.ldap.Rdn;
  50. import javax.net.ssl.KeyManager;
  51. import javax.net.ssl.KeyManagerFactory;
  52. import javax.net.ssl.X509TrustManager;
  53. import org.slf4j.Logger;
  54. import org.slf4j.LoggerFactory;
  55. import static com.dmdirc.util.LogUtils.USER_ERROR;
  56. /**
  57. * Manages storage and validation of certificates used when connecting to SSL servers.
  58. *
  59. * @since 0.6.3m1
  60. */
  61. public class CertificateManager implements X509TrustManager {
  62. private static final Logger LOG = LoggerFactory.getLogger(CertificateManager.class);
  63. /** Connection that owns this manager. */
  64. private final Connection connection;
  65. /** The server name the user is trying to connect to. */
  66. private final String serverName;
  67. /** The configuration manager to use for settings. */
  68. private final AggregateConfigProvider config;
  69. /** The set of CAs from the global cacert file. */
  70. private final Set<X509Certificate> globalTrustedCAs = new HashSet<>();
  71. /** Used to synchronise the manager with the certificate dialog. */
  72. private final Semaphore actionSem = new Semaphore(0);
  73. /** The event bus to post errors to. */
  74. private final EventBus eventBus;
  75. /** The action to perform. */
  76. private CertificateAction action;
  77. /** A list of problems encountered most recently. */
  78. private final List<CertificateException> problems = new ArrayList<>();
  79. /** The chain of certificates currently being validated. */
  80. private X509Certificate[] chain;
  81. /** The user settings to write to. */
  82. private final ConfigProvider userSettings;
  83. /** Locator to use to find a system keystore. */
  84. private final KeyStoreLocator keyStoreLocator;
  85. /**
  86. * Creates a new certificate manager for a client connecting to the specified server.
  87. *
  88. * @param serverName The name the user used to connect to the server
  89. * @param config The configuration manager to use
  90. * @param userSettings The user settings to write to.
  91. * @param eventBus The event bus to post errors to
  92. */
  93. public CertificateManager(
  94. final Connection connection,
  95. final String serverName,
  96. final AggregateConfigProvider config,
  97. final ConfigProvider userSettings,
  98. final EventBus eventBus) {
  99. this.connection = connection;
  100. this.serverName = serverName;
  101. this.config = config;
  102. this.userSettings = userSettings;
  103. this.eventBus = eventBus;
  104. this.keyStoreLocator = new KeyStoreLocator();
  105. loadTrustedCAs();
  106. }
  107. /**
  108. * Loads the trusted CA certificates from the Java cacerts store.
  109. */
  110. private void loadTrustedCAs() {
  111. try {
  112. final KeyStore keyStore = keyStoreLocator.getKeyStore();
  113. if (keyStore != null) {
  114. final PKIXParameters params = new PKIXParameters(keyStore);
  115. globalTrustedCAs.addAll(params.getTrustAnchors().stream()
  116. .map(TrustAnchor::getTrustedCert)
  117. .collect(Collectors.toList()));
  118. }
  119. } catch (InvalidAlgorithmParameterException | KeyStoreException ex) {
  120. LOG.warn(USER_ERROR, "Unable to load trusted certificates", ex);
  121. }
  122. }
  123. /**
  124. * Retrieves a KeyManager[] for the client certificate specified in the configuration, if there
  125. * is one.
  126. *
  127. * @return A KeyManager to use for the SSL connection
  128. */
  129. public KeyManager[] getKeyManager() {
  130. if (config.hasOptionString("ssl", "clientcert.file")) {
  131. try (FileInputStream fis = new FileInputStream(config.getOption("ssl",
  132. "clientcert.file"))) {
  133. final char[] pass;
  134. if (config.hasOptionString("ssl", "clientcert.pass")) {
  135. pass = config.getOption("ssl", "clientcert.pass").toCharArray();
  136. } else {
  137. pass = null;
  138. }
  139. final KeyStore ks = KeyStore.getInstance("pkcs12");
  140. ks.load(fis, pass);
  141. final KeyManagerFactory kmf = KeyManagerFactory.getInstance(
  142. KeyManagerFactory.getDefaultAlgorithm());
  143. kmf.init(ks, pass);
  144. return kmf.getKeyManagers();
  145. } catch (FileNotFoundException ex) {
  146. LOG.warn(USER_ERROR, "Certificate file not found", ex);
  147. } catch (GeneralSecurityException | IOException ex) {
  148. LOG.warn(USER_ERROR, "Unable to get key manager", ex);
  149. }
  150. }
  151. return null;
  152. }
  153. @Override
  154. public void checkClientTrusted(final X509Certificate[] chain, final String authType)
  155. throws CertificateException {
  156. throw new CertificateException("Not supported.");
  157. }
  158. /**
  159. * Determines if the specified certificate is trusted by the user.
  160. *
  161. * @param certificate The certificate to be checked
  162. *
  163. * @return True if the certificate matches one in the trusted certificate store, or if the
  164. * certificate's details are marked as trusted in the DMDirc configuration file.
  165. */
  166. public TrustResult isTrusted(final X509Certificate certificate) {
  167. try {
  168. final String sig = Base64.getEncoder().encodeToString(certificate.getSignature());
  169. if (config.hasOptionString("ssl", "trusted") && config.getOptionList("ssl",
  170. "trusted").contains(sig)) {
  171. return TrustResult.TRUSTED_MANUALLY;
  172. } else {
  173. for (X509Certificate trustedCert : globalTrustedCAs) {
  174. if (Arrays.equals(certificate.getSignature(), trustedCert.getSignature())
  175. && certificate.getIssuerDN().getName()
  176. .equals(trustedCert.getIssuerDN().getName())) {
  177. certificate.verify(trustedCert.getPublicKey());
  178. return TrustResult.TRUSTED_CA;
  179. }
  180. }
  181. }
  182. } catch (GeneralSecurityException ex) {
  183. return TrustResult.UNTRUSTED_EXCEPTION;
  184. }
  185. return TrustResult.UNTRUSTED_GENERAL;
  186. }
  187. /**
  188. * Determines whether the given certificate has a valid CN or alternate name for this server's
  189. * hostname.
  190. *
  191. * @param certificate The certificate to be validated
  192. *
  193. * @return True if the certificate is valid for this server's host, false otherwise
  194. */
  195. public boolean isValidHost(final X509Certificate certificate) {
  196. final Map<String, String> fields = getDNFieldsFromCert(certificate);
  197. if (fields.containsKey("CN") && isMatchingServerName(fields.get("CN"))) {
  198. return true;
  199. }
  200. try {
  201. if (certificate.getSubjectAlternativeNames() != null) {
  202. for (List<?> entry : certificate.getSubjectAlternativeNames()) {
  203. final int type = (Integer) entry.get(0);
  204. // DNS or IP
  205. if ((type == 2 || type == 7) && isMatchingServerName((String) entry.get(1))) {
  206. return true;
  207. }
  208. }
  209. }
  210. } catch (CertificateParsingException ex) {
  211. return false;
  212. }
  213. return false;
  214. }
  215. /**
  216. * Checks whether the specified target matches the server name this certificate manager was
  217. * initialised with.
  218. *
  219. * Target names may contain wildcards per RFC2818.
  220. *
  221. * @since 0.6.5
  222. * @param target The target to compare to our server name
  223. *
  224. * @return True if the target matches, false otherwise
  225. */
  226. protected boolean isMatchingServerName(final String target) {
  227. final String[] targetParts = target.split("\\.");
  228. final String[] serverParts = serverName.split("\\.");
  229. if (targetParts.length != serverParts.length) {
  230. // Fail fast if they don't match
  231. return false;
  232. }
  233. for (int i = 0; i < serverParts.length; i++) {
  234. if (!serverParts[i].matches("\\Q" + targetParts[i].replace("*", "\\E.*\\Q") + "\\E")) {
  235. return false;
  236. }
  237. }
  238. return true;
  239. }
  240. @Override
  241. public void checkServerTrusted(final X509Certificate[] chain, final String authType)
  242. throws CertificateException {
  243. this.chain = Arrays.copyOf(chain, chain.length);
  244. problems.clear();
  245. checkHost(chain);
  246. if (checkIssuer(chain)) {
  247. problems.clear();
  248. }
  249. if (!problems.isEmpty()) {
  250. eventBus.publishAsync(new ServerCertificateProblemEncounteredEvent(connection, this,
  251. Arrays.asList(chain), problems));
  252. try {
  253. actionSem.acquire();
  254. } catch (InterruptedException ie) {
  255. throw new CertificateException("Thread aborted", ie);
  256. } finally {
  257. problems.clear();
  258. eventBus.publishAsync(new ServerCertificateProblemResolvedEvent(connection, this));
  259. }
  260. switch (action) {
  261. case DISCONNECT:
  262. throw new CertificateException("Not trusted");
  263. case IGNORE_PERMANENTLY:
  264. final List<String> list = new ArrayList<>(config
  265. .getOptionList("ssl", "trusted"));
  266. list.add(Base64.getEncoder().encodeToString(chain[0].getSignature()));
  267. userSettings.setOption("ssl", "trusted", list);
  268. break;
  269. case IGNORE_TEMPORARILY:
  270. // Do nothing, continue connecting
  271. break;
  272. }
  273. }
  274. }
  275. /**
  276. * Checks that some issuer in the certificate chain is trusted, either by the global CA list,
  277. * or manually by the user.
  278. *
  279. * @param chain The chain of certificates to check.
  280. * @return True if the certificate is trusted manually, false otherwise (i.e., trusted globally
  281. * OR untrusted).
  282. */
  283. private boolean checkIssuer(final X509Certificate... chain) {
  284. boolean manual = false;
  285. boolean verified = false;
  286. for (X509Certificate cert : chain) {
  287. final TrustResult trustResult = isTrusted(cert);
  288. // Check that the certificate is in-date
  289. try {
  290. cert.checkValidity();
  291. } catch (CertificateException ex) {
  292. problems.add(ex);
  293. }
  294. // Check that we trust an issuer
  295. verified |= trustResult.isTrusted();
  296. if (trustResult == TrustResult.TRUSTED_MANUALLY) {
  297. manual = true;
  298. }
  299. }
  300. if (!verified) {
  301. problems.add(new CertificateNotTrustedException("Issuer is not trusted"));
  302. }
  303. return manual;
  304. }
  305. /**
  306. * Checks that the host of the leaf certificate is the same as the server we are connected to.
  307. *
  308. * @param chain The chain of certificates to check.
  309. */
  310. private void checkHost(final X509Certificate... chain) {
  311. // Check that the cert is issued to the correct host
  312. if (!isValidHost(chain[0])) {
  313. problems.add(new CertificateDoesntMatchHostException(
  314. "Certificate was not issued to " + serverName));
  315. }
  316. }
  317. /**
  318. * Gets the chain of certificates currently being validated, if any.
  319. *
  320. * @return The chain of certificates being validated
  321. */
  322. public X509Certificate[] getChain() {
  323. return chain;
  324. }
  325. /**
  326. * Gets the set of problems that were encountered with the last certificate.
  327. *
  328. * @return The set of problems encountered, or any empty collection if there is no current
  329. * validation attempt ongoing.
  330. */
  331. public Collection<CertificateException> getProblems() {
  332. return problems;
  333. }
  334. /**
  335. * Sets the action to perform for the request that's in progress.
  336. *
  337. * @param action The action that's been selected
  338. */
  339. public void setAction(final CertificateAction action) {
  340. this.action = action;
  341. actionSem.release();
  342. }
  343. /**
  344. * Retrieves the name of the server to which the user is trying to connect.
  345. *
  346. * @return The name of the server that the user is trying to connect to
  347. */
  348. public String getServerName() {
  349. return serverName;
  350. }
  351. /**
  352. * Reads the fields from the subject's designated name in the specified certificate.
  353. *
  354. * @param cert The certificate to read
  355. *
  356. * @return A map of the fields in the certificate's subject's designated name
  357. */
  358. public static Map<String, String> getDNFieldsFromCert(final X509Certificate cert) {
  359. final Map<String, String> res = new HashMap<>();
  360. try {
  361. final LdapName name = new LdapName(cert.getSubjectX500Principal().getName());
  362. for (Rdn rdn : name.getRdns()) {
  363. res.put(rdn.getType(), rdn.getValue().toString());
  364. }
  365. } catch (InvalidNameException ex) {
  366. // Don't care
  367. }
  368. return res;
  369. }
  370. @Override
  371. public X509Certificate[] getAcceptedIssuers() {
  372. return globalTrustedCAs.toArray(new X509Certificate[globalTrustedCAs.size()]);
  373. }
  374. }