Java Code Examples for javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier()

The following examples show how to use javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HTTPSTrustManager.java    From styT with Apache License 2.0 6 votes vote down vote up
public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });

    SSLContext sslContext = null;
    if (trustManagers == null) {
        trustManagers = new TrustManager[]{new HTTPSTrustManager()};
    }

    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }
}
 
Example 2
Source File: TestUtils.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
public static void init() {
    // set up system properties for local IDE debug
    if (System.getProperty("mmsConfigFile") == null) {
        System.setProperty("mmsConfigFile", "src/test/resources/config.properties");
    }
    if (System.getProperty("METRICS_LOCATION") == null) {
        System.setProperty("METRICS_LOCATION", "build/logs");
    }
    if (System.getProperty("LOG_LOCATION") == null) {
        System.setProperty("LOG_LOCATION", "build/logs");
    }

    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);

        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier((s, sslSession) -> true);
    } catch (GeneralSecurityException e) {
        // ignore
    }
}
 
Example 3
Source File: AsyncHttpClientFactoryEmbed.java    From parallec with Apache License 2.0 6 votes vote down vote up
/**
 * Disable certificate verification.
 *
 * @throws KeyManagementException
 *             the key management exception
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 */
private void disableCertificateVerification()
        throws KeyManagementException, NoSuchAlgorithmException {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    final HostnameVerifier verifier = new HostnameVerifier() {
        @Override
        public boolean verify(final String hostname,
                final SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(verifier);
}
 
Example 4
Source File: EclipseSWTTrustManager.java    From developer-studio with Apache License 2.0 6 votes vote down vote up
public static void initiate() {
	// if (initiated) return;
	SSLContext sc;
	try {
		TrustManager[] trustAllCerts = new TrustManager[] { new EclipseSWTTrustManager() };
		sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
	initiated = true;
}
 
Example 5
Source File: CookieHttpsClientTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {
    // Wait for server to get started.
    while (!serverReady) {
        Thread.sleep(50);
    }

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }});

    URL url = new URL("https://localhost:" + serverPort +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example 6
Source File: CookieHttpsClientTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {
    // Wait for server to get started.
    while (!serverReady) {
        Thread.sleep(50);
    }

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }});

    URL url = new URL("https://localhost:" + serverPort +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example 7
Source File: SSLCertificateValidation.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void disable() {
    try {
        SSLContext sslc = SSLContext.getInstance("TLS");
        TrustManager[] trustManagerArray = { new NullX509TrustManager() };
        sslc.init(null, trustManagerArray, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: CargoBuildProcessAdapterHttpsTest.java    From teamcity-deployer-plugin with Apache License 2.0 5 votes vote down vote up
@AfterMethod
@Override
public void tearDown() throws Exception {
  myTomcat.stop();
  HttpsURLConnection.setDefaultHostnameVerifier(myDefaultHostnameVerifier);
  super.tearDown();
}
 
Example 9
Source File: SSLUtilities.java    From onvif with Apache License 2.0 5 votes vote down vote up
/**
 * Set the default Hostname Verifier to an instance of a fake class that trust all hostnames. This
 * method uses the old deprecated API from the com.sun.ssl package.
 *
 * @deprecated see {@link #_trustAllHostnames()}.
 */
private static void __trustAllHostnames() {
  // Create a trust manager that does not validate certificate chains
  if (__hostnameVerifier == null) {
    __hostnameVerifier = new _FakeHostnameVerifier();
  } // if
  // Install the all-trusting host name verifier
  HttpsURLConnection.setDefaultHostnameVerifier(__hostnameVerifier);
}
 
Example 10
Source File: EmailUtil.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the httpClient.
 */
public static void initialize() throws XPathExpressionException {

    DefaultHttpClient client = new DefaultHttpClient();

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    Scheme sch = new Scheme("https", 443, socketFactory);
    ClientConnectionManager mgr = client.getConnectionManager();
    mgr.getSchemeRegistry().register(sch);
    httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}
 
Example 11
Source File: CleanUpCommand.java    From testgrid with Apache License 2.0 5 votes vote down vote up
public CleanUpCommand(int status, int remainingBuildCount, TestPlanUOW testPlanUOW, List<String> datasource,
                      String grafanaUrl) {
    HostnameVerifier allHostsValid = new HostValidator();
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    this.status = status;
    this.remainingBuildCount = remainingBuildCount;
    this.testPlanUOW = testPlanUOW;
    this.datasource = datasource;
    this.grafanaUrl = grafanaUrl;

}
 
Example 12
Source File: Tanstagi.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
private void untrustEveryone() {
    if(defaultVerifier != null) {
        HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
    }
    if(defaultSSLSocketFactory != null) {
         HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }
}
 
Example 13
Source File: AbstractSecureJettyTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeSecureClass()
    throws IOException, GeneralSecurityException
{
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    HttpsURLConnection.setDefaultHostnameVerifier( ( string, ssls ) -> true );
    HttpsURLConnection.setDefaultSSLSocketFactory( buildTrustSSLContext().getSocketFactory() );
}
 
Example 14
Source File: JCurl.java    From JCurl with Apache License 2.0 5 votes vote down vote up
/**
 * Disable SSL hostname verification.
 * @param disableChecks
 * @return
 */
public Builder trustAllHostnames(boolean disableChecks) {
  instance.trustAllHostnames = disableChecks;
  if (disableChecks) {
    HttpsURLConnection.setDefaultHostnameVerifier(new AllValidatingHostnameVerifier());
  }
  return this;
}
 
Example 15
Source File: GridCommonAbstractTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
    // Disable SSL hostname verifier.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override public boolean verify(String s, SSLSession sslSes) {
            return true;
        }
    });

    super.beforeTest();
}
 
