8

我需要抓取已过期/自签名证书的内部公司网站。没有人会为该主机配置有效证书,所以我必须使用不安全的连接。

curl--insecure为此目的的旗帜,

Scala finagle 库有.tlsWithoutValidation()模式。

问题:是否有具有类似选项的 Kotlin 库?

UPD:到目前为止,我正在使用Fuel和这里找到的 javish 解决方法,但仍在寻找更好的方法..

fun useInsecureSSL() {

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

    val sc = SSLContext.getInstance("SSL")
    sc.init(null, trustAllCerts, java.security.SecureRandom())
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.socketFactory)

    // Create all-trusting host name verifier
    val allHostsValid = HostnameVerifier { _, _ -> true }

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid)
}

上述解决方法有效,但是它过于冗长,并且似乎为我的应用程序建立的每个连接设置了不安全模式,而不仅仅是特定的连接。

4

1 回答 1

6

FuelManagerFuel 允许您通过该类创建自己的 Fuel 客户端实例。管理器让您可以设置自己的HostnameVerifierSSLSocketFactory然后使用这些配置创建客户端。见https://github.com/kittinunf/Fuel/blob/1.16.0/fuel/src/main/kotlin/com/github/kittinunf/fuel/core/FuelManager.kt#L31-L43

val manager : FuelManager = FuelManager().apply {
  val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
    override fun getAcceptedIssuers(): Array<X509Certificate>? = null
    override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) = Unit
    override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) = Unit
  })

  socketFactory = SSLContext.getInstance("SSL").apply {
    init(null, trustAllCerts, java.security.SecureRandom())
  }.socketFactory

  hostnameVerifier = HostnameVerifier { _, _ -> true }
}

然后检查是否只有通过此自定义FuelManager的连接是不受信任的以及不受信任的连接,我们这样做:

val (_, untrustedResp, untrustedResult) = manager.request(Method.GET, "https://internal/company/site").response()
assert(untrustedResp.statusCode == 200)
val (bytes, _) = untrustedResult
assert(bytes != null)


val (_, trustedResp, trustedResult) = "https://internal/company/site".httpGet().response()
assert(trustedResp.statusCode != 200)
val (bytes, error) = trustedResult
assert(bytes == null)
println(error) // javax.net.ssl.SSLHandshakeException: PKIX path building failed: ...

自定义FuelManager能够成功发出请求,因为它信任所有证书,但对于未使用自定义管理器的连接,我们可以看到它返回javax.net.ssl.SSLHandshakeException.

于 2018-12-07T08:27:42.690 回答