Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier.

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:com.inovex.zabbixmobile.activities.BaseActivity.java

/**
 * Binds the data service and sets up the action bar.
 *//*from  w w w  .  j a  va2  s.  co  m*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    ZaxPreferences prefs = ZaxPreferences.getInstance(getApplicationContext());
    if (prefs.isDarkTheme())
        setTheme(R.style.AppThemeDark);
    else
        setTheme(R.style.AppTheme);
    super.onCreate(savedInstanceState);

    finishReceiver = new FinishReceiver();
    registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH));

    bindService();

    // (re-) instantiate progress dialog
    mLoginProgress = (LoginProgressDialogFragment) getSupportFragmentManager()
            .findFragmentByTag(LoginProgressDialogFragment.TAG);

    if (mLoginProgress == null) {
        mLoginProgress = LoginProgressDialogFragment.getInstance();
    }

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        MemorizingTrustManager mtm = new MemorizingTrustManager(this);
        sc.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(
                mtm.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier()));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:org.xdi.oxauth.BaseTest.java

public static DefaultHttpClient createHttpClient(HostnameVerifierType p_verifierType) {
    if (p_verifierType != null && p_verifierType != HostnameVerifierType.DEFAULT) {
        switch (p_verifierType) {
        case ALLOW_ALL:
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            return new DefaultHttpClient(mgr, client.getParams());
        case DEFAULT:
            return new DefaultHttpClient();
        }//from   w  ww .j a  va  2s.  co m
    }
    return new DefaultHttpClient();
}

From source file:org.dcm4chee.xds2.src.tool.pnrsnd.PnRSnd.java

private void configTLS() {
    final HostnameVerifier origHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    final String allowedUrlHost = props.getProperty("allowedUrlHost");
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            if (!origHostnameVerifier.verify(urlHostName, session)) {
                if (isAllowedUrlHost(urlHostName)) {
                    log.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                } else {
                    return false;
                }/*w w w  .jav a2s.c o m*/
            }
            return true;
        }

        private boolean isAllowedUrlHost(String urlHostName) {
            if (allowedUrlHost == null || "CERT".equals(allowedUrlHost))
                return false;
            if (allowedUrlHost.equals("*"))
                return true;
            return allowedUrlHost.equals(urlHostName);
        }

    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;/*from ww  w  .j  a v  a 2s  . co  m*/

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}

From source file:org.sharegov.cirm.StartUp.java

public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*  w w  w .j a v a2  s .  c  om*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("Check client trusted");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("Check server trusted");

        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // TODO Auto-generated method stub
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        // SSLContext sc = SSLContext.getInstance("SSL");
        // sc.init(null, trustAllCerts, new SecureRandom());
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        // see:http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
        // see:https://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage
        org.apache.commons.httpclient.protocol.Protocol.registerProtocol("https",
                new org.apache.commons.httpclient.protocol.Protocol("https",
                        (ProtocolSocketFactory) new SslContextedSecureProtocolSocketFactory(ctx, false), 443));
        SSLContext.setDefault(ctx);
    } catch (Exception e) {
    }
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/*from   w  ww  .  ja  v  a  2 s .  c o m*/
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:org.apache.geode.management.internal.cli.commands.ConnectCommand.java

