List of usage examples for javax.net.ssl HttpsURLConnection getDefaultHostnameVerifier
public static HostnameVerifier getDefaultHostnameVerifier()
HostnameVerifier
that is inherited by new instances of this class. From source file:com.easou.common.util.CommonUtils.java
/** * Contacts the remote URL and returns the response. * // w w w . j a v a 2 s . co m * @param constructedUrl * the url to contact. * @param encoding * the encoding to use. * @return the response. */ public static String getResponseFromServer(final URL constructedUrl, final String encoding) { return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), encoding); }
From source file:net.i2p.util.I2PSSLSocketFactory.java
/** * Validate the hostname//w w w . j a v a 2s. c o m * * ref: https://developer.android.com/training/articles/security-ssl.html * ref: http://op-co.de/blog/posts/java_sslsocket_mitm/ * ref: http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/ * * @throws SSLException on hostname verification failure * @since 0.9.20 */ public static void verifyHostname(I2PAppContext ctx, SSLSocket socket, String host) throws SSLException { Log log = ctx.logManager().getLog(I2PSSLSocketFactory.class); if (ctx.getBooleanProperty(PROP_DISABLE) || host.equals("localhost") || host.equals("127.0.0.1") || host.equals("::1") || host.equals("0:0:0:0:0:0:0:1")) { if (log.shouldWarn()) log.warn("Skipping hostname validation for " + host); return; } HostnameVerifier hv; if (SystemVersion.isAndroid()) { // https://developer.android.com/training/articles/security-ssl.html hv = HttpsURLConnection.getDefaultHostnameVerifier(); } else { // haha the above may work for Android but it doesn't in Oracle // // quote http://kevinlocke.name/bits/2012/10/03/ssl-certificate-verification-in-dispatch-and-asynchttpclient/ : // Unlike SSLContext, using the Java default (HttpsURLConnection.getDefaultHostnameVerifier) // is not a viable option because the default HostnameVerifier expects to only be called // in the case that there is a mismatch (and therefore always returns false) while some // of the AsyncHttpClient providers (e.g. Netty, the default) call it on all connections. // To make matters worse, the check is not trivial (consider SAN and wildcard matching) // and is implemented in sun.security.util.HostnameChecker (a Sun internal proprietary API). // This leaves the developer in the position of either depending on an internal API or // finding/copying/creating another implementation of this functionality. // hv = new DefaultHostnameVerifier(getDefaultMatcher(ctx)); } SSLSession sess = socket.getSession(); // Verify that the certicate hostname is for mail.google.com // This is due to lack of SNI support in the current SSLSocket. if (!hv.verify(host, sess)) { throw new SSLHandshakeException("SSL hostname verify failed, Expected " + host + // throws SSLPeerUnverifiedException //", found " + sess.getPeerPrincipal() + // returns null //", found " + sess.getPeerHost() + // enable logging for DefaultHostnameVerifier to find out the CN and SANs " - set " + PROP_DISABLE + "=true to disable verification (dangerous!)"); } // At this point SSLSocket performed certificate verificaiton and // we have performed hostname verification, so it is safe to proceed. }
From source file:org.wso2.carbon.identity.sts.passive.ui.PassiveSTS.java
private void openURLWithNoTrust(String realm) throws IOException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override//from www . j a v a 2 s . com public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // Nothing to implement } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // Nothing to implement } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); String renegotiation = System.getProperty("sun.security.ssl.allowUnsafeRenegotiation"); try { HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true"); new URL(realm).getContent(); } finally { HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory); HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier); System.getProperty("sun.security.ssl.allowUnsafeRenegotiation", renegotiation); } } catch (Exception ignore) { if (log.isDebugEnabled()) { log.debug("Error while installing trust manager", ignore); } } }
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; }/* www .java2 s .c om*/ } 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:com.inovex.zabbixmobile.activities.BaseActivity.java
/** * Binds the data service and sets up the action bar. *//*ww w .ja v a2 s . com*/ @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:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java
public void requestToken() { AuthorizationGrant grant;/*from w w w. jav a 2s.co m*/ if (authCode == null) { if (resourceOwnerCredentialsGrant == null) { System.err .println("Authentication Code is null and no user/password set, stopping token retrieval"); return; } else { grant = resourceOwnerCredentialsGrant; } } else { grant = new AuthorizationCodeGrant(authCode, redirectURI); } TokenRequest tokenReq = new TokenRequest(providerMetadata.getTokenEndpointURI(), new ClientSecretBasic(clientID, clientInformation.getSecret()), grant); HTTPResponse tokenHTTPResp = null; try { tokenHTTPResp = tokenReq.toHTTPRequest().send(HttpsURLConnection.getDefaultHostnameVerifier(), HttpsURLConnection.getDefaultSSLSocketFactory()); } catch (SerializeException | IOException e) { // TODO proper error handling e.printStackTrace(); } // Parse and check response TokenResponse tokenResponse = null; try { tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp); } catch (ParseException e) { // TODO proper error handling e.printStackTrace(); } if (tokenResponse instanceof TokenErrorResponse) { ErrorObject error = ((TokenErrorResponse) tokenResponse).getErrorObject(); // TODO error handling System.err.println("Error at token retrieval"); System.err.println(error); return; } OIDCTokenResponse accessTokenResponse = (OIDCTokenResponse) tokenResponse; accessToken = accessTokenResponse.getOIDCTokens().getAccessToken(); idToken = accessTokenResponse.getOIDCTokens().getIDToken(); }
From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java
public void requestUserInfo() { if (accessToken == null) { System.err.println("Access Token null, stopping UserInfo retrieval"); return;//from w w w. j a va 2s. c o m } UserInfoRequest userInfoReq = new UserInfoRequest(userInfoEndpointURI, (BearerAccessToken) accessToken); HTTPResponse userInfoHTTPResp = null; try { userInfoHTTPResp = userInfoReq.toHTTPRequest().send(HttpsURLConnection.getDefaultHostnameVerifier(), HttpsURLConnection.getDefaultSSLSocketFactory()); } catch (SerializeException | IOException e) { // TODO proper error handling e.printStackTrace(); } UserInfoResponse userInfoResponse = null; try { userInfoResponse = UserInfoResponse.parse(userInfoHTTPResp); } catch (ParseException e) { // TODO proper error handling e.printStackTrace(); } if (userInfoResponse instanceof UserInfoErrorResponse) { UserInfoErrorResponse errorResponse = ((UserInfoErrorResponse) userInfoResponse); ErrorObject error = errorResponse.getErrorObject(); System.err.println(errorResponse.indicatesSuccess()); System.err.println("Userinfo retrieval failed:"); System.err.println(errorResponse); System.err.println(error); System.err.println(error.getHTTPStatusCode()); System.err.println(userInfoHTTPResp.getStatusCode()); System.err.println(userInfoHTTPResp.getContent()); System.err.println(userInfoHTTPResp.getWWWAuthenticate()); System.err.println(userInfoHTTPResp.getLocation()); } UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) userInfoResponse; userInfoClaims = successResponse.getUserInfo().toJSONObject(); }
From source file:com.kenai.redminenb.repository.RedmineRepository.java
static PoolingClientConnectionManager createConnectionManager() throws SSLInitializationException { SSLSocketFactory socketFactory = SSLSocketFactory.getSystemSocketFactory(); socketFactory.setHostnameVerifier(new X509HostnameVerifier() { @Override// w w w.j a v a 2 s .c om public void verify(String string, SSLSocket ssls) throws IOException { if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) { throw new SSLException("Hostname did not verify"); } } @Override public void verify(String string, X509Certificate xc) throws SSLException { throw new SSLException("Check not implemented yet"); } @Override public void verify(String string, String[] strings, String[] strings1) throws SSLException { throw new SSLException("Check not implemented yet"); } @Override public boolean verify(String string, SSLSession ssls) { return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls); } }); PoolingClientConnectionManager connectionManager = RedmineManagerFactory .createConnectionManager(Integer.MAX_VALUE, socketFactory); return connectionManager; }