使用okHttp信任所有证书


111

为了进行测试,我试图将套接字工厂添加到我的okHttp客户端中,该客户端工厂在设置代理时会信任所有内容。这已经做过很多次了,但是我对可信任套接字工厂的实现似乎缺少了一些东西:

class TrustEveryoneManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }

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

final InetAddress ipAddress = InetAddress.getByName("XX.XXX.XXX.XXX"); // some IP
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipAddress, 8888)));

SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager[]{new TrustEveryoneManager()};
sslContext.init(null, trustManagers, null);
client.setSslSocketFactory(sslContext.getSocketFactory);

没有任何请求从我的应用程序发送出去,也没有任何异常记录在日志中,因此它似乎在okHttp中静默失败。经过进一步调查,似乎Connection.upgradeToTls()在强制握手时在okHttp中吞下了一个异常。我得到的例外是:javax.net.ssl.SSLException: SSL handshake terminated: ssl=0x74b522b0: SSL_ERROR_ZERO_RETURN occurred. You should never see this.

下面的代码生成一个SSLContext,就像在创建不引发任何异常的SSLSocketFactory时的魅力一样:

protected SSLContext getTrustingSslContext() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final SSLContextBuilder trustingSSLContextBuilder = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true; // Accepts any ssl cert whether valid or not.
                }
            });
    return trustingSSLContextBuilder.build();
}

问题是我试图从我的应用程序中完全删除所有Apache HttpClient依赖项。用Apache HttpClient生成的基础代码SSLContext看起来似乎很简单,但是由于我无法配置我的代码,因此我显然缺少了一些东西SSLContext

有人能够在不使用Apache HttpClient的情况下产生我想要的SSLContext实现吗?


2
“出于测试目的,我正在尝试向信任所有内容的okHttp客户端添加套接字工厂” –是什么让您认为这首先是个好主意?
CommonsWare 2014年

1
仅在我完全信任的网络上调用它。
seato 2014年

这导致java.net.SocketTimeoutException: Read timed out
IgorGanapolsky

Answers:


249

万一有人落在这里,对我有用的(唯一)解决方案就是创建此处OkHttpClient说明的类似内容。

这是代码:

private static OkHttpClient getUnsafeOkHttpClient() {
  try {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
          @Override
          public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
          }

          @Override
          public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
          }

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

    // Install the all-trusting trust manager
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
    builder.hostnameVerifier(new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });

    OkHttpClient okHttpClient = builder.build();
    return okHttpClient;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

15
为什么SSLTLS呢?
IgorGanapolsky 2015年

1
非常感谢!缺乏有关改造的文档(使用okhttp),这种代码示例一次又一次地为我节省了很多时间。
Warpzit

8
请注意,此方法不适用于当前版本的OkHttp。使用3.1.1似乎完全坏了。从3.1.2开始,X509TrustManager.getAcceptedIssuers()必须返回一个空数组,而不是null。有关更多信息,请参见此提交(向下滚动并查看RealTrustRootIndex.java下的注释)。
jbxbergdev

12
我已经尝试过了,但是仍然遇到Handshake failed异常。有什么建议?
Esteban


13

不推荐使用以下方法

sslSocketFactory(SSLSocketFactory sslSocketFactory)

考虑将其更新为

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

13

更新OkHttp 3.0,该getAcceptedIssuers()函数必须返回一个空数组,而不是null


2
@Override public X509Certificate [] getAcceptedIssuers(){return new X509Certificate [] {}; // StackOverflow}
Ervin Zhang

11

SSLSocketFactory不公开其X509TrustManager,这是OkHttp用来构建干净证书链的字段。相反,此方法必须使用反射来提取信任管理器。应用程序应该更喜欢调用sslSocketFactory(SSLSocketFactory,X509TrustManager),这样可以避免这种反射。

来源:OkHttp文档

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslContext.getSocketFactory(),
    new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

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

这不适用于自签名证书。导致401未经授权的错误。
IgorGanapolsky

5
哪里sslContext来的?
Anonsage

3
您如何初始化sslContext
kiltek

9

如果有人需要,这是sonxurxo在Kotlin的解决方案。

private fun getUnsafeOkHttpClient(): OkHttpClient {
    // Create a trust manager that does not validate certificate chains
    val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        }

        override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
    })

    // Install the all-trusting trust manager
    val sslContext = SSLContext.getInstance("SSL")
    sslContext.init(null, trustAllCerts, java.security.SecureRandom())
    // Create an ssl socket factory with our all-trusting manager
    val sslSocketFactory = sslContext.socketFactory

    return OkHttpClient.Builder()
        .sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
        .hostnameVerifier { _, _ -> true }.build()
}


7

我为Kotlin做了扩展功能。将其粘贴到所需的位置,然后在创建时将其导入OkHttpClient

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
    val naiveTrustManager = object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
    }

    val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
        val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

    sslSocketFactory(insecureSocketFactory, naiveTrustManager)
    hostnameVerifier(HostnameVerifier { _, _ -> true })
    return this
}

像这样使用它:

val okHttpClient = OkHttpClient.Builder().apply {
    // ...
    if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
        ignoreAllSSLErrors()
    //...
}.build()

您实际上可以像这样使用它:OkHttpClient.Builder().ignoreAllSSLErrors().connectTimeout(api.timeout,TimeUnit.SECONDS).writeTimeout(api.timeout,TimeUnit.SECONDS)等,毕竟这是一个构建器模式
Emanuel Moecklin

1

如果有人需要,这就是Scala解决方案

def anUnsafeOkHttpClient(): OkHttpClient = {
val manager: TrustManager =
  new X509TrustManager() {
    override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}

    override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}

    override def getAcceptedIssuers = Seq.empty[X509Certificate].toArray
  }
val trustAllCertificates =  Seq(manager).toArray

val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCertificates, new java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
val okBuilder = new OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCertificates(0).asInstanceOf[X509TrustManager])
okBuilder.hostnameVerifier(new NoopHostnameVerifier)
okBuilder.build()

}


-12

您绝不应该在代码中覆盖证书验证!如果需要进行测试,请使用内部/测试CA,然后在设备或仿真器上安装CA根证书。如果您不知道如何设置CA,则可以使用BurpSuite或Charles Proxy。


37
哦,拜托 如果您在一家公司工作,并且他们强迫您通过VPN连接到他们的HTTPS服务器,该怎么办?您如何在测试中模拟?
IgorGanapolsky

5
雅,这是最纯正的洗猪场。我们仅在测试版本中对此进行编译,因此没有危险。
亚当
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.