问题:
我们可以使用Charles抓https的包,原理是利用中间人攻击,所以app的请求并不是安全的。怎样避免Charles抓https的包呢?答案是:SSL Pinning
中间人攻击的原理
伪造信任证书,对客户端充当服务器,对服务器充当客户端。
SSL Pinning 的原理
在客户端内置服务器的证书或者公钥,客户端连接服务器时,对比内置证书或公钥是否与服务器的证书或公钥一致,不一致则断开连接。这样就可以让中间人伪造的证书无法通过验证。
SSL Pinning 的类型
- 内置证书
将证书放入app的bundle里。服务器的证书修改或者过期时需要同步更新app。 - 内置公钥
将证书的公钥硬编码进代码里。只要服务器的公钥不变,就不用更新app。
在Alamofire 5 中使用 SSL Pinning
提供了两个类:
PinnedCertificatesTrustEvaluator
PublicKeysTrustEvaluator
以PinnedCertificatesTrustEvaluator
为例:
- 获取证书数据
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
}
}
复制代码
- 构建session
// 1
let evaluators = [
"api.stackexchange.com":
PinnedCertificatesTrustEvaluator(certificates: [
Certificates.stackExchange
])
]
let session: Session
// 2
private init() {
session = Session(
serverTrustManager: ServerTrustManager(evaluators: evaluators)
)
}
复制代码
参考资料
Preventing Man-in-the-Middle Attacks in iOS with SSL Pinning
转载于:https://juejin.im/post/5cf0d193f265da1b8e7085a8