Https security verification

Source: Internet
Author: User
Tags openssl x509 subdomain name

Https security verification

Recently, in order to meet Apple's https requirements, I finally wrote a method

Verify that the SSL Certificate meets ATS requirements

Nscurl -- ats-diagnostics -- verbose https: // your domain name

PASS meets requirements

Output ATS-compliant certificates

Openssl s_client-connect your domain name: 443 </dev/null 2>/dev/null | openssl x509-outform DER> https. cer

1. For AFNetWorking (versions earlier than 2.6.0)

AFSecurityPolicy has three authentication modes:

AFSSLPinningModeNone

This mode indicates that SSL pinning is not performed,
Verify the certificate returned by the server only in the trusted organization list of the system, just like the browser. If the certificate is issued by a trusted organization, it will pass, and if it is generated by your server, it will not pass.

AFSSLPinningModeCertificate

This mode indicates that the certificate is verified by using the certificate binding method. The client needs to save a copy of the certificate from the server. Here, the verification is divided into two steps. The first step is to verify the domain name validity period and other information of the certificate, the second step is to compare whether the certificate returned by the server is consistent with that returned by the client.

AFSSLPinningModePublicKey

This mode is also verified by certificate binding. The client must have a copy of the server certificate,
Only the public key in the certificate is verified, and the validity period of the certificate is not verified. As long as the Public Key is correct, communication will not be eavesdropped, because the intermediary does not have a private key and cannot unbind data encrypted by the public key.

 

//The SSL certificate issued by the organization that is new to the app

AFSecurityPolicy * securityPolicy = [AFSecurityPolicy policyWithPinningMode: AFSSLPinningModeCertificate];

// Whether allowInvalidCertificates allows invalid certificates (that is, self-built Certificates). The default value is NO // if you need to verify the self-built certificate, you need to set it to YES

SecurityPolicy. allowInvalidCertificates = YES;

// Verify the domain name of validatesDomainName. The default value is YES;

// If the Domain Name of the certificate is inconsistent with the domain name you requested, set this item to NO. If it is set to NO, that is, the server uses the certificate issued by other trusted organizations, you can also establish a connection, which is very dangerous. It is recommended to open it.

// Set it to NO, which is mainly used in this case: the client requests a subdomain name while the certificate has another domain name. Because the domain names on the SSL certificate are independent, if the domain name registered on the certificate is www.google.com, then mail.google.com cannot be verified. Of course, if you have money, you can register a wildcard domain name * .google.com, however, this is expensive.

// If it is set to NO, we recommend that you add the validation logic for the corresponding domain name.

SecurityPolicy. validatesDomainName = YES;

// ValidatesCertificateChain: whether to verify the entire certificate chain. The default value is YES.

// If it is set to YES, the certificate chain on the Trust Object returned by the server will be compared with the locally imported certificate, which means that if your certificate chain is like this:

// GeoTrust Global CA // Google Internet Authority G2

// * .Google.com // In addition to importing * .google.com, you also need to import all the CA certificates (GeoTrust Global CA, Google Internet Authority G2) on the certificate chain );

// If the self-built certificate is used, you can set YES to enhance security. If the certificate is issued by a trusted CA, we recommend that you disable the authentication, because the one-to-one comparison of the entire certificate chain is completely unnecessary (please check the source code );

SecurityPolicy. validatesCertificateChain = NO; // not required before 2.6.0.

RequestOperationManager. securityPolicy = securityPolicy;

// Self-built Certificate

You also need to import the certificate to the local project and add the following code in days

NSData * cerData = [self getSSLCerByCerName: @ "Name of the local SSL Certificate"];
[SecurityPolicy setPinnedCertificates: @ [cerData];

// Obtain the SSL Certificate

+ (NSData *) getSSLCerByCerName :( NSString *) cerName {
NSString * cerPath = [[NSBundle mainBundle] pathForResource: cerName
OfType: @ "cer"];
NSData * certData = [NSData dataWithContentsOfFile: cerPath];
Return certData;
}

 

2. For NSURLConnection

API for verifying the certificate

The verification process for related APIs in the Security Framework is as follows:

1). First, obtain the trusted Object to be verified ). This Trust Object is obtained differently in different application scenarios. For NSURLConnection, it is obtained from the delegate method.-connection:willSendRequestForAuthenticationChallenge:Obtain from the callback parameter challenge ([challenge.protectionSpace serverTrust]).

2). Verify the Trust Object by default.SecTrustEvaluateThe validity of each level of digital signature on the certificate chain will be verified based on the Trust Object verification policy at the first level (the last part is explained) to evaluate the validity of the certificate.

3). If the Second Step passes the verification, you can directly pass the verification under general security requirements and go to the next step: generate a credential using the Trust Object ([NSURLCredential credentialForTrust:serverTrust]), Passed in the sender of challenge ([challenge.sender useCredential:cred forAuthenticationChallenge:challenge]) Process and establish a connection.

4). If you have higher security requirements, you can continue to perform more rigorous verification on the Trust Object. A common method is to import a certificate locally to verify that the Trust Object matches the imported certificate. For more methods, see Enforcing Stricter Server Trust Evaluation. This part is explained in the AFNetworking source code.

5) if the verification fails, cancel the Challenge-Response Authentication verification process and reject the connection request.

Ps: if the certificate is self-built, the default verification method of step 2 is not used, because the digital signature of the Root CA of the self-built certificate is not in the Trust List of the operating system.

The API and process for iOS authorization verification are generally understood. Next, let's look at the code implementation in NSURLConnection:

 

// NSURLConnection Https security verification
-(BOOL) connection :( NSURLConnection *) connection canAuthenticateAgainstProtectionSpace :( NSURLProtectionSpace *) protectionSpace {
Return [protectionSpace. authenticationMethod isinclutostring: NSURLAuthenticationMethodServerTrust];
}
// Self-built certificates are not trusted by security organizations.
-(Void) connection :( NSURLConnection *) connection willSendRequestForAuthenticationChallenge :( NSURLAuthenticationChallenge *) challenge {
Static CFArrayRef certs;
If (! Certs ){
NSData * certData = [NSData dataWithContentsOfFile: [NSBundle mainBundle]
PathForResource: @ "Name of the SSL certificate in the local project" ofType: @ "cer"];
SecCertificateRef rootcert
= SecCertificateCreateWithData (kCFAllocatorDefault, CFBridgingRetain (certData ));
Const void * array [1] = {rootcert };
Certs = CFArrayCreate (NULL, array, 1, & kCFTypeArrayCallBacks );
CFRelease (rootcert );
}

SecTrustRef trust = [[challenge protectionSpace] serverTrust];
// A certificate corresponds to multiple domain names without domain name verification
NSMutableArray * policies = [NSMutableArray array];
// BasicX509 does not verify whether the domain name is the same
SecPolicyRef policy = SecPolicyCreateBasicX509 ();
[Policies addObject :( _ bridge_transfer id) policy];
SecTrustSetPolicies (trust, (_ bridge CFArrayRef) policies );
Int err;
SecTrustResultType trustResult = 0;
Err = SecTrustSetAnchorCertificates (trust, certs );
If (err = noErr ){
Err = SecTrustEvaluate (trust, & trustResult );
}
CFRelease (trust );
// KSecTrustResultUnspecified: The system implicitly trusts this certificate.
// KSecTrustResultProceed: the user adds his/her own trust anchor and explicitly tells the system that the certificate is trustworthy.
BOOL trusted = (err = noErr)
& (TrustResult = kSecTrustResultProceed)
| (TrustResult = kSecTrustResultUnspecified ));
If (trusted ){
[Challenge. sender useCredential: [NSURLCredential credentialForTrust: challenge. protectionSpace. serverTrust]
ForAuthenticationChallenge: challenge];
} Else {
[Challenge. sender cancelAuthenticationChallenge: challenge];
}
}


// The SSL certificate is authorized by a trusted institution and does not need to be stored locally.
-(Void) connection :( NSURLConnection *) connection willSendRequestForAuthenticationChallenge :( NSURLAuthenticationChallenge *) challenge {
// 1) obtain the trust object
SecTrustRef trust = challenge. protectionSpace. serverTrust;
SecTrustResultType result;

// A certificate corresponds to multiple domain names without domain name verification
NSMutableArray * policies = [NSMutableArray array];
// BasicX509 does not verify whether the domain name is the same
SecPolicyRef policy = SecPolicyCreateBasicX509 ();
[Policies addObject :( _ bridge_transfer id) policy];
SecTrustSetPolicies (trust, (_ bridge CFArrayRef) policies );

// 2) SecTrustEvaluate verifies the trust.
OSStatus status = SecTrustEvaluate (trust, & result );
If (status = errSecSuccess &&
(Result = kSecTrustResultProceed |
Result = kSecTrustResultUnspecified )){
// 3) if the verification succeeds, the NSURLCredential credential cred is generated and the challenge sender is notified to use this credential to continue the connection.
NSURLCredential * cred = [NSURLCredential credentialForTrust: trust];
[Challenge. sender useCredential: cred forAuthenticationChallenge: challenge];

} Else {
// 5) The verification fails. Cancel the verification process.
[Challenge. sender cancelAuthenticationChallenge: challenge];
}
}

 

Related Article

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.