Example usage for javax.net.ssl X509TrustManager getAcceptedIssuers

List of usage examples for javax.net.ssl X509TrustManager getAcceptedIssuers

Introduction

In this page you can find the example usage for javax.net.ssl X509TrustManager getAcceptedIssuers.

Prototype

public X509Certificate[] getAcceptedIssuers();

Source Link

Document

Return an array of certificate authority certificates which are trusted for authenticating peers.

Usage

From source file:com.nesscomputing.tinyhttp.ssl.HttpsTrustManagerFactory.java

@Nonnull
private static X509TrustManager trustManagerFromKeystore(final KeyStore keystore)
        throws GeneralSecurityException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    trustManagerFactory.init(keystore);/*www . ja  va  2s. c  om*/

    final TrustManager[] tms = trustManagerFactory.getTrustManagers();

    for (final TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            final X509TrustManager manager = X509TrustManager.class.cast(tm);
            final X509Certificate[] acceptedIssuers = manager.getAcceptedIssuers();
            LOG.debug("Found TrustManager with %d authorities.", acceptedIssuers.length);
            for (int i = 0; i < acceptedIssuers.length; i++) {
                X509Certificate issuer = acceptedIssuers[i];
                LOG.trace("Issuer #%d, subject DN=<%s>, serial=<%s>", i, issuer.getSubjectDN(),
                        issuer.getSerialNumber());
            }

            return manager;
        }
    }
    throw new IllegalStateException("Could not locate X509TrustManager!");
}

From source file:com.nesscomputing.httpclient.internal.HttpClientTrustManagerFactory.java

@Nonnull
private static X509TrustManager trustManagerFromKeystore(final KeyStore keystore)
        throws GeneralSecurityException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    trustManagerFactory.init(keystore);//w ww  . j  a v a 2s.  c  o m

    final TrustManager[] tms = trustManagerFactory.getTrustManagers();

    for (TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            final X509TrustManager manager = (X509TrustManager) tm;
            X509Certificate[] acceptedIssuers = manager.getAcceptedIssuers();
            LOG.debug("Found TrustManager with %d authorities.", acceptedIssuers.length);
            for (int i = 0; i < acceptedIssuers.length; i++) {
                X509Certificate issuer = acceptedIssuers[i];

                LOG.trace("Issuer #%d, subject DN=<%s>, serial=<%s>", i, issuer.getSubjectDN(),
                        issuer.getSerialNumber());
            }

            return manager;
        }
    }
    throw new IllegalStateException("Could not find an X509TrustManager");
}

From source file:edu.vt.middleware.ldap.ssl.AggregateTrustManager.java

/** {@inheritDoc} */
public X509Certificate[] getAcceptedIssuers() {
    final List<X509Certificate> issuers = new ArrayList<X509Certificate>();
    if (trustManagers != null) {
        for (X509TrustManager tm : trustManagers) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("invoking getAcceptedIssuers invoked for " + tm);
            }/*from w  w  w  .j a  v a  2s .com*/
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                issuers.add(cert);
            }
        }
    }
    return issuers.toArray(new X509Certificate[issuers.size()]);
}

From source file:org.apache.hadoop.security.ssl.ReloadingX509TrustManager.java

