詳解IOS如何防止抓包
抓包原理
其實(shí)原理很是簡(jiǎn)單:一般抓包都是通過代理服務(wù)來冒充你的服務(wù)器,客戶端真正交互的是這個(gè)假冒的代理服務(wù),這個(gè)假冒的服務(wù)再和我們真正的服務(wù)交互,這個(gè)代理就是一個(gè)中間者 ,我們所有的數(shù)據(jù)都會(huì)通過這個(gè)中間者,所以我們的數(shù)據(jù)就會(huì)被抓取。HTTPS 也同樣會(huì)被這個(gè)中間者偽造的證書來獲取我們加密的數(shù)據(jù)。
防止抓包
為了數(shù)據(jù)的更安全,那么我們?nèi)绾蝸矸乐贡蛔グ?/p>
第一種思路是:如果我們能判斷是否有代理,有代理那么就存在風(fēng)險(xiǎn)。
第二種思路:針對(duì)HTTPS 請(qǐng)求。我們判斷證書的合法性。
第一種方式的實(shí)現(xiàn):
一、發(fā)起請(qǐng)求之前判斷是否存在代理,存在代理就直接返回,請(qǐng)求失敗。
CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); CFStringRef proxyStr = CFDictionaryGetValue(dicRef, kCFNetworkProxiesHTTPProxy); NSString *proxy = (__bridge NSString *)(proxyStr);
+ (BOOL)getProxyStatus { NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]); NSArray *proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[NSURL URLWithString:@"http://www.baidu.com"], (CFDictionaryRef)proxySettings) autorelease]); NSDictionary *settings = [proxies objectAtIndex:0]; NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]); NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]); NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]); if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) { //沒有設(shè)置代理 return NO; } else { //設(shè)置代理了 return YES; } }
二、我們可以在請(qǐng)求配置中清空代理,讓請(qǐng)求不走代理
我們通過hook到sessionWithConfiguration: 方法。然后清空代理
+ (void)load{ Method method1 = class_getClassMethod([NSURLSession class],@selector(sessionWithConfiguration:)); Method method2 = class_getClassMethod([NSURLSession class],@selector(px_sessionWithConfiguration:)); method_exchangeImplementations(method1, method2); Method method3 = class_getClassMethod([NSURLSession class],@selector(sessionWithConfiguration:delegate:delegateQueue:)); Method method4 = class_getClassMethod([NSURLSession class],@selector(px_sessionWithConfiguration:delegate:delegateQueue:)); method_exchangeImplementations(method3, method4); } + (NSURLSession*)px_sessionWithConfiguration:(NSURLSessionConfiguration*)configuration delegate:(nullable id)delegate delegateQueue:(nullable NSOperationQueue*)queue { if(configuration) configuration.connectionProxyDictionary = @{}; return [self px_sessionWithConfiguration:configuration delegate:delegate delegateQueue:queue]; } + (NSURLSession*)px_sessionWithConfiguration:(NSURLSessionConfiguration*)configuration { if(configuration) configuration.connectionProxyDictionary = @{}; return [self px_sessionWithConfiguration:configuration]; }
第二種思路的實(shí)現(xiàn):
主要是針對(duì)HTTPS 請(qǐng)求,對(duì)證書的一個(gè)驗(yàn)證。
通過 SecTrustRef 獲取服務(wù)端證書的內(nèi)容
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; for (CFIndex i = 0; i < certificateCount; i++) { SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; } return [NSArray arrayWithArray:trustChain]; }
然后讀取本地證書的內(nèi)容進(jìn)行對(duì)比
NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"cer"];//證書的路徑 NSData *certData = [NSData dataWithContentsOfFile:cerPath]; SSet<NSData*> * set = [[NSSet alloc]initWithObjects:certData , nil]; // 本地證書內(nèi)容 // 服務(wù)端證書內(nèi)容 NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { if ([set containsObject:trustChainCertificate]) { // 證書驗(yàn)證通過 } }
SSL Pinning(AFN+SSL Pinning)推薦
SSL Pinning,即SSL證書綁定。通過SSL證書綁定來驗(yàn)證服務(wù)器身份,防止應(yīng)用被抓包。
1、取到證書
客戶端需要證書(Certification file), .cer格式的文件。可以跟服務(wù)器端索取。
如果他們給個(gè).pem文件,要使用命令行轉(zhuǎn)換:
openssl x509 -inform PEM -in name.pem -outform DER -out name.cer
如果給了個(gè).crt文件,請(qǐng)這樣轉(zhuǎn)換:
openssl x509 -in name.crt -out name.cer -outform der
如果啥都不給你,你只能自己動(dòng)手了:
openssl s_client -connect www.website.com:443 </dev/null 2>/dev/null | openssl x509 -outform DER > myWebsite.cer**
2、把證書加進(jìn)項(xiàng)目中
把生成的.cer證書文件直接拖到你項(xiàng)目的相關(guān)文件夾中,記得勾選Copy items if neede和Add to targets。
3、參數(shù)名意思
AFSecurityPolicy
SSLPinningMode
AFSecurityPolicy是AFNetworking中網(wǎng)絡(luò)通信安全策略模塊。它提供三種SSL Pinning Mode
/**
## SSL Pinning Modes
The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes.
enum {
AFSSLPinningModeNone,
AFSSLPinningModePublicKey,
AFSSLPinningModeCertificate,
}
`AFSSLPinningModeNone`
Do not used pinned certificates to validate servers.
`AFSSLPinningModePublicKey`
Validate host certificates against public keys of pinned certificates.
`AFSSLPinningModeCertificate`
Validate host certificates against pinned certificates.
*/
AFSSLPinningModeNone:完全信任服務(wù)器證書;
AFSSLPinningModePublicKey:只比對(duì)服務(wù)器證書和本地證書的Public Key是否一致,如果一致則信任服務(wù)器證書;
AFSSLPinningModeCertificate:比對(duì)服務(wù)器證書和本地證書的所有內(nèi)容,完全一致則信任服務(wù)器證書;
選擇那種模式呢?
AFSSLPinningModeCertificate:最安全的比對(duì)模式。但是也比較麻煩,因?yàn)樽C書是打包在APP中,如果服務(wù)器證書改變或者到期,舊版本無法使用了,我們就需要用戶更新APP來使用最新的證書。
AFSSLPinningModePublicKey:只比對(duì)證書的Public Key,只要Public Key沒有改變,證書的其他變動(dòng)都不會(huì)影響使用。
如果你不能保證你的用戶總是使用你的APP的最新版本,所以我們使用AFSSLPinningModePublicKey。
allowInvalidCertificates
/** Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. */ @property (nonatomic, assign) BOOL allowInvalidCertificates;
是否信任非法證書,默認(rèn)是NO。
validatesDomainName
/** Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. */ @property (nonatomic, assign) BOOL validatesDomainName;
是否校驗(yàn)證書中DomainName字段,它可能是IP,域名如*.google.com,默認(rèn)為YES,嚴(yán)格保證安全性。
4、使用AFSecurityPolicy設(shè)置SLL Pinning
+ (AFHTTPSessionManager *)manager { static AFHTTPSessionManager *manager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config]; AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:[AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]]]; manager.securityPolicy = securityPolicy; }); return manager; }
擴(kuò)展
Android 防止抓包
1、單個(gè)接口訪問不帶代理的
URL url = new URL(urlStr); urlConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
2、OkHttp框架
OkHttpClient client = new OkHttpClient().newBuilder().proxy(Proxy.NO_PROXY).build();
以上就是詳解IOS如何防止抓包的詳細(xì)內(nèi)容,更多關(guān)于IOS如何防止抓包的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
iOS實(shí)現(xiàn)去除html標(biāo)簽的方法匯總
相信大家在做網(wǎng)站的時(shí)候,經(jīng)常會(huì)遇到去除html標(biāo)簽的問題,下面這篇文章主要給大家總結(jié)介紹了關(guān)于iOS如何實(shí)現(xiàn)去除html標(biāo)簽的一些方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-10-10分享一個(gè)關(guān)于Storyboard 跳轉(zhuǎn)與傳值
近日不忙,給大家分享一個(gè)關(guān)于storyboard跳轉(zhuǎn)傳值的相關(guān)知識(shí),感興趣的朋友一起看看吧2015-12-12iOS App設(shè)計(jì)模式開發(fā)中對(duì)interpreter解釋器模式的運(yùn)用
這篇文章主要介紹了iOS App設(shè)計(jì)模式開發(fā)中對(duì)interpreter解釋器模式的運(yùn)用,示例為傳統(tǒng)的Objective-C寫成,需要的朋友可以參考下2016-04-04iOS頁面跳轉(zhuǎn)及數(shù)據(jù)傳遞(三種)
本文主要介紹了iOS頁面跳轉(zhuǎn)的三種方法及數(shù)據(jù)傳遞的方法。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03iOS實(shí)現(xiàn)列表與網(wǎng)格兩種視圖的相互切換
相信大家應(yīng)該也都發(fā)現(xiàn)了,在現(xiàn)在很多的電商app中,都會(huì)有列表視圖和網(wǎng)格兩種視圖的相互切換。例如京東和淘寶。這樣更利于提高用戶的體驗(yàn)度,所以這篇文章小編就是大家分享下利用iOS實(shí)現(xiàn)列表與網(wǎng)格兩種視圖相互切換的方法,文中介紹的很詳細(xì),感興趣的下面來一起看看吧。2016-10-10理解iOS多線程應(yīng)用的開發(fā)以及線程的創(chuàng)建方法
這篇文章主要介紹了理解iOS多線程應(yīng)用的開發(fā)以及線程的創(chuàng)建方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11