AFSecurityPolicy這個(gè)類是針對(duì)HTTPS連接時(shí)做的證書認(rèn)證集峦,這里我們假設(shè)你已經(jīng)對(duì)HTTPS連接有了一定的了解。
也是比較簡(jiǎn)單的一個(gè)類啊将硝,看源碼吧
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
};
一個(gè)枚舉類型,定義了HTTPS的三種驗(yàn)證模式:
AFSSLPinningModeNone
這個(gè)模式本地沒有保存證書屏镊,只驗(yàn)證服務(wù)器證書是不是系統(tǒng)受信任證書列表里的證書簽發(fā)的依疼。
AFSSLPinningModePublicKey
這個(gè)模式表示本地存有證書,驗(yàn)證證書的有效期等信息闸衫,也就是將本地證書設(shè)置為錨點(diǎn)證書涛贯,然后驗(yàn)證證書有效性,再判斷本地證書和服務(wù)器證書是否一致蔚出。
AFSSLPinningModeCertificate
這個(gè)模式同樣是本地存有證書弟翘,只是驗(yàn)證時(shí)只驗(yàn)證證書里的公鑰,不驗(yàn)證證書的有效期等信息骄酗。
/**
只讀屬性稀余,證書驗(yàn)證模式,只能在初始化的時(shí)候設(shè)置
*/
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/**
本地證書的集合
*/
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
/**
是否允許無效的證書趋翻,默認(rèn)是NO
*/
@property (nonatomic, assign) BOOL allowInvalidCertificates;
/**
是否驗(yàn)證域名睛琳,默認(rèn)是YES
*/
@property (nonatomic, assign) BOOL validatesDomainName;
AFSecurityPolicy的一些基本屬性,都很簡(jiǎn)單踏烙。
/**
返回指定目錄下的證書
*/
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
/**
默認(rèn)驗(yàn)證策略的初始化
*/
+ (instancetype)defaultPolicy;
/**
根據(jù)制定的驗(yàn)證模式初始化
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
/**
根據(jù)指定的驗(yàn)證模式和本地證書初始化
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
/**
返回服務(wù)器證書是否能夠被信任师骗,在NSUrlSessionDelegate的`URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler`方法中被調(diào)用
serverTrust 服務(wù)器證書驗(yàn)證對(duì)象
domain 域名
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(nullable NSString *)domain;
如果不制定驗(yàn)證模式,就是在默認(rèn)的AFSSLPinningModeNone驗(yàn)證模式下驗(yàn)證讨惩,所以不需要本地證書辟癌,但是如果要自己設(shè)置驗(yàn)證模式,就可能需要本地證書荐捻,所以需要指定證書或者獲取工程下的所有證書黍少。
#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
static NSData * AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
__Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
return (__bridge_transfer NSData *)data;
_out:
if (data) {
CFRelease(data);
}
return nil;
}
#endif
OSStatus SecItemExport(CFTypeRef secItemOrArray, SecExternalFormat outputFormat, SecItemImportExportFlags flags, const SecItemImportExportKeyParameters *keyParams, CFDataRef _Nullable *exportedData);
這個(gè)函數(shù)是把secItemOrArray導(dǎo)出到exportedData寡夹。
__Require_noErr_Quiet(errorCode, exceptionLabel)
就是當(dāng)errocode不為0時(shí) goto到exceptionLabel執(zhí)行。
static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
return [(__bridge id)key1 isEqual:(__bridge id)key2];
#else
return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
#endif
}
這個(gè)很簡(jiǎn)單厂置,比較兩個(gè)key是否相等菩掏,用于AFSSLPinningModePublicKey模式下比較公鑰。
static id AFPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil;
SecCertificateRef allowedCertificate;
SecCertificateRef allowedCertificates[1];
CFArrayRef tempCertificates = nil;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
/**
certificate轉(zhuǎn)換為SecCertificateRef類型的證書
certificate 通過(__bridge CFDataRef)轉(zhuǎn)換成 CFDataRef
allocator CFAllocator分配證書昵济。
data DER編碼的X.509證書智绸。
*/
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
//allowedCertificate如果是空跳轉(zhuǎn)到_out
__Require_Quiet(allowedCertificate != NULL, _out);
// 給allowedCertificates賦值
allowedCertificates[0] = allowedCertificate;
// 新建CF數(shù)組 tempCertificates
tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
// 新建policy為X.509
policy = SecPolicyCreateBasicX509();
// 根據(jù)證書、驗(yàn)證策略砸紊、創(chuàng)建SecTrustRef對(duì)象賦值給allowedTrust传于,如果出錯(cuò)就跳到_out標(biāo)記處
__Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
// 校驗(yàn)證書,出錯(cuò)跳轉(zhuǎn)到_out醉顽。
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
//copy出allowedTrust的公鑰
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
...
return allowedPublicKey;
}
這個(gè)函數(shù)就是獲取證書文件的公鑰沼溜,需要了解的知識(shí)點(diǎn)都寫在注釋里了,看一下就可以了游添。
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
BOOL isValid = NO;
SecTrustResultType result;
__Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
_out:
return isValid;
}
這個(gè)函數(shù)就是判斷SecTrustRef對(duì)象是否是有效的系草,SecTrustEvaluate(serverTrust, &result)
這句就是驗(yàn)證serverTrust,然后把驗(yàn)證結(jié)果賦值給result唆涝。
kSecTrustResultUnspecified
表示系統(tǒng)里有該證書的根證書找都,而且校驗(yàn)通過。
kSecTrustResultProceed
用戶設(shè)置了錨點(diǎn)證書廊酣,驗(yàn)證通過能耻。
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return [NSArray arrayWithArray:trustChain];
}
這個(gè)函數(shù)是用來獲取服務(wù)器提供需要驗(yàn)證的證書鏈。
SecTrustGetCertificateCount
獲取SecTrustRef對(duì)象中的證書數(shù)量亡驰。
SecTrustGetCertificateAtIndex
獲取SecTrustRef對(duì)象中的第index個(gè)證書晓猛。
static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
SecPolicyRef policy = SecPolicyCreateBasicX509();
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust;
__Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
SecTrustResultType result;
__Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
_out:
...
continue;
}
CFRelease(policy);
return [NSArray arrayWithArray:trustChain];
}
前面和獲取服務(wù)器驗(yàn)證證書鏈的方法都一樣,就不說了凡辱。
CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
從someCertificates數(shù)組中copy 1個(gè)元素用于新創(chuàng)建的C數(shù)組中戒职。
SecTrustCreateWithCertificates(certificates, policy, &trust)
根據(jù)證書certificates和驗(yàn)證策略policy創(chuàng)建一個(gè)SecTrustRef對(duì)象。
SecTrustCopyPublicKey (trust)
獲取SecTrustRef對(duì)象中的publickey透乾。
中間一些初始化洪燥、獲取本地證書的方法就不說了,直接看重點(diǎn)
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
//log里已經(jīng)說得很清楚了乳乌,如果你要驗(yàn)證自簽名證書的域名捧韵,那么就不能用AFSSLPinningModeNone模式,
//而且必須copy服務(wù)器證書到本地
if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
// https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
// According to the docs, you should only trust your provided certs for evaluation.
// Pinned certificates are added to the trust. Without pinned certificates,
// there is nothing to evaluate against.
//
// From Apple Docs:
// "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
// Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
return NO;
}
NSMutableArray *policies = [NSMutableArray array];
// 如果需要驗(yàn)證domain汉操,那么就需要SecPolicyCreateSSL函數(shù)創(chuàng)建驗(yàn)證策略纫版,
//server 參數(shù)為true表示驗(yàn)證整個(gè)SSL證書鏈
//hostname 傳入domain,用于判斷整個(gè)證書鏈上的domain是否和此處傳入domain一致
if (self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
} else {
// 如果不需要驗(yàn)證domain客情,就使用默認(rèn)的BasicX509驗(yàn)證策略
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
// 為serverTrust設(shè)置驗(yàn)證策略
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
// 如果SSLPinningMode為 AFSSLPinningModeNone其弊,表示你不使用SSL pinning
//使用AFServerTrustIsValid函數(shù)驗(yàn)證serverTrust是否可信任,如果信任返回YES
//判斷用戶是否信任自建證書膀斋,如果信任返回YES
if (self.SSLPinningMode == AFSSLPinningModeNone) {
return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
}
//如果不允許自建證書梭伐,serverTrust又不被信任,那么就表示驗(yàn)證不通過返回NO
else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return NO;
}
switch (self.SSLPinningMode) {
case AFSSLPinningModeNone:
default:
return NO;
//使用SSL Pinning方式驗(yàn)證證書
//要驗(yàn)證整個(gè)證書一致才能通過
case AFSSLPinningModeCertificate: {
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for (NSData *certificateData in self.pinnedCertificates) {
//SecCertificateCreateWithData函數(shù)把本地存儲(chǔ)的服務(wù)器證書拷貝數(shù)據(jù)轉(zhuǎn)換為DER編碼的 X.509證書
//然后加入pinnedCertificates數(shù)組中
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
// 將pinnedCertificates設(shè)置成需要參與驗(yàn)證的Anchor Certificate(錨點(diǎn)證書仰担,通過SecTrustSetAnchorCertificates設(shè)置了參與校驗(yàn)錨點(diǎn)證書之后糊识,假如驗(yàn)證的數(shù)字證書是這個(gè)錨點(diǎn)證書的子節(jié)點(diǎn),即驗(yàn)證的數(shù)字證書是由錨點(diǎn)證書對(duì)應(yīng)CA或子CA簽發(fā)的摔蓝,或是該證書本身赂苗,則信任該證書),具體就是調(diào)用SecTrustEvaluate來驗(yàn)證贮尉。
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
//判斷服務(wù)器證書是否是有效的(是否由上面設(shè)置的錨點(diǎn)證書或其子證書簽發(fā)拌滋,有效期等信息)
if (!AFServerTrustIsValid(serverTrust)) {
return NO;
}
// 獲取服務(wù)器需要驗(yàn)證的證書鏈
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
//驗(yàn)證是否有本地證書與服務(wù)器返回的證書量一致的,如果有就返回YES
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
return YES;
}
}
return NO;
}
//驗(yàn)證公鑰(Publickey)一致就可以了
case AFSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0;
//獲取服務(wù)器返回的證書的Publickey
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
// 依次遍歷本地Publickey和服務(wù)器Publickey猜谚,如果有一致的败砂,那么就給trustedPublicKeyCount +1
for (id trustChainPublicKey in publicKeys) {
for (id pinnedPublicKey in self.pinnedPublicKeys) {
//用AFSecKeyIsEqualToKey函數(shù)驗(yàn)證publickey
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
trustedPublicKeyCount += 1;
}
}
}
return trustedPublicKeyCount > 0;
}
}
return NO;
}
需要解釋的都放在注釋里了
如有錯(cuò)誤,請(qǐng)不吝賜教魏铅,謝謝昌犹!