private void configureHttpsURLConnection(SSLConfig sslConfig, boolean skipSslVerification) throws Exception {
    KeyManager[] keyManagers = getKeyManagers(sslConfig);
    TrustManager[] trustManagers = getTrustManagers(sslConfig, skipSslVerification);

    if (skipSslVerification) {
        HttpsURLConnection.setDefaultHostnameVerifier((String s, SSLSession sslSession) -> true);
    }/*w  w w.ja  v a  2s.  c o m*/

    SSLContext ssl = SSLContext.getInstance(SSLUtil.getSSLAlgo(SSLUtil.readArray(sslConfig.getProtocols())));

    ssl.init(keyManagers, trustManagers, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
}

From source file:org.wso2.carbon.mediation.registry.ESBRegistry.java

/**
 * Configure the ESB registry using registry parameters.
 * <p/>/*from   w  w w  . ja v a  2s .  co  m*/
 * root: FILE:directory -   registry is on local host
 * directory is used to access metadata
 * <p/>
 * root: http/https:location -  has to specify one of the following settings
 * localRegistry - location of the local registry
 * metadataService - url of the service to access metadata
 * If none of above parameters are given "registry" FOLDER is taken as the local registry.
 *
 * @param name name of the config
 * @param value value of the config
 */
private void addConfigProperty(String name, String value) {

    if (localRegistry == null) {
        // registry root should always end with "/"
        if (ESBRegistryConstants.LOCAL_REGISTRY_ROOT.endsWith(URL_SEPARATOR)) {
            localRegistry = ESBRegistryConstants.LOCAL_REGISTRY_ROOT;
        } else {
            localRegistry = ESBRegistryConstants.LOCAL_REGISTRY_ROOT + URL_SEPARATOR;
        }
    }
    if (name != null && value != null) {
        if (name.equals("root")) {

            // root should always end with '/'
            // therefore, property keys do not have to begin with '/', which could be misleading
            try {
                URL url = new URL(value);
                if ("file".equals(url.getProtocol())) {
                    try {
                        url.openStream();
                    } catch (IOException ignored) {
                        if (!localRegistry.endsWith(URL_SEPARATOR)) {
                            localRegistry = localRegistry + URL_SEPARATOR;
                        }
                        url = new URL(url.getProtocol() + ":" + localRegistry + url.getPath());
                        try {
                            url.openStream();
                        } catch (IOException e) {
                            log.error("Unable to open a connection to url : " + url, e);
                        }
                    }
                }
                if (url.getProtocol().equals("file")) {
                    registryProtocol = FILE;

                    registryType = ESBRegistryConstants.LOCAL_HOST_REGISTRY;

                    if (url.getPath().endsWith(URL_SEPARATOR)) {
                        localRegistry = RegistryHelper.getSystemDependentPath(url.getPath());
                    } else {
                        localRegistry = RegistryHelper.getSystemDependentPath(url.getPath()) + File.separator;
                    }

                } else if (url.getProtocol().equals("http")) {
                    registryProtocol = HTTP;
                } else if (url.getProtocol().equals("https")) {
                    registryProtocol = HTTPS;
                }

                if (!value.endsWith(URL_SEPARATOR)) {
                    value = value + URL_SEPARATOR;
                }

            } catch (MalformedURLException e) {
                // don't set the root if this is not a valid URL
                handleException("Registry root should be a valid URL.", e);
            }
        }

        if (name.equals("localRegistry")) {
            registryType = ESBRegistryConstants.LOCAL_HOST_REGISTRY;

            // registry root always ends with "/"
            if (!value.endsWith(File.separator)) {
                value = value + File.separator;
            }
            localRegistry = value;
        }

        if (name.equals("matadataService")) {
            registryType = ESBRegistryConstants.REMOTE_HOST_REGISTRY;
            metaDataService = value;
        }

        // check if host name verification is disabled
        if (name.equalsIgnoreCase("disableHostNameVerification")) {
            if (value.equalsIgnoreCase("true")) {
                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                };

                HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }
        }

    } else {
        log.debug("Name and Value must need");
    }
}

From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java

private boolean isServiceAvailable(String target) {

    HostnameVerifier hv = new HostnameVerifier() {
        @Override//from   w w w  .j  ava 2 s. c  o  m
        public boolean verify(String urlHostName, SSLSession session) {
            if (urlHostName.equals(session.getPeerHost())) {
                return true;
            } else {
                return false;
            }
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    try {
        URL url = new URL(target + "?wsdl");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sslconn = (HttpsURLConnection) con;
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(),
                    new java.security.SecureRandom());
            sslconn.setSSLSocketFactory(context.getSocketFactory());
            sslconn.connect();
            if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                sslconn.disconnect();
                return true;
            }
        } else {
            con.connect();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return true;
            }
        }
    } catch (Exception e) {
        Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e);
    }
    return false;
}

From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java

private void doHostNameVerification() {
    if (!this.getEnableHostNameVerification()) {
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }/* w ww  .  j a  v  a2  s .co m*/
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
}