Creating a secure app! HTTPS for the iOS security series

Source: Internet
Author: User
Tags decrypt go daddy ssl certificate asymmetric encryption

2015-08-11 08:59 Edit: suiling Category: iOS development Source: Jaminzzhang's blog

Jaminzzhang

How do I create a secure app? This is a problem that every mobile developer has to face. In mobile app development, development engineers generally lack security considerations, and because of the closeness of the iOS platform, the security problems encountered are much less than that of Android, which leads many iOS developers to have little in-depth security. But for a qualified software developer, security knowledge is one of the essential knowledge.

For an jailbroken iOS device, malware intrusion is largely eliminated due to the powerful sandbox and authorization mechanism, and Apple's own app Store. But in addition to the system security, we still face a lot of security issues: network security, data security, each involving a very wide, security is a very large issue, I am not a professional security experts, but from the developer's point of view, analysis of the security problems we often encounter, and put forward the usual solution to communicate with you.

Every software engineer is obligated to protect the privacy and security of user data.

The first is the network security, the OSI model each layer will face the corresponding network security issues, involving a broad, and network security is also the area of security development of the most prosperous areas. In this article, we are simply explaining the knowledge of HTTPS core concepts and the implementation on the iOS platform in the simplest possible way from the perspective of mobile application development. It is recommended that applications that are still using HTTP be upgraded to HTTPS.

Introduction: The era of Internet full-site HTTPS has arrived

1. HTTPS

In fact, HTTPS from the end of the data analysis, and HTTP is not any difference, HTTPS is to put the HTTP protocol packets into the SSL/TSL layer encryption, the TCP/IP layer constitutes a data datagram to transmit, in order to ensure the security of the transmission of data, and for the receiver, in the ssl/ When the TSL decrypts the received packets, it passes the data to the HTTP protocol layer, which is the normal HTTP data. Both HTTP and SSL/TSL are in the application layer of the OSI model. Switching from HTTP to HTTPS is a very simple process, and we need to understand a few concepts before doing a specific switching operation:

Ssl/tsl

About SSL/TSL, Nanyi's two blog posts are a good introduction:

    • Overview of the operating mechanism of SSL/TLS protocol

    • Graphical SSL/TLS protocol

Simply put, SSL/TSL through four handshake, the main exchange of three information:

1. Digital certificate: The certificate contains information such as the public key, usually sent to the client by the server, the receiver by verifying that the certificate is issued by a trusted CA, or with a local certificate relative to determine whether the certificate is trustworthy, if two-way authentication is required, Both the server and the client need to send a digital certificate to the other party for verification;

2. Three random numbers: These three random numbers form the "conversation key"that is used to decrypt the data for symmetric encryption during subsequent communication.

First the client first sends the first random number N1, then the server returns to the second random number N2 (this process also sends the previously mentioned certificate to the client), both of which are plaintext, and the third random number N3 (this random number is called Premaster secret), The client uses the public key of the digital certificate for asymmetric encryption to the server, and the server decrypts it with the private key that it knows only, obtaining a third random number. Only, the server and the client have three random number n1+n2+n3, and then use these three random numbers to generate a "conversation key", after which the communication is to use this "dialogue key" for symmetric encryption and decryption. Because of this process, the server's private key is only used to decrypt the third random number, never transmitted over the network, so long as the private key is not compromised, then the data is safe.

3. Encrypted communication protocol: It is the two sides to negotiate which encryption method, if the two supported encryption method does not match, then cannot communicate;

There is a common question about why a random number should be three? Only the last random number N3, okay?

This is due to the SSL/TLS design, it is assumed that the server does not believe that all clients can provide a full random number, if a client provides random number is not random, it greatly increases the "dialogue key" is the risk of being cracked, so the random number of three groups to form the final random number, to ensure the randomness of the stochastic number, This ensures that the dialog key security is generated for each build.

Digital certificates

A digital certificate is an electronic document that contains information about the holder, a public key, and a digital signature that proves that the certificate is valid. The PKI (Public Key Infrastructure) specification system is composed of digital certificates and related public key management and authentication technologies. In general, digital certificates are issued and managed by a digital certificate authority (Certificate Authority, CA), and assume responsibility for the legality of public key in the PKI system; There are many types of digital certificates, and HTTPS uses SSL certificates.

How do you verify that the digital certificate was issued by a CA and not by a third party? Before answering this question, we need to understand the organizational structure of the CA first. First, the CA organizational structure, the topmost is the root CA, the root CA can be authorized to multiple level two CAs, and the level two CA can also authorize multiple three-level CAs, so the CA's organizational structure is a tree structure. For the SSL certificate market, it is mainly carved up by Symantec (with VeriSign and GeoTrust), Comodo SSL, Go Daddy and GlobalSign. After understanding the organization of the CA, take a look at the issuance process for digital certificates:

A digital certificate issuing agency CA, after receiving the applicant's information, checks and determines the true validity of the information, and then produces a document that complies with the standards of the previous year. The certificate content of the certificate includes the holder information and the public key are provided by the applicant, and the digital signature is the CA agency to hash the contents of the certificate to wait until, and this digital signature is we verify that the certificate is a trusted CA-issued data.

After receiving a copy of the digital certificate Cer1, the content of the certificate is hashed until H1, and then the public key is found in the digital certificate of the institution CA1 The certificate is issued, the digital signature on the certificate is decrypted, and the certificate Cer1 signed Hash digest H2; compare H1 and H2, if equal, Indicates that the certificate has not been tampered with. But this time still do not know whether the CA is legal, we see in the CA agency digital certificate, this certificate is public, everyone can get to. The digital signature in this certificate is generated on the previous level, so it can be verified recursively until the root CA. The root CA is self-validating, that is, his digital signature is generated by his own private key. A legitimate root CA is added to the list of authoritative trusted CAs by the browser and the operating system, which completes the final validation. So, be sure to protect your environment (browser/operating system) in the root CA trust list, trust the root CA is to trust all the root CA under all the child CA issued certificates, do not arbitrarily add the root CA certificate.

After understanding the above two concepts, there is a preliminary understanding of HTTPS, and below we see how to implement HTTPS support on iOS.

2. Implement HTTPS support

First of all, you need to be clear about the use of Http/https, because OSX and iOS platform provides a variety of APIs to support different purposes, the official document "Making HTTP and HTTPS requests" has detailed instructions, and the document "HTTPS Server Trust Evaluation The knowledge of HTTPS authentication in detail, here is not much to say. This article mainly explains our most commonly used nsurlconnection support HTTPS implementation (Nsurlsession implementation method is similar, just require authorization to prove that the callback is not the same), And how to use afnetworking this very popular third-party library to support HTTPS. This article assumes that you have sufficient knowledge of HTTP and Nsurlconnection interfaces.

API to validate certificates

The relevant API in the security framework, the validation process is as follows:

1). The first step is to obtain the trust object that needs to be validated. This trust object is not the same in different application scenarios, and for nsurlconnection, it is-connection from the delegate method: Willsendrequestforauthenticationchallenge: Callback back in the parameter challenge gets ([Challenge.protectionspace serverTrust]).

2). Use the system default authentication method to verify the trust Object. Sectrustevaluate will evaluate the validity of the certificate by verifying the validity of each level of digital signature on the certificate chain (explained in the previous section), based on the authentication strategy of the Trust object, first-level upwards.

3). If the second step verification is passed, the general security requirements can be directly verified through, into the next step: Use Trust object to generate a voucher ([nsurlcredential credentialfortrust:servertrust]), The sender of the incoming challenge ([Challenge.sender usecredential:cred forauthenticationchallenge:challenge]) processes and establishes the connection.

4). If there is a stronger security requirement, you can continue to validate the trust object more rigorously. A common way is to import the certificate locally to verify that the Trust object matches the imported certificate. There are more ways to view enforcing stricter Server Trust Evaluation, which is explained in the Afnetworking source code.

5). If the validation fails, cancel the Challenge-response authentication verification process and reject the connection request.

PS: If it is a self-built certificate, it will skip the second step and use the third to verify that the digital signature of the root CA for the self-built certificate is not in the operating system's trust list.

The API and process for iOS authorization validation is probably understood, and below, let's look at the code implementation in Nsurlconnection:

Using Nsurlconnection to support HTTPS implementations

 Now start the connectionNSURL * httpsURL = [NSURL  urlwithstring:@ "Https://www.google.com"];self.connection = [nsurlconnection  connectionwithrequest:[nsurlrequest requestwithurl:httpsurl] delegate:self];     Callback-  (void) connection: (nsurlconnection *) Connection willsendrequestforauthenticationchallenge :(nsurlauthenticationchallenge *) challenge {    //1) Get trust object     SecTrustRef trust = challenge.protectionSpace.serverTrust;     SECTRUSTRESULTTYPE RESULT;        //2) Sectrustevaluate the Trust to verify the     osstatus status = sectrustevaluate (trust,  &result);    if  (status == errsecsuccess &&          (result == ksectrustresultproceed | |         result == ksectrustresultunspecified))  {                 //3) Verify success, Generate Nsurlcredential voucher cred, telling challenge sender to use this voucher to continue the connection          nsurlcredential *cred = [nsurlcredential credentialfortrust:trust];         [challenge.sender usecredential:cred forauthenticationchallenge: challenge];            } else {             //5) validation failed, cancel this verification process          [challenge.sender cancelAuthenticationChallenge:challenge];           }}

The

Above is the code that validates the certificate through the system default validation process. What if we were the self-built certificate? In this way, the certificate of the server inside the trust object is not issued by a trusted CA, so it is not successful to authenticate directly with Sectrustevaluate. Or, even if the certificate returned by the server is issued by a trusted CA, how do you determine if the certificate is the specific certificate we want? This requires that you import the certificate locally, set it to the anchor Certificate (which is the root certificate) that needs to be validated, and then call Sectrustevaluate to verify. The code is as follows

Import the certificate first nsstring * cerpath = ...; Path to the  //certificate nsdata * cerdata = [nsdata datawithcontentsoffile:cerpath]; Seccertificateref certificate = seccertificatecreatewithdata (NULL,  (__bridge  CFDATAREF) (Cerdata)); self.trustedcertificates = @[cfbridgingrelease (certificate)];//callback-  (void) Connection: (nsurlconnection *) Connection willsendrequestforauthenticationchallenge: ( nsurlauthenticationchallenge *) challenge {    //1) Get trust object     SecTrustRef trust = challenge.protectionSpace.serverTrust;     sectrustresulttype result;    //Note: This will set the previously imported certificate to the Trust object of the following authentication anchor  certificate    sectrustsetanchorcertificates (trust,  (__BRIDGE CFARRAYREF) self.trustedcertificates);     //2) Sectrustevaluate will look for certificates previously sectrustsetanchorcertificates set or system defaultThe certificate provided, the trust is verified     osstatus status = sectrustevaluate (trust, & Result);    if  (status == errsecsuccess &&          (result == ksectrustresultproceed | |         result == ksectrustresultunspecified))  {                 //3) Verify success, Generate Nsurlcredential voucher cred, telling challenge sender to use this voucher to continue the connection          nsurlcredential *cred = [nsurlcredential credentialfortrust:trust];         [challenge.sender usecredential:cred forauthenticationchallenge: challenge];            } else {             //5) validation failed, cancel thisVerification Process         [challenge.sender cancelauthenticationchallenge: challenge];          }}

It is recommended to validate the certificate in a way that imports the certificate locally to ensure sufficient security. For more verification methods, please see the Official document "HTTPS Server Trust Evaluation"

Using afnetworking to support HTTPS

Afnetworking is one of the most popular third-party open source repositories developed by Ios/osx, the author of the very famous IOS/OSX developer Mattt Thompson, whose blog Nshipster is also a great place for IOS/OSX developers to learn and broaden their technical horizons. Afnetworking has already encapsulated the above logic code, even more perfect, in the Afsecuritypolicy file, interested in reading the code of this module;

Configuring HTTPS support on Afnetworking is simple:

nsurl * url = [nsurl urlwithstring:@ "https://www.google.com"]; Afhttprequestoperationmanager * requestoperationmanager = [[afhttprequestoperationmanager  alloc] initwithbaseurl:url];d Ispatch_queue_t requestqueue = dispatch_create_serial_ Queue_for_name ("Krequestcompletionqueue");requestoperationmanager.completionqueue = requestqueue; Afsecuritypolicy * securitypolicy = [afsecuritypolicy policywithpinningmode: afsslpinningmodecertificate];//allowinvalidcertificates  whether to allow invalid certificates (that is, self-built certificates), default is no//if you need to verify the self-built certificate, Need to be set to yessecuritypolicy.allowinvalidcertificates = yes;//validatesdomainname  if you need to verify the domain name, default to yes;// If the domain name of the certificate does not match the domain name you requested, you need to set it to no//primarily for this situation: the client is requesting a subdomain, and the certificate is on a different domain name. Because the domain name on the SSL certificate is independent, if the domain name registered on the certificate is www.google.com, then mail.google.com cannot be verified; Of course, the rich can register the wildcard name *.google.com, but this is still relatively expensive. securitypolicy.validatesdomainname = no;//validatescertificatechain  if the entire certificate chain is validated, the default is yes//set to Yes, will be servedThe certificate chain on the Trust object returned by the service is compared to the locally imported certificate, which means that if your certificate chain is such://geotrust global ca //     google internet authority g2//        *. google.com//then, in addition to importing *.google.com, you need to import all the CA certificates on the certificate chain (geotrust global ca, google internet  AUTHORITY G2);//If the certificate is self-built, it can be set to Yes, enhanced security, if it is a certificate issued by a trusted CA, it is recommended to turn off the validation ;securitypolicy.validatescertificatechain = no;requestoperationmanager.securitypolicy =  securitypolicy;

This is afnetworking to support the main configuration of HTTPS, Afhttpsessionmanager with the Basic agreement, will not repeat.

3. Summary

Although HTTPS compared to HTTP, there will be a certain performance disadvantage, but for the rapid development of the network, mobile device performance doubled today, security is more we should consider. The whole network HTTPS is not so far away.

Stay tuned for the security of memory data security and persistent data.

Creating a secure app! HTTPS for the iOS security series

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.