简体   繁体   English

Java SSL:如何禁用主机名验证

[英]Java SSL: how to disable hostname verification

Is there a way for the standard java SSL sockets to disable hostname verfication for ssl connections with a property?标准 java SSL 套接字有没有办法禁用具有属性的 ssl 连接的主机名验证? The only way I found until now, is to write a hostname verifier which returns true all the time.到目前为止,我发现的唯一方法是编写一个主机名验证器,它始终返回 true。

Weblogic provides this possibility, it is possible to disable the hostname verification with the following property: Weblogic 提供了这种可能性,可以使用以下属性禁用主机名验证:

-Dweblogic.security.SSL.ignoreHostnameVerify -Dweblogic.security.SSL.ignoreHostnameVerify

It should be possible to create custom java agent that overrides default HostnameVerifier :应该可以创建覆盖默认HostnameVerifier自定义java 代理

import javax.net.ssl.*;
import java.lang.instrument.Instrumentation;

public class LenientHostnameVerifierAgent {
    public static void premain(String args, Instrumentation inst) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }
}

Then just add -javaagent:LenientHostnameVerifierAgent.jar to program's java startup arguments.然后只需将-javaagent:LenientHostnameVerifierAgent.jar添加到程序的 java 启动参数中。

The answer from @Nani doesn't work anymore with Java 1.8u181. @Nani 的答案不再适用于 Java 1.8u181。 You still need to use your own TrustManager, but it needs to be a X509ExtendedTrustManager instead of a X509TrustManager :您仍然需要使用自己的 TrustManager,但它需要是X509ExtendedTrustManager而不是X509TrustManager

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;

public class Test {

   public static void main (String [] args) throws IOException {
      // This URL has a certificate with a wrong name
      URL url = new URL ("https://wrong.host.badssl.com/");

      try {
         // opening a connection will fail
         url.openConnection ().connect ();
      } catch (SSLHandshakeException e) {
         System.out.println ("Couldn't open connection: " + e.getMessage ());
      }

      // Bypassing the SSL verification to execute our code successfully
      disableSSLVerification ();

      // now we can open the connection
      url.openConnection ().connect ();

      System.out.println ("successfully opened connection to " + url + ": " + ((HttpURLConnection) url.openConnection ()).getResponseCode ());
   }

   // Method used for bypassing SSL verification
   public static void disableSSLVerification () {

      TrustManager [] trustAllCerts = new TrustManager [] {new X509ExtendedTrustManager () {
         @Override
         public void checkClientTrusted (X509Certificate [] chain, String authType, Socket socket) {

         }

         @Override
         public void checkServerTrusted (X509Certificate [] chain, String authType, Socket socket) {

         }

         @Override
         public void checkClientTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

         }

         @Override
         public void checkServerTrusted (X509Certificate [] chain, String authType, SSLEngine engine) {

         }

         @Override
         public java.security.cert.X509Certificate [] getAcceptedIssuers () {
            return null;
         }

         @Override
         public void checkClientTrusted (X509Certificate [] certs, String authType) {
         }

         @Override
         public void checkServerTrusted (X509Certificate [] certs, String authType) {
         }

      }};

      SSLContext sc = null;
      try {
         sc = SSLContext.getInstance ("SSL");
         sc.init (null, trustAllCerts, new java.security.SecureRandom ());
      } catch (KeyManagementException | NoSuchAlgorithmException e) {
         e.printStackTrace ();
      }
      HttpsURLConnection.setDefaultSSLSocketFactory (sc.getSocketFactory ());
   }
}

There is no hostname verification in standard Java SSL sockets or indeed SSL, so that's why you can't set it at that level.标准 Java SSL 套接字或 SSL 中没有主机名验证,因此您不能将其设置在该级别。 Hostname verification is part of HTTPS (RFC 2818): that's why it manifests itself as javax.net.ssl.HostnameVerifier, which is applied to an HttpsURLConnection.主机名验证是 HTTPS (RFC 2818) 的一部分:这就是为什么它显示为 javax.net.ssl.HostnameVerifier,它应用于 HttpsURLConnection。

I also had the same problem while accessing RESTful web services.我在访问 RESTful Web 服务时也遇到了同样的问题。 And I their with the below code to overcome the issue:我用下面的代码来克服这个问题:

public class Test {
    //Bypassing the SSL verification to execute our code successfully 
    static {
        disableSSLVerification();
    }

    public static void main(String[] args) {    
        //Access HTTPS URL and do something    
    }
    //Method used for bypassing SSL verification
    public static void disableSSLVerification() {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }

        } };

        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

It worked for me.它对我有用。 try it!!尝试一下!!

In case you're using apache's http-client 4:如果您使用的是 apache 的 http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

@user207421 is right, there is no hostname verification in standard Java SSL sockets or indeed SSL. @user207421 是对的,标准 Java SSL 套接字或 SSL 中没有主机名验证。
But X509ExtendedTrustManager implement the host name check logic(see it's javadoc).但是X509ExtendedTrustManager实现了主机名检查逻辑(参见 javadoc)。 To disable this, We can set SSLParameters .endpointIdentificationAlgorithm to null as JDK AbstractAsyncSSLConnection did:要禁用此功能,我们可以像JDK AbstractAsyncSSLConnection那样将 SSLParameters .endpointIdentificationAlgorithm 设置为 null:

        if (!disableHostnameVerification)
            sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); // default is null

disableHostnameVerification is read from property: jdk.internal.httpclient.disableHostnameVerification。 disableHostnameVerification从属性读取:jdk.internal.httpclient.disableHostnameVerification。

How to modify SSLParameters Object is dependends on the specify soft you use。如何修改 SSLParameters 对象取决于您使用的指定软件。

as spring webflux WebClient:作为 spring webflux WebClient:

HttpClient httpClient = HttpClient.create()
    .secure(sslContextSpec ->
        sslContextSpec
            .sslContext(sslContext)
            .handlerConfigurator(sslHandler -> {
                SSLEngine engine = sslHandler.engine();
                SSLParameters newSslParameters = engine.getSSLParameters(); // 返回的是一个新对象
                // 参考:https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.net.http/share/classes/jdk/internal/net/http/AbstractAsyncSSLConnection.java#L116
                newSslParameters.setEndpointIdentificationAlgorithm(null);
                engine.setSSLParameters(newSslParameters);
            })
    )
    
WebClient webclient = WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM