日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android 根证书管理与证书验证

發(fā)布時(shí)間:2024/4/11 Android 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 根证书管理与证书验证 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

PKI 體系依賴(lài)證書(shū)執(zhí)行極為關(guān)鍵的身份驗(yàn)證,以此確認(rèn)服務(wù)端的可信任性。證書(shū)驗(yàn)證在 SSL/TLS 握手過(guò)程中完成,驗(yàn)證過(guò)程通常包含三個(gè)步驟:

  • 驗(yàn)證證書(shū)的合法性:這一步主要是驗(yàn)證證書(shū)是由合法有效的 CA 簽發(fā)的。在客戶(hù)端預(yù)先保存一個(gè)可靠的 CA 的根證書(shū)庫(kù),比如 FiexFox、Chrome、Android、Microsoft 等都有維護(hù)自己的根證書(shū)庫(kù),并據(jù)此驗(yàn)證服務(wù)端證書(shū)鏈的合法性。PKI 體系借助于可靠的中心化身份驗(yàn)證系統(tǒng),即 CA,為服務(wù)端的身份合法性背書(shū)。根證書(shū)庫(kù)的安全是 PKI 系統(tǒng)正常工作非常關(guān)鍵的部分。

  • 驗(yàn)證證書(shū)域名的匹配性:服務(wù)端的證書(shū)都是為特定域名簽發(fā)的,證書(shū)就像是網(wǎng)站的身份證一樣。通過(guò)驗(yàn)證域名匹配性,可以有效的防止身份的仿冒,比如經(jīng)營(yíng)著 A 網(wǎng)站的經(jīng)營(yíng)者,攔截用戶(hù)請(qǐng)求,并冒充 B 網(wǎng)站的身份,盜取信息。如果客戶(hù)端不對(duì)域名的匹配性做檢查,則將造成極大的攻擊面,拿到任何一個(gè)域名的合法證書(shū)的人都將可以仿冒目標(biāo)服務(wù)器。

  • 證書(shū)釘扎驗(yàn)證:這是 PKI 體系中比較新的一種增強(qiáng)安全性的機(jī)制。目前的證書(shū)簽發(fā)機(jī)構(gòu) CA 非常多,總數(shù)大概有幾百個(gè)上千個(gè),每個(gè) CA 都可以為任何域名簽發(fā)合法有效的證書(shū),因而眾多的 CA 就造成了非常大的攻擊面。比如某個(gè) CA 被攻破,或者犯了其它什么錯(cuò)誤,為攻擊者簽發(fā)了 www.google.com 等域名的證書(shū),則攻擊者將可以仿冒這些網(wǎng)站。證書(shū)釘扎機(jī)制正是為了解決這一問(wèn)題而產(chǎn)生——證書(shū)釘扎機(jī)制中,在客戶(hù)端將特定域名的證書(shū)與特定的簽發(fā)者綁定,即客戶(hù)端只承認(rèn)特定簽發(fā)者簽發(fā)的某個(gè)域名的證書(shū),而不承認(rèn)其它 CA 為該域名簽發(fā)的證書(shū)。通過(guò)這種方式,來(lái)解除大量 CA 這個(gè)攻擊面的威脅。

  • 在 Android 系統(tǒng)的 Java 應(yīng)用程序中,證書(shū)驗(yàn)證通常由不同層面的多個(gè)組件完成。第一步的證書(shū)合法性驗(yàn)證,主要由 Java 標(biāo)準(zhǔn)庫(kù)的 javax.net.ssl.SSLSocket 在 startHandshake() 方法中完成,后面兩個(gè)步驟由更上層的組件完成,比如 HTTPS 庫(kù) OkHttp 等。

    本文主要討論 Android 中根證書(shū)庫(kù)的管理和證書(shū)的合法性驗(yàn)證。(本文分析說(shuō)明主要依據(jù) android-7.1.1/android-7.1.2 系統(tǒng)的行為,可以通過(guò) Google 的 OpenGrok 服務(wù)器 閱讀 Android 系統(tǒng)的源碼。)

    Android 的根證書(shū)管理

    在 AOSP 源碼庫(kù)中,CA 根證書(shū)主要存放在 system/ca-certificates 目錄下,而在 Android 系統(tǒng)中,則存放在 /system/etc/security/ 目錄下,以 Android 7.1.1 系統(tǒng)的 Pixel 設(shè)備為例:

    sailfish:/ # ls -l /system/etc/security/ total 40 drwxr-xr-x 2 root root 4096 2017-07-18 16:37 cacerts drwxr-xr-x 2 root root 4096 2017-07-18 16:36 cacerts_google -rw-r--r-- 1 root root 4995 2017-07-18 16:03 mac_permissions.xml -rw-r--r-- 1 root root 1073 2017-07-18 16:59 otacerts.zip

    其中 cacerts_google 目錄下的根證書(shū),主要用于 system/update_engine、external/libbrillo 和 system/core/crash_reporter 等模塊,cacerts 目錄下的根證書(shū)則用于所有的應(yīng)用。cacerts 目錄下的根證書(shū),即 Android 系統(tǒng)的根證書(shū)庫(kù),像下面這樣:

    sailfish:/ # ls -l /system/etc/security/cacerts total 2408 -rw-r--r-- 1 root root 4767 2017-07-18 16:37 00673b5b.0 -rw-r--r-- 1 root root 7195 2017-07-18 16:37 02756ea4.0 -rw-r--r-- 1 root root 4919 2017-07-18 16:37 02b73561.0 -rw-r--r-- 1 root root 7142 2017-07-18 16:37 03f2b8cf.0 -rw-r--r-- 1 root root 2877 2017-07-18 16:37 04f60c28.0 -rw-r--r-- 1 root root 4836 2017-07-18 16:37 052e396b.0 -rw-r--r-- 1 root root 5322 2017-07-18 16:37 08aef7bb.0 -rw-r--r-- 1 root root 4922 2017-07-18 16:37 0d5a4e1c.0 -rw-r--r-- 1 root root 2308 2017-07-18 16:37 0d69c7e1.0 -rw-r--r-- 1 root root 4614 2017-07-18 16:37 10531352.0 -rw-r--r-- 1 root root 4716 2017-07-18 16:37 111e6273.0 -rw-r--r-- 1 root root 5375 2017-07-18 16:37 119afc2e.0 -rw-r--r-- 1 root root 4927 2017-07-18 16:37 124bbd54.0 . . . . . .

    它們都是 PEM 格式的 X.509 證書(shū)。Android 系統(tǒng)通過(guò) SystemCertificateSource、DirectoryCertificateSource 和 CertificateSource 等類(lèi)管理系統(tǒng)根證書(shū)庫(kù)。CertificateSource定義(位于frameworks/base/core/java/android/security/net/config/CertificateSource.java)了可以對(duì)根證書(shū)庫(kù)執(zhí)行的操作,主要是對(duì)根證書(shū)的獲取和查找:

    package android.security.net.config;import java.security.cert.X509Certificate; import java.util.Set;/** @hide */ public interface CertificateSource {Set<X509Certificate> getCertificates();X509Certificate findBySubjectAndPublicKey(X509Certificate cert);X509Certificate findByIssuerAndSignature(X509Certificate cert);Set<X509Certificate> findAllByIssuerAndSignature(X509Certificate cert);void handleTrustStorageUpdate(); }

    DirectoryCertificateSource 類(lèi)則基于文件系統(tǒng)上分開(kāi)存放的根證書(shū)文件的形式保存的根證書(shū)庫(kù),提供證書(shū)的創(chuàng)建、獲取和查找操作,這個(gè)類(lèi)的定義(位于frameworks/base/core/java/android/security/net/config/DirectoryCertificateSource.java)如下:

    package android.security.net.config;import android.os.Environment; import android.os.UserHandle; import android.util.ArraySet; import android.util.Log; import android.util.Pair; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Set; import libcore.io.IoUtils;import com.android.org.conscrypt.Hex; import com.android.org.conscrypt.NativeCrypto;import javax.security.auth.x500.X500Principal;/*** {@link CertificateSource} based on a directory where certificates are stored as individual files* named after a hash of their SubjectName for more efficient lookups.* @hide*/ abstract class DirectoryCertificateSource implements CertificateSource {private static final String LOG_TAG = "DirectoryCertificateSrc";private final File mDir;private final Object mLock = new Object();private final CertificateFactory mCertFactory;private Set<X509Certificate> mCertificates;protected DirectoryCertificateSource(File caDir) {mDir = caDir;try {mCertFactory = CertificateFactory.getInstance("X.509");} catch (CertificateException e) {throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);}}protected abstract boolean isCertMarkedAsRemoved(String caFile);@Overridepublic Set<X509Certificate> getCertificates() {// TODO: loading all of these is wasteful, we should instead use a keystore style API.synchronized (mLock) {if (mCertificates != null) {return mCertificates;}Set<X509Certificate> certs = new ArraySet<X509Certificate>();if (mDir.isDirectory()) {for (String caFile : mDir.list()) {if (isCertMarkedAsRemoved(caFile)) {continue;}X509Certificate cert = readCertificate(caFile);if (cert != null) {certs.add(cert);}}}mCertificates = certs;return mCertificates;}}@Overridepublic X509Certificate findBySubjectAndPublicKey(final X509Certificate cert) {return findCert(cert.getSubjectX500Principal(), new CertSelector() {@Overridepublic boolean match(X509Certificate ca) {return ca.getPublicKey().equals(cert.getPublicKey());}});}@Overridepublic X509Certificate findByIssuerAndSignature(final X509Certificate cert) {return findCert(cert.getIssuerX500Principal(), new CertSelector() {@Overridepublic boolean match(X509Certificate ca) {try {cert.verify(ca.getPublicKey());return true;} catch (Exception e) {return false;}}});}@Overridepublic Set<X509Certificate> findAllByIssuerAndSignature(final X509Certificate cert) {return findCerts(cert.getIssuerX500Principal(), new CertSelector() {@Overridepublic boolean match(X509Certificate ca) {try {cert.verify(ca.getPublicKey());return true;} catch (Exception e) {return false;}}});}@Overridepublic void handleTrustStorageUpdate() {synchronized (mLock) {mCertificates = null;}}private static interface CertSelector {boolean match(X509Certificate cert);}private Set<X509Certificate> findCerts(X500Principal subj, CertSelector selector) {String hash = getHash(subj);Set<X509Certificate> certs = null;for (int index = 0; index >= 0; index++) {String fileName = hash + "." + index;if (!new File(mDir, fileName).exists()) {break;}if (isCertMarkedAsRemoved(fileName)) {continue;}X509Certificate cert = readCertificate(fileName);if (cert == null) {continue;}if (!subj.equals(cert.getSubjectX500Principal())) {continue;}if (selector.match(cert)) {if (certs == null) {certs = new ArraySet<X509Certificate>();}certs.add(cert);}}return certs != null ? certs : Collections.<X509Certificate>emptySet();}private X509Certificate findCert(X500Principal subj, CertSelector selector) {String hash = getHash(subj);for (int index = 0; index >= 0; index++) {String fileName = hash + "." + index;if (!new File(mDir, fileName).exists()) {break;}if (isCertMarkedAsRemoved(fileName)) {continue;}X509Certificate cert = readCertificate(fileName);if (cert == null) {continue;}if (!subj.equals(cert.getSubjectX500Principal())) {continue;}if (selector.match(cert)) {return cert;}}return null;}private String getHash(X500Principal name) {int hash = NativeCrypto.X509_NAME_hash_old(name);return Hex.intToHexString(hash, 8);}private X509Certificate readCertificate(String file) {InputStream is = null;try {is = new BufferedInputStream(new FileInputStream(new File(mDir, file)));return (X509Certificate) mCertFactory.generateCertificate(is);} catch (CertificateException | IOException e) {Log.e(LOG_TAG, "Failed to read certificate from " + file, e);return null;} finally {IoUtils.closeQuietly(is);}} }

    獲取根證書(shū)庫(kù)的 getCertificates() 操作在第一次被調(diào)用時(shí),遍歷文件系統(tǒng),并加載系統(tǒng)所有的根證書(shū)文件,并緩存起來(lái),以備后面訪問(wèn)。根證書(shū)的查找操作,主要依據(jù)證書(shū)文件的文件名進(jìn)行,證書(shū)文件被要求以 [SubjectName 的哈希值].[Index] 的形式命名。

    SystemCertificateSource 類(lèi)主要定義(位于frameworks/base/core/java/android/security/net/config/SystemCertificateSource.java)了系統(tǒng)根證書(shū)庫(kù)的路徑,以及無(wú)效一個(gè)根證書(shū)的機(jī)制:

    package android.security.net.config;import android.os.Environment; import android.os.UserHandle; import java.io.File;/*** {@link CertificateSource} based on the system trusted CA store.* @hide*/ public final class SystemCertificateSource extends DirectoryCertificateSource {private static class NoPreloadHolder {private static final SystemCertificateSource INSTANCE = new SystemCertificateSource();}private final File mUserRemovedCaDir;private SystemCertificateSource() {super(new File(System.getenv("ANDROID_ROOT") + "/etc/security/cacerts"));File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());mUserRemovedCaDir = new File(configDir, "cacerts-removed");}public static SystemCertificateSource getInstance() {return NoPreloadHolder.INSTANCE;}@Overrideprotected boolean isCertMarkedAsRemoved(String caFile) {return new File(mUserRemovedCaDir, caFile).exists();} }

    Android 系統(tǒng)的根證書(shū)位于 /system/etc/security/cacerts/ 目錄下。用戶(hù)可以通過(guò)將特定根證書(shū)復(fù)制到用戶(hù)配置目錄的 cacerts-removed 目錄下來(lái)無(wú)效一個(gè)根證書(shū)。

    Android framework 還提供了另外一個(gè)用于加載并訪問(wèn)用戶(hù)根證書(shū)庫(kù)的組件 UserCertificateSource,這個(gè)類(lèi)的定義(位于 frameworks/base/core/java/android/security/net/config/UserCertificateSource.java)如下:

    package android.security.net.config;import android.os.Environment; import android.os.UserHandle; import java.io.File;/*** {@link CertificateSource} based on the user-installed trusted CA store.* @hide*/ public final class UserCertificateSource extends DirectoryCertificateSource {private static class NoPreloadHolder {private static final UserCertificateSource INSTANCE = new UserCertificateSource();}private UserCertificateSource() {super(new File(Environment.getUserConfigDirectory(UserHandle.myUserId()), "cacerts-added"));}public static UserCertificateSource getInstance() {return NoPreloadHolder.INSTANCE;}@Overrideprotected boolean isCertMarkedAsRemoved(String caFile) {return false;} }

    這個(gè)組件與 SystemCertificateSource 類(lèi)似,只是它定義了用戶(hù)根證書(shū)庫(kù)的路徑。

    相關(guān)的幾個(gè)組件結(jié)構(gòu)如下圖:

    證書(shū)鏈合法性驗(yàn)證

    有了根證書(shū)庫(kù)之后,根證書(shū)庫(kù)又是如何被用于 SSL/TLS 握手的證書(shū)驗(yàn)證過(guò)程的呢?

    證書(shū)的合法性由 Java 標(biāo)準(zhǔn)庫(kù)的 javax.net.ssl.SSLSocket 在 startHandshake() 方法中完成。對(duì)于 Android 系統(tǒng)而言,SSLSocket 基于 OpenSSL 庫(kù)實(shí)現(xiàn),這一實(shí)現(xiàn)由 external/conscrypt 模塊提供,SSLSocket 的實(shí)現(xiàn)為 OpenSSLSocketImpl 類(lèi)(位于external/conscrypt/src/main/java/org/conscrypt/OpenSSLSocketImpl.java)。

    OpenSSLSocketImpl.startHandshake() 中的 SSL/TLS 握手是一個(gè)極為精巧的過(guò)程,我們略過(guò)詳細(xì)的握手過(guò)程,主要關(guān)注證書(shū)驗(yàn)證的部分。

    OpenSSLSocketImpl.startHandshake() 通過(guò) NativeCrypto 類(lèi)(位于external/conscrypt/src/main/java/org/conscrypt/NativeCrypto.java)中的靜態(tài)本地層方法 SSL_do_handshake() 方法執(zhí)行握手操作:

    /*** Returns the sslSessionNativePointer of the negotiated session. If this is* a server negotiation, supplying the {@code alpnProtocols} will enable* ALPN negotiation.*/public static native long SSL_do_handshake(long sslNativePointer,FileDescriptor fd,SSLHandshakeCallbacks shc,int timeoutMillis,boolean client_mode,byte[] npnProtocols,byte[] alpnProtocols)throws SSLException, SocketTimeoutException, CertificateException;

    NativeCrypto 類(lèi)內(nèi)部定義了一組將會(huì)在本地層由與 SSL 握手相關(guān)的 OpenSSL C/C++ 代碼調(diào)用的回調(diào) SSLHandshakeCallbacks,在上面的 SSL_do_handshake() 方法中,這組回調(diào)作為參數(shù)傳入本地層。

    SSLHandshakeCallbacks 定義如下:

    /*** A collection of callbacks from the native OpenSSL code that are* related to the SSL handshake initiated by SSL_do_handshake.*/public interface SSLHandshakeCallbacks {/*** Verify that we trust the certificate chain is trusted.** @param sslSessionNativePtr pointer to a reference of the SSL_SESSION* @param certificateChainRefs chain of X.509 certificate references* @param authMethod auth algorithm name** @throws CertificateException if the certificate is untrusted*/public void verifyCertificateChain(long sslSessionNativePtr, long[] certificateChainRefs,String authMethod) throws CertificateException;/*** Called on an SSL client when the server requests (or* requires a certificate). The client can respond by using* SSL_use_certificate and SSL_use_PrivateKey to set a* certificate if has an appropriate one available, similar to* how the server provides its certificate.** @param keyTypes key types supported by the server,* convertible to strings with #keyType* @param asn1DerEncodedX500Principals CAs known to the server*/public void clientCertificateRequested(byte[] keyTypes,byte[][] asn1DerEncodedX500Principals)throws CertificateEncodingException, SSLException;/*** Gets the key to be used in client mode for this connection in Pre-Shared Key (PSK) key* exchange.** @param identityHint PSK identity hint provided by the server or {@code null} if no hint* provided.* @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)* by this method. This identity will be provided to the server.* @param key buffer to be populated with key material by this method.** @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an* error occurred in which case the handshake will be aborted.*/public int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);/*** Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key* exchange.** @param identityHint PSK identity hint provided by this server to the client or* {@code null} if no hint was provided.* @param identity PSK identity provided by the client.* @param key buffer to be populated with key material by this method.** @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an* error occurred in which case the handshake will be aborted.*/public int serverPSKKeyRequested(String identityHint, String identity, byte[] key);/*** Called when SSL state changes. This could be handshake completion.*/public void onSSLStateChange(long sslSessionNativePtr, int type, int val);}

    其中 verifyCertificateChain() 回調(diào)用于服務(wù)端證書(shū)的驗(yàn)證。Android 系統(tǒng)通過(guò)這一回調(diào),將根證書(shū)庫(kù)的管理模塊和底層 OpenSSL 的 SSL/TLS 握手及身份驗(yàn)證連接起來(lái)。

    SSLHandshakeCallbacks 回調(diào)由 OpenSSLSocketImpl 實(shí)現(xiàn),verifyCertificateChain() 的實(shí)現(xiàn)如下:

    @SuppressWarnings("unused") // used by NativeCrypto.SSLHandshakeCallbacks@Overridepublic void verifyCertificateChain(long sslSessionNativePtr, long[] certRefs, String authMethod)throws CertificateException {try {X509TrustManager x509tm = sslParameters.getX509TrustManager();if (x509tm == null) {throw new CertificateException("No X.509 TrustManager");}if (certRefs == null || certRefs.length == 0) {throw new SSLException("Peer sent no certificate");}OpenSSLX509Certificate[] peerCertChain = new OpenSSLX509Certificate[certRefs.length];for (int i = 0; i < certRefs.length; i++) {peerCertChain[i] = new OpenSSLX509Certificate(certRefs[i]);}// Used for verifyCertificateChain callbackhandshakeSession = new OpenSSLSessionImpl(sslSessionNativePtr, null, peerCertChain,getHostnameOrIP(), getPort(), null);boolean client = sslParameters.getUseClientMode();if (client) {Platform.checkServerTrusted(x509tm, peerCertChain, authMethod, this);if (sslParameters.isCTVerificationEnabled(getHostname())) {byte[] tlsData = NativeCrypto.SSL_get_signed_cert_timestamp_list(sslNativePointer);byte[] ocspData = NativeCrypto.SSL_get_ocsp_response(sslNativePointer);CTVerifier ctVerifier = sslParameters.getCTVerifier();CTVerificationResult result =ctVerifier.verifySignedCertificateTimestamps(peerCertChain, tlsData, ocspData);if (result.getValidSCTs().size() == 0) {throw new CertificateException("No valid SCT found");}}} else {String authType = peerCertChain[0].getPublicKey().getAlgorithm();Platform.checkClientTrusted(x509tm, peerCertChain, authType, this);}} catch (CertificateException e) {throw e;} catch (Exception e) {throw new CertificateException(e);} finally {// Clear this before notifying handshake completed listenershandshakeSession = null;}}

    OpenSSLSocketImpl 的 verifyCertificateChain() 從 sslParameters 獲得 X509TrustManager,然后在 Platform.checkServerTrusted() (com.android.org.conscrypt.Platform,位于 external/conscrypt/src/compat/java/org/conscrypt/Platform.java)中執(zhí)行服務(wù)端證書(shū)合法有效性的檢查:

    public static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain,String authType, OpenSSLSocketImpl socket) throws CertificateException {if (!checkTrusted("checkServerTrusted", tm, chain, authType, Socket.class, socket)&& !checkTrusted("checkServerTrusted", tm, chain, authType, String.class,socket.getHandshakeSession().getPeerHost())) {tm.checkServerTrusted(chain, authType);}}

    Platform.checkServerTrusted() 通過(guò)執(zhí)行 X509TrustManager 的 checkServerTrusted() 方法執(zhí)行證書(shū)有合法性檢查。

    X509TrustManager 來(lái)自于 OpenSSLSocketImpl 的 sslParameters,那 sslParameters 又來(lái)自于哪里呢?OpenSSLSocketImpl 的 sslParameters 由對(duì)象的創(chuàng)建者傳入:

    public class OpenSSLSocketImplextends javax.net.ssl.SSLSocketimplements NativeCrypto.SSLHandshakeCallbacks, SSLParametersImpl.AliasChooser,SSLParametersImpl.PSKCallbacks { . . . . . .private final SSLParametersImpl sslParameters; . . . . . .protected OpenSSLSocketImpl(SSLParametersImpl sslParameters) throws IOException {this.socket = this;this.peerHostname = null;this.peerPort = -1;this.autoClose = false;this.sslParameters = sslParameters;}protected OpenSSLSocketImpl(String hostname, int port, SSLParametersImpl sslParameters)throws IOException {super(hostname, port);this.socket = this;this.peerHostname = hostname;this.peerPort = port;this.autoClose = false;this.sslParameters = sslParameters;}protected OpenSSLSocketImpl(InetAddress address, int port, SSLParametersImpl sslParameters)throws IOException {super(address, port);this.socket = this;this.peerHostname = null;this.peerPort = -1;this.autoClose = false;this.sslParameters = sslParameters;}protected OpenSSLSocketImpl(String hostname, int port,InetAddress clientAddress, int clientPort,SSLParametersImpl sslParameters) throws IOException {super(hostname, port, clientAddress, clientPort);this.socket = this;this.peerHostname = hostname;this.peerPort = port;this.autoClose = false;this.sslParameters = sslParameters;}protected OpenSSLSocketImpl(InetAddress address, int port,InetAddress clientAddress, int clientPort,SSLParametersImpl sslParameters) throws IOException {super(address, port, clientAddress, clientPort);this.socket = this;this.peerHostname = null;this.peerPort = -1;this.autoClose = false;this.sslParameters = sslParameters;}/*** Create an SSL socket that wraps another socket. Invoked by* OpenSSLSocketImplWrapper constructor.*/protected OpenSSLSocketImpl(Socket socket, String hostname, int port,boolean autoClose, SSLParametersImpl sslParameters) throws IOException {this.socket = socket;this.peerHostname = hostname;this.peerPort = port;this.autoClose = autoClose;this.sslParameters = sslParameters;// this.timeout is not set intentionally.// OpenSSLSocketImplWrapper.getSoTimeout will delegate timeout// to wrapped socket}

    也就是說(shuō),OpenSSLSocketImpl 的 sslParameters 來(lái)自于 javax.net.ssl.SSLSocketFactory,即 OpenSSLSocketFactoryImpl。OpenSSLSocketFactoryImpl 定義(位于 external/conscrypt/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java)如下:

    package org.conscrypt;import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException;public class OpenSSLSocketFactoryImpl extends javax.net.ssl.SSLSocketFactory {private final SSLParametersImpl sslParameters;private final IOException instantiationException;public OpenSSLSocketFactoryImpl() {SSLParametersImpl sslParametersLocal = null;IOException instantiationExceptionLocal = null;try {sslParametersLocal = SSLParametersImpl.getDefault();} catch (KeyManagementException e) {instantiationExceptionLocal = new IOException("Delayed instantiation exception:");instantiationExceptionLocal.initCause(e);}this.sslParameters = sslParametersLocal;this.instantiationException = instantiationExceptionLocal;}public OpenSSLSocketFactoryImpl(SSLParametersImpl sslParameters) {this.sslParameters = sslParameters;this.instantiationException = null;}@Overridepublic String[] getDefaultCipherSuites() {return sslParameters.getEnabledCipherSuites();}@Overridepublic String[] getSupportedCipherSuites() {return NativeCrypto.getSupportedCipherSuites();}@Overridepublic Socket createSocket() throws IOException {if (instantiationException != null) {throw instantiationException;}return new OpenSSLSocketImpl((SSLParametersImpl) sslParameters.clone());}@Overridepublic Socket createSocket(String hostname, int port) throws IOException, UnknownHostException {return new OpenSSLSocketImpl(hostname, port, (SSLParametersImpl) sslParameters.clone());}@Overridepublic Socket createSocket(String hostname, int port, InetAddress localHost, int localPort)throws IOException, UnknownHostException {return new OpenSSLSocketImpl(hostname,port,localHost,localPort,(SSLParametersImpl) sslParameters.clone());}@Overridepublic Socket createSocket(InetAddress address, int port) throws IOException {return new OpenSSLSocketImpl(address, port, (SSLParametersImpl) sslParameters.clone());}@Overridepublic Socket createSocket(InetAddress address,int port,InetAddress localAddress,int localPort)throws IOException {return new OpenSSLSocketImpl(address,port,localAddress,localPort,(SSLParametersImpl) sslParameters.clone());}@Overridepublic Socket createSocket(Socket s, String hostname, int port, boolean autoClose)throws IOException {return new OpenSSLSocketImplWrapper(s,hostname,port,autoClose,(SSLParametersImpl) sslParameters.clone());} }

    OpenSSLSocketImpl 最主要的職責(zé),即是將 SSL/TLS 參數(shù) SSLParametersImpl 與 SSLSocket 粘起來(lái)。主要來(lái)看默認(rèn)情況下 SSLParametersImpl 的 X509TrustManager 是什么(位于external/conscrypt/src/main/java/org/conscrypt/SSLParametersImpl.java ):

    /*** Initializes the parameters. Naturally this constructor is used* in SSLContextImpl.engineInit method which directly passes its* parameters. In other words this constructor holds all* the functionality provided by SSLContext.init method.* See {@link javax.net.ssl.SSLContext#init(KeyManager[],TrustManager[],* SecureRandom)} for more information*/protected SSLParametersImpl(KeyManager[] kms, TrustManager[] tms,SecureRandom sr, ClientSessionContext clientSessionContext,ServerSessionContext serverSessionContext, String[] protocols)throws KeyManagementException {this.serverSessionContext = serverSessionContext;this.clientSessionContext = clientSessionContext;// initialize key managersif (kms == null) {x509KeyManager = getDefaultX509KeyManager();// There's no default PSK key managerpskKeyManager = null;} else {x509KeyManager = findFirstX509KeyManager(kms);pskKeyManager = findFirstPSKKeyManager(kms);}// initialize x509TrustManagerif (tms == null) {x509TrustManager = getDefaultX509TrustManager();} else {x509TrustManager = findFirstX509TrustManager(tms);}// initialize secure random// We simply use the SecureRandom passed in by the caller. If it's// null, we don't replace it by a new instance. The native code below// then directly accesses /dev/urandom. Not the most elegant solution,// but faster than going through the SecureRandom object.secureRandom = sr;// initialize the list of cipher suites and protocols enabled by defaultenabledProtocols = NativeCrypto.checkEnabledProtocols(protocols == null ? NativeCrypto.DEFAULT_PROTOCOLS : protocols).clone();boolean x509CipherSuitesNeeded = (x509KeyManager != null) || (x509TrustManager != null);boolean pskCipherSuitesNeeded = pskKeyManager != null;enabledCipherSuites = getDefaultCipherSuites(x509CipherSuitesNeeded, pskCipherSuitesNeeded);}protected static SSLParametersImpl getDefault() throws KeyManagementException {SSLParametersImpl result = defaultParameters;if (result == null) {// single-check idiomdefaultParameters = result = new SSLParametersImpl(null,null,null,new ClientSessionContext(),new ServerSessionContext(),null);}return (SSLParametersImpl) result.clone();}. . . . . . /*** @return X.509 trust manager or {@code null} for none.*/protected X509TrustManager getX509TrustManager() {return x509TrustManager;}. . . . . . /*** Gets the default X.509 trust manager.* <p>* TODO: Move this to a published API under dalvik.system.*/public static X509TrustManager getDefaultX509TrustManager()throws KeyManagementException {X509TrustManager result = defaultX509TrustManager;if (result == null) {// single-check idiomdefaultX509TrustManager = result = createDefaultX509TrustManager();}return result;}private static X509TrustManager createDefaultX509TrustManager()throws KeyManagementException {try {String algorithm = TrustManagerFactory.getDefaultAlgorithm();TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);tmf.init((KeyStore) null);TrustManager[] tms = tmf.getTrustManagers();X509TrustManager trustManager = findFirstX509TrustManager(tms);if (trustManager == null) {throw new KeyManagementException("No X509TrustManager in among default TrustManagers: "+ Arrays.toString(tms));}return trustManager;} catch (NoSuchAlgorithmException e) {throw new KeyManagementException(e);} catch (KeyStoreException e) {throw new KeyManagementException(e);}}

    將 createDefaultX509TrustManager() 的代碼復(fù)制到我們的應(yīng)用程序中,就像下面這樣:

    private X509TrustManager systemDefaultTrustManager() {try {TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init((KeyStore) null);TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {throw new IllegalStateException("Unexpected default trust managers:"+ Arrays.toString(trustManagers));}return (X509TrustManager) trustManagers[0];} catch (GeneralSecurityException e) {throw new AssertionError(); // The system has no TLS. Just give up.}}

    在應(yīng)用程序執(zhí)行時(shí)打斷點(diǎn),借助于 Android Studio 確認(rèn)系統(tǒng)默認(rèn)的 X509TrustManager 是什么,不難確認(rèn),它是 android.security.net.config.RootTrustManager。android.security.net.config.RootTrustManager 的 checkServerTrusted() 定義(位于 frameworks/base/core/java/android/security/net/config/RootTrustManager.java)如下:

    @Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType, Socket socket)throws CertificateException {if (socket instanceof SSLSocket) {SSLSocket sslSocket = (SSLSocket) socket;SSLSession session = sslSocket.getHandshakeSession();if (session == null) {throw new CertificateException("Not in handshake; no session available");}String host = session.getPeerHost();NetworkSecurityConfig config = mConfig.getConfigForHostname(host);config.getTrustManager().checkServerTrusted(certs, authType, socket);} else {// Not an SSLSocket, use the hostname unaware checkServerTrusted.checkServerTrusted(certs, authType);}}@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType, SSLEngine engine)throws CertificateException {SSLSession session = engine.getHandshakeSession();if (session == null) {throw new CertificateException("Not in handshake; no session available");}String host = session.getPeerHost();NetworkSecurityConfig config = mConfig.getConfigForHostname(host);config.getTrustManager().checkServerTrusted(certs, authType, engine);}@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType)throws CertificateException {if (mConfig.hasPerDomainConfigs()) {throw new CertificateException("Domain specific configurations require that hostname aware"+ " checkServerTrusted(X509Certificate[], String, String) is used");}NetworkSecurityConfig config = mConfig.getConfigForHostname("");config.getTrustManager().checkServerTrusted(certs, authType);}/*** Hostname aware version of {@link #checkServerTrusted(X509Certificate[], String)}.* This interface is used by conscrypt and android.net.http.X509TrustManagerExtensions do not* modify without modifying those callers.*/public List<X509Certificate> checkServerTrusted(X509Certificate[] certs, String authType,String hostname) throws CertificateException {if (hostname == null && mConfig.hasPerDomainConfigs()) {throw new CertificateException("Domain specific configurations require that the hostname be provided");}NetworkSecurityConfig config = mConfig.getConfigForHostname(hostname);return config.getTrustManager().checkServerTrusted(certs, authType, hostname);}

    NetworkSecurityConfig 的 getTrustManager() 定義(位于 frameworks/base/core/java/android/security/net/config/NetworkSecurityConfig.java)如下:

    public NetworkSecurityTrustManager getTrustManager() {synchronized(mTrustManagerLock) {if (mTrustManager == null) {mTrustManager = new NetworkSecurityTrustManager(this);}return mTrustManager;}}

    NetworkSecurityConfig 將管根證書(shū)庫(kù)的組件 SystemCertificateSource 、 UserCertificateSource 和執(zhí)行證書(shū)合法性驗(yàn)證的 NetworkSecurityTrustManager 粘起來(lái):

    public static final Builder getDefaultBuilder(int targetSdkVersion) {Builder builder = new Builder().setCleartextTrafficPermitted(DEFAULT_CLEARTEXT_TRAFFIC_PERMITTED).setHstsEnforced(DEFAULT_HSTS_ENFORCED)// System certificate store, does not bypass static pins..addCertificatesEntryRef(new CertificatesEntryRef(SystemCertificateSource.getInstance(), false));// Applications targeting N and above must opt in into trusting the user added certificate// store.if (targetSdkVersion <= Build.VERSION_CODES.M) {// User certificate store, does not bypass static pins.builder.addCertificatesEntryRef(new CertificatesEntryRef(UserCertificateSource.getInstance(), false));}return builder;}

    同時(shí) NetworkSecurityConfig 還提供了一些根據(jù)特定條件查找根證書(shū)的操作:

    public Set<TrustAnchor> getTrustAnchors() {synchronized (mAnchorsLock) {if (mAnchors != null) {return mAnchors;}// Merge trust anchors based on the X509Certificate.// If we see the same certificate in two TrustAnchors, one with overridesPins and one// without, the one with overridesPins wins.// Because mCertificatesEntryRefs is sorted with all overridesPins anchors coming first// this can be simplified to just using the first occurrence of a certificate.Map<X509Certificate, TrustAnchor> anchorMap = new ArrayMap<>();for (CertificatesEntryRef ref : mCertificatesEntryRefs) {Set<TrustAnchor> anchors = ref.getTrustAnchors();for (TrustAnchor anchor : anchors) {X509Certificate cert = anchor.certificate;if (!anchorMap.containsKey(cert)) {anchorMap.put(cert, anchor);}}}ArraySet<TrustAnchor> anchors = new ArraySet<TrustAnchor>(anchorMap.size());anchors.addAll(anchorMap.values());mAnchors = anchors;return mAnchors;}} . . . . . .public NetworkSecurityTrustManager getTrustManager() {synchronized(mTrustManagerLock) {if (mTrustManager == null) {mTrustManager = new NetworkSecurityTrustManager(this);}return mTrustManager;}}/** @hide */public TrustAnchor findTrustAnchorBySubjectAndPublicKey(X509Certificate cert) {for (CertificatesEntryRef ref : mCertificatesEntryRefs) {TrustAnchor anchor = ref.findBySubjectAndPublicKey(cert);if (anchor != null) {return anchor;}}return null;}/** @hide */public TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate cert) {for (CertificatesEntryRef ref : mCertificatesEntryRefs) {TrustAnchor anchor = ref.findByIssuerAndSignature(cert);if (anchor != null) {return anchor;}}return null;}/** @hide */public Set<X509Certificate> findAllCertificatesByIssuerAndSignature(X509Certificate cert) {Set<X509Certificate> certs = new ArraySet<X509Certificate>();for (CertificatesEntryRef ref : mCertificatesEntryRefs) {certs.addAll(ref.findAllCertificatesByIssuerAndSignature(cert));}return certs;}

    真正執(zhí)行證書(shū)合法性驗(yàn)證的還不是 NetworkSecurityTrustManager,而是 TrustManagerImpl(位于 external/conscrypt/src/platform/java/org/conscrypt/TrustManagerImpl.java),由 NetworkSecurityTrustManager 的定義(位于frameworks/base/core/java/android/security/net/config/NetworkSecurityTrustManager.java)不難看出這一點(diǎn):

    public NetworkSecurityTrustManager(NetworkSecurityConfig config) {if (config == null) {throw new NullPointerException("config must not be null");}mNetworkSecurityConfig = config;try {TrustedCertificateStoreAdapter certStore = new TrustedCertificateStoreAdapter(config);// Provide an empty KeyStore since TrustManagerImpl doesn't support null KeyStores.// TrustManagerImpl will use certStore to lookup certificates.KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());store.load(null);mDelegate = new TrustManagerImpl(store, null, certStore);} catch (GeneralSecurityException | IOException e) {throw new RuntimeException(e);}} . . . . . .@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType)throws CertificateException {checkServerTrusted(certs, authType, (String) null);}@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType, Socket socket)throws CertificateException {List<X509Certificate> trustedChain =mDelegate.getTrustedChainForServer(certs, authType, socket);checkPins(trustedChain);}@Overridepublic void checkServerTrusted(X509Certificate[] certs, String authType, SSLEngine engine)throws CertificateException {List<X509Certificate> trustedChain =mDelegate.getTrustedChainForServer(certs, authType, engine);checkPins(trustedChain);}/*** Hostname aware version of {@link #checkServerTrusted(X509Certificate[], String)}.* This interface is used by conscrypt and android.net.http.X509TrustManagerExtensions do not* modify without modifying those callers.*/public List<X509Certificate> checkServerTrusted(X509Certificate[] certs, String authType,String host) throws CertificateException {List<X509Certificate> trustedChain = mDelegate.checkServerTrusted(certs, authType, host);checkPins(trustedChain);return trustedChain;}private void checkPins(List<X509Certificate> chain) throws CertificateException {PinSet pinSet = mNetworkSecurityConfig.getPins();if (pinSet.pins.isEmpty()|| System.currentTimeMillis() > pinSet.expirationTime|| !isPinningEnforced(chain)) {return;}Set<String> pinAlgorithms = pinSet.getPinAlgorithms();Map<String, MessageDigest> digestMap = new ArrayMap<String, MessageDigest>(pinAlgorithms.size());for (int i = chain.size() - 1; i >= 0 ; i--) {X509Certificate cert = chain.get(i);byte[] encodedSPKI = cert.getPublicKey().getEncoded();for (String algorithm : pinAlgorithms) {MessageDigest md = digestMap.get(algorithm);if (md == null) {try {md = MessageDigest.getInstance(algorithm);} catch (GeneralSecurityException e) {throw new RuntimeException(e);}digestMap.put(algorithm, md);}if (pinSet.pins.contains(new Pin(algorithm, md.digest(encodedSPKI)))) {return;}}}// TODO: Throw a subclass of CertificateException which indicates a pinning failure.throw new CertificateException("Pin verification failed");}

    TrustedCertificateStoreAdapter 為根證書(shū)庫(kù)提供了 TrustedCertificateStore 接口的查找操作,以方便 TrustManagerImpl 使用(位于frameworks/base/core/java/android/security/net/config/TrustedCertificateStoreAdapter.java):

    public class TrustedCertificateStoreAdapter extends TrustedCertificateStore {private final NetworkSecurityConfig mConfig;public TrustedCertificateStoreAdapter(NetworkSecurityConfig config) {mConfig = config;}@Overridepublic X509Certificate findIssuer(X509Certificate cert) {TrustAnchor anchor = mConfig.findTrustAnchorByIssuerAndSignature(cert);if (anchor == null) {return null;}return anchor.certificate;}@Overridepublic Set<X509Certificate> findAllIssuers(X509Certificate cert) {return mConfig.findAllCertificatesByIssuerAndSignature(cert);}@Overridepublic X509Certificate getTrustAnchor(X509Certificate cert) {TrustAnchor anchor = mConfig.findTrustAnchorBySubjectAndPublicKey(cert);if (anchor == null) {return null;}return anchor.certificate;}@Overridepublic boolean isUserAddedCertificate(X509Certificate cert) {// isUserAddedCertificate is used only for pinning overrides, so use overridesPins here.TrustAnchor anchor = mConfig.findTrustAnchorBySubjectAndPublicKey(cert);if (anchor == null) {return false;}return anchor.overridesPins;}

    不難看出 Android 中 Java 層證書(shū)驗(yàn)證的過(guò)程如下圖所示:

    OpenSSLSocketImpl.startHandshake() 和 NativeCrypto.SSL_do_handshake() 執(zhí)行完整的 SSL/TLS 握手過(guò)程。證書(shū)合法性驗(yàn)證作為 SSL/TLS 握手的一個(gè)重要步驟,通過(guò)本地層調(diào)用的 Java 層的回調(diào)方法 SSLHandshakeCallbacks.verifyCertificateChain() 完成,OpenSSLSocketImpl 實(shí)現(xiàn)這一回調(diào)。OpenSSLSocketImpl.verifyCertificateChain()、Platform.checkServerTrusted()、RootTrustManager.checkServerTrusted() 和NetworkSecurityTrustManager.checkServerTrusted() 用于將真正的根據(jù)系統(tǒng)根證書(shū)庫(kù)執(zhí)行證書(shū)合法性驗(yàn)證的 TrustManagerImpl 和 SSL/TLS 握手過(guò)程粘起來(lái)。OpenSSLSocketFactoryImpl 將 OpenSSLSocketImpl 和 SSLParametersImpl 粘起來(lái)。SSLParametersImpl 將 OpenSSLSocketImpl 和 RootTrustManager 粘起來(lái)。

    NetworkSecurityConfig 將 RootTrustManager 和 NetworkSecurityTrustManager 粘起來(lái)。NetworkSecurityConfig、NetworkSecurityTrustManager 和 TrustedCertificateStoreAdapter 將 TrustManagerImpl 和管理系統(tǒng)根證書(shū)庫(kù)的 SystemCertificateSource 粘起來(lái)。

    TrustManagerImpl 是證書(shū)合法性驗(yàn)證的核心,它會(huì)查找系統(tǒng)根證書(shū)庫(kù),并對(duì)服務(wù)端證書(shū)的合法性做驗(yàn)證。

    這個(gè)過(guò)程的調(diào)用棧如下:

    com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted() android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted() android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted() android.security.net.config.RootTrustManager.checkServerTrusted() com.android.org.conscrypt.Platform.checkServerTrusted() com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain() com.android.org.conscrypt.NativeCrypto.SSL_do_handshake() com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake() com.android.okhttp.Connection.connectTls()

    還有兩個(gè)問(wèn)題,一是 SSLParametersImpl 是如何找到的 RootTrustManager;二是如何定制或者影響證書(shū)合法性的驗(yàn)證過(guò)程。

    TrustManager 的查找

    Java 加密體系架構(gòu)(JCA)是一個(gè)非常靈活的架構(gòu),它的整體結(jié)構(gòu)如下圖:

    Java 應(yīng)用程序通過(guò)接口層訪問(wèn)加密服務(wù),接口層的組成包括 JAAS(Java Authentication Authorization Service,Java驗(yàn)證和授權(quán)API)、JSSE(Java Secure Socket Extension,Java 安全 套接字?jǐn)U展)、JGSS(Java Generic Security Service )和 CertPath等。具體的組件如我們前面看到的 CertificateFactory、TrustManagerFactory 和 SSLSocketFactory 等。

    JCA 還定義了一組加密服務(wù) Provider 接口,如 javax.net.ssl.SSLContextSpi 和 javax.net.ssl.TrustManagerFactorySpi 等。加密服務(wù)的實(shí)現(xiàn)者實(shí)現(xiàn)這些接口,并通過(guò) java.security.Security 提供的接口注冊(cè)進(jìn) JCA 框架。

    對(duì)于 Android 系統(tǒng)來(lái)說(shuō),TrustManagerFactory 加密服務(wù)的注冊(cè)是在 ActivityThread 的 handleBindApplication() 中做的,相關(guān)代碼(位于 frameworks/base/core/java/android/app/ActivityThread.java)如下:

    // Install the Network Security Config Provider. This must happen before the application// code is loaded to prevent issues with instances of TLS objects being created before// the provider is installed.Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");NetworkSecurityConfigProvider.install(appContext);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

    NetworkSecurityConfigProvider 類(lèi)的定義(位于 frameworks/base/core/java/android/security/net/config/NetworkSecurityConfigProvider.java)如下:

    package android.security.net.config;import android.content.Context; import java.security.Security; import java.security.Provider;/** @hide */ public final class NetworkSecurityConfigProvider extends Provider {private static final String PREFIX =NetworkSecurityConfigProvider.class.getPackage().getName() + ".";public NetworkSecurityConfigProvider() {// TODO: More clever name than thissuper("AndroidNSSP", 1.0, "Android Network Security Policy Provider");put("TrustManagerFactory.PKIX", PREFIX + "RootTrustManagerFactorySpi");put("Alg.Alias.TrustManagerFactory.X509", "PKIX");}public static void install(Context context) {ApplicationConfig config = new ApplicationConfig(new ManifestConfigSource(context));ApplicationConfig.setDefaultInstance(config);int pos = Security.insertProviderAt(new NetworkSecurityConfigProvider(), 1);if (pos != 1) {throw new RuntimeException("Failed to install provider as highest priority provider."+ " Provider was installed at position " + pos);}libcore.net.NetworkSecurityPolicy.setInstance(new ConfigNetworkSecurityPolicy(config));} }

    在 NetworkSecurityConfigProvider.install() 方法中,通過(guò) Security.insertProviderAt() 將 NetworkSecurityConfigProvider 注冊(cè)進(jìn) JCA 框架中。從 NetworkSecurityConfigProvider 的構(gòu)造函數(shù)可以看到,它將 android.security.net.config.RootTrustManagerFactorySpi 帶進(jìn) JCA 框架。

    android.security.net.config.RootTrustManagerFactorySpi 的定義(位于 frameworks/base/core/java/android/security/net/config/RootTrustManagerFactorySpi.java)如下:

    package android.security.net.config;import android.util.Pair; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.Set; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactorySpi;import com.android.internal.annotations.VisibleForTesting;/** @hide */ public class RootTrustManagerFactorySpi extends TrustManagerFactorySpi {private ApplicationConfig mApplicationConfig;private NetworkSecurityConfig mConfig;@Overridepublic void engineInit(ManagerFactoryParameters spec)throws InvalidAlgorithmParameterException {if (!(spec instanceof ApplicationConfigParameters)) {throw new InvalidAlgorithmParameterException("Unsupported spec: " + spec + ". Only "+ ApplicationConfigParameters.class.getName() + " supported");}mApplicationConfig = ((ApplicationConfigParameters) spec).config;}@Overridepublic void engineInit(KeyStore ks) throws KeyStoreException {if (ks != null) {mApplicationConfig = new ApplicationConfig(new KeyStoreConfigSource(ks));} else {mApplicationConfig = ApplicationConfig.getDefaultInstance();}}@Overridepublic TrustManager[] engineGetTrustManagers() {if (mApplicationConfig == null) {throw new IllegalStateException("TrustManagerFactory not initialized");}return new TrustManager[] { mApplicationConfig.getTrustManager() };}@VisibleForTestingpublic static final class ApplicationConfigParameters implements ManagerFactoryParameters {public final ApplicationConfig config;public ApplicationConfigParameters(ApplicationConfig config) {this.config = config;}} }

    RootTrustManagerFactorySpi 的 TrustManager 來(lái)自于 ApplicationConfig,ApplicationConfig 中 TrustManager 相關(guān)的代碼(位于 frameworks/base/core/java/android/security/net/config/ApplicationConfig.java)如下:

    public final class ApplicationConfig {private static ApplicationConfig sInstance;private static Object sLock = new Object();private Set<Pair<Domain, NetworkSecurityConfig>> mConfigs;private NetworkSecurityConfig mDefaultConfig;private X509TrustManager mTrustManager; . . . . . ./*** Returns the {@link X509TrustManager} that implements the checking of trust anchors and* certificate pinning based on this configuration.*/public X509TrustManager getTrustManager() {ensureInitialized();return mTrustManager;} . . . . . .private void ensureInitialized() {synchronized(mLock) {if (mInitialized) {return;}mConfigs = mConfigSource.getPerDomainConfigs();mDefaultConfig = mConfigSource.getDefaultConfig();mConfigSource = null;mTrustManager = new RootTrustManager(this);mInitialized = true;}}

    ApplicationConfig 的 TrustManager 是 RootTrustManager。

    再來(lái)看 JCA 接口層的 javax.net.ssl.TrustManagerFactory 的定義:

    public class TrustManagerFactory {// The providerprivate Provider provider;// The provider implementation (delegate)private TrustManagerFactorySpi factorySpi;// The name of the trust management algorithm.private String algorithm; . . . . . .public final static String getDefaultAlgorithm() {String type;type = AccessController.doPrivileged(new PrivilegedAction<String>() {public String run() {return Security.getProperty("ssl.TrustManagerFactory.algorithm");}});if (type == null) {type = "SunX509";}return type;} . . . . . ./*** Creates a TrustManagerFactory object.** @param factorySpi the delegate* @param provider the provider* @param algorithm the algorithm*/protected TrustManagerFactory(TrustManagerFactorySpi factorySpi,Provider provider, String algorithm) {this.factorySpi = factorySpi;this.provider = provider;this.algorithm = algorithm;} . . . . . .public static final TrustManagerFactory getInstance(String algorithm)throws NoSuchAlgorithmException {GetInstance.Instance instance = GetInstance.getInstance("TrustManagerFactory", TrustManagerFactorySpi.class,algorithm);return new TrustManagerFactory((TrustManagerFactorySpi)instance.impl,instance.provider, algorithm);} . . . . . .public final void init(KeyStore ks) throws KeyStoreException {factorySpi.engineInit(ks);}/*** Initializes this factory with a source of provider-specific* trust material.* <P>* In some cases, initialization parameters other than a keystore* may be needed by a provider. Users of that particular provider* are expected to pass an implementation of the appropriate* <CODE>ManagerFactoryParameters</CODE> as defined by the* provider. The provider can then call the specified methods in* the <CODE>ManagerFactoryParameters</CODE> implementation to obtain the* needed information.** @param spec an implementation of a provider-specific parameter* specification* @throws InvalidAlgorithmParameterException if an error is* encountered*/public final void init(ManagerFactoryParameters spec) throwsInvalidAlgorithmParameterException {factorySpi.engineInit(spec);}/*** Returns one trust manager for each type of trust material.** @throws IllegalStateException if the factory is not initialized.** @return the trust managers*/public final TrustManager[] getTrustManagers() {return factorySpi.engineGetTrustManagers();}

    TrustManagerFactory 通過(guò) JCA 框架提供的 sun.security.jca.GetInstance 找到注冊(cè)的 javax.net.ssl.TrustManagerFactorySpi。應(yīng)用程序通過(guò) javax.net.ssl.TrustManagerFactory -> android.security.net.config.RootTrustManagerFactorySpi -> android.security.net.config.ApplicationConfig 得到 android.security.net.config.RootTrustManager,即 X509TrustManager。

    私有 CA 簽名證書(shū)的應(yīng)用

    自簽名證書(shū)是無(wú)需別的證書(shū)為其簽名來(lái)證明其合法性的證書(shū),根證書(shū)都是自簽名證書(shū)。私有 CA 簽名證書(shū)則是指,為域名證書(shū)簽名的 CA,其合法有效性沒(méi)有得到廣泛的認(rèn)可,該 CA 的根證書(shū)沒(méi)有被內(nèi)置到系統(tǒng)中。

    在實(shí)際的開(kāi)發(fā)過(guò)程中,有時(shí)為了節(jié)省昂貴的購(gòu)買(mǎi)證書(shū)的費(fèi)用,而想要自己給自己的服務(wù)器的域名簽發(fā)域名證書(shū),這即是私有 CA 簽名的證書(shū)。為了能夠使用這種證書(shū),需要在客戶(hù)端預(yù)埋根證書(shū),并對(duì)客戶(hù)端證書(shū)合法性驗(yàn)證的過(guò)程進(jìn)行干預(yù),通過(guò)我們預(yù)埋的根證書(shū)為服務(wù)端的證書(shū)做合法性驗(yàn)證,而不依賴(lài)系統(tǒng)的根證書(shū)庫(kù)。

    自定義 javax.net.ssl.SSLSocket 的代價(jià)太高,通常不會(huì)通過(guò)自定義 javax.net.ssl.SSLSocket 來(lái)修改服務(wù)端證書(shū)的合法性驗(yàn)證過(guò)程。以此為基礎(chǔ),從上面的分析中不難看出,要想定制 OpenSSLSocketImpl 的證書(shū)驗(yàn)證過(guò)程,則必然要改變 SSLParametersImpl,要改變 OpenSSLSocketImpl 的 SSLParametersImpl,則必然需要修改 SSLSocketFactory。修改 SSLSocketFactory 常常是一個(gè)不錯(cuò)的方法。

    在 Java 中,SSLContext 正是被設(shè)計(jì)用于這一目的。創(chuàng)建定制了 SSLParametersImpl,即定制了 TrustManager 的 SSLSocketFactory 的方法如下:

    TrustManager[] trustManagers = new TrustManager[] { new HelloX509TrustManager() };;SSLContext context = null;try {context = SSLContext.getInstance("TLS");context.init(null, trustManagers, new SecureRandom());} catch (NoSuchAlgorithmException e) {Log.i(TAG,"NoSuchAlgorithmException INFO:"+e.getMessage());} catch (KeyManagementException e) {Log.i(TAG, "KeyManagementException INFO:" + e.getMessage());}HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

    SSLContext 的相關(guān)方法實(shí)現(xiàn)(位于libcore/ojluni/src/main/java/javax/net/ssl/SSLContext.java)如下:

    private final SSLContextSpi contextSpi; . . . . . .public static SSLContext getInstance(String protocol)throws NoSuchAlgorithmException {GetInstance.Instance instance = GetInstance.getInstance("SSLContext", SSLContextSpi.class, protocol);return new SSLContext((SSLContextSpi)instance.impl, instance.provider,protocol);} . . . . . .public final void init(KeyManager[] km, TrustManager[] tm,SecureRandom random)throws KeyManagementException {contextSpi.engineInit(km, tm, random);}/*** Returns a <code>SocketFactory</code> object for this* context.** @return the <code>SocketFactory</code> object* @throws IllegalStateException if the SSLContextImpl requires* initialization and the <code>init()</code> has not been called*/public final SSLSocketFactory getSocketFactory() {return contextSpi.engineGetSocketFactory();}

    其中 SSLContextSpi 為 OpenSSLContextImpl,該類(lèi)的實(shí)現(xiàn)(位于external/conscrypt/src/main/java/org/conscrypt/OpenSSLContextImpl.java)如下:

    package org.conscrypt;import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; import java.security.SecureRandom; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContextSpi; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager;/*** OpenSSL-backed SSLContext service provider interface.*/ public class OpenSSLContextImpl extends SSLContextSpi {/*** The default SSLContextImpl for use with* SSLContext.getInstance("Default"). Protected by the* DefaultSSLContextImpl.class monitor.*/private static DefaultSSLContextImpl DEFAULT_SSL_CONTEXT_IMPL;/** TLS algorithm to initialize all sockets. */private final String[] algorithms;/** Client session cache. */private final ClientSessionContext clientSessionContext;/** Server session cache. */private final ServerSessionContext serverSessionContext;protected SSLParametersImpl sslParameters;/** Allows outside callers to get the preferred SSLContext. */public static OpenSSLContextImpl getPreferred() {return new TLSv12();}protected OpenSSLContextImpl(String[] algorithms) {this.algorithms = algorithms;clientSessionContext = new ClientSessionContext();serverSessionContext = new ServerSessionContext();}/*** Constuctor for the DefaultSSLContextImpl.** @param dummy is null, used to distinguish this case from the public* OpenSSLContextImpl() constructor.*/protected OpenSSLContextImpl() throws GeneralSecurityException, IOException {synchronized (DefaultSSLContextImpl.class) {this.algorithms = null;if (DEFAULT_SSL_CONTEXT_IMPL == null) {clientSessionContext = new ClientSessionContext();serverSessionContext = new ServerSessionContext();DEFAULT_SSL_CONTEXT_IMPL = (DefaultSSLContextImpl) this;} else {clientSessionContext = DEFAULT_SSL_CONTEXT_IMPL.engineGetClientSessionContext();serverSessionContext = DEFAULT_SSL_CONTEXT_IMPL.engineGetServerSessionContext();}sslParameters = new SSLParametersImpl(DEFAULT_SSL_CONTEXT_IMPL.getKeyManagers(),DEFAULT_SSL_CONTEXT_IMPL.getTrustManagers(), null, clientSessionContext,serverSessionContext, algorithms);}}/*** Initializes this {@code SSLContext} instance. All of the arguments are* optional, and the security providers will be searched for the required* implementations of the needed algorithms.** @param kms the key sources or {@code null}* @param tms the trust decision sources or {@code null}* @param sr the randomness source or {@code null}* @throws KeyManagementException if initializing this instance fails*/@Overridepublic void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr)throws KeyManagementException {sslParameters = new SSLParametersImpl(kms, tms, sr, clientSessionContext,serverSessionContext, algorithms);}@Overridepublic SSLSocketFactory engineGetSocketFactory() {if (sslParameters == null) {throw new IllegalStateException("SSLContext is not initialized.");}return Platform.wrapSocketFactoryIfNeeded(new OpenSSLSocketFactoryImpl(sslParameters));}

    如我們前面討論,驗(yàn)證服務(wù)端證書(shū)合法性是 PKI 體系中,保障系統(tǒng)安全極為關(guān)鍵的環(huán)節(jié)。如果不驗(yàn)證服務(wù)端證書(shū)的合法性,則即使部署了 HTTPS,HTTPS 也將形同虛設(shè),毫無(wú)價(jià)值。因而在我們自己實(shí)現(xiàn)的 X509TrustManager 中,加載預(yù)埋的根證書(shū),并據(jù)此驗(yàn)證服務(wù)端證書(shū)的合法性必不可少,這一檢查在 checkServerTrusted() 中完成。然而為了使我們實(shí)現(xiàn)的 X509TrustManager 功能更完備,在根據(jù)我們預(yù)埋的根證書(shū)驗(yàn)證失敗后,我們?cè)偈褂孟到y(tǒng)默認(rèn)的 X509TrustManager 做驗(yàn)證,像下面這樣:

    private final class HelloX509TrustManager implements X509TrustManager {private X509TrustManager mSystemDefaultTrustManager;private X509Certificate mCertificate;private HelloX509TrustManager() {mCertificate = loadRootCertificate();mSystemDefaultTrustManager = systemDefaultTrustManager();}private X509Certificate loadRootCertificate() {String certName = "netease.crt";X509Certificate certificate = null;InputStream certInput = null;try {certInput = new BufferedInputStream(MainActivity.this.getAssets().open(certName));CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");certificate = (X509Certificate) certificateFactory.generateCertPath(certInput).getCertificates().get(0);} catch (IOException e) {e.printStackTrace();} catch (CertificateException e) {e.printStackTrace();} finally {if (certInput != null) {try {certInput.close();} catch (IOException e) {}}}return certificate;}private X509TrustManager systemDefaultTrustManager() {try {TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init((KeyStore) null);TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {throw new IllegalStateException("Unexpected default trust managers:"+ Arrays.toString(trustManagers));}return (X509TrustManager) trustManagers[0];} catch (GeneralSecurityException e) {throw new AssertionError(); // The system has no TLS. Just give up.}}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {mSystemDefaultTrustManager.checkClientTrusted(chain, authType);}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {for (X509Certificate certificate : chain) {try {certificate.verify(mCertificate.getPublicKey());return;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (NoSuchProviderException e) {e.printStackTrace();} catch (SignatureException e) {e.printStackTrace();}}mSystemDefaultTrustManager.checkServerTrusted(chain, authType);}@Overridepublic X509Certificate[] getAcceptedIssuers() {return mSystemDefaultTrustManager.getAcceptedIssuers();}}

    此外,也可以不自己實(shí)現(xiàn) X509TrustManager,而僅僅修改 X509TrustManager 所用的根證書(shū)庫(kù),就像下面這樣:

    private TrustManager[] createX509TrustManager() {CertificateFactory cf = null;InputStream in = null;TrustManager[] trustManagers = nulltry {cf = CertificateFactory.getInstance("X.509");in = getAssets().open("ca.crt");Certificate ca = cf.generateCertificate(in);KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());keystore.load(null, null);keystore.setCertificateEntry("ca", ca);String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);tmf.init(keystore);trustManagers = tmf.getTrustManagers();} catch (CertificateException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyStoreException e) {e.printStackTrace();} catch (IOException e1) {e1.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}return trustManagers;}

    自己實(shí)現(xiàn) X509TrustManager 接口和通過(guò) TrustManagerFactory,僅定制 KeyStore 這兩種創(chuàng)建 X509TrustManager 對(duì)象的方式,當(dāng)然是后一種方式更好一些了。如我們前面看到的,系統(tǒng)的 X509TrustManager 實(shí)現(xiàn) RootTrustManager 集成自 X509ExtendedTrustManager,而不是直接實(shí)現(xiàn)的 X509TrustManager 接口 。JCA 的接口層也在隨著新的安全協(xié)議和 SSL 庫(kù)的發(fā)展在不斷擴(kuò)展,在具體的 Java 加密服務(wù)實(shí)現(xiàn)中,可能會(huì)實(shí)現(xiàn)并依賴(lài)這些擴(kuò)展的功能,如上面看到的 X509TrustManager,而且加密服務(wù)的實(shí)現(xiàn)中常常通過(guò)反射,來(lái)動(dòng)態(tài)依賴(lài)一些擴(kuò)展的接口。因而,自己實(shí)現(xiàn) X509TrustManager 接口時(shí),以及其它加密相關(guān)的接口時(shí),如 SSLSocket 等,可能會(huì)破壞一些功能。

    很多時(shí)候可以看到,為了使用私有 CA 簽名的證書(shū),而定制域名匹配驗(yàn)證的邏輯,即自己實(shí)現(xiàn) HostnameVerifier。不過(guò)通常情況下,網(wǎng)絡(luò)庫(kù)都會(huì)按照規(guī)范對(duì)域名與證書(shū)的匹配性做嚴(yán)格的檢查,因而不是那么地有必要,除非域名證書(shū)有什么不那么規(guī)范的地方。

    關(guān)于證書(shū)釘扎,在使用私有 CA 簽名的證書(shū)時(shí),通常似乎也沒(méi)有那么必要。

    參考文章:

    Android https 自定義 證書(shū) 問(wèn)題
    Android實(shí)現(xiàn)https網(wǎng)絡(luò)通信之添加指定信任證書(shū)/信任所有證書(shū)
    HTTPS(含SNI)業(yè)務(wù)場(chǎng)景“IP直連”方案說(shuō)明
    HTTP Public Key Pinning 介紹
    Java https請(qǐng)求 HttpsURLConnection

    Done。

    總結(jié)

    以上是生活随笔為你收集整理的Android 根证书管理与证书验证的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。