我需要抓取已过期/自签名证书的公司内部网站。没有人会为该主机配置有效的证书,所以我必须使用不安全的连接。
curl
为此目的有--insecure
个标记,
Scala finagle库具有.tlsWithoutValidation()
模式。
问题:是否有类似选项的Kotlin库?
UPD :到目前为止,我正在使用Fuel找到here的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)
}
上面的解决方法可行,但它过于冗长,似乎为我的应用程序的每个连接设置了不安全模式,而不仅仅是针对特定的连接。
答案 0 :(得分:3)
Fuel允许您通过FuelManager
类创建自己的Fuel客户端实例。管理器允许您设置自己的HostnameVerifier
和SSLSocketFactory
,然后使用配置的客户端创建客户端。参见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
。