Search in sources :

Example 26 with HTTPConduit

use of org.apache.cxf.transport.http.HTTPConduit in project fabric8 by fabric8io.

the class WebClients method configureCaCert.

public static void configureCaCert(WebClient webClient, String caCertData, File caCertFile) {
    try {
        KeyStore trustStore = createTrustStore(caCertData, caCertFile);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();
        TLSClientParameters params = conduit.getTlsClientParameters();
        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }
        TrustManager[] existingTrustManagers = params.getTrustManagers();
        if (existingTrustManagers != null && existingTrustManagers.length > 0) {
            List<TrustManager> list = new ArrayList<>();
            list.addAll(Arrays.asList(existingTrustManagers));
            list.addAll(Arrays.asList(trustManagers));
            trustManagers = list.toArray(new TrustManager[list.size()]);
        }
        params.setTrustManagers(trustManagers);
    } catch (Exception e) {
        LOG.error("Could not create trust manager for " + caCertFile, e);
    }
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ArrayList(java.util.ArrayList) KeyStore(java.security.KeyStore) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TrustEverythingSSLTrustManager(io.fabric8.utils.ssl.TrustEverythingSSLTrustManager) TrustManager(javax.net.ssl.TrustManager)

Example 27 with HTTPConduit

use of org.apache.cxf.transport.http.HTTPConduit in project testcases by coheigea.

the class TLSOCSPClientAuthTest method testTLSOCSPClientAuthPass.

@org.junit.Test
public void testTLSOCSPClientAuthPass() throws Exception {
    try {
        Security.setProperty("ocsp.responderURL", "http://localhost:12345");
        Security.setProperty("ocsp.enable", "true");
        SpringBusFactory bf = new SpringBusFactory();
        URL busFile = TLSOCSPClientAuthTest.class.getResource("cxf-client.xml");
        Bus bus = bf.createBus(busFile.toString());
        SpringBusFactory.setDefaultBus(bus);
        SpringBusFactory.setThreadDefaultBus(bus);
        URL wsdl = TLSOCSPClientAuthTest.class.getResource("DoubleIt.wsdl");
        Service service = Service.create(wsdl, SERVICE_QNAME);
        QName portQName = new QName(NAMESPACE, "DoubleItTLSOCSPClientAuthPort");
        DoubleItPortType transportPort = service.getPort(portQName, DoubleItPortType.class);
        updateAddressPort(transportPort, PORT);
        // Configure TLS (no ocsp on the client side)
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(ClassLoaderUtils.getResourceAsStream("clientstore.jks", this.getClass()), "cspass".toCharArray());
        tmf.init(keyStore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "ckpass".toCharArray());
        TLSClientParameters tlsParams = new TLSClientParameters();
        tlsParams.setTrustManagers(tmf.getTrustManagers());
        tlsParams.setKeyManagers(kmf.getKeyManagers());
        tlsParams.setDisableCNCheck(true);
        Client client = ClientProxy.getClient(transportPort);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        http.setTlsClientParameters(tlsParams);
        doubleIt(transportPort, 25);
    } finally {
        Security.setProperty("ocsp.responderURL", "");
        Security.setProperty("ocsp.enable", "false");
    }
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) Bus(org.apache.cxf.Bus) TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) SpringBusFactory(org.apache.cxf.bus.spring.SpringBusFactory) QName(javax.xml.namespace.QName) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Service(javax.xml.ws.Service) DoubleItPortType(org.example.contract.doubleit.DoubleItPortType) Client(org.apache.cxf.endpoint.Client) KeyStore(java.security.KeyStore) URL(java.net.URL) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 28 with HTTPConduit

use of org.apache.cxf.transport.http.HTTPConduit in project ddf by codice.

the class SecureCxfClientFactoryImpl method configureTimeouts.

/**
 * Configures the connection and receive timeouts. If any of the parameters are null, the timeouts
 * will be set to the system default.
 *
 * @param clientConfiguration Client configuration used for outgoing requests.
 * @param connectionTimeout Connection timeout in milliseconds.
 * @param receiveTimeout Receive timeout in milliseconds.
 */