Example 16
Source File: SSLUtilities.java    From onvif with Apache License 2.0 5 votes vote down vote up
/** Set the default Hostname Verifier to an instance of a fake class that trust all hostnames. */
private static void _trustAllHostnames() {
  // Create a trust manager that does not validate certificate chains
  if (_hostnameVerifier == null) {
    _hostnameVerifier = new FakeHostnameVerifier();
  } // if
  // Install the all-trusting host name verifier:
  HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
}
 
Example 17
Source File: SslUtils.java    From lemon with Apache License 2.0 4 votes vote down vote up
public static void ignoreSsl() throws Exception {
    System.setProperty("jsse.enableSNIExtension", "false");
    trustAllHttpsCertificates();
    HttpsURLConnection
            .setDefaultHostnameVerifier(new MockHostnameVerifier());
}
 
Example 18
Source File: ConfigurationModuleHostNameVerifier.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public void init(Configuration config) {
   LOG.debug("Initializing ConfigurationModule " + this.getClass().getName());
   LOG.warn("Activating bypass: Hostname verifcation. DO NOT USE THIS IN PRODUCTION.");
   this.oldHostNameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
   HttpsURLConnection.setDefaultHostnameVerifier(new ConfigurationModuleHostNameVerifier.BypassHostnameVerifier());
}
 
Example 19
Source File: ConfigurationModuleHostNameVerifier.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public void unload() throws TechnicalConnectorException {
   LOG.debug("Unloading ConfigurationModule " + this.getClass().getName());
   HttpsURLConnection.setDefaultHostnameVerifier(this.oldHostNameVerifier);
}
 
Example 20
Source File: VMwareClient.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Establish a connection to the vCenter.
 */
public void connect() throws Exception {
    // FIXME what to do?
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    int numFailedLogins = 0;
    boolean repeatLogin = true;

    while (repeatLogin) {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            VimService vimService = new VimService();
            VimPortType vimPort = vimService.getVimPort();
            Map<String, Object> ctxt = ((BindingProvider) vimPort)
                    .getRequestContext();

            ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
            ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY,
                    Boolean.TRUE);

            ManagedObjectReference morSvcInstance = new ManagedObjectReference();
            morSvcInstance.setType("ServiceInstance");
            morSvcInstance.setValue("ServiceInstance");
            ServiceContent serviceContent = vimPort
                    .retrieveServiceContent(morSvcInstance);
            vimPort.login(serviceContent.getSessionManager(), user,
                    password, null);
            connection = new ServiceConnection(vimPort, serviceContent);
            LOG.debug("Established connection to vSphere. URL: " + url
                    + ", UserId: " + user);

            repeatLogin = false;
        } catch (Exception e) {
            LOG.error("Failed to establish connection to vSphere. URL: "
                    + url + ", UserId: " + user, e);
            if (numFailedLogins > 2) {
                throw e;
            }
            numFailedLogins++;
            repeatLogin = true;
            try {
                Thread.sleep(3000);
            } catch (@SuppressWarnings("unused") InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}