当前位置:网站首页 > 通栏广告 > 正文

移动端h5防劫持 防止广告注入

作者:admin发布时间:2021-09-17分类:通栏广告浏览:评论:13


导读:在SSL握手阶段,客户端浏览器会认证服务器的身份,这是通过“证书”来实现的,证书由证书权威(CA)为某个域名签发,可以理解为网站的身份证件,客户端需要对这个证件进行认证,需要确...

移动端h5防劫持 防止广告注入

在SSL握手阶段,客户端浏览器会认证服务器的身份,这是通过“证书”来实现的,证书由证书权威(CA)为某个域名签发,可以理解为网站的身份证件,客户端需要对这个证件进行认证,需要确定该证书是否属于目标网站并确认证书本身是否有效。最后在握手阶段,通信的双方还会协商出一个用于加密和解密的会话密钥。

SSL握手阶段结束之后,服务器和客户端使用协商出的会话密钥对交互的数据进行加密/解密操作,对于HTTP协议来说,就是将HTTP请求和应答经过加密之后再发送到网络上。

移动端处理:

1.移动端拦截协议、只拦截自己的加载本地的js相关。-、-

2.可以创建黑名单、服务端下发、实时动态更新黑名单、手机端代码拦截名单中的域名或者请求

代码处理:

((){(WebViewview,Stringurl){showLogInfo("拦截到的url----"+url);Stringadvertising="http://"+sharedPreferencesUtil.getData(Constant.IP,RequestConfig.IP)+":"+sharedPreferencesUtil.getData(Constant.PORT,RequestConfig.IPPORT);if(url.contains(pre)){MapString,Stringmap=getParamsMap(url,pre);Stringcode=map.get("code");Stringdata=map.get("data");parseCode(code,data);returntrue;}elseif(!url.contains(advertising)){showLogError("拦截到植入广告,广告的url——"+url);returntrue;}else{returnfalse;}}});

iOS处理代码:

1.在WebView代理里拦截

2.全局拦截请求

