iosiphonesslapp-transport-securitycertificate-pinning

SSL Pinning using AFNetworking in iOS not working


I am using AFnetworking. My application webserver is in TLS 1.2. I want to add Certificate pinning to my iOS app. My code as below:

       AFHTTPSessionManager *manager=[[AFHTTPSessionManager manager] initWithBaseURL:serviceURL];

    NSSet *certificates = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certificates];
    policy.validatesDomainName = YES;
    policy.allowInvalidCertificates = YES;
    opManager.securityPolicy = policy;

I have my valid server certificate in my bundle and with this code webservices are working fine. But when I tried the same with an incorrect sample certificate, that time also webservices are working. I even tried with no certificates in bundle, that time also, webservices are working fine. Could anyone please explain this? AppTransportSecurity is turned ON in my app.

    <key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
</dict>

Solution

  • I found a solution to this issue. Please find below the code I used to replace existing code. It's working as expected.

            AFHTTPSessionManager *opManager=[[AFHTTPSessionManager manager] initWithBaseURL:baseUrl];
        opManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        opManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
        // SSL Pinning
        NSString *certificatePath = [[NSBundle mainBundle] pathForResource:@"xxxxxxxx.com" ofType:@"der"];
        NSData *certificateData = [NSData dataWithContentsOfFile:certificatePath];
    
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
        [securityPolicy setAllowInvalidCertificates:YES];
        [securityPolicy setPinnedCertificates:@[certificateData]];
        [opManager setSecurityPolicy:securityPolicy];