Search in sources :

Example 1 with TrustManagerTrustAll

use of com.helger.commons.ws.TrustManagerTrustAll in project peppol-commons by phax.

the class SSLConnectFuncTest method testConnect.

@Test
public void testConnect() throws Exception {
    // Load the client certificate
    final KeyStore aKeyStore = KeyStoreHelper.loadKeyStoreDirect(KEYSTORE_TYPE, KEYSTORE_PATH, KEYSTORE_PASSWORD);
    final KeyManagerFactory aKMF = KeyManagerFactory.getInstance("SunX509");
    aKMF.init(aKeyStore, KEYSTORE_PASSWORD.toCharArray());
    // Trust all
    final TrustManager[] aTrustMgrs = new TrustManager[] { new TrustManagerTrustAll(false) };
    // SSL context
    final SSLContext aSSLContext = SSLContext.getInstance("TLS");
    aSSLContext.init(aKMF.getKeyManagers(), aTrustMgrs, null);
    // Configure and open connection
    final HttpsURLConnection aURLConn = (HttpsURLConnection) new URL(SML_INFO.getManagementServiceURL()).openConnection();
    aURLConn.setSSLSocketFactory(aSSLContext.getSocketFactory());
    aURLConn.setHostnameVerifier(new HostnameVerifierVerifyAll(true));
    aURLConn.setRequestMethod("GET");
    // Debug status on URL connection
    if (true) {
        LOGGER.info("Status code:  " + aURLConn.getResponseCode());
        LOGGER.info("Cipher suite: " + aURLConn.getCipherSuite());
        LOGGER.info("Encoding:     " + aURLConn.getContentEncoding());
        if (true) {
            int i = 0;
            for (final Certificate aCert : aURLConn.getServerCertificates()) {
                LOGGER.info(" Cert " + (++i) + ":");
                LOGGER.info("  Cert type:  " + aCert.getType());
                LOGGER.info("  Hash code:  " + aCert.hashCode());
                LOGGER.info("  Algorithm:  " + aCert.getPublicKey().getAlgorithm());
                LOGGER.info("  Format:     " + aCert.getPublicKey().getFormat());
                if (aCert instanceof X509Certificate) {
                    final X509Certificate aX509 = (X509Certificate) aCert;
                    LOGGER.info("   Principal: " + aX509.getIssuerX500Principal());
                    LOGGER.info("   Subject:   " + aX509.getSubjectX500Principal());
                }
            }
        }
    }
    try {
        // Show success
        final String sResult = StreamHelper.getAllBytesAsString(aURLConn.getInputStream(), StandardCharsets.UTF_8);
        LOGGER.info("\n" + sResult);
    } catch (final IOException ex) {
        // Show error
        final String sError = StreamHelper.getAllBytesAsString(aURLConn.getErrorStream(), StandardCharsets.UTF_8);
        LOGGER.info("\n" + sError);
    }
}
Also used : SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) HostnameVerifierVerifyAll(com.helger.commons.ws.HostnameVerifierVerifyAll) TrustManagerTrustAll(com.helger.commons.ws.TrustManagerTrustAll) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 2 with TrustManagerTrustAll

use of com.helger.commons.ws.TrustManagerTrustAll in project peppol-commons by phax.

the class AbstractSMLClientTestCase method createConfiguredSSLSocketFactory.

@Nullable
public static final SSLSocketFactory createConfiguredSSLSocketFactory(@Nonnull final ISMLInfo aSMLInfo, final boolean bDebug) throws Exception {
    if (!aSMLInfo.isClientCertificateRequired())
        return null;
    // Main key storage
    final KeyStore aKeyStore = KeyStoreHelper.loadKeyStoreDirect(KEYSTORE_TYPE, KEYSTORE_PATH, KEYSTORE_PASSWORD);
    // Key manager
    final KeyManagerFactory aKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    aKeyManagerFactory.init(aKeyStore, KEYSTORE_PASSWORD.toCharArray());
    // Assign key manager and empty trust manager to SSL context
    final SSLContext aSSLCtx = SSLContext.getInstance("TLS");
    aSSLCtx.init(aKeyManagerFactory.getKeyManagers(), new TrustManager[] { new TrustManagerTrustAll(bDebug) }, null);
    return aSSLCtx.getSocketFactory();
}
Also used : SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) TrustManagerTrustAll(com.helger.commons.ws.TrustManagerTrustAll) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Nullable(javax.annotation.Nullable)