@Override
public X509Certificate[] getAcceptedIssuers() {
    X509Certificate[] issuers = EMPTY;
    X509TrustManager tm = trustManagerRef.get();
    if (tm != null) {
        issuers = tm.getAcceptedIssuers();
    }/*from ww w.  j a v  a 2 s . co  m*/
    return issuers;
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayService.java

private void createKeystore() {
    try {/*ww  w . jav  a  2  s .co m*/
        sslKeystore.load(null, null);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        // Copy current certs into our keystore so we can use it...
        // TODO: don't actually do this...
        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            sslKeystore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    saveKeystore();
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509TrustManager getCustomTrustManager(final X509TrustManager defaultTrustManager,
        final KeystoreConfig keystoreConfig, final boolean acceptUnverifiedCertificates,
        final KeyStore trustStore) {
    return new X509TrustManager() {
        private final Log log = LogFactory.getLog(X509TrustManager.class);

        public X509Certificate[] getAcceptedIssuers() {
            return defaultTrustManager.getAcceptedIssuers();
        }// w ww. j a  v a2s.  co m

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException e) {
                CertificateExpiredException expiredCertException = getCertExpiredException(e);
                if (expiredCertException != null) {
                    log.error("Fail the connection because received certificate is expired. "
                            + "Please update the certificate.", expiredCertException);
                    throw new CertificateException(e);
                }
                if (acceptUnverifiedCertificates) {
                    log.info("Import the certification. (Received certificate is not trusted by keystore)");
                    importCertificate(chain);
                } else {
                    log.warn(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath());
                    log.debug(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath()
                                    + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates,
                            e);
                    throw new CertificateException(e);
                }
            }
        }

        private CertificateExpiredException getCertExpiredException(Exception e) {
            while (e != null) {
                if (e instanceof CertificateExpiredException) {
                    return (CertificateExpiredException) e;
                }
                e = (Exception) e.getCause();
            }
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            defaultTrustManager.checkClientTrusted(chain, authType);
        }

        private void importCertificate(X509Certificate[] chain) throws CertificateException {
            FileOutputStream keyStoreFileOutputStream = null;
            boolean hasLock = false;
            final boolean debug = log.isDebugEnabled();
            final StopWatch watch = new StopWatch();
            try {
                for (X509Certificate cert : chain) {
                    String[] cnValues = AbstractVerifier.getCNs(cert);
                    String alias;

                    if (cnValues != null && cnValues.length > 0) {
                        alias = cnValues[0];
                    } else {
                        alias = "UnknownCN";
                    }

                    alias += "-ts=" + System.currentTimeMillis();

                    trustStore.setCertificateEntry(alias, cert);
                }
                KEYSTORE_WRITER_LOCK.lockInterruptibly();
                hasLock = true;
                keyStoreFileOutputStream = new FileOutputStream(keystoreConfig.getFilePath());
                trustStore.store(keyStoreFileOutputStream, keystoreConfig.getFilePassword().toCharArray());
            } catch (FileNotFoundException e) {
                // Can't find the keystore in the path
                log.error("Can't find the keystore in " + keystoreConfig.getFilePath() + ". Error message:"
                        + e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                log.error("The algorithm is not supported. Error message:" + e.getMessage(), e);
            } catch (Exception e) {
                // expect KeyStoreException, IOException
                log.error("Exception when trying to import certificate: " + e.getMessage(), e);
            } finally {
                close(keyStoreFileOutputStream);
                keyStoreFileOutputStream = null;
                if (hasLock) {
                    KEYSTORE_WRITER_LOCK.unlock();
                }
                if (debug)
                    log.debug("importCert: " + watch);
            }
        }

        private void close(FileOutputStream keyStoreFileOutputStream) {
            if (keyStoreFileOutputStream != null) {
                try {
                    keyStoreFileOutputStream.close();
                } catch (IOException e) {
                    log.error(e, e);
                }
            }
        }
    };
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*from   w ww. j  a  va 2 s.  c  o  m*/

    if (registry == null) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
                break;
            }
        }

        X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers();
        if (acceptedIssuers != null) {
            // If this is null, something is really wrong...
            int issuerNum = 1;
            for (X509Certificate cert : acceptedIssuers) {
                trustStore.setCertificateEntry("issuer" + issuerNum, cert);
                issuerNum++;
            }
        } else {
            LOG.log(Level.INFO, "Didn't find any new certificates to trust.");
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(trustStore,
                new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts)));
        SSLContext sslContext = sslContextBuilder.build();
        SSLContext.setDefault(sslContext);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts)));

        this.registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
    }
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;/*from  w  w w.  j  a  va  2 s  .co m*/
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = true;
            checkCertTrusted(chain, authType);
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}