我正在使用 AFNetworking 3.0 。我有一个带有https证书的网络服务器,该证书由Global Sign签名。我想将证书固定添加到我的iOS应用程序中。我的代码如下:
- (AFSecurityPolicy*)customSecurityPolicy{
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
[securityPolicy setAllowInvalidCertificates:NO];
[securityPolicy setValidatesDomainName:YES];
//securityPolicy.validatesCertificateChain = NO;
[securityPolicy setPinnedCertificates:[NSKeyedUnarchiver unarchiveObjectWithData:certData]];
return securityPolicy;
}
我的客户代码:
NSString *url = SERVER_URL;
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
manager.securityPolicy = [utils customSecurityPolicy];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
我们使用burp suite作为中间人代理,我们能够中断请求并监视请求的内容。
那么,我如何正确实施证书锁定?
答案 0 :(得分:1)
这是AFNetworking之外的有效问题,您发现的唯一内容就是您使用库实现curl --cacert
操作的方式。
在 AFNetworking 的特定情况下,我遇到这种情况:
let sessionManager = AFHTTPSessionManager()
sessionManager.responseSerializer = AFJSONResponseSerializer()
sessionManager.requestSerializer = AFJSONRequestSerializer()
let configuration = ServiceConfiguration.sharedInstance.configuration
if let policy = configuration?.getSecurityPolicy()?.policy() as? AFSecurityPolicy {
sessionManager.securityPolicy = policy
}
方法getSecurityPolicy
返回RequestSecurityPolicy
的可选对象(即协议)。
要制作AFSecurityPolicy,我有:
import AFNetworking
class SSLPinningPolicy: NSObject, RequestSecurityPolicy {
// MARK: - Private properties -
private var certificatesDictionary: [String: Data] = [:]
// MARK: - Initilizers -
init(certicatePaths: [String]) {
super.init()
for path in certicatePaths {
if let certPath = Bundle.main.path(forResource: path, ofType: "der") {
let url = URL(fileURLWithPath: certPath)
do {
let data = try Data(contentsOf: url)
self.certificatesDictionary[path] = data
} catch {
}
}
}
}
// MARK: - RequestSecurityPolicy delegates -
func policy() -> AnyObject {
let policy = AFSecurityPolicy(pinningMode: .certificate)
policy.allowInvalidCertificates = true
policy.pinnedCertificates = self.certificates()
return policy
}
func certificates() -> Set<Data> {
return Set(self.certificatesDictionary.map { $0.value })
}
}
加号
要将我的证书从.pem
转换为.der
,您只需在shell中使用 openssl :
openssl x509 -outform der -in MyCertificate.pem -out MyCertificate.der