在iOS9之后,在默认情况下是不能发送HTTP请求,推荐使用HTTPS,当然你可以在plist里面设置NSAppTransportSecurity
的NSAllowsArbitraryLoads为true,App就依然支持HTTP请求
而AFSecurityPolicy主要的作用就是验证HTTPS请求的证书的有效性
AFSecurityPolicy是安全策略类,有三种SSL Pinning模式
1 2 3 4 5 typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { AFSSLPinningModeNone,// 在证书列表中校验服务端返回的证书 AFSSLPinningModePublicKey,// 客户端要有服务端的证书拷贝,只是验证时只验证证书里的公钥 AFSSLPinningModeCertificate,// 客户端要有服务端的证书拷贝,第一步先验证证书域名/有效期等信息,第二步对服务端返回的证书和客户端返回的是否一致 };
这个是证书集合,泛型里面表示了集合里面是NSData类型,表明这个是用来存证书数据的集合,这些证书根据SSL Pinning模式来和服务器进行校验,默认是没有证书的,我们需要调用+ certificatesInBundle:方法将bundle里面的证书文件转成里面是data类型的集合
1 @property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
1 2 3 4 5 6 7 8 9 10 11 12 13 + (NSSet *)certificatesInBundle:(NSBundle *)bundle { // 获取证书 NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; // 将证书文件转成data for (NSString *path in paths) { NSData *certificateData = [NSData dataWithContentsOfFile:path]; [certificates addObject:certificateData]; } return [NSSet setWithSet:certificates]; }
有三种初始化的方法,一种是默认策略,AFSSLPinningModeNone
1 2 3 4 5 6 + (instancetype)defaultPolicy { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = AFSSLPinningModeNone; return securityPolicy; }
第二种是自定义一个安全策略,然后读取cer文件放到集合里面
1 2 3 + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; }
1 2 3 4 5 6 7 8 9 10 + (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; }
第三种则是需要我们多传入一个证书集合
1 2 3 4 5 6 7 8 + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = pinningMode; [securityPolicy setPinnedCertificates:pinnedCertificates]; return securityPolicy; }
设置证书的时候,就是把上面初始化时传入的证书取出公钥,再把公钥保存到mutablePinnedPublicKeys集合中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 - (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; } }
在AFPublicKeyForCertificate
方法里面,做了一系列操作后返回公钥,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 static id AFPublicKeyForCertificate(NSData *certificate) { id allowedPublicKey = nil; SecCertificateRef allowedCertificate; SecCertificateRef allowedCertificates[1]; CFArrayRef tempCertificates = nil; SecPolicyRef policy = nil; SecTrustRef allowedTrust = nil; SecTrustResultType result; // 取出证书SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); __Require_Quiet(allowedCertificate != NULL, _out); // 生成证书数组 allowedCertificates[0] = allowedCertificate; tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); // 生成SecPolicyRef policy = SecPolicyCreateBasicX509(); __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); // 从SecPolicyRef中取出公钥 allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); _out: // 一些资源的释放 return allowedPublicKey; }
-[evaluateServerTrust:forDomain:]
方法是AFSecurityPolicy
类最长也是最重要的方法,它用来验证服务端是否是受信的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain { // 苹果文档中表示不要隐式地信任自己签名的证书,取而代之的是应该增加自己的CA证书到受信列表里 if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); return NO; } // policies增加SecPolicyRef NSMutableArray *policies = [NSMutableArray array]; if (self.validatesDomainName) { [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; } else { [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; } // 设置信任的policies应当被验证 SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); // 向系统内置的根证书验证服务端返回的证书是否合法 if (self.SSLPinningMode == AFSSLPinningModeNone) { return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { return NO; } // 根据SSLPinningMode对服务端是否受信进行校验 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's 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; }