新手學(xué)易語言多久可以做網(wǎng)站中國優(yōu)秀網(wǎng)頁設(shè)計案例
hostnameVerifier
- 方法簡介
- 核心原理
- 參考資料
方法簡介
本篇博文以O(shè)khttp 4.6.0來解析hostnameVerfier
的作用,顧名思義,該方法的主要作用就是鑒定hostnname
的合法性。Okhttp在初始化的時候我們可以自己配置hostnameVerfier
:
new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).writeTimeout(35, TimeUnit.SECONDS) .hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {//注意這里在生產(chǎn)環(huán)境中千萬不要直接寫死true return true;}}).build();
但是網(wǎng)上好多資料將verfiy
直接返回true是十分危險的。當(dāng)然如果vertify返回fasle意味著hostname驗證不通過,http請求無法成功,比如我以自己的博客地址發(fā)起http請求,錯誤信息如下:
{http errorCode=-500, mErrorMsg=Hostname yanchen.blog.csdn.net not verified:certificate: sha256/tlnf6pbfeu257hnJ9e6j4A1ZWH3vVMzn3Zn3F9kLHdg=DN: CN=*.blog.csdn.netsubjectAltNames: [*.blog.csdn.net]}
執(zhí)行vertify的地方是在RealConnection里面,執(zhí)行之后。
除了自定義hostnameVerfier
之外,Okhttp提供了默認實現(xiàn),現(xiàn)在就分析下起內(nèi)部原理。
核心原理
在Okhttp內(nèi)置了OkHostnameVerifier,該方法通過session.peerCertificates[0] as X509Certificate
獲取證書的對象
override fun verify(host: String, session: SSLSession): Boolean {return try {verify(host, session.peerCertificates[0] as X509Certificate)} catch (_: SSLException) {false}}fun verify(host: String, certificate: X509Certificate): Boolean {return when {host.canParseAsIpAddress() -> verifyIpAddress(host, certificate)else -> verifyHostname(host, certificate)}}
通過X509Certificate對象提供了一系列g(shù)et方法可以獲取到證書的公鑰,序列號等一系列信息。見下圖:
最終會調(diào)用verifyHostname
方法,通過certificate獲取getSubjectAltNames
拿到SubjectAltName
之后,將hostname與SubjectAltName
進行比對,如果符合就返回true,否則就返回fasle.
private fun verifyHostname(hostname: String, certificate: X509Certificate): Boolean {val hostname = hostname.toLowerCase(Locale.US)return getSubjectAltNames(certificate, ALT_DNS_NAME).any {verifyHostname(hostname, it)}}//hostname和SubjectAltName比對
private fun verifyHostname(hostname: String?, pattern: String?): Boolean {var hostname = hostnamevar pattern = pattern//檢驗客戶端域名的有效性if (hostname.isNullOrEmpty() ||hostname.startsWith(".") ||hostname.endsWith("..")) {// Invalid domain namereturn false}//檢驗證書中SubjectAltName的有效性if (pattern.isNullOrEmpty() ||pattern.startsWith(".") ||pattern.endsWith("..")) {// Invalid pattern/domain namereturn false}// Normalize hostname and pattern by turning them into absolute domain names if they are not// yet absolute. This is needed because server certificates do not normally contain absolute// names or patterns, but they should be treated as absolute. At the same time, any hostname// presented to this method should also be treated as absolute for the purposes of matching// to the server certificate.// www.android.com matches www.android.com// www.android.com matches www.android.com.// www.android.com. matches www.android.com.// www.android.com. matches www.android.comif (!hostname.endsWith(".")) {hostname += "."}if (!pattern.endsWith(".")) {pattern += "."}// Hostname and pattern are now absolute domain names.pattern = pattern.toLowerCase(Locale.US)// Hostname and pattern are now in lower case -- domain names are case-insensitive.if ("*" !in pattern) {// Not a wildcard pattern -- hostname and pattern must match exactly.return hostname == pattern}// Wildcard pattern// WILDCARD PATTERN RULES:// 1. Asterisk (*) is only permitted in the left-most domain name label and must be the// only character in that label (i.e., must match the whole left-most label).// For example, *.example.com is permitted, while *a.example.com, a*.example.com,// a*b.example.com, a.*.example.com are not permitted.// 2. Asterisk (*) cannot match across domain name labels.// For example, *.example.com matches test.example.com but does not match// sub.test.example.com.// 3. Wildcard patterns for single-label domain names are not permitted.if (!pattern.startsWith("*.") || pattern.indexOf('*', 1) != -1) {// Asterisk (*) is only permitted in the left-most domain name label and must be the only// character in that labelreturn false}// Optimization: check whether hostname is too short to match the pattern. hostName must be at// least as long as the pattern because asterisk must match the whole left-most label and// hostname starts with a non-empty label. Thus, asterisk has to match one or more characters.if (hostname.length < pattern.length) {return false // Hostname too short to match the pattern.}if ("*." == pattern) {return false // Wildcard pattern for single-label domain name -- not permitted.}// Hostname must end with the region of pattern following the asterisk.val suffix = pattern.substring(1)if (!hostname.endsWith(suffix)) {return false // Hostname does not end with the suffix.}// Check that asterisk did not match across domain name labels.val suffixStartIndexInHostname = hostname.length - suffix.lengthif (suffixStartIndexInHostname > 0 &&hostname.lastIndexOf('.', suffixStartIndexInHostname - 1) != -1) {return false // Asterisk is matching across domain name labels -- not permitted.}// Hostname matches pattern.return true}
那么SubjectAltName
是什么?我們可以通過如下方法獲取:
new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {try {X509Certificate x509Certificate= (X509Certificate) session.getPeerCertificates()[0];Collection<List<?>> subjectAltNames = x509Certificate.getSubjectAlternativeNames();for (List<?> subjectAltName : subjectAltNames) {if (subjectAltName == null || subjectAltName.size() < 2) continue;int type = (int)subjectAltName.get(0);if (type!= 2) continue;String altName = (String)subjectAltName.get(1);LogUtil.logD("hostnameVerifier","x509Certificate altName=="+altName);}} catch (Exception e) {} return true;}}
Okhttp 內(nèi)置的hostname校驗邏輯很簡單,大家可以自行查看起源碼即可。
參考資料
- Android CertificateSource系統(tǒng)根證書的檢索和獲取
- Android https TrustManager checkServerTrusted 詳解
- Android RootTrustManager 證書校驗簡單分析
- Android CertificateSource系統(tǒng)根證書的檢索和獲取
- Android AndroidNSSP的簡單說明
- Okhttp之RealConnection建立鏈接簡單分析