Use SSL Pinning prevent man in the middle attacks

problem:

We can use https Charles grab bag, it is the use of middle attacks, so security is not a request of the app. How to avoid https Charles caught the bag? The answer is: SSL Pinning

Principle middleman attacks

Trust forged certificate, the client acts as a server, the server acts as a client.

The principle of SSL Pinning

When connected to the server, the certificate or public key built consistent comparison whether the server public key certificate or client public key or certificate built-in server, client, inconsistent then disconnect. This allows intermediaries forged certificate can not be verified.

SSL Pinning type

  1. Built-in certificate
    certificate into the app bundle inside. The server's certificate needs to be synchronized to update or revise app expires.
  2. Built-in public key
    public key hard-coded into the code of the certificate. As long as the public key of the same server, do not update app.

Alamofire 5 used in the SSL Pinning

It provides two classes:

  • PinnedCertificatesTrustEvaluator
  • PublicKeysTrustEvaluator

With PinnedCertificatesTrustEvaluatoran example:

  1. Obtain a certificate data
struct Certificates {
  static let stackExchange =
    Certificates.certificate(filename: "stackexchange.com")
  
  private static func certificate(filename: String) -> SecCertificate {
    let filePath = Bundle.main.path(forResource: filename, ofType: "der")!
    let data = try! Data(contentsOf: URL(fileURLWithPath: filePath))
    let certificate = SecCertificateCreateWithData(nil, data as CFData)!
    
    return certificate
  }
}
复制代码
  1. Construction of session
// 1
let evaluators = [
  "api.stackexchange.com":
    PinnedCertificatesTrustEvaluator(certificates: [
      Certificates.stackExchange
    ])
]

let session: Session

// 2
private init() {
  session = Session(
    serverTrustManager: ServerTrustManager(evaluators: evaluators)
  )
}
复制代码

Reference material

Preventing Man-in-the-Middle Attacks in iOS with SSL Pinning

Reproduced in: https: //juejin.im/post/5cf0d193f265da1b8e7085a8

Guess you like

Origin blog.csdn.net/weixin_34291004/article/details/91422680