详解IOS如何防止抓包

2022-07-22,,

抓包原理

其实原理很是简单:一般抓包都是通过代理服务来冒充你的服务器,客户端真正交互的是这个假冒的代理服务,这个假冒的服务再和我们真正的服务交互,这个代理就是一个中间者 ,我们所有的数据都会通过这个中间者,所以我们的数据就会被抓取。https 也同样会被这个中间者伪造的证书来获取我们加密的数据。

防止抓包

为了数据的更安全,那么我们如何来防止被抓包。

第一种思路是:如果我们能判断是否有代理,有代理那么就存在风险。

第二种思路:针对https 请求。我们判断证书的合法性。

第一种方式的实现:

一、发起请求之前判断是否存在代理,存在代理就直接返回,请求失败。

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"])
    {
        //没有设置代理
        return no;
    }
    else
    {
        //设置代理了
        return yes;
    }
}

二、我们可以在请求配置中清空代理,让请求不走代理

我们通过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];
}

​ 第二种思路的实现:

主要是针对https 请求,对证书的一个验证。

通过 sectrustref 获取服务端证书的内容

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];
}

然后读取本地证书的内容进行对比

nsstring *cerpath = [[nsbundle mainbundle] pathforresource:@"certificate" oftype:@"cer"];//证书的路径
nsdata *certdata = [nsdata datawithcontentsoffile:cerpath];
sset<nsdata*> * set = [[nsset alloc]initwithobjects:certdata  , nil];  // 本地证书内容
// 服务端证书内容
nsarray *servercertificates = afcertificatetrustchainforservertrust(servertrust);
for (nsdata *trustchaincertificate in [servercertificates reverseobjectenumerator]) {
    if ([set containsobject:trustchaincertificate]) {
        // 证书验证通过
    }
}

ssl pinning(afn+ssl pinning)推荐

ssl pinning,即ssl证书绑定。通过ssl证书绑定来验证服务器身份,防止应用被抓包。

1、取到证书

客户端需要证书(certification file), .cer格式的文件。可以跟服务器端索取。

如果他们给个.pem文件,要使用命令行转换:

openssl x509 -inform pem -in name.pem -outform der -out name.cer

如果给了个.crt文件,请这样转换:

openssl x509 -in name.crt -out name.cer -outform der

如果啥都不给你,你只能自己动手了:

openssl s_client -connect www.website.com:443 </dev/null 2>/dev/null | openssl x509 -outform der > mywebsite.cer**

2、把证书加进项目中

把生成的.cer证书文件直接拖到你项目的相关文件夹中,记得勾选copy items if neede和add to targets。

3、参数名意思

afsecuritypolicy

sslpinningmode

afsecuritypolicy是afnetworking中网络通信安全策略模块。它提供三种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:完全信任服务器证书;

afsslpinningmodepublickey:只比对服务器证书和本地证书的public key是否一致,如果一致则信任服务器证书;

afsslpinningmodecertificate:比对服务器证书和本地证书的所有内容,完全一致则信任服务器证书;

选择那种模式呢?

afsslpinningmodecertificate:最安全的比对模式。但是也比较麻烦,因为证书是打包在app中,如果服务器证书改变或者到期,旧版本无法使用了,我们就需要用户更新app来使用最新的证书。

afsslpinningmodepublickey:只比对证书的public key,只要public key没有改变,证书的其他变动都不会影响使用。
如果你不能保证你的用户总是使用你的app的最新版本,所以我们使用afsslpinningmodepublickey。

allowinvalidcertificates

/**
 whether or not to trust servers with an invalid or expired ssl certificates. defaults to `no`.
 */
@property (nonatomic, assign) bool allowinvalidcertificates;

是否信任非法证书,默认是no。

validatesdomainname

/**
 whether or not to validate the domain name in the certificate's cn field. defaults to `yes`.
 */
@property (nonatomic, assign) bool validatesdomainname;

是否校验证书中domainname字段,它可能是ip,域名如*.google.com,默认为yes,严格保证安全性。

4、使用afsecuritypolicy设置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;
}

扩展

android 防止抓包

1、单个接口访问不带代理的

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如何防止抓包的详细内容,更多关于ios如何防止抓包的资料请关注其它相关文章!

《详解IOS如何防止抓包.doc》

下载本文的Word格式文档,以方便收藏与打印。