Example 3 with TrustManagerTrustAll

use of com.helger.commons.ws.TrustManagerTrustAll in project phoss-smp by phax.

the class SMPKeyManager method createSSLContext.

/**
 * Create an SSLContext based on the configured key store and trust store.
 * This is required for communication with the SMI/SML as well as other
 * network dependent components like the Peppol Directory.
 *
 * @return A new {@link SSLContext} and never <code>null</code>.
 * @throws GeneralSecurityException
 *         In case something goes wrong :)
 */
@Nonnull
public SSLContext createSSLContext() throws GeneralSecurityException {
    // Key manager
    final KeyManagerFactory aKeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    aKeyManagerFactory.init(getKeyStore(), SMPServerConfiguration.getKeyStoreKeyPassword());
    // Trust manager
    final TrustManager[] aTrustManagers;
    if (SMPTrustManager.isTrustStoreValid()) {
        // Explicitly use the configured truststore
        final TrustManagerFactory aTrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        aTrustManagerFactory.init(SMPTrustManager.getInstance().getTrustStore());
        aTrustManagers = aTrustManagerFactory.getTrustManagers();
    } else {
        // No trust store defined
        aTrustManagers = new TrustManager[] { new TrustManagerTrustAll() };
        LOGGER.warn("No truststore is configured, so the build SSL/TLS connection will trust all hosts!");
    }
    // Assign key manager and empty trust manager to SSL/TLS context
    final SSLContext aSSLCtx = SSLContext.getInstance("TLS");
    aSSLCtx.init(aKeyManagerFactory.getKeyManagers(), aTrustManagers, null);
    return aSSLCtx;
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContext(javax.net.ssl.SSLContext) TrustManagerTrustAll(com.helger.commons.ws.TrustManagerTrustAll) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) Nonnull(javax.annotation.Nonnull)

Example 4 with TrustManagerTrustAll

use of com.helger.commons.ws.TrustManagerTrustAll in project peppol-practical by phax.

the class PagePublicToolsSMPSML method _loadKeyStoreAndCreateSSLSocketFactory.

