該文章閱讀的AFNetworking的版本爲3.2.0。html
AFSecurityPolicy
這個類是用於驗證HTTPS請求的證書是否正確。安全
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
};
複製代碼
這個枚舉定義了服務器證書驗證模式:bash
AFSSLPinningModeNone
不使用證書驗證服務器服務器
AFSSLPinningModePublicKey
使用證書中的公鑰驗證服務器app
AFSSLPinningModeCertificate
使用證書驗證服務器dom
/**
服務器證書驗證模式,默認是不驗證
*/
@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/**
驗證服務器的證書的集合,默認狀況下,AFNetworking會搜索工程中全部.cer的證書文件,但不會將某個證書做爲默認。若是想建立AFSecurityPolicy對象,就先調用certificatesInBundle方法加載證書,而後調用policyWithPinningMode:withPinnedCertificates方法建立對象
*/
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
/**
是否信任無效或者過時的證書,默認爲否
*/
@property (nonatomic, assign) BOOL allowInvalidCertificates;
/**
是否驗證證書中的域名,默認爲是
*/
@property (nonatomic, assign) BOOL validatesDomainName;
複製代碼
/**
用這個方法查找包含在指定包中的全部的證書
*/
+ (NSSet <NSData *> *)certificatesInBundle:(NSBundle *)bundle;
/**
實例化工廠方法,默認的配置包括不容許無效或者過時證書、驗證域名、不驗證證書和證書中公鑰
*/
+ (instancetype)defaultPolicy;
/**
指定證書驗證模式的實例化工廠方法
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode;
/**
指定證書驗證模式和證書的實例化工廠方法
*/
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet <NSData *> *)pinnedCertificates;
/**
驗證是否信任服務器
*/
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(nullable NSString *)domain;
複製代碼
這個方法是將key轉爲NSData類型ide
#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
複製代碼
這個方法是判斷兩個key是否相等post
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
}
複製代碼
這個方法是用來從證書中取出公鑰學習
static id AFPublicKeyForCertificate(NSData *certificate) {
id allowedPublicKey = nil;
SecCertificateRef allowedCertificate;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out);
policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
__Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
_out:
if (allowedTrust) {
CFRelease(allowedTrust);
}
if (policy) {
CFRelease(policy);
}
if (allowedCertificate) {
CFRelease(allowedCertificate);
}
return allowedPublicKey;
}
複製代碼
這個方法是判斷服務器是否能夠信任ui
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;
}
複製代碼
這個方法是用來得到服務器返回的全部的證書
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];
}
複製代碼
這個方法是用來得到服務器返回的全部的證書中的公鑰
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:
if (trust) {
CFRelease(trust);
}
if (certificates) {
CFRelease(certificates);
}
continue;
}
CFRelease(policy);
return [NSArray arrayWithArray:trustChain];
}
複製代碼
這裏面頻繁使用了兩個宏:__Require_Quiet
和__Require_noErr_Quiet
,咱們來看一下他們的定義:
#ifndef __Require_Quiet
#define __Require_Quiet(assertion, exceptionLabel) \
do \
{ \
if ( __builtin_expect(!(assertion), 0) ) \
{ \
goto exceptionLabel; \
} \
} while ( 0 )
#endif
複製代碼
能夠看出__Require_Quiet
這個宏的做用是當斷言爲假時,跳轉並執行標記以後的代碼
#ifndef __Require_noErr_Quiet
#define __Require_noErr_Quiet(errorCode, exceptionLabel) \
do \
{ \
if ( __builtin_expect(0 != (errorCode), 0) ) \
{ \
goto exceptionLabel; \
} \
} while ( 0 )
#endif
複製代碼
能夠看出__Require_noErr_Quiet
這個宏的做用是當斷言爲真時,跳轉並執行標記以後的代碼
/**
保存服務器證書驗證模式
*/
@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
/**
保存證書中的公鑰的集合
*/
@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
複製代碼
+ (NSSet *)certificatesInBundle:(NSBundle *)bundle {
// 獲取包中全部後綴爲.cer的文件路徑
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
// 遍歷文件路徑並將其對應的文件轉換爲NSData類型數據
NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
// 返回轉換爲二進制的證書的集合
return [NSSet setWithSet:certificates];
}
+ (NSSet *)defaultPinnedCertificates {
// 獲取默認證書列表
static NSSet *_defaultPinnedCertificates = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
_defaultPinnedCertificates = [self certificatesInBundle:bundle];
});
return _defaultPinnedCertificates;
}
+ (instancetype)defaultPolicy {
// 按照默認實例化對象
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
return securityPolicy;
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
// 調用全能實例化方法
return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
}
+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
// 實例化對象並設置屬性
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = pinningMode;
[securityPolicy setPinnedCertificates:pinnedCertificates];
return securityPolicy;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
// 驗證證書中的域名
self.validatesDomainName = YES;
return self;
}
- (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates;
// 若是設置了證書,就取出證書中的公鑰並保存
if (self.pinnedCertificates) {
NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
for (NSData *certificate in self.pinnedCertificates) {
id publicKey = AFPublicKeyForCertificate(certificate);
if (!publicKey) {
continue;
}
[mutablePinnedPublicKeys addObject:publicKey];
}
self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
} else {
self.pinnedPublicKeys = nil;
}
}
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
// 當使用自建證書驗證域名時,必須使用AFSSLPinningModePublicKey或者AFSSLPinningModeCertificate進行驗證
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];
if (self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
} else {
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
// 添加安全策略,爲serverTrust設置驗證策略,即告訴客戶端如何驗證serverTrust
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
// 若是驗證策略爲不驗證
if (self.SSLPinningMode == AFSSLPinningModeNone) {
// 若是信任無效或者過時證書則直接經過驗證,不然根絕驗證證書狀況返回
return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
// 若是驗證策略爲驗證,但未驗證經過而且不信任無效或者過時證書,返回未經過
} else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return NO;
}
/**
當代碼走到這兒的時候表明:
1.有驗證策略
2.證書驗證經過
3.不信任無效或者過時證書
*/
switch (self.SSLPinningMode) {
// 若是沒有驗證策略不經過驗證
case AFSSLPinningModeNone:
default:
return NO;
// 若是驗證策略爲驗證整個證書
case AFSSLPinningModeCertificate: {
// 遍歷本地的證書進行驗證
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for (NSData *certificateData in self.pinnedCertificates) {
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
// 若是驗證不經過就返回
if (!AFServerTrustIsValid(serverTrust)) {
return NO;
}
// 驗證本地證書和服務器返回的證書是否相同,若是相同才經過驗證
// obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it is the Root CA)
NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
return YES;
}
}
return NO;
}
// 若是驗證策略爲驗證證書的公鑰
case AFSSLPinningModePublicKey: {
// 獲取服務器返回的公鑰和本地的公鑰進行對比,只要有一個相同就經過驗證
NSUInteger trustedPublicKeyCount = 0;
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
for (id trustChainPublicKey in publicKeys) {
for (id pinnedPublicKey in self.pinnedPublicKeys) {
if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
trustedPublicKeyCount += 1;
}
}
}
return trustedPublicKeyCount > 0;
}
}
return NO;
}
複製代碼
+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
return [NSSet setWithObject:@"pinnedCertificates"];
}
複製代碼
添加依賴鍵,使pinnedPublicKeys
屬性依賴於pinnedCertificates
屬性,當pinnedCertificates
屬性值發生變化時,pinnedPublicKeys
的觀察者也能獲得通知
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
[coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
[coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
[coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
}
複製代碼
關於NSSecureCoding
在AFNetworking源碼閱讀(二)——從AFURLRequestSerialization入手的"4.1.2.4.7 NSSecureCoding協議方法的實現"中已經解釋過了,就再也不復述
- (instancetype)copyWithZone:(NSZone *)zone {
AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
securityPolicy.SSLPinningMode = self.SSLPinningMode;
securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
securityPolicy.validatesDomainName = self.validatesDomainName;
securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
return securityPolicy;
}
複製代碼
由於對HTTP和SSL不是很瞭解,因此只作了一些大概功能的閱讀。想詳細瞭解的話仍是得先認真學習HTTP和SSL相關知識。
源碼閱讀系列:AFNetworking
源碼閱讀:AFNetworking(二)——AFURLRequestSerialization
源碼閱讀:AFNetworking(三)——AFURLResponseSerialization
源碼閱讀:AFNetworking(四)——AFSecurityPolicy
源碼閱讀:AFNetworking(五)——AFNetworkReachabilityManager
源碼閱讀:AFNetworking(六)——AFURLSessionManager
源碼閱讀:AFNetworking(七)——AFHTTPSessionManager
源碼閱讀:AFNetworking(八)——AFAutoPurgingImageCache
源碼閱讀:AFNetworking(九)——AFImageDownloader
源碼閱讀:AFNetworking(十)——AFNetworkActivityIndicatorManager
源碼閱讀:AFNetworking(十一)——UIActivityIndicatorView+AFNetworking
源碼閱讀:AFNetworking(十二)——UIButton+AFNetworking
源碼閱讀:AFNetworking(十三)——UIImageView+AFNetworking
源碼閱讀:AFNetworking(十四)——UIProgressView+AFNetworking