最近在整理技术点的时候发现电脑上存有一些知识点的记录,是之前在开发的过程当中遇到的一些问题,如今再从新梳理了出来web
项目需求:防止webview里面的数据被抓包,给app中的webview也加上https校验,防止攻击 https校验原理、加密原理、证书制做等已经有不少文章介绍,相信你们已经很熟悉了;本文只讲在多家服务器资源访问的状况下对web实现https校验的部分。objective-c
参数 | 描述 |
---|---|
clientAuth=false | 单向SSL验证 |
clientAuth=true | 双向SSL验证 |
clientAuth=want | 不强制验证客户端证书 |
下面展现的是常规的web双向https校验安全
SecTrustResultType result;
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCerts);
OSStatus status = SecTrustEvaluate(serverTrust, &result);
if (status == errSecSuccess &&
(result == kSecTrustResultProceed ||
result == kSecTrustResultUnspecified)) {
NSURLCredential *card = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
复制代码
//从证书链中获取概要信息
NSString *summary = CFBridgingRelease(SecCertificateCopySubjectSummary(SecTrustGetCertificateAtIndex(challenge.protectionSpace.serverTrust, 0)));
NSLog(@"当前请求证书概要=%@",summary);
//获取信任管理对象,里面包含了待验证的证书,和自定义的策略
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([summary containsString:@".xxxx.com"]) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"xxxx" ofType:@"der"];
NSData *certData = [NSData dataWithContentsOfFile:path];
//从der数据中建立证书对象
NSMutableArray *pinnedCerts = [NSMutableArray arrayWithObjects:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData), nil];
SecTrustResultType result;
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCerts);
OSStatus status = SecTrustEvaluate(serverTrust, &result);
if (status == errSecSuccess &&
(result == kSecTrustResultProceed ||
result == kSecTrustResultUnspecified)) {
NSURLCredential *card = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
} else {
//中断本次连接
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}else {
NSURLCredential *card = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}else {
NSURLCredential *card = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, card);
}
复制代码
1.通过测试对于设置了web的ATS=NO,plist是否加白名单状况: (1)加了白名单 不论是https仍是http均可以正常访问,因为设置了ATS=NO,必需校验,代理会收到校验的回调 (2)未加白名单 a、https能够访问,前提条件(1)这个域名服务器证书有效没有过时(2)webview的校验代理没有和本地证书匹配,直接经过,好比不是本身公司的域名访问 b、http没法正常访问服务器
2.除了web当时还考虑到图片的安全性问题;好比某个二维码支付界面或者好友头像,抓包工具中设置的其它有效证书那么也就能抓到图片,查看源码知道SDWebimage是不校验本地证书的,因此若是要考虑图片的安全性须要改这里的源码,和webview中校验的方法同样就能够了,原理相同。app
ps:除了以上校验客户端和服务端的证书所有信息之外,还能够经过 SecTrustCopyPublicKey(trust) 取出各自证书信息里面的公钥进行对比,也是能够达到一样的效果,这里就再也不细说了,感兴趣的同窗能够本身尝试一下。工具