在目前的 iOS 和 Android 上,App 進行 SSL 通信時,客戶端默認並不會主動校驗服務器證書是否已失效。
iOS 系統會定期拉取所訪問服務器的證書信息並緩存在本地;Android 端則完全不做這類檢測。
如果應用與服務器進行 SSL 通信時不做任何證書有效性校驗,就可能面臨用戶信息洩露等安全風險——中間人攻擊正是利用這一點。
證書有效性檢測主要有兩種機制:CRL 與 OCSP。OCSP 的優勢在於時效性更高、開銷更小,本文重點介紹基於 OCSP 的實現方式。
iOS 上不同的通信 API 對應不同的校驗入口。WKWebView、NSURLSession、NSURLConnection 這幾類可以用一套通用做法解決,核心是在 challenge 回調裡攔截並自行判斷證書信任狀態:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([[[UtilCrlOcsp alloc] init] isServerTrustProceedOrUnspecifiedWithAuthenticationChallenge:challenge]) {
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
[self updateTextViewMessage:error.description];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
[self updateTextViewMessage:response.description];
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([[[UtilCrlOcsp alloc] init] isServerTrustProceedOrUnspecifiedWithAuthenticationChallenge:challenge]) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else {
[challenge.sender cancelAuthenticationChallenge:challenge];
}
}
}至於 WebView 和 CFNetwork 這類通信方式,需要額外實現一些回調方法,具體可以參考蘋果官方文檔的說明。
Android 上有現成的 CRL 相關 API,用它做證書有效性檢測比較省事。但 OCSP 沒有任何官方支持,需要從零開始實現,可以參考 Bouncy Castle 的相關組件。以下以 OCSP 的校驗流程為例:
if (true || basicResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider('BC').build(rootCert.getPublicKey()))) {
SingleResp[] responses = basicResponse.getResponses();
byte[] reqNonce = getNonce(request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
byte[] resNonce = getNonce(basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce));
// validate the nonce if it is present
if (reqNonce == null || resNonce == null || Arrays.equals(reqNonce, resNonce)) {
for (int i = 0; i != responses.length;) {
putLog('OCSP certificate number ' + responses[i].getCertID().getSerialNumber());
if (responses[i].getCertStatus() == CertificateStatus.GOOD) {
putLog('---OCSP status GOOD');
return true;
}
else if (responses[i].getCertStatus() instanceof RevokedStatus) {
putLog('---OCSP status Revoked');
return false;
}
else {
putLog('---OCSP status ' + responses[i].getCertStatus());
return false;
}
}
}本文只介紹了基於 OCSP 的證書有效性檢測思路,真要落到項目裡,還需要結合自身的業務場景、性能開銷和失敗策略進一步權衡設計。