@Nullable
private static SSLSocketFactory _loadKeyStoreAndCreateSSLSocketFactory(@Nonnull final IKeyStoreType aKeyStoreType, @Nullable final String sSecurityProvider, @Nullable final IFileItem aKeyStoreFile, @Nullable final String sKeyStorePassword, @Nonnull final FormErrorList aFormErrors, @Nonnull final Locale aDisplayLocale) {
    KeyStore aKeyStore = null;
    if (aKeyStoreFile == null || aKeyStoreFile.getSize() == 0L)
        aFormErrors.addFieldError(FIELD_KEYSTORE, "A key store file must be selected!");
    else if (sKeyStorePassword == null) {
        aFormErrors.addFieldError(FIELD_KEYSTORE_PW, "The key store password is missing!");
    } else {
        // Try to load the key store
        try (final InputStream aIS = aKeyStoreFile.getInputStream()) {
            aKeyStore = StringHelper.hasText(sSecurityProvider) ? aKeyStoreType.getKeyStore(sSecurityProvider) : aKeyStoreType.getKeyStore();
            aKeyStore.load(aIS, sKeyStorePassword.toCharArray());
            // Get all aliases
            final ICommonsList<String> aAllAliases = CollectionHelper.newList(aKeyStore.aliases());
            LOGGER.info("Successfully loaded key store of type " + aKeyStoreType.getID() + " containing " + aAllAliases.size() + " aliases");
            // Check key and certificate count
            final LocalDate aNow = PDTFactory.getCurrentLocalDate();
            int nKeyCount = 0;
            int nCertificateCount = 0;
            int nInvalidKeyCount = 0;
            for (final String sAlias : aAllAliases) {
                final boolean bIsKeyEntry = aKeyStore.isKeyEntry(sAlias);
                final boolean bIsCertificateEntry = aKeyStore.isCertificateEntry(sAlias);
                if (bIsKeyEntry)
                    ++nKeyCount;
                if (bIsCertificateEntry)
                    ++nCertificateCount;
                LOGGER.info("  Alias '" + sAlias + "'" + (bIsKeyEntry ? " [key entry]" : "") + (bIsCertificateEntry ? " [certificate]" : ""));
                if (bIsKeyEntry)
                    try {
                        // Read key and check for validity
                        final KeyStore.ProtectionParameter aProtection = new KeyStore.PasswordProtection(sKeyStorePassword.toCharArray());
                        final KeyStore.Entry aEntry = aKeyStore.getEntry(sAlias, aProtection);
                        if (aEntry instanceof KeyStore.PrivateKeyEntry) {
                            final Certificate aCert = ((KeyStore.PrivateKeyEntry) aEntry).getCertificate();
                            if (aCert instanceof X509Certificate) {
                                final X509Certificate aX509Cert = (X509Certificate) aCert;
                                final LocalDate aNotBefore = PDTFactory.createLocalDate(aX509Cert.getNotBefore());
                                final LocalDate aNotAfter = PDTFactory.createLocalDate(aX509Cert.getNotAfter());
                                if (aNow.isBefore(aNotBefore)) {
                                    final String sMsg = "The key '" + sAlias + "' in the keystore is not valid before " + PDTToString.getAsString(aNotBefore, aDisplayLocale) + "!";
                                    LOGGER.error(sMsg);
                                    aFormErrors.addFieldError(FIELD_KEYSTORE, sMsg);
                                    nInvalidKeyCount++;
                                }
                                if (aNow.isAfter(aNotAfter)) {
                                    final String sMsg = "The key '" + sAlias + "' in the keystore is not valid after " + PDTToString.getAsString(aNotAfter, aDisplayLocale) + "!";
                                    LOGGER.error(sMsg);
                                    aFormErrors.addFieldError(FIELD_KEYSTORE, sMsg);
                                    nInvalidKeyCount++;
                                }
                            }
                        }
                    } catch (final Exception ex) {
                    // Ignore
                    }
            }
            if (nInvalidKeyCount > 0) {
                // Error messages are already displayed
                aKeyStore = null;
            } else if (nKeyCount != 1) {
                final String sMsg = "The keystore must contain exactly one key entry but " + nKeyCount + " key entries and " + nCertificateCount + " certificate entries were found!";
                LOGGER.error(sMsg);
                aFormErrors.addFieldError(FIELD_KEYSTORE, sMsg);
                aKeyStore = null;
            }
        } catch (final Exception ex) {
            final String sMsg = "The key store could not be loaded with the provided password. ";
            aFormErrors.addFieldError(FIELD_KEYSTORE_PW, sMsg + AppCommonUI.getTechnicalDetailsString(ex, true));
            aKeyStore = null;
        }
    }
    SSLSocketFactory aSocketFactory = null;
    if (aKeyStore != null) {
        // Try to create the socket factory from the provided key store
        try {
            final KeyManagerFactory aKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            aKeyManagerFactory.init(aKeyStore, sKeyStorePassword.toCharArray());
            final SSLContext aSSLContext = SSLContext.getInstance("TLS");
            aSSLContext.init(aKeyManagerFactory.getKeyManagers(), new TrustManager[] { new TrustManagerTrustAll(false) }, null);
            aSocketFactory = aSSLContext.getSocketFactory();
            LOGGER.info("Successfully created TLS socket factory with the provided keystore password!");
        } catch (final Exception ex) {
            final String sMsg = "Failed to use the provided key store for TLS connection. ";
            aFormErrors.addFieldError(FIELD_KEYSTORE, sMsg + AppCommonUI.getTechnicalDetailsString(ex, true));
        }
    }
    return aSocketFactory;
}
Also used : ICommonsList(com.helger.commons.collection.impl.ICommonsList) InputStream(java.io.InputStream) PDTToString(com.helger.commons.datetime.PDTToString) PDTFromString(com.helger.commons.datetime.PDTFromString) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) LocalDate(java.time.LocalDate) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) UnknownHostException(java.net.UnknownHostException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TrustManagerTrustAll(com.helger.commons.ws.TrustManagerTrustAll) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Nullable(javax.annotation.Nullable)

Example 5 with TrustManagerTrustAll

use of com.helger.commons.ws.TrustManagerTrustAll in project phoss-directory by phax.

the class IndexerResourceTest method setUp.

@Before
public void setUp() throws GeneralSecurityException, IOException {
    // Set test BC provider first!
    PDMetaManager.setBusinessCardProvider(IndexerResourceTest::_createMockBC);
    PDMetaManager.getInstance();
    final File aTestClientCertificateKeyStore = new File("src/test/resources/smp.pilot.jks");
    if (aTestClientCertificateKeyStore.exists()) {
        // https
        m_aServer = MockServer.startSecureServer();
        final KeyStore aKeyStore = KeyStoreHelper.loadKeyStoreDirect(EKeyStoreType.JKS, aTestClientCertificateKeyStore.getAbsolutePath(), "peppol");
        // Try to create the socket factory from the provided key store
        final KeyManagerFactory aKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        aKeyManagerFactory.init(aKeyStore, "peppol".toCharArray());
        final SSLContext aSSLContext = SSLContext.getInstance("TLS");
        aSSLContext.init(aKeyManagerFactory.getKeyManagers(), new TrustManager[] { new TrustManagerTrustAll(false) }, null);
        final Client aClient = ClientBuilder.newBuilder().sslContext(aSSLContext).hostnameVerifier(new HostnameVerifierVerifyAll(false)).build();
        m_aTarget = aClient.target(MockServer.BASE_URI_HTTPS);
    } else {
        // http only
        LOGGER.warn("The SMP pilot keystore is missing for the tests! Client certificate handling will not be tested!");
        ClientCertificateValidator.allowAllForTests(true);
        m_aServer = MockServer.startRegularServer();
        final Client aClient = ClientBuilder.newClient();
        m_aTarget = aClient.target(MockServer.BASE_URI_HTTP);
    }
}
Also used : HostnameVerifierVerifyAll(com.helger.commons.ws.HostnameVerifierVerifyAll) SSLContext(javax.net.ssl.SSLContext) Client(javax.ws.rs.client.Client) File(java.io.File) KeyStore(java.security.KeyStore) TrustManagerTrustAll(com.helger.commons.ws.TrustManagerTrustAll) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Before(org.junit.Before)

Aggregations

TrustManagerTrustAll (com.helger.commons.ws.TrustManagerTrustAll)10 SSLContext (javax.net.ssl.SSLContext)10 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)7 KeyStore (java.security.KeyStore)6 Nonnull (javax.annotation.Nonnull)4 HostnameVerifierVerifyAll (com.helger.commons.ws.HostnameVerifierVerifyAll)3 File (java.io.File)2 Certificate (java.security.cert.Certificate)2 X509Certificate (java.security.cert.X509Certificate)2 Nullable (javax.annotation.Nullable)2 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)2 TrustManager (javax.net.ssl.TrustManager)2 Client (javax.ws.rs.client.Client)2 Before (org.junit.Before)2 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 ICommonsList (com.helger.commons.collection.impl.ICommonsList)1 PDTFromString (com.helger.commons.datetime.PDTFromString)1 PDTToString (com.helger.commons.datetime.PDTToString)1 ISMLInfo (com.helger.peppol.sml.ISMLInfo)1 ManageParticipantIdentifierServiceCaller (com.helger.peppol.smlclient.ManageParticipantIdentifierServiceCaller)1