4

我正在使用AFNetworking 3.0。我有一个带有由 Global Sign 签名的 https 证书的网络服务器。我想将证书固定添加到我的 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 套件作为中间人代理,我们能够中断请求并监控请求的内容。

那么,如何正确实施证书固定?

4

1 回答 1

3

这是 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
于 2017-04-20T08:58:51.773 回答