Search in sources :

Example 6 with KeyStore

use of java.security.KeyStore in project camel by apache.

the class HttpsServerTestSupport method getSSLContext.

@Override
protected SSLContext getSSLContext() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(KEYSTORE), PASSWORD.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(new FileInputStream(KEYSTORE), PASSWORD.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    SSLContext sslcontext = SSLContext.getInstance(SECURE_SOCKET_PROTOCOL);
    sslcontext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    return sslcontext;
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 7 with KeyStore

use of java.security.KeyStore in project flink by apache.

the class SSLUtils method createSSLServerContext.

/**
	 * Creates the SSL Context for the server if SSL is configured
	 *
	 * @param sslConfig
	 *        The application configuration
	 * @return The SSLContext object which can be used by the ssl transport server
	 * 	       Returns null if SSL is disabled
	 * @throws Exception
	 *         Thrown if there is any misconfiguration
	 */
public static SSLContext createSSLServerContext(Configuration sslConfig) throws Exception {
    Preconditions.checkNotNull(sslConfig);
    SSLContext serverSSLContext = null;
    if (getSSLEnabled(sslConfig)) {
        LOG.debug("Creating server SSL context from configuration");
        String keystoreFilePath = sslConfig.getString(ConfigConstants.SECURITY_SSL_KEYSTORE, null);
        String keystorePassword = sslConfig.getString(ConfigConstants.SECURITY_SSL_KEYSTORE_PASSWORD, null);
        String certPassword = sslConfig.getString(ConfigConstants.SECURITY_SSL_KEY_PASSWORD, null);
        String sslProtocolVersion = sslConfig.getString(ConfigConstants.SECURITY_SSL_PROTOCOL, ConfigConstants.DEFAULT_SECURITY_SSL_PROTOCOL);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream keyStoreFile = null;
        try {
            keyStoreFile = new FileInputStream(new File(keystoreFilePath));
            ks.load(keyStoreFile, keystorePassword.toCharArray());
        } finally {
            if (keyStoreFile != null) {
                keyStoreFile.close();
            }
        }
        // Set up key manager factory to use the server key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, certPassword.toCharArray());
        // Initialize the SSLContext
        serverSSLContext = SSLContext.getInstance(sslProtocolVersion);
        serverSSLContext.init(kmf.getKeyManagers(), null, null);
    }
    return serverSSLContext;
}
Also used : SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) File(java.io.File) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 8 with KeyStore

use of java.security.KeyStore in project kafka by apache.

the class TestSslUtils method createEmptyKeyStore.

private static KeyStore createEmptyKeyStore() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    // initialize
    ks.load(null, null);
    return ks;
}
Also used : KeyStore(java.security.KeyStore)

Example 9 with KeyStore

use of java.security.KeyStore in project hive by apache.

the class HiveConnection method getHttpClient.

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE.equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH)));
    String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();
    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : sessConfMap.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
       * Add an interceptor which sets the appropriate header in the request.
       * It does the kerberos authentication and get the final service ticket,
       * for sending to the server before every request.
       * In https mode, the entire information is encrypted
       */
        requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        // Check for delegation token, if present add it in the header
        String tokenStr = getClientDelegationToken(sessConfMap);
        if (tokenStr != null) {
            requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders);
        } else {
            /**
       * Add an interceptor to pass username/password in the header.
       * In https mode, the entire information is encrypted
       */
            requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders);
        }
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom().setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

            @Override
            public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
                int statusCode = response.getStatusLine().getStatusCode();
                boolean ret = statusCode == 401 && executionCount <= 1;
                // interceptor
                if (ret) {
                    context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                }
                return ret;
            }

            @Override
            public long getRetryInterval() {
                // Immediate retry
                return 0;
            }
        });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Add an interceptor to add in an XSRF header
    httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLConnectionSocketFactory socketFactory;
        SSLContext sslContext;
        /**
       * The code within the try block throws: SSLInitializationException, KeyStoreException,
       * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException &
       * UnrecoverableKeyException. We don't want the client to retry on any of these,
       * hence we catch all and throw a SQLException.
       */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLConnectionSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build();
                socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null));
            }
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();
            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Savepoint(java.sql.Savepoint) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 10 with KeyStore

use of java.security.KeyStore in project hbase by apache.

the class KeyStoreTestUtil method createTrustStore.

public static void createTrustStore(String filename, String password, String alias, Certificate cert) throws GeneralSecurityException, IOException {
    KeyStore ks = createEmptyKeyStore();
    ks.setCertificateEntry(alias, cert);
    saveKeyStore(ks, filename, password);
}
Also used : KeyStore(java.security.KeyStore)

Aggregations

KeyStore (java.security.KeyStore)738 IOException (java.io.IOException)190 X509Certificate (java.security.cert.X509Certificate)189 FileInputStream (java.io.FileInputStream)163 KeyStoreException (java.security.KeyStoreException)151 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)138 InputStream (java.io.InputStream)125 Certificate (java.security.cert.Certificate)124 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)119 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)114 SSLContext (javax.net.ssl.SSLContext)112 PrivateKey (java.security.PrivateKey)94 CertificateException (java.security.cert.CertificateException)94 File (java.io.File)82 ByteArrayInputStream (java.io.ByteArrayInputStream)75 CertificateFactory (java.security.cert.CertificateFactory)75 Key (java.security.Key)61 UnrecoverableKeyException (java.security.UnrecoverableKeyException)55 TrustManager (javax.net.ssl.TrustManager)47 KeyManagementException (java.security.KeyManagementException)40