One of the iOS Security series: HTTPS

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

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 jailbroken iOS devices, malware intrusion (non-jailbreak) is largely eliminated due to the powerful sandbox and authorization mechanism, and Apple's own app Store. But in addition to 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, the analysis of the various security problems we often encounter, and put forward the usual solution, Exchange and study with fellow students.

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.

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, which is usually sent to the client by the server, and the receiver verifies whether the certificate is trusted by a trusted CA or is relative to the local certificate, and 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. In this way, both 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 can not 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 contained in the certificate of the holder information and public key are provided by the applicant, and the digital signature is the CA authority to hash the contents of the certificate obtained, and this digital signature is that we verify that the certificate is a trusted CA-issued data.

Assume that the certificate was issued by a certificate authority, CA1.

1) received a copy of the digital certificate Cer1, the contents of the certificate to do hash to get H1;

2) Find the public key from the CA1 certificate of the institution that issued the certificate, decrypt the digital signature on the certificate, get the hash digest H2 of the certificate Cer1 signature;

3) Comparing H1 and H2, such as equality, indicates that the certificate has not been tampered with.

4) 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.

The general operating system and browser only contains the certificate of the root CA authority, while configuring the Web server HTTPS, will also configure the entire certificate chain, so the entire verification process from the last leaf node certificate, with the parent node check child nodes, a layer of validation of the entire certificate chain credibility.

A metaphor: parent (Root CA digital certificate)-Child (CA digital certificate)-grandchild (digital certificate) Three generations, assuming that the father has no other brothers (equivalent to the root CA is unique), if the child and the parent DNA paternity test, detection of DNA site (i.e. certificate signature) the same, it is basically determined that the child is born by the father , Sun and son. This makes it possible to make sure that the sun is a parent, the rightful heir to the parent (Root CA digital certificate). The verification of digital certificates is based on the same principle.

Basic Constraint Checksum Vulnerability

Does that matter how many layers you can keep trusting? Theoretically, it is possible, but there is a problem. Suppose I purchased a certificate from a trusted CA institution, will the certificate issued with this certificate also be trusted by the operating system and the browser? Obviously should not believe, because I am not a CA agency, if I issued a certificate is also trusted, then I can issue any domain name of the certificate for forgery attacks. This is the well-known basic constraint checksum vulnerability, and the basic constraint in the certificates contains the maximum depth that is not a CA authority, and a valid certificate path (that is, The CA can also continue to issue the CA authority certificate and its path depth for issuing the child CA certificate. But a few years ago, both Microsoft and Apple had a loophole that did not properly verify the information.

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 scenarios, and for nsurlconnection, it is -connection:willSendRequestForAuthenticationChallenge: obtained from the parameter challenge returned by the delegate method callback ( [challenge.protectionSpace serverTrust] ).

2). Use the system default authentication method to verify the trust Object. The validity of SecTrustEvaluate the certificate is assessed 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 of verification passed, the general security requirements, you can directly verify through, into the next: Use Trust object to generate a voucher ( [NSURLCredential credentialForTrust:serverTrust] ), incoming Challenge sender ( [challenge.sender useCredential:cred forAuthenticationChallenge:challenge] ) processing, establish a 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, then the second system default authentication method is not used, because the digital signature of the root CA of the self-built certificate is not in the operating system 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 the Trust objectSectrustref Trust =Challenge.protectionSpace.serverTrust;  Sectrustresulttype result; //p) Sectrustevaluate Authentication to trustOsstatus status = Sectrustevaluate (Trust, &Amp;result); if(Status = = Errsecsuccess) &&(Result= = Ksectrustresultproceed | | (result==ksectrustresultunspecified)) {//3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential to continue connectionnsurlcredential*cred =[Nsurlcredential Credentialfortrust:trust];  [Challenge.sender usecredential:cred Forauthenticationchallenge:challenge]; } Else{//5) Verification failure, cancel this verification process[Challenge.sender Cancelauthenticationchallenge:challenge]; }}

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 SecTrustEvaluate is not successful to authenticate directly with it. 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 the local import of the certificate, set to participate in the validation of the anchor Certificate (anchor certificate, by SecTrustSetAnchorCertificates setting the participating Check anchor certificate, if the verified digital certificate is the child node of this anchor certificate, That is, the verified digital certificate is issued by the corresponding CA or sub-CA of the anchor certificate, or the certificate itself, the certificate is trusted, and then called SecTrustEvaluate to verify. The code is as follows

//Import the certificate firstNSString* Cerpath = ...;//path to the certificateNSData* 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 the Trust objectSectrustref Trust=Challenge.protectionSpace.serverTrust; Sectrustresulttype result;//Note: Here the previously imported certificate is set to the anchor certificate of the Trust object as verified belowSectrustsetanchorcertificates (Trust, (__bridge cfarrayref) self.trustedcertificates); //p) Sectrustevaluate will find the certificate set by the previous sectrustsetanchorcertificates or the default certificate provided by the system to verify the trust .osstatus Status= Sectrustevaluate (Trust, &Amp;result); if(Status = = Errsecsuccess) &&(Result= = Ksectrustresultproceed | | (result==ksectrustresultunspecified)) {//3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential to continue connectionnsurlcredential*cred =[Nsurlcredential Credentialfortrust:trust];  [Challenge.sender usecredential:cred Forauthenticationchallenge:challenge]; } Else{//5) Verification failure, cancel this verification 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 to No//If you need to validate your self-built certificate, you need to set it to Yessecuritypolicy.allowinvalidcertificates=YES;
//Validatesdomainname If you need to verify the domain name, the default is yes;//if the domain name of the certificate does not match the domain name you requested, you need to set the entry to no, and if it is set to No, the server can also establish a connection by using a certificate issued by another trusted authority, which is very dangerous and is recommended to be opened. //set to No, mainly used in this case: the client is requesting a subdomain, and the certificate is 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. //if set to No, it is recommended that you add the check logic for the corresponding domain name. Securitypolicy.validatesdomainname=YES;
//Validatescertificatechain whether to validate the entire certificate chain, the default is Yes//set to Yes, the certificate chain on the trust object returned by the server is compared to the locally imported certificate, which means that if your certificate chain is this://geotrust Global CA//Google Internet Authority G2//*.google.com//then, in addition to importing *.google.com, you also need to import all 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 authentication, because the entire certificate chain one by one is not necessary (see source code);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.

One of the iOS Security series: HTTPS

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.