protected void configureTimeouts(ClientConfiguration clientConfiguration, Integer connectionTimeout, Integer receiveTimeout) {
    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure timeouts", this);
        return;
    }
    HTTPClientPolicy httpClientPolicy = httpConduit.getClient();
    if (httpClientPolicy == null) {
        httpClientPolicy = new HTTPClientPolicy();
    }
    if (connectionTimeout != null) {
        httpClientPolicy.setConnectionTimeout(connectionTimeout);
    } else {
        httpClientPolicy.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
    }
    if (receiveTimeout != null) {
        httpClientPolicy.setReceiveTimeout(receiveTimeout);
    } else {
        httpClientPolicy.setReceiveTimeout(DEFAULT_RECEIVE_TIMEOUT);
    }
    if (httpClientPolicy.isSetConnectionTimeout()) {
        LOGGER.debug("Connection timeout has been set.");
    } else {
        LOGGER.debug("Connection timeout has NOT been set.");
    }
    if (httpClientPolicy.isSetReceiveTimeout()) {
        LOGGER.debug("Receive timeout has been set.");
    } else {
        LOGGER.debug("Receive timeout has NOT been set.");
    }
    httpConduit.setClient(httpClientPolicy);
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy)

Example 29 with HTTPConduit

use of org.apache.cxf.transport.http.HTTPConduit in project ddf by codice.

the class SecureCxfClientFactoryImpl method configureConduit.

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;
    }
    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }
    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }
    tlsParams.setDisableCNCheck(disableCnCheck);
    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }
    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}", System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && keyInfo.getKeystorePath() != null) {
        keyStoreFile = keyInfo.getKeystorePath();
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }
    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile, trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }
    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }
    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }
    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }
            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }
            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }
    httpConduit.setTlsClientParameters(tlsParams);
}
Also used : TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) Path(java.nio.file.Path) Bus(org.apache.cxf.Bus) InputStream(java.io.InputStream) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy)

Example 30 with HTTPConduit

use of org.apache.cxf.transport.http.HTTPConduit in project tbd-studio-se by Talend.

the class AmbariClientBuilder method build.

/**
 * Build a client proxy, for a specific proxy type.
 *
 * @param proxyType proxy type class
 * @return client proxy stub
 */
protected <T> T build(Class<T> proxyType) {
    String address = generateAddress();
    T rootResource;
    // We want to ensure that the shared bean isn't set concurrently in multiple callers
    synchronized (AmbariClientBuilder.class) {
        JAXRSClientFactoryBean bean = cleanFactory(clientStaticResources.getUnchecked(proxyType));
        bean.setAddress(address);
        if (username != null) {
            bean.setUsername(username);
            bean.setPassword(password);
        }
        if (enableLogging) {
            bean.setFeatures(Arrays.<AbstractFeature>asList(new LoggingFeature()));
        }
        rootResource = bean.create(proxyType);
    }
    boolean isTlsEnabled = address.startsWith("https://");
    ClientConfiguration config = WebClient.getConfig(rootResource);
    HTTPConduit conduit = (HTTPConduit) config.getConduit();
    if (isTlsEnabled) {
        TLSClientParameters tlsParams = new TLSClientParameters();
        if (!validateCerts) {
            tlsParams.setTrustManagers(new TrustManager[] { new AcceptAllTrustManager() });
        } else if (trustManagers != null) {
            tlsParams.setTrustManagers(trustManagers);
        }
        tlsParams.setDisableCNCheck(!validateCn);
        conduit.setTlsClientParameters(tlsParams);
    }
    HTTPClientPolicy policy = conduit.getClient();
    policy.setConnectionTimeout(connectionTimeoutUnits.toMillis(connectionTimeout));
    policy.setReceiveTimeout(receiveTimeoutUnits.toMillis(receiveTimeout));
    return rootResource;
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) LoggingFeature(org.apache.cxf.feature.LoggingFeature) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) ClientConfiguration(org.apache.cxf.jaxrs.client.ClientConfiguration)

Aggregations

HTTPConduit (org.apache.cxf.transport.http.HTTPConduit)158 Client (org.apache.cxf.endpoint.Client)65 Test (org.junit.Test)60 HTTPClientPolicy (org.apache.cxf.transports.http.configuration.HTTPClientPolicy)52 URL (java.net.URL)43 TLSClientParameters (org.apache.cxf.configuration.jsse.TLSClientParameters)43 Bus (org.apache.cxf.Bus)36 QName (javax.xml.namespace.QName)24 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)23 KeyStore (java.security.KeyStore)21 Greeter (org.apache.hello_world.Greeter)21 SOAPService (org.apache.hello_world.services.SOAPService)21 Service (javax.xml.ws.Service)18 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)17 InputStream (java.io.InputStream)15 AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)15 IOException (java.io.IOException)13 ExecutionException (java.util.concurrent.ExecutionException)13 TrustManager (javax.net.ssl.TrustManager)13 WebClient (org.apache.cxf.jaxrs.client.WebClient)11