preface

HTTPS is an HTTP protocol that can be understood as a secure channel. On the basis of HTTP transmission, HTTPS authenticates and transmits contents in ciphertext mode. The following describes what HTTPS does

https

The HTTPS request process can be divided into two parts: asymmetric encryption and decryption using public and private keys for authentication (public to private or private to public encryption and decryption), and symmetric encryption for data transmission

In this way, the identities of both parties can be verified more securely, and the contents can be transmitted at high speed to the maximum extent. The process of symmetric encryption and decryption requires the secret key, so the process of obtaining the secret key is obtained during the authentication of both parties

After the authentication of the first HTTPS request, the secret key will be obtained, so the following network requests do not need to authenticate the identity, and can be directly carried out with the secret key. When the application is reopened, the identity needs to be re-verified and the secret key updated

Therefore, the HTTPS interaction process goes through the following steps:

1. After three handshakes between the client and the server, the client sends the SSL version information. The client random_C (random number random_client on the client) and the encryption algorithm is sent to the server

2. The server returns the SSL version, random_s(random number random_server on the server), server certificate, and public key to the client

3, the client verify whether the certificate is legal, legal to continue, otherwise issued a warning (the most obvious is the browser open location page)

4. After the client verification is completed, it will pass its supported symmetric encryption scheme to the server for its choice

5. After receiving a supported symmetric encryption mode, the server selects an encryption mode with a higher degree of encryption

6. The server sends the selected symmetric encryption mode to the client in plain text

7. After receiving the encryption method, the client generates a random code pre-master, which serves as the symmetric encryption key. After encrypting with the public key, the client sends the code to the server

8. After receiving the encrypted message, the server used the private key to decrypt it, got the random code of the client, and combined it into the secret key (random_c + pre-master + random_s).

9. Use the encryption key for symmetric encryption and decryption, and start communication

That is, steps 1 to 8 are the authentication process, and step 9 is the formal transmission process

You can also see an important file in THE HTTPS transfer, the SSL certificate, which is usually purchased from an SSL agent. When purchased, the certificate and key are obtained

The interaction diagram is shown below

Most of these steps are done with the help of the system, which will be explained later with AFNetworking

AFNetworking’s Challenge

The Challenge callback method is found in AFNetworking, and this is where the HTTPS challenges are addressed

As shown in the figure below, AFNetworking eventually uses NSURLSession to make the request. The server returns 401 Access Denied for the HTTPS request. This is where the client needs to process the Challenge. The challenge process is where we get the public key of the certificate, and what we need to do in the challenge is verify the certificate

The code for handling the challenge challenge in AFNetworking is shown below

// The challenge processing type is default
/ * NSURLSessionAuthChallengeUseCredential: using the specified certificate NSURLSessionAuthChallengePerformDefaultHandling: The default process NSURLSessionAuthChallengeCancelAuthenticationChallenge: Cancel NSURLSessionAuthChallengeRejectProtectionSpace challenge: to reject the challenge and try a validation to protect space; Ignore the certificate parameter */
// Security authentication policy for the certificate
typedef NS_ENUM(NSUInteger, AFSSLPinningMode) {
     // Do not authenticate the server using fixed certificates (local). Verify directly from the list of trusted authorities IN the client system
    AFSSLPinningModeNone,
    // The representative verifies the PublicKey in the certificate returned by the server. If the PublicKey passes, the PublicKey passes; otherwise, the PublicKey does not pass
    AFSSLPinningModePublicKey,
    // The representative verifies both the certificate returned by the server and the local certificate. If the certificate is passed, the certificate is passed; otherwise, the certificate is not passed
    AFSSLPinningModeCertificate,
};

- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler: (void (^)(NSURLSessionAuthChallengeDisposition disposition,
     NSURLCredential *credential))completionHandler
{
    // The challenge processing type is default
    NSURLSessionAuthChallengeDisposition disposition = 
        NSURLSessionAuthChallengePerformDefaultHandling;

    // Certificate Indicates the certificate
    __block NSURLCredential *credential = nil;/ / certificate

    // A custom approach to how to address server-side authentication challenges
    if (self.sessionDidReceiveAuthenticationChallenge) {
        disposition = self.sessionDidReceiveAuthenticationChallenge
            (session, challenge, &credential);
    } else {
        // 1. Determine whether the receiving server challenge method is a trust certificate (certificate verification)
        if ([challenge.protectionSpace.authenticationMethod 
            isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            //SecTrustRef(serverTrust): specifies the object to be authenticated, which contains the certificate to be authenticated (provided by the server) and the supported authentication methods
            // The default securityPolicy is AFSSLPinningModeNone. That is, the local certificate is not used for verification, that is, one-way authentication
            / / will generally put the SSL certificates in the local, set up AFSSLPinningModePublicKey and AFSSLPinningModeCertificate
            // Use the local certificate for verification, namely bidirectional authentication
            if ([self.securityPolicy 
                evaluateServerTrust:challenge.protectionSpace.serverTrust 
                forDomain:challenge.protectionSpace.host]) {
                 // 2. If the certificate verification succeeds, it takes out the trusted certificate from the protected space and calls back to the server
                credential = [NSURLCredential 
                    credentialForTrust:challenge.protectionSpace.serverTrust];
               // Define the challenge
                if (credential) {
                    // Certificate challenge
                    disposition = NSURLSessionAuthChallengeUseCredential;
                } else {
                    // Default challengedisposition = NSURLSessionAuthChallengePerformDefaultHandling; }}else {
                 // Cancel the challengedisposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; }}else {
            // Default challenge modedisposition = NSURLSessionAuthChallengePerformDefaultHandling; }}// Complete the challenge
    // 3. Send the trusted credentials to the server
    if(completionHandler) { completionHandler(disposition, credential); }}Copy the code

As can be seen above, the authentication mode requires the trust certificate. If yes, the authentication mode starts and the default challenge handling mode is used. Otherwise, the authentication mode must pass the authentication of the client

1. If the client authentication policy is default (AFSSLPinningModeNone), then verify from the list of trusted authorities and trusted cas. You can understand the one-way authentication process of the server, and the client has no precise authentication method (no original public key certificate).

There are also intermediaries that use homemade certificates, known as illegal certificates, by asking the user to download the certificate and trust it, so the certificate downloaded from the server will pass if it is consistent with the certificate. (This is also a man-in-the middle attack, such as Charles capture HTTPS, which lets you download a certificate and trust it.)

2, can be set to use the publicKey to verify (AFSSLPinningModePublicKey), public key way is to use local public key in the certificate of public key and returned by the server certificate, check, even if the server update certificate, as long as the public key is changeless, still can finish the checking, otherwise failure, Bidirectional authentication process for client and server

3 and join a local certificate file. (cer), USES the local certificate validation strategy (AFSSLPinningModeCertificate), using certificates compared with server SSL certificate validation, exactly the calibration certificate success, can continue to access, otherwise cancel the visit, Bidirectional authentication process for client and server

Generally, you do not need to customize the verification process. You only need to set the security policy and corresponding parameters when using the certificate. For example, the local certificate file is required for certificate verification.

// Obtain the local certificate
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];
NSData   *data    = [NSData dataWithContentsOfFile:cerPath];
// Add the certificate set
NSSet    *cerSet  = [NSSet setWithObject:data];
// Set the security policy for certificate verification to local certificate verification
AFSecurityPolicy *security = [AFSecurityPolicy 
    policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerSet];
//[AFSecurityPolicy defaultPolicy]; // This is the default if not set
// Enable certificate verification
security.allowInvalidCertificates = YES;
security.validatesDomainName      = NO; // Whether to verify the domain name

// Start the HTTPS network request
NSString *urlstr = @"XXX";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy        = [self securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:urlstr parameters:nil progress:nil 
success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

}];
Copy the code

conclusion

Before configuring HTTPS, you need to purchase an SSL certificate or use an SSL certificate that is free of charge. Generally, the server sends the certificate, and the client receives and verifies the certificate (one-way authentication, which is relatively dangerous). Generally, the client uses the local SSL certificate for bidirectional authentication, which is relatively secure

You can also guess through the above steps, when using a browser to access a web page is a scenario, the verification process is all done by the browser, and basically only from the market authority of the certificate trust list to verify

From the above HTTPS interaction process, we can see that the user can operate the HTTPS interaction process is actually very narrow range, mainly is the certificate authentication policy, and what the Internet said md5, SHA256, RSA for asymmetric encryption, which is not applied to HTTPS, generally used for user identity verification, password leakage prevention and so on

The HTTPS function can be easily understood as that asymmetric public and private keys are used to negotiate a secret key for encryption during transmission. The secret key is used to symmetrically encrypt the request and reponse information during transmission. The intercepted information on the network is ciphertext, which can be understood as that HTTPS is used at the transport layer

In the actual development, we need to further confirm the user’s operation and place the user to maliciously tamper with data. Generally, in the request parameters, the token of the user is used as the secret key, and the string is formed according to the request parameter information according to certain rules, and then the asymmetric encryption is used for encryption. After receiving the data (using the secret key to translate the transmitted content from the ciphertext to the plaintext), the server encrypts the data according to information such as the token and the negotiated encryption rules. Then, the server compares the request to the consistent party and executes the request

The token is a temporary token saved by the system for a user. The token will expire after a certain period of time. If the token is about to expire, you need to update it or re-log in to update it

The last

After HTTP is captured by the proxy, the plaintext return value is captured intact, while HTTPS receives ciphertext. How to capture packets without a secret key? Can you imagine where to start?

Note: Charles HTTPS capture process is a man-in-the-middle attack, you can refer to this article to understand HTTPS and man-in-the-middle attack

Each receiving knowledge is also a joy to share with you is the beginning of progress!