#import"ZMURLProtocol.h"staticNSString*constURLProtocolHandledKey=@"URLProtocolHandledKey";staticNSDictionary*_holdUpDic;@interfaceZMURLProtocol()NSURLConnectionDelegate@property(nonatomic,strong)NSURLConnection*connection;@end@implementationZMURLProtocol+(NSDictionary*)getHoldUpDic{if(!_holdUpDic){#pragmamark-这里是获取黑白名单的数据/*[AFNetWorkpostWithURL:@""Params:@""Success:^(NSURLSessionDataTask*task,idresponseObject){//获取广告拦截资料_holdUpDic=responseObject;//写入本地plist文件BOOLsuccess=[_holdUpDicwriteToFile:pathatomically:YES];if(success){NSLog(@"写入成功");}else{NSLog(@"写入失败");}}];_holdUpDic=[NSDictionarydictionaryWithContentsOfFile:path];*/}return_holdUpDic;}+(BOOL)canInitWithRequest:(NSURLRequest*)request{//只处理http和https请求NSString*scheme=[[requestURL]scheme];if(([schemecaseInsensitiveCompare:@"http"]==NSOrderedSame)||([schemecaseInsensitiveCompare:@"https"]==NSOrderedSame)){//看看是否已经处理过了,防止无限循环if([NSURLProtocolpropertyForKey:URLProtocolHandledKeyinRequest:request]){returnNO;}returnYES;//处理}returnNO;}+(NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request{//网页发生变动[[NSNotificationCenterdefaultCenter]postNotificationName:PageChangeNotificationobject:selfuserInfo:nil];//NSLog(@"canonicalRequestForRequest:%@",request.URL.absoluteString);NSMutableURLRequest*mutableReqeust=[requestmutableCopy];mutableReqeust=[selfredirectHostInRequset:mutableReqeust];returnmutableReqeust;}+(BOOL)requestIsCacheEquivalent:(NSURLRequest*)atoRequest:(NSURLRequest*)b{return[superrequestIsCacheEquivalent:atoRequest:b];}-(void)startLoading{NSMutableURLRequest*mutableReqeust=[[selfrequest]mutableCopy];//打标签,防止无限循环[NSURLProtocolsetProperty:@YESforKey:URLProtocolHandledKeyinRequest:mutableReqeust];//self.connection=[NSURLConnectionconnectionWithRequest:mutableReqeustdelegate:self];}//-(void)stopLoading{[self.connectioncancel];}#pragmamark-NSURLConnectionDelegate-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError*)error{[self.clientURLProtocol:selfdidFailWithError:error];}-(NSURLRequest*)connection:(NSURLConnection*)connectionwillSendRequest:(NSURLRequest*)requestredirectResponse:(NSURLResponse*)response{//if(response!=nil)//{//[[selfclient]URLProtocol:selfwasRedirectedToRequest:requestredirectResponse:response];//}//这里需要回传[selfclient]消息,那么需要重定向的网页就会出现问题:host不对或者造成跨域调用导致资源无法加载[[selfclient]URLProtocol:selfwasRedirectedToRequest:requestredirectResponse:response];//returnrequest;//这里如果返回request会重新请求一次returnnil;}-(BOOL)connectionShouldUseCredentialStorage:(NSURLConnection*)connection{returnYES;}-(void)connection:(NSURLConnection*)connectiondidReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{[self.clientURLProtocol:selfdidReceiveAuthenticationChallenge:challenge];}-(void)connection:(NSURLConnection*)connectiondidCancelAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{[self.clientURLProtocol:selfdidCancelAuthenticationChallenge:challenge];}-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse*)response{[self.clientURLProtocol:selfdidReceiveResponse:responsecacheStoragePolicy:NSURLCacheStorageNotAllowed];}-(void)connection:(NSURLConnection*)connectiondidReceiveData:(NSData*)data{[self.clientURLProtocol:selfdidLoadData:data];}-(NSCachedURLResponse*)connection:(NSURLConnection*)connectionwillCacheResponse:(NSCachedURLResponse*)cachedResponse{returncachedResponse;}-(void)connectionDidFinishLoading:(NSURLConnection*)connection{[self.clientURLProtocolDidFinishLoading:self];}#pragmamark--private+(NSMutableURLRequest*)redirectHostInRequset:(NSMutableURLRequest*)request{//没有域名的URL请求就原路返回,不能返回nil,不然在跳转APP的时候会被拦截返回空出错(或者其他情况).//eg:mqq://im/chat?chat_type=wpauin=****version=1src_type=web跳转到指定QQ用户的聊天窗口if([request.URLhost].length==0){returnrequest;}NSString*originUrlString=request.URL.absoluteString;//获取主机名字,在这里执行正则匹配NSString*originHostString=[request.URLhost];NSRangehostRange=[originUrlStringrangeOfString:originHostString];//找不到主机名,返回if(hostRange.location==NSNotFound){returnrequest;}if(originUrlString!=nil){//获取拦截的黑白名单数据(过滤名单)//这个是自定义方法,你们自己随意发挥,哈哈哈.#warning---思路实现/*这里的匹配黑白名单一般只是**匹配域名**思路1:匹配白名单-匹配黑名单-如果两个都没有,就向服务器打印日志.(拉外网)思路2:匹配白名单以下代码运用思路1实现eg:这个是过滤的规则的例子格式.*(.qq.com|api.weibo.com|.weibo.com|.baidu.com|.weixin.qq.com|.sina.com|.sina.cn).**/NSDictionary*dic=[selfgetHoldUpDic];if(!dic)//如果为空不处理黑白名单{returnrequest;}//白名单NSString*whiteList=dic[@"whiteList"];//黑名单NSString*blackList=dic[@"blackList"];#pragmamark-白名单匹配//1.1将正则表达式设置为OC规则if(![whiteListisEqualToString:@""]){NSRegularExpression*regular1=[[NSRegularExpressionalloc]initWithPattern:whiteListoptions:NSRegularExpressionCaseInsensitiveerror:nil];//2.利用规则测试字符串获取匹配结果NSArray*results1=[regular1matchesInString:originUrlStringoptions:0range:NSMakeRange(0,originUrlString.length)];if(results1.count0)//是白名单,允许访问{returnrequest;}}#pragmamark-黑名单匹配if(![blackListisEqualToString:@""]){//1.1将正则表达式设置为OC规则NSRegularExpression*regular2=[[NSRegularExpressionalloc]initWithPattern:blackListoptions:NSRegularExpressionCaseInsensitiveerror:nil];//2.利用规则匹配字符串获取匹配结果NSArray*results2=[regular2matchesInString:originUrlStringoptions:0range:NSMakeRange(0,originUrlString.length)];if(results2.count0)//黑名单,返回nil;{returnrequest;}}if(![whiteListisEqualToString:@""]![blackListisEqualToString:@""]){#pragmamark-发送到服务端打印日志}}returnrequest;}@end

H5处理:

嵌入的代码基本都是iframe,把以下js代码加入body标签内,以删除iframe(记得用script标签包裹)

//以下代码为删除嵌入广告vardel_times=0,deTimer=null;functionadGo(){variframe=document.getElementsByTagName('iframe')[0];if(iframe){console.log(iframe)//循环iframe父类,直到找到body和body的下一级,然后整个嵌入的代码删除。varbodyNode={tagName:''},iframeParent,targetNode=iframe.parentNode;while(bodyNode.tagName!='BODY'){bodyNode=targetNode;if(bodyNode.tagName!='BODY'){iframeParent=targetNode;targetNode=targetNode.parentNode;}}if(iframeParent)//如果iframe有父类bodyNode.removeChild(iframeParent);elsebodyNode.removeChild(iframe);}del_times++;if(del_times10)window.clearInterval(deTimer)}deTimer=self.setInterval(adGo,1000);//把这个1000,调低一点,比如200

以上就是处理方法,如有遗漏请大家指正。

©著作权归作者所有,转载或内容合作请联系作者


已有13位网友发表了看法:

欢迎 发表评论: