IOS9 all HTTP requests to https: The IOS9 system sends a network request that uses TLS 1.2 SSL uniformly. With the TLS 1.2 protocol, the purpose is to enforce enhanced data access security, and related network requests under the System Foundation framework will no longer default to unsecured network protocols such as Http, and TLS 1.2 is used by default. The server therefore needs to be updated to parse the relevant data. If not updated, you can reverse the unsecured network request by declaring it in Info.plist.
For example: If the original HTTP is a plastic pipe, easy to be punctured, then the new design of HTTPS today is like in the original plastic pipe, and then a layer of metal pipe. As a result, the original plastic pipe is still running, and secondly, after being reinforced with metal, it is not easy to be punctured.
Currently, the most widely used is TLS 1.0, followed by SSL 3.0. However, the majority of browsers have implemented TLS 1.2 support.
Apple lets your HTTP use the SSL/TLS protocol, which lets you go from http to https
HTTP communications that do not use SSL/TLS are non-encrypted communications!
All information is transmitted in plaintext, bringing three major risks:
Eavesdropping risk (eavesdropping): Third parties can learn the content of the communication.
Tamper risk (tampering): Third parties may modify the communication content.
Impersonation risk (pretending): A third party can participate in the communication by impersonating another person.
The SSL/TLS protocol is designed to address these three risks and is expected to achieve:
All information is encrypted and third parties cannot eavesdrop.
With the verification mechanism, once tampered with, the communication parties will immediately find.
Equipped with identity card to prevent identity from being impersonated.
The TLS 1.2 protocol enforces enhanced network requests under the framework of the data access security system Foundation and will no longer default to unsecured network protocols such as Http, with TLS 1.2 being used by default. The server therefore needs to be updated to parse the relevant data. If not updated, you can reverse the unsecured network request by declaring it in Info.plist.
Scenario One: Immediately let the company's server upgrade use TLS 1.2
Scenario Two: Although Apple does not recommend, but can be declared in the Info.plist, back to the insecure network request will still allow the app to access the specified HTTP, or even arbitrary HTTP,
See GIF diagram for a sample demo see Demo1
As the official Apple document says:
The XML source in the Info.plist configuration is as follows:
1234 |
nsapptransportsecurity nsexceptiondomains yourserver.com nsincludessubdomains nstemporaryexceptionallowsinsecurehttploads nstemporaryexceptionminimumtlsversion tlsv1.1 |
If your application (a Third-party Web browser, for instance) needs to connect to arbitrary hosts, you can configure it Li Ke this:
12 |
NSAppTransportSecurity NSAllowsArbitraryLoads |
Disclaimer: Currently Apple's official documentation does not mention how to configure the Info.plist, I will closely follow the official documentation, if mentioned, and then update this article.
Access to HTTP and HTTPS protocols in iOS
A recent project started with the HTTP protocol for client-server interaction, which later needed to be changed to the HTTPS protocol. Some problems were identified during the modification, and the solution was as follows:
HTTP:
NSString *urlstring =[nsstring stringwithformat:@ "https://127.0.0.1/default.aspx?user=%@" @ "111"];
Nsmutableurlrequest *request = [[[[Nsmutableurlrequest alloc] init] autorelease];
[Request Seturl:[nsurl urlwithstring:urlstring];
[Request sethttpmethod:@ "GET"];
nshttpurlresponse* urlresponse = nil;
Nserror *error = [[Nserror alloc] init];
NSData *responsedata = [nsurlconnection sendsynchronousrequest:request returningresponse:&urlresponse Error: &error];
nsmutablestring *result = [[Nsmutablestring alloc] Initwithdata:responsedata encoding:nsutf8stringencoding];
NSLog (@ "The result string is:%@", result);
HTTPS
Event triggering
{
NSString *urlstring =[nsstring stringwithformat:@ "https://127.0.0.1/default.aspx?user=%@" @ "111"];
Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] Initwithurl:[nsurl urlwithstring:urlstring] CachePolicy : Nsurlrequestreloadignoringlocalcachedata Timeoutinterval:5];
Set request mode to get
[Request sethttpmethod:@ "GET"];
Add user session ID
[Request addvalue:@ "text/html" forhttpheaderfield:@ "Content-type"];
Connection Send Request
Finished = false;
Nsurlconnection *conn = [[Nsurlconnection alloc] initwithrequest:request delegate:self];
Plug the thread, wait for the end
while (!finished) {
[[Nsrunloop Currentrunloop] Runmode:nsdefaultrunloopmode beforedate:[nsdate Distantfuture]];
}
}
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (nsurlresponse*) response
{}
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
[_waitingdialog dismisswithclickedbuttonindex:0 Animated:no];
[Connection release];
}
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error
{
}
-(BOOL) Connectionshouldusecredentialstorage: (nsurlconnection *) connection{
return NO;
}
The following two paragraphs are the focus, to server-side single-HTTPS authentication, the IOS client ignores certificate validation.
-(BOOL) connection: (Nsurlconnection *) connection canauthenticateagainstprotectionspace: (Nsurlprotectionspace *) Protectionspace {
return [Protectionspace.authenticationmethod Isequaltostring:nsurlauthenticationmethodservertrust];
}
-(void) connection: (Nsurlconnection *) connection Didreceiveauthenticationchallenge: (Nsurlauthenticationchallenge * ) Challenge {
NSLog (@ "Didreceiveauthenticationchallenge%@%zd", [[Challenge Protectionspace] authenticationmethod], (ssize_t) [ Challenge Previousfailurecount]);
if ([Challenge.protectionSpace.authenticationMethod Isequaltostring:nsurlauthenticationmethodservertrust]) {
[[Challenge Sender] Usecredential:[nsurlcredential CredentialForTrust:challenge.protectionSpace.serverTrust] Forauthenticationchallenge:challenge];
[[Challenge Sender] continuewithoutcredentialforauthenticationchallenge:challenge];
}
}
NSLog (@ "Get the whole response");
[Receiveddata setlength:0];
}
Working with Data
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
}
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:
- Digital Certificate: The certificate contains information such as the public key, usually by the server to the client, 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 side authentication;
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.
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 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 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, 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 = [Nsurlcon Nection connectionwithrequest:[nsurlrequest Requestwithurl:httpsurl] delegate:self];//callback-(void) connection: ( Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: (Nsurlauthenticationchallenge *) Challenge { 1) Acquire Trust object Sectrustref Trust = Challenge.protectionSpace.serverTrust; Sectrustresulttype result; 2) sectrustevaluate authentication to trust osstatus status = Sectrustevaluate (trust, &result); if (status = = Errsecsuccess && (result = = Ksectrustresultproceed | | result = = ksectrustresultunspecified) {//3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential to continue the connection Nsur Lcredential *cred = [nsurlcredential credentialfortrust:trust]; [Challenge.sender usecredential:cred Forauthenticationchallenge:challenge]; } else {//5) validation failed, canceling this validation 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 that the certificate be imported locally, set to anchor Certificate (which is the root certificate) that needs to be validated, and then called SecTrustEvaluate
to verify. The code is as follows
First Import Certificate NSString * Cerpath = ...; The path of 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 SecTrustRe F trust = Challenge.protectionSpace.serverTrust; Sectrustresulttype result; Note: Here, the previously imported certificate is set to the anchor Certificate Sectrustsetanchorcertificates (trust, __bridge Cfarrayref) of the Trust object as verified below Self.trustedcertificates); 2) Sectrustevaluate will find the certificate set by the previous sectrustsetanchorcertificates or the default certificate provided by the system, verify the trust osstatus status = Sectrustevaluate (trust, &result); if (status = = Errsecsuccess && (result = = Ksectrustresultproceed | | result = = ksectrustresultunspecified) {//3) Verify success, generate Nsurlcredential voucher cred, tell challenge sender to use this credential toContinue to connect nsurlcredential *cred = [nsurlcredential credentialfortrust:trust]; [Challenge.sender usecredential:cred Forauthenticationchallenge:challenge]; } else {//5) validation failed, canceling this validation 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), the default is no//if you need to verify 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 this 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 Verifies the entire certificate chain, default is yes//set to Yes, will return the trust of the server The certificate chain on the object 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//that , except import *Google.com, you will also need to import all CA certificates on the certificate chain (GeoTrust Global CA, Google Internet Authority G2), or, if you are building your own certificate, you can set it to Yes for 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.
More secure HTTPS