How to use SSL pinning to make your iOS app more secure

Source: Internet
Author: User
Tags ssl certificate dns spoofing

SSL pinning plays a very important role in building a highly secure mobile app. Today, however, many users are using wireless mobile devices to access countless unsecured wireless networks.

This article mainly covers the SSL pinning technology to help us deal with the most common security attacks-man-in-the-middle attacks (MITM).

SSL (Secure Socket Layer) ensures that the client-server encrypts the content of the communication on the HTTP request----is specified as HTTPS (HTTP on SSL). This encryption system is based on PKI (Pbulic key Infrastructure, public key System) and (session key, conversation key). The reason why session key is introduced is that the encryption and decryption of the public/private key consumes processing power, which slows down the entire communication process.

SSL Security---Authentication

SSL security is a certificate-based trust chain. When a communication begins, the client checks the server's SSL certificate to see if the certificate is trusted by the credit root CA authority or other user trust structure.

Although SSL communication is considered to be a very secure and indestructible, man-in-the-middle attack is still a real threat, and it can be implemented in several ways, such as ARP cache poisoning, DNS spoofing, and so on.

For ARP cache poisoning, it can be easily understood that the man-in-the-middle is attacked by the IP mapping of the Address Resolution Protocol to the MAC address of the device. For example, let's use three characters to describe a simple network:

A common user device U

Attacker's device A

Router R

The attacker's device a can send an ARP-dependent packet to the user device U, masquerading himself as a router R. In order to complete the man-in-the-middle attack, a sends another ARP dependency to R, telling the router that it is U. In this case, a is the middle of communication between U and R, and a can eavesdrop and intercept information. IP forwarding is often used by attackers to communicate seamlessly between user devices and routers. This means that through IP forwarding, attackers can steal and listen, but users and routers are not aware.

DNS spoofing is primarily the domain name mapping of the attacker's broken server. An attacker attempts to force DNS to return an incorrect address, which is the address of the attacker's computer.

SSL pinning

We use SSL pinning to ensure that the app communication only occurs on the specified server. The prerequisite is that the SSL certificate of the price target server is placed in the app. This certificate is used for session configuration. Here I briefly describe the use of SSL pinning on nsurlsession.

When it comes to nsurlsession using SSL pinning is a bit tricky because in afnetworking, it already has a packaged class that can be configured using it. There is no way to set up a set of certificates to automatically cancel all response that do not match local certificates. We need to perform a check manually to implement the SSL pinning on the nsurlsession. We are honored that we can use the security ' s framework C API.

We can start with a default session configuration for the Nsurlsession object.

nsurlsessionconfiguration *seeconfig = [nsurlsessionconfiguration defaultsessionconfiguration ];

nsurlsession *session = [nsurlsession sessionwithconfiguration: Seeconfig Delegate :self delegatequeue:nil];

Nsurlsession uses Nsurlsessiontask to send a request, I use the Datataskwithurl:completionhandler: Method for SSL pinning testing. The send request resembles the following:

    Nsurlsessiondatatask *task = [session datataskwithrequest:[nsurlrequest Requestwithurl:testurl];    [Task resume];

The method simply returns a task object and then uses the Resume method to send the request, or to perform a task.

Is the SSL pinning in:

URLSession:didReceiveChallenge:completionHandler:Delegate

Implemented in the method. On the Nsurlsession object, we set ourselves as the proxy to invoke the method.

- (void) Urlsession: (Nsurlsession *) session Didreceivechallenge: (Nsurlauthenticationchallenge *) challenge Completionhandler: (void(^) (Nsurlsessionauthchallengedisposition, Nsurlcredential *_nullable)) Completionhandler {//get a remote certificateSectrustref Servertrust =Challenge.protectionSpace.serverTrust; Seccertificateref Certificate= Sectrustgetcertificateatindex (Servertrust,0); //set the SSL policy to detect the primary domain nameNsmutablearray *policies =[Nsmutablearray array]; [Policies AddObject: (__bridge_transferID) Secpolicycreatessl (true, (__bridge cfstringref) challenge.protectionSpace.host)]; //Verifying server CertificatesSectrustresulttype result; Sectrustevaluate (Servertrust,&result); BOOL Certificateisvalid= (Result = = Ksectrustresultunspecified | | result = =ksectrustresultproceed); //get local and remote certificate dataNSData *remotecertificatedata =cfbridgingrelease (Seccertificatecopydata (certificate)); NSString*pathtocer = [[NSBundle mainbundle] Pathforresource:@"brhttp"OfType:@"cer"]; NSData*localcertificate =[NSData Datawithcontentsoffile:pathtocer]; //Check    if([Remotecertificatedata isequaltodata:localcertificate] &&certificateisvalid) {nsurlcredential*credential =[Nsurlcredential Credentialfortrust:servertrust];    Completionhandler (nsurlsessionauthchallengeusecredential,credential); }Else{Completionhandler (nsurlsessionauthchallengecancelauthenticationchallenge,null); }}

At the beginning of the method, we use Sectrustgetcertificateatindex to get the SSL certificate data of the server. Then use the certificate evaluation settings policies. The certificate uses Sectrustevaluate evaluation and then returns one of several authentication result types:

typedef uint32_t SECTRUSTRESULTTYPE;enum{ksectrustresultinvalid=0, Ksectrustresultproceed=1, ksectrustresultconfirm Sec_deprecated_attribute=2, Ksectrustresultdeny=3, Ksectrustresultunspecified=4, Ksectrustresultrecoverabletrustfailure=5, Ksectrustresultfataltrustfailure=6, Ksectrustresultothererror=7};

If we get the result of a type other than Ksectrustresultproceed and ksectrustresultunspecified, we can assume that the certificate is invalid (untrusted).

So far we have not done anything other than detecting remote server certificate evaluation, we need to seccertificateref to get his nsdata for SSL pinning detection. This seccertificateref comes from Challenge.protectionSpace.serverTrust. The local nsdata is from a local. cer certificate file. Then we use IsEqual to do the SSL pinning.

If the nsdata of the remote server certificate equals the local certificate data, then it can be evaluated, we can verify the identity of the server and then communicate, and also use Completionhandler ( Nsurlsessionauthchallengeusecredential,credential) executes the request.

However, if two data is not equal, we use Completionhandler (nsurlsessionauthchallengecancelauthenticationchallenge,null) method to cancel the execution of the datatask so that communication with the server can be denied.

This is the use of SSL pinning in Nsurlsession.

Attached Source: Https://pan.baidu.com/s/1mio6ZnM

How to use SSL pinning to make your iOS app more secure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.