iOS 功能展示

iOS系统的TLS链验证

2017-08-06  本文已影响388人  thinkq

概述

在iOS网络请求中需要验证SSL握手中的证书,遇到这个验证问题,文档中的说法是Authentication Challenges ,由于英文不好,没有翻译成汉语。下文中的Authentication Challenges 都是指验证SSL中证书

URLSession:task:didReceiveChallenge:completionHandler:是为了让我们决定怎么响应Authentication Challenges.

在这个代理方法里有三个选择:

为了帮助做出正确的选择,方法传递了一个NSURLAuthenticationChallenge实例对象,包含了已经尝试认证过的次数,上次尝试认证用的凭证,创建认证凭证(NSURLCredential对象)需要用到的NSURLProtectionSpace对象。

如果身份认证原先已经失败过(例如如果用户改了自己的密码),可以通过challenge.proposedCredential获得上次失败的凭证,然后弹窗告诉用户。

调用challenge. previousFailureCount获取已经尝试认证的次数,可以用来提醒用户或者用于进行认证次数限制。

响应Authentication Challenge

◇ 提供一个认证凭证(NSURLCredential对象)

要尝试进行身份认证,app要创建一个NSURLCredential对象,其包含了服务器预期的格式的身份验证信息。

通过challenge.protectionSpace.authenticationMethod类型决定提供什么样的NSURLCredential对象。有如下几种类型:

创建好NSURLCredential对象后,使用完成回调块回传给服务端。(例如将包含用户名和密码的credential回传给服务端)如下:

completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

第一个参数填写NSURLSessionAuthChallengeUseCredential,表示当前认证的凭证为第二个参数传递的NSURLCredential对象。
NSURLSessionAuthChallengeUseCredential是一个枚举类型值,还有另外三个值,等下我们会一一看到

大部分app支持https只需要验证服务端的真实性,验证服务端证书,即:APP请求接口的时候需要处理Server trust authentication (NSURLAuthenticationMethodServerTrust)

当客户端第一次发送请求的时候,服务器会返回一个包含公钥的受保护空间(challenge.protectionSpace),当我们发送请求的时候,公钥会将请求加密再发送给服务器,服务器接到请求之后,用自带的私钥进行解密,如果正确再返回数据。
如下:

image.png
参考自iOS - HTTPS

◇ 尝试没有凭证而继续

代理选择不提供凭证而继续,设置完成block
completionHandler的第一个参数为NSURLSessionAuthChallengePerformDefaultHandling或者NSURLSessionAuthChallengeRejectProtectionSpace

例如https中服务端如果使用CA签发的证书的话,delegate中可以不实现URLSession:task:didReceiveChallenge:completionHandler:方法,系统框架会内部实现证书验证实现验证服务端的真实性

如果实现了的话还想让系统自己自动处理的话,直接传递
NSURLSessionAuthChallengePerformDefaultHandling给完成block:

completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);      

◇ 取消authentication challenge

在代理中选择取消authentication challenge,设置完成block
completionHandler的第一个参数为 NSURLSessionAuthChallengeCancelAuthenticationChallenge

https中如果签名证书没通过系统验证,则可以使用这个选项,相应的请求也会被取消。

completionHandler( NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);

验证服务端证书的真实性

◇ 服务端使用CA签发的证书

上文说过CA签发的证书的话,直接不实现URLSession:task:didReceiveChallenge:completionHandler:或者实现了直接给完成回调block传递NSURLSessionAuthChallengePerformDefaultHandling,系统框架都会自动实现验证服务端的真实性。
利用上篇文章创建的项目请求github(github的证书是由CA签名认证过的,所以系统认证就可以通过),以下两种方式都可以在控制台打印出github首页的html代码

★ 第一种:不实现认证相关代理方法

//- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
// completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
//    BLog();
//}
//
//- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
//didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
// completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
//    BLog();
//}

★ 第二种传递NSURLSessionAuthChallengePerformDefaultHandling

//- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
// completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
//    BLog();
//}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    BLog();
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

◇ 服务端使用自签发的证书

首先根据博客1分钟搭建自定义域名的本地HTTPS开发服务器在本地搭建了一个简单的https服务器,以便学习(可以直接下载文末的demo,里边给了server和iOS端代码,只需要按照文末的教程,启动server就行)。

index.html里只写了“12345”,只是为了证明我们请求成功了然后打印出来。

图A


localhost.png

继续用原先的代码,改下地址:

static NSString *localhostString = @"https://1.zhaoqing.cn:4443/";
- (void)sessionTaskInit {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:localhostString]];
    self.dataTask = [self.session dataTaskWithRequest:request];
}
// 开始方法
- (void)resume {
    [self.dataTask resume];
}

如果代理方法不变(继续使用刚才访问github一样的代理方法):

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    BLog();
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

结果会:

2017-07-31 15:35:50.579 Session[5525:308688] error:Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “1.zhaoqing.cn” which could put your confidential information at risk." UserInfo={NSLocalizedDescription=The certificate for this server is invalid. You might be connecting to a server that is pretending to be “1.zhaoqing.cn” which could put your confidential information at risk., NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, NSUnderlyingError=0x78749400 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9813, _kCFStreamErrorCodeKey=-9813, _kCFStreamErrorDomainKey=3, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x789a4d40>, kCFStreamPropertySSLPeerCertificates=<CFArray 0x7869cb00 [0xd7a098]>{type = immutable, count = 1, values = (
    0 : <cert(0x789a4740) s: *.zhaoqing.cn i: *.zhaoqing.cn>
)}}}, _kCFStreamErrorCodeKey=-9813, NSErrorFailingURLStringKey=https://1.zhaoqing.cn:4443/, NSErrorPeerCertificateChainKey=<CFArray 0x7869cb00 [0xd7a098]>{type = immutable, count = 1, values = (
    0 : <cert(0x789a4740) s: *.zhaoqing.cn i: *.zhaoqing.cn>
)}, NSErrorClientCertificateStateKey=0, NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x789a4d40>, NSErrorFailingURLKey=https://1.zhaoqing.cn:4443/}

一堆提示告诉我们服务端证书无效,因为这是我们自签名的没经过权威认证的嘛!

对于这种情况我们需要在代理方法中执行自定义TLS链验证,下篇笔记执行自定义TLS链验证我们会解决这个问题。

demo

◇ demo地址:

iOS系统的TLS链验证

◇ demo教程

1 下载demo里两个文件夹,server和client,server是https服务端代码,client是iOS代码

2 在终端下cd到server文件夹下,执行

python https.py

https服务端就跑起来了
3 运行iOS代码就可以了

参考:

Authentication Challenges and TLS Chain Validation
iOS - HTTPS

上一篇下一篇

猜你喜欢

热点阅读