Example usage for javax.net.ssl SSLContext setDefault

List of usage examples for javax.net.ssl SSLContext setDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext setDefault.

Prototype

public static void setDefault(SSLContext context) 

Source Link

Document

Sets the default SSL context.

Usage

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName//www .  j a  v  a2  s.  c  om
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:org.openanzo.client.cli.CommandLineInterface.java

static int processCommand(CommandContext context, boolean exitOnException, String... arguments) {
    IConsole cw = context != null ? context.getConsoleWriter() : null;
    if (cw == null) {
        cw = DEFAULT_CONSOLE;//from   ww w  .  j av  a  2  s.c  o m
    }
    boolean beep = false;
    String subcommand = arguments[0];
    try {
        for (SubCommand sc : subcommands) {
            if (sc.getName().equals(subcommand)) {
                boolean showStackTrace = false;
                boolean pauseOnExit = false;
                try {
                    Options options = sc.getOptions();
                    appendGlobalOptions(options);
                    CommandLineParser parser = new PosixParser();
                    String[] subcommandArgs = (String[]) ArrayUtils.subarray(arguments, 1, arguments.length);
                    CommandLine cl = parser.parse(options, subcommandArgs);

                    pauseOnExit = cl.hasOption(PAUSE_EXIT_OPTION.getOpt());
                    if (context == null) {
                        context = createContext(DEFAULT_CONSOLE, cl, options, arguments);
                    }

                    // set up the trust manager
                    boolean trustAll = cl.hasOption(TRUST_OPTION.getOpt());
                    showStackTrace = cl.hasOption(SHOW_TRACE_OPTION.getOpt());
                    beep = cl.hasOption(BEEP_OPTION.getOpt());
                    TrustManager[] myTMs = new TrustManager[] {
                            new AnzoTrustManager(trustAll, showStackTrace) };
                    SSLContext ctx = SSLContext.getInstance("TLS");
                    ctx.init(null, myTMs, new java.security.SecureRandom());
                    SSLContext.setDefault(ctx);

                    return sc.invoke(cl, context, context.getAnzoClient());
                } catch (ParseException e) {
                    cw.writeError("error: ");
                    cw.printException(e, showStackTrace);
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("anzo", sc.getOptions());
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (InvalidArgumentException e) {
                    cw.printException(e, showStackTrace);
                    sc.printHelp(cw);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (CommandException ae) {
                    if (ae.getCause() != null && ae.getCause() instanceof AnzoException) {
                        if (((AnzoException) ae.getCause())
                                .getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED) {
                            cw.writeError("Connection failed.");
                        }
                    }
                    cw.printException(ae, showStackTrace);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (UpdateServerException e) {
                    cw.writeError(e.getUserMessage());
                    for (List<AnzoException> exceptions : e.getErrors()) {
                        if (exceptions != null) {
                            for (AnzoException ae : exceptions) {
                                if (ae.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED)
                                    cw.writeError("Connection failed.");
                                cw.printException(ae, showStackTrace);
                            }
                        }
                    }
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (AnzoException e) {
                    if (e.getErrorCode() == ExceptionConstants.COMBUS.JMS_CONNECT_FAILED)
                        cw.writeError("Connection failed.");
                    cw.printException(e, showStackTrace);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (AnzoRuntimeException e) {
                    cw.printException(e, showStackTrace);
                    sc.printHelp(cw);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (NoSuchAlgorithmException e) {
                    cw.writeError("Error with ssl:");
                    cw.printException(e, showStackTrace);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                } catch (KeyManagementException e) {
                    cw.writeError("Error with ssl:");
                    cw.printException(e, showStackTrace);
                    if (exitOnException)
                        exitOnError(1, pauseOnExit);
                }
            }
        }

        if (subcommand.startsWith("-")) {
            cw.writeError("Option not allowed before subcommand: " + subcommand);
        } else if (subcommand.equals("help")) {
            if (arguments.length < 2) {
                printHelp(cw);
            } else {
                String helpSubcommand = arguments[1];
                for (SubCommand sc : subcommands) {
                    if (sc.getName().equals(helpSubcommand)) {
                        sc.printHelp(cw);
                        return 0;
                    }
                }
                cw.writeError("unrecognized subcommand: " + helpSubcommand);
            }
        } else {
            cw.writeError("unrecognized subcommand: " + subcommand);
        }
    } finally {
        if (cw != null && beep) {
            cw.beep();
        }
    }
    return 0;
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@After
public void teardown() throws Exception {
    if (defaultSSLContext != null) {
        SSLContext.setDefault(defaultSSLContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }/*from  www .j a v  a  2s  .  c o m*/

    if (restClient != null) {
        restClient.shutdown(timeout);
        restClient = null;
    }

    if (serverEndpoint != null) {
        serverEndpoint.closeAsync().get(timeout.getSize(), timeout.getUnit());
        serverEndpoint = null;
    }
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

public static void setHttpsClientCert(String certificateFile, String certPassword) {
    try {//from w  w w .  j a v a 2s .  com
        if (certificateFile == null || !new File(certificateFile).exists()) {
            return;
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream keyInput = new FileInputStream(certificateFile);
        keyStore.load(keyInput, certPassword.toCharArray());
        keyInput.close();
        keyManagerFactory.init(keyStore, certPassword.toCharArray());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
        SSLContext.setDefault(context);
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } catch (CertificateException e) {
    } catch (UnrecoverableKeyException e) {
    } catch (KeyManagementException e) {
    }
}

From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java

protected SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/* w w w . j  a va  2  s.c o m*/

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:org.apache.stratos.cli.RestCommandLineService.java

/**
 * Authenticate and login to stratos server.
 *
 * @param serverURL     URL of the server
 * @param username      username//w  w w  . j  a v  a2s.  c  o  m
 * @param password      password
 * @param validateLogin validate login
 * @return boolean
 * @throws Exception
 */
public boolean login(String serverURL, String username, String password, boolean validateLogin)
        throws Exception {
    try {
        // Avoid validating SSL certificate
        SSLContext sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        throw new RuntimeException("Error while authentication process!", e);
    }

    // Initialize client
    try {
        initializeRestClient(serverURL, username, password);

        if (log.isDebugEnabled()) {
            log.debug("Initialized REST Client for user {}", username);
        }
    } catch (AxisFault e) {
        String message = "Error connecting to the stratos server";
        printError(message, e);
        throw new CommandException(e);
    }

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        if (validateLogin) {
            HttpResponse response = restClient.doGet(httpClient, restClient.getBaseURL() + ENDPOINT_INIT);

            if (response != null) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 200) {
                    return true;
                } else {
                    System.out.println("Invalid value is set for STRATOS_URL");
                }
            }
            return false;
        } else {
            // Just return true as we don't need to validate
            return true;
        }
    } catch (ConnectException e) {
        String message = "Could not connect to stratos manager";
        printError(message, e);
        return false;
    } catch (java.lang.NoSuchMethodError e) {
        String message = "Authentication failed!";
        printError(message, e);
        return false;
    } catch (Exception e) {
        if (e.getCause() instanceof MalformedChallengeException) {
            String message = "Authentication failed. Please check your username/password";
            printError(message, e);
            return false;
        }
        String message = "An unknown error occurred: " + e.getMessage();
        printError(message, e);
        return false;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory/*from w  w  w .j  a  v a  2s  .  c o  m*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Initialize this SocketCreator./*  ww  w  .  j  a  v a  2s  . c  o m*/
 * <p>
 * Caller must synchronize on the SocketCreator instance.
 */
@SuppressWarnings("hiding")
private void initialize() {
    try {
        // set p2p values...
        if (SecurableCommunicationChannel.CLUSTER.equals(sslConfig.getSecuredCommunicationChannel())) {
            if (this.sslConfig.isEnabled()) {
                System.setProperty("p2p.useSSL", "true");
                System.setProperty("p2p.oldIO", "true");
                System.setProperty("p2p.nodirectBuffers", "true");
            } else {
                System.setProperty("p2p.useSSL", "false");
            }
        }

        try {
            if (this.sslConfig.isEnabled() && sslContext == null) {
                sslContext = createAndConfigureSSLContext();
                SSLContext.setDefault(sslContext);
            }
        } catch (Exception e) {
            throw new GemFireConfigException("Error configuring GemFire ssl ", e);
        }

        // make sure TCPConduit picks up p2p properties...
        org.apache.geode.internal.tcp.TCPConduit.init();

        initializeClientSocketFactory();
        this.ready = true;
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // If this ever returns, rethrow the error. We're poisoned
        // now, so don't let this thread continue.
        throw err;
    } catch (Error t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        t.printStackTrace();
        throw t;
    } catch (RuntimeException re) {
        re.printStackTrace();
        throw re;
    }
}

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);//w  w w .  j  a  v  a2  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:org.wso2.developerstudio.eclipse.esb.project.ui.wizard.ImportCloudConnectorWizardPage.java

private HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setIntParameter(HTTP_SOCKET_TIMEOUT, TIMEOUT);
    SSLContext ctx;/*from w w  w  . j  a v  a 2  s.c  o  m*/
    ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);
    return httpclient;
}