倾城一屁博妹一笑 2020-06-12
如果使用自签名证书,需要在AFSecurityPolicy中允许无效证书:
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; [securityPolicy setAllowInvalidCertificates:YES];
实际情况下,网络请求依然失败,并且提示:
In order to validate a domain name for self signed certificates, you MUST use pinning.
网上查询资料,大多数答案都说需要把域名验证关闭:
[securityPolicy setValidatesDomainName:NO];
这样做网络请求确实成功了,但是实际上自签名证书也是可以包含域名的,即Common Name(CN)字段。理论上这个validatesDomainName
属性应当与自签名无关。
查看AFSecurityPolicy
源码,发现当使用自签名证书时,如果validatesDomainName
值为YES,会直接网络请求失败:
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain { 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; }
根据注释信息可以看到,AFNetworking
要求对一个自签名证书的域名验证是要走证书绑定模式。推测这么做是为了安全方面的考量,如果使用自签名证书,不验证证书的有效性,无法避免中间人攻击,强制证书绑定可以避免这个问题。
至于设置validatesDomainName
为NO
网络请求就能成功,因为它能够破坏AFNetworking
的限制条件,证书验证能够执行且不验证域名。从另一个方面说,既然不验证证书有效性也不验证域名,使用者对中间人攻击已经不关心了,网络请求能够成功也没问题。
将cer格式证书拖到工程内,新建AFSSLPinningModePublicKey
或AFSSLPinningModeCertificate
模式的AFSecurityPolicy
,设置允许无效证书:
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; [securityPolicy setAllowInvalidCertificates:YES];
新版的AFNetworking
会自动扫描工程中的cer证书文件,并将证书数据设置到属性中:
@property (nonatomic, strong, nullable) NSSet <NSData *> *pinnedCertificates;
这样就完成了。
AFNetworking使用自签名证书,推荐使用证书绑定模式。如果担心证书更新问题或不关心中间人攻击,可以选择不绑定证书,设置不验证域名。