什么是DNS劫持
DNS劫持就是通过劫持了DNS服务器,通过某些手段取得某域名的解析记录控制权,进而修改此域名的解析结果,导致对该域名的访问由原IP地址转入到修改后的指定IP,其结果就是对特定的网址不能访问或访问的是假网址,从而实现窃取资料或者破坏原有正常服务的目的。
常见的DNS劫持现象网络运营商向网页中注入了Javascript代码,甚至直接将我们的网页请求转发到他们自己的广告页面或者通过自己的DNS服务器将用户请求的域名指向到非法地址
如何解决DNS被劫持
全站使用HTTPS协议,或者采用HttpDNS,通过HTTP向自建的DNS服务器或者安全的DNS服务器发送域名解析请求,然后根据解析结果设置客户端的Host指向,从而绕过网络运营商的DNS解析服务。
本文的解决方案
客户端对WebView的html请求进行DNS解析。优先使用阿里、腾讯、114等公共安全的DNS服务器解析客户端的所有指定域名的http请求。相对来讲我们自己的服务域名变化较少,对此我们做了一个白名单,把凡是访问包含我们公司域名的请求都必须通过白名单的解析和DNS验证。从而杜绝被劫持的情况出现,这时候NSURLProtocol就派上用场了。
NSURLProtocol
这是一个抽象类,所以在oc中只能通过继承来重写父类的方法。
@interface XRKURLProtocol : NSURLProtocol
@end
然后在AppDelegate的 application:didFinishLaunchingWithOptions: 方法或者程序首次请求网络数据之前去注册这个NSURLProtocol的子类
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSURLProtocol registerClass:[XRKURLProtocol class]];
}
注册了自定义的urlProtocol子类后,之后每一个http请求都会先经过该类过滤并且通过+canInitWithRequest:
这个方法返回一个布尔值告诉系统该请求是否需要处理,返回Yes才能进行后续处理。
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {
return NO;
}
//http和https都会出现dns劫持情况,都需要处理
NSString *scheme = [[request URL] scheme];
if (([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame)) {
// 判断请求是否为白名单
NSArray *whiteLists = [XRKConfigManager sharedManager].whiteList;
if (whiteLists && [whiteLists isKindOfClass:[NSArray class]]) {
for (NSString *url in whiteLists) {
if (request.URL.host && [request.URL.host hasSuffix:url]) {
return YES;
}
}
}
}
return NO;
}
+canonicalRequestForRequest:
这个父类的抽象方法子类必须实现。
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
以下是官方对这个方法的解释。当我们想对某个请求添加请求头或者返回新的请求时,可以在这个方法里自定义然后返回,一般情况下直接返回参数里的NSURLRequest实例即可。
It is up to each concrete protocol implementation to define what “canonical” means. A protocol should guarantee that the same input request always yields the same canonical form.
+requestIsCacheEquivalent:toRquest:
这个方法能够判断当拦截URL相同时是否使用缓存数据,以下例子是直接返回父类实现。
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
return [super requestIsCacheEquivalent:a toRequest:b];
}
-startLoading
和-stopLoading
两个方法分别告诉NSURLProtocol实现开始和取消请求的处理。
- (void)startLoading {
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
//打标签,防止无限循环
[NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];
// dns解析
NSMutableURLRequest *request = [self.class replaceHostInRequset:mutableReqeust];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
+ (NSMutableURLRequest *)replaceHostInRequset:(NSMutableURLRequest *)request {
if ([request.URL host].length == 0) {
return request;
}
NSString *originUrlString = [request.URL absoluteString];
NSString *originHostString = [request.URL host];
NSRange hostRange = [originUrlString rangeOfString:originHostString];
if (hostRange.location == NSNotFound) {
return request;
}
//用HappyDNS 替换host
NSMutableArray *array = [NSMutableArray array];
/// 第一dns解析为114,第二解析才是系统dns
[array addObject:[[QNResolver alloc] initWithAddress:@"114.114.115.115"]];
[array addObject:[QNResolver systemResolver]];
QNDnsManager *dnsManager = [[QNDnsManager alloc] init:array networkInfo:[QNNetworkInfo normal]];
NSArray *queryArray = [dnsManager query:originHostString];
if (queryArray && queryArray.count > 0) {
NSString *ip = queryArray[0];
if (ip && ip.length) {
// 替换host
NSString *urlString = [originUrlString stringByReplacingCharactersInRange:hostRange withString:ip];
NSURL *url = [NSURL URLWithString:urlString];
request.URL = url;
[request setValue:originHostString forHTTPHeaderField:@"Host"];
}
}
return request;
}
- (void)stopLoading {
[self.connection cancel];
}
由于我们在-startLoading
中新建了一个NSURLConnection实例,因此要实现NSURLConnectionDelegate
的委托方法。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.client URLProtocol:self didLoadData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.client URLProtocolDidFinishLoading:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self.client URLProtocol:self didFailWithError:error];
}
至此,通过NSURLProtocol和QNDnsManager(七牛DNS解析开源库)可以解决DNS劫持问题。但是NSURLProtocol还有更多的用途,以下是本文第二个内容:webView上web请求的资源本地化。
Web资源本地化
这里只举一个简单的示例,同样是在上述NSURLProtocol的子类的-startLoading
方法里
- (void)startLoading {
NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
// 处理MIME type
NSString *mimeType = nil;
mutableReqeust = [self.class replaceLocalSource:mutableReqeust];
NSString *pathComponent = mutableReqeust.URL.absoluteString.lastPathComponent;
if ([pathComponent hasSuffix:@"js"]) {
mimeType = @"text/javascript";
} else if ([pathComponent hasSuffix:@"css"]) {
mimeType = @"text/css";
}
if (mimeType) {
NSData *data = [NSData dataWithContentsOfFile:mutableReqeust.URL.absoluteString];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[[self request] URL]
MIMEType:mimeType
expectedContentLength:[data length]
textEncodingName:@"UTF8"];
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}
}
#pragma mark - 判断是否是本地资源
+ (BOOL)canReplaceLocalSource:(NSURLRequest *)request {
NSString *absoluteString = request.URL.absoluteString;
for (NSString *localSourceurl in [self localSourceArray]) {
if ([absoluteString isEqualToString:localSourceurl]) {
return YES;
}
}
return NO;
}
网友评论