😊😊😊Alamofire thematic directory. Welcome timely feedback and exchange

  • Alamofire (1) – URLSession prerequisite skill
  • Alamofire (2) — Background download
  • Alamofire (3) — Request
  • Alamofire (4) — Details you need to know
  • Alamofire (5) — Response
  • Alamofire (6) — Multiple form uploads
  • Alamofire (7) — Safety certification
  • Alamofire (8) — Final Chapter (Network Monitoring & Notifications & Downloader Packaging)

Alamofire Directory through train — Harmonious learning, not impatient!


This chapter will cover HTTP security authentication. HTTP provides a range of technologies and machines that can be used to track identity, perform security checks, and control access to content. This article will help you understand why HTTPS is so important. Alamofire’s handling of safety certification will also be introduced

HTTP features

  • 1️ retail. Support client/server mode.

  • 2️ discount: when customers request service to the server, they only need to transmit the request method and path. The commonly used request methods are GET, HEAD and POST. Each method specifies a different type of contact between the client and the server. Because HTTP protocol is simple, the HTTP server program size is small, so the communication speed is very fast.

  • 3️ flexible: HTTP allows transmission of arbitrary types of data objects. The Type being transferred is marked by content-Type, which is the identifier used in the HTTP package to indicate the Content Type.

  • 4️ connectionless: The meaning of connectionless is to limit the processing of only one request per connection. The server disconnects from the customer after processing the request and receiving the reply from the customer. In this way, transmission time can be saved.

  • 5️ disstateless: HTTP is a stateless protocol. Stateless means that the protocol has no memory for transaction processing. The lack of state means that if the previous information is needed for subsequent processing, it must be retransmitted, which can result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it doesn’t need the previous information.

Because of these characteristics, flexible HTTP has many problems

  • Communication using plaintext [without encrypting the content]
  • Without authenticating the identity of the communicator, both the client and the server communicate at will
  • Unable to prove the integrity of the packet

Symmetric encryption & asymmetric encryption

  • 1️ : symmetric encryption: The secret key used for encryption and decryption in symmetric encryption is the same. That is, encryption and decryption are the same secret key. So the security of the secret key is very important, and the secret key must not be made public

Example: Suppose a Client and a Server communicate. They agree on a secret key. The Client uses the secret key to encrypt the transmission. The Server receives the message and decrypts it with the secret key. Such a communication process is symmetric encryption process.

Disadvantages: The disadvantage of symmetric encryption is that if the secret key is leaked, the communication between Client and Server is not secure

  • 2️ asymmetric encryption: there is a pair of secret keys called public key and private key, public key is public, everyone can own, but there is only one private key. Both public and private keys can be encrypted. However, only the private key can decrypt the ciphertext encrypted by the public key, and all the public keys encrypted by the private key can be decrypted. This is asymmetric encryption.

For example, if ClientA, ClientB, and ClientC communicate with the Server, the Server has a pair of public and private keys, retains its own unique private key, and exposes its own public key to the public. In this way, ClientA, ClientB, and ClientC can obtain their public keys. The ciphertext encrypted by ClientA’s public key can be decrypted only by the Server’s private key. In this way, the information transmitted by ClientA is secure, because even if an intermediate hacker obtains the ciphertext encrypted by the public key, the hacker cannot decrypt it without the private key.

Disadvantages: Asymmetric encryption only ensures that the message sent from the Client to the Server is secure, because there is only one private key in the Server’s hands, but conversely, the message sent from the Server to the Client is not secure, because the public key is available for everyone to download, so everyone can decrypt the information.

HTTPS Secure Transmission

Hypertext Transfer Protocol Secure (Hypertext Transfer Protocol Secure) HTTPS, often called HTTP over TLS, HTTP over SSL, or HTTP Secure, is a transport protocol for Secure communication over a computer network. HTTPS communicates over HTTP, but uses SSL/TLS to encrypt packets. HTTPS is developed to provide identity authentication for web servers and protect the privacy and integrity of exchanged data.

The encryption process

  • The server logs in its public key to the digital certificate Authority.
  • A digital certificate authority uses its own private key to digitally sign the server’s public password and issue a public key certificate.
  • After obtaining the public key certificate of the server, the client uses the public key of the DIGITAL Signature Authentication Authority to verify the digital signature on the public key certificate of the server.
  • Use the public key of the server to encrypt the packet and send it.
  • The server decrypts the message with the private key.

