如何使用NSURLConnection与SSL连接以获得不受信任的证书?

2020/10/30 16:02 · ios ·  · 0评论

我有以下简单的代码可以连接到SSL网页

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];

如果证书是自签名证书,它将产生错误,但是Error Domain=NSURLErrorDomain Code=-1202 UserInfo=0xd29930 "untrusted server certificate".是否有办法将其设置为始终接受连接(就像在浏览器中可以按accept一样)还是可以绕过它?

有支持的API可以完成此任务!在您的NSURLConnection代表中添加以下内容

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    if ([trustedHosts containsObject:challenge.protectionSpace.host])
      [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

  [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

请注意,connection:didReceiveAuthenticationChallenge:可以在以后向用户显示对话框之后,将其消息发送给Challenge.sender(很多),等等。

如果您不愿意(或无法使用)私有API,则有一个称为ASIHTTPRequest的开源(BSD许可证)库,该提供了较低层的包装CFNetwork APIs他们最近引入了允许HTTPS connections通过-setValidatesSecureCertificate:API使用自签名或不受信任的证书的功能。如果您不想提取整个库,则可以将源代码用作自己实现相同功能的参考。

理想情况下,应该只有两种情况:iOS应用程序何时需要接受不受信任的证书。

方案A:您已连接到使用自签名证书的测试环境。

方案B:您正在HTTPS使用代理流量MITM Proxy like Burp Suite, Fiddler, OWASP ZAP, etc.,代理将返回由自签名CA签名的证书,以便代理能够捕获HTTPS流量。

由于明显的原因,生产主机永远不要使用不受信任的证书

如果您需要让iOS模拟器接受不受信任的证书以进行测试,则强烈建议您不要更改应用程序逻辑,以禁用NSURLConnectionAPI提供的内置证书验证如果在不删除此逻辑的情况下将其发布给公众,则它很容易受到中间人攻击。

出于测试目的,接受不信任证书的推荐方法是将对证书进行签名的证书颁发机构(CA)证书导入到iOS Simulator或iOS设备上。我写了一篇简短的博客文章,演示了如何在iOS模拟器上执行此操作:

使用ios模拟器接受不受信任的证书

NSURLRequest有一个称为的私有方法setAllowsAnyHTTPSCertificate:forHost:,该方法可以完全满足您的需求。您可以通过类别定义allowsAnyHTTPSCertificateForHost:方法NSURLRequest,然后将其设置YES为要覆盖的主机返回

为了补充已接受的答案,为了提高安全性,您可以将服务器证书或您自己的根CA证书添加到钥匙串(https://stackoverflow.com/a/9941559/1432048),但是仅执行此操作不会使NSURLConnection有效自动验证您的自签名服务器。您仍然需要将以下代码添加到您的NSURLConnection委托中,它是从Apple示例代码AdvancedURLConnections复制而来,并且您需要从Apple示例代码向您的项目中添加两个文件(Credentials.h,Credentials.m)。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//        if ([trustedHosts containsObject:challenge.protectionSpace.host])

    OSStatus                err;
    NSURLProtectionSpace *  protectionSpace;
    SecTrustRef             trust;
    SecTrustResultType      trustResult;
    BOOL                    trusted;

    protectionSpace = [challenge protectionSpace];
    assert(protectionSpace != nil);

    trust = [protectionSpace serverTrust];
    assert(trust != NULL);
    err = SecTrustEvaluate(trust, &trustResult);
    trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));

    // If that fails, apply our certificates as anchors and see if that helps.
    //
    // It's perfectly acceptable to apply all of our certificates to the SecTrust
    // object, and let the SecTrust object sort out the mess.  Of course, this assumes
    // that the user trusts all certificates equally in all situations, which is implicit
    // in our user interface; you could provide a more sophisticated user interface
    // to allow the user to trust certain certificates for certain sites and so on).

    if ( ! trusted ) {
        err = SecTrustSetAnchorCertificates(trust, (CFArrayRef) [Credentials sharedCredentials].certificates);
        if (err == noErr) {
            err = SecTrustEvaluate(trust, &trustResult);
        }
        trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
    }
    if(trusted)
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

我对此一无所获,但是我发现这对我的需求确实非常有效。shouldAllowSelfSignedCert是我的BOOL变量。只需添加到您的NSURLConnection代理中,您就可以在每个连接的基础上快速绕开。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space {
     if([[space authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) {
          if(shouldAllowSelfSignedCert) {
               return YES; // Self-signed cert will be accepted
          } else {
               return NO;  // Self-signed cert will be rejected
          }
          // Note: it doesn't seem to matter what you return for a proper SSL cert
          //       only self-signed certs
     }
     // If no other authentication is required, return NO for everything else
     // Otherwise maybe YES for NSURLAuthenticationMethodDefault and etc.
     return NO;
}

在iOS 9中,所有无效或自签名证书的SSL连接都将失败。这是iOS 9.0或更高版本以及OS X 10.11和更高版本上新的App Transport Security功能的默认行为

您可以Info.plist通过字典中将设置NSAllowsArbitraryLoads来覆盖此行为但是,我建议仅出于测试目的而覆盖此设置。YESNSAppTransportSecurity

在此处输入图片说明

有关信息,请参阅此处的App Transport技术说明

内森·德弗里斯(Nathan de Vries)发布的类别解决方法将通过AppStore私有API检查,在您无法控制该NSUrlConnection对象的情况下非常有用一个示例是NSXMLParser打开您提供的URL,但不公开NSURLRequest或的示例NSURLConnection

在iOS 4中,解决方法似乎仍然有效,但仅在设备上,模拟器不再调用该allowsAnyHTTPSCertificateForHost:方法。

您必须使用NSURLConnectionDelegate允许HTTPS连接,iOS8中有新的回调。

不推荐使用:

connection:canAuthenticateAgainstProtectionSpace:
connection:didCancelAuthenticationChallenge:
connection:didReceiveAuthenticationChallenge:

相反,您需要声明:

connectionShouldUseCredentialStorage: -发送以确定URL加载程序是否应使用凭据存储来验证连接。

connection:willSendRequestForAuthenticationChallenge: -告诉代表该连接将发送一个身份验证质询的请求。

有了willSendRequestForAuthenticationChallenge你可以使用challenge像你过时方法,比如做:

// Trusting and not trusting connection to host: Self-signed certificate
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

我发布了一些摘要代码(基于我注意到的其他人的工作),使您可以根据自己生成的证书(以及如何获取免费证书)进行正确的身份验证-请参阅Cocoanetics的评论底部

我的代码在这里github

如果您要继续使用sendSynchronousRequest,请在以下解决方案中工作:

FailCertificateDelegate *fcd=[[FailCertificateDelegate alloc] init];

NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] init]];
[c start];    
NSData *d=[fcd getData];

您可以在这里看到它:Objective-C SSL同步连接

You can use this Code

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
     if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust)
     {
         [[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]] forAuthenticationChallenge:challenge];
     }
}

Use -connection:willSendRequestForAuthenticationChallenge: instead of these Deprecated Methods

Deprecated:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace  
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

With AFNetworking I have successfully consumed https webservice with below code,

NSString *aStrServerUrl = WS_URL;

// Initialize AFHTTPRequestOperationManager...
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES; 
[manager POST:aStrServerUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    successBlock(operation, responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    errorBlock(operation, error);
}];
本文地址:http://ios.askforanswer.com/ruheshiyongnsurlconnectionyussllianjieyihuodebushouxinrendezhengshu.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!