You can see the workflow, which is basically divided into three stages:

  • 1️ retail: authentication server. The browser has a trusted built-inCA institutionList and save theseCA institutionThe certificate. The first stage server provides the dataCA institutionAuthenticates the issued server certificate, if authenticates the server certificateCA institution, exists in the browser trustedCA institutionList, and the information in the server certificate is the same as the website (domain name, etc.) that is currently being visited, then the browser considers the server to be trusted and obtains the server public key from the server certificate for subsequent flow. Otherwise, the browser will prompt the user to decide whether to continue or not, depending on the user’s choice. Of course, we can manage this trustCA institutionList, add the ones we want to trustCA institutionOr remove what we don’t trustCA institution.
  • 2️ negotiation session key. After authenticating the server and obtaining the public key of the server, the client uses the public key to encrypt communication with the server and negotiates two session keys: the client session key for encrypting data sent from the client to the server, and the server session key for encrypting data sent from the server to the client. The reason why two symmetric keys need to be negotiated on the premise that a server public key can be used to encrypt communication is that asymmetric encryption is more complex. Symmetric encryption can save computing resources during data transmission. In addition, session keys are randomly generated, and each negotiation results are different. Therefore, session keys are secure.
  • 3️ encrypted communication. In this case, both the client and server have the session key for this communication. All subsequent Http data is encrypted using the session key. In this way, it is difficult for other users on the network to steal and tamper with the data transmitted between the client and the server, thus ensuring the privacy and integrity of the data.

Alamofire secure transmission

Let’s start with the visa verification process

1️ discount: configuration from visa information

fileprivate func lgtrustSession(a) -> SessionManager{
    
    let policies: [String:ServerTrustPolicy] = [
        hostUrl1: .pinCertificates(
            certificates: ServerTrustPolicy.certificates(),
            validateCertificateChain: false,
            validateHost: true),
        hostUrl2: .disableEvaluation,
        hostUrl3: .pinPublicKeys(
            publicKeys: ServerTrustPolicy.publicKeys(),
            validateCertificateChain: false,
            validateHost: true)]let sesionManager = SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
    return sesionManager
}
Copy the code
  • Parameter 1:certificatesIt stands for certificate
  • Argument 2:validateCertificateChainIndicates whether to validate the certificate chain
  • Parameter 3:validateHostIndicates whether the child address is verified

AlamofireThere are six modes of security authentication policy. The three modes are most commonly used:.pinCertificatesCertificate verification mode,.pinPublicKeysPublic key authentication mode and.disableEvaluationDo not validate schemas.

  • .performDefaultEvaluationBy default, only valid certificates can pass authentication
  • .performRevokedEvaluationAn additional setting for deregistering certificates
  • .pinCertificatesIn certificate verification mode, the client verifies the certificate returned by the server and the local certificate. If the certificate is correct, the client continues to perform the verification.
  • .pinPublicKeysIn public key authentication mode, the client combines the certificate returned by the server with the certificate saved locallyPublicKeyPart of the verification, if correct, continue to execute.
  • .disableEvaluationValidation under this option is always passed, unconditional trust.
  • .customEvaluationCustom validation, which returns a Boolean result.

2️ discount: Certificate and public key information acquisition

Here, the author used to traverse the whole project bundle to obtain the certificate

public static func certificates(in bundle: Bundle = Bundle.main)- > [SecCertificate] {
    var certificates: [SecCertificate] = []

    let paths = Set([".cer".".CER".".crt".".CRT".".der".".DER"].map { fileExtension in
        bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil)
    }.joined())

    for path in paths {
        if
            let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData.let certificate = SecCertificateCreateWithData(nil, certificateData)
        {
            certificates.append(certificate)
        }
    }
    return certificates
}
Copy the code
  • Walk through the bundle to get the entire project".cer", ".CER", ".crt", ".CRT", ".der", ".DER"And then the mapping splice
  • Get filedataData acquisition information
  • The same is true for the public key
public static func publicKeys(in bundle: Bundle = Bundle.main)- > [SecKey] {
    var publicKeys: [SecKey] = []

    for certificate in certificates(in: bundle) {
        if let publicKey = publicKey(for: certificate) {
            publicKeys.append(publicKey)
        }
    }
    return publicKeys
}
Copy the code

3️ discount

urlSession(
        _ session: URLSession,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition.URLCredential?). ->Void)
Copy the code
  • ChallengeIn order to authenticate the user, a challenge is sent to the visitor, who is then asked to provide a correct answer to identify himself or herself
  • URLProtectionSpaceThis represents a protected area on the server that requires a challenge to access. It has the following common attributes
// realm is the identifier for ProtectionSpace,
// A set of resources on the server are identified as protectionSpaces using the same authentication method through a realm.
open var realm: String? { get }
// Determine if the password for this protected space can be safely sent
open var receivesCredentialSecurely: Bool { get }
// The server where the resource resides
open var host: String { get }
// Port of the server where the resource resides
open var port: Int { get }
// If it is a proxy, get the type of this protected space
open var proxyType: String? { get }
// Get the protocol resource of the resource
open var `protocol` :String? { get }
// The challenge uses authentication
open var authenticationMethod: String { get }
Copy the code

The following challenge authentication methods are commonly used

  • NSURLAuthenticationMethodHTTPBasic: Basic HTTP authentication. The server asks the client for the user name and password
  • NSURLAuthenticationMethodClientCertificate: Client certificate authentication: The server queries the client for the identity certificate
  • NSURLAuthenticationMethodServerTrust:Certificate authentication on the server: The client verifies the certificate on the server. Server-side certificate authentication in HTTPS falls into this category.

UrlCredential

It is the client’s response to a server-side challenge. Depending on the authentication method, there are the following UrlCredential types:

  • Based on the user name and passwordUrlCredential
  • Based on the client certificateUrlCredential
  • Server-based certificateUrlCredential// This is what we use to verify the server side certificate
  • They correspond to thetaUrlCredentialThree ways of constructing.Refer to the Apple development documentation for details

SecTrust

  • For certificates and certificates in iOSAccept PolicyThe packaging. The system authenticates the background certificate by actually authenticating the object.Build Apple development documentation for details
  • CFType used to perform x.509 certificate trust assessment

The following specific code analysis

if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
    let host = challenge.protectionSpace.host
    // Returns a policy that exactly matches the given host
    if
        letserverTrustPolicy = session.serverTrustPolicyManager? .serverTrustPolicy(forHost: host),// Return a SecTrustRef that represents the state of the SSL transaction state of the server
        let serverTrust = challenge.protectionSpace.serverTrust
    {
        // Evaluates whether server trust is valid for a given host.
        if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
            disposition = .useCredential
            credential = URLCredential(trust: serverTrust)
        } else {
            disposition = .cancelAuthenticationChallenge
        }
    }
}
Copy the code
  • Returns the policy that exactly matches the given host
  • Returns a SecTrustRef that represents the state of the SSL transaction state of the server
  • Evaluates whether server trust is valid for a given host
  • The callback function tells the system what to do about the challengeUrlCredential

Verification method:public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool

  • PerformDefaultEvaluation strategy mode

    • Create a policy object that evaluates the SSL certificate chain
    • Set the policy that should verify trust toserverTrust
    • calltrustIsValidStart verifying matches
  • PerformRevokedEvaluation strategy mode

    • Create a policy object that evaluates the SSL certificate chain
    • Returns the policy object used to check for certificate revocation.
    • Set the policy that should verify trust toserverTrustHere is a group
    • calltrustIsValidStart verifying matches
  • . PinCertificates policy mode

    • If you validate the certificate chain
      • Create a policy object that evaluates the SSL certificate chain
      • Set the policy that should verify trust toserverTrust
      • Sets the anchor certificate for the given trust
      • In addition, re-enable the trust anchor certificate throughSecTrustSetAnchorCertificates API
      • calltrustIsValidStart verifying matches
    • If you do not validate the certificate chain
      • Obtain the trusted certificate information data
      • Gets all the certificate information groups currently passed in
      • Match If the certificate group information passed in contains trusted certificates, return true and useouterLoopOne jump straight out
  • . In pinPublicKeys mode

    • If you validate the certificate chain
      • Create a policy object that evaluates the SSL certificate chain
      • Set the policy that should verify trust toserverTrust
      • calltrustIsValidStart verifying matches
    • If you do not validate the certificate chain
      • Matches whether the incoming public key contains trusted public key information, returns true if it does, and usesouterLoopOne jump straight out
  • . DisableEvaluation In policy mode

    • serverTrustIsValid = trueNo authentication is required
  • . In customEvaluation policy mode

    • serverTrustIsValid = closure(serverTrust, host)Authentication processing closure is provided externally, and authentication policy scheme is provided by users themselves

Here we also provide a professional introduction to the certificate chain article

4️ discount: certificate completion, can direct normal communication!

conclusion

This article about security authentication involves the characteristics of HTTP and HTTPS, as well as encryption methods, and finally analyzes the security authentication of Alamofire. It seems that the process is complicated, which is actually a certificate or public key matching problem, but many iOS developers often do not want to get involved. Knowledge is dull and difficult to understand! However, the world is so great and beautiful that it is often far away and dangerous, and it is rare for people to see it. Therefore, it is impossible to reach it unless you are ambitious. IOS advanced advanced no other, is to sink down, seriously polish yourself! 💪 💪 💪

The next article begins with the protocol oriented programming section. Thank you all for your attention!

Just ask who else is there right now? 45 degrees up in the sky, damn it! My charm with no place to put it!