【问题标题】:SSL Pinning on iOSiOS 上的 SSL 固定
【发布时间】:2013-05-17 15:40:36
【问题描述】:

为了提高我的应用程序的安全性并保护用户免受 MITM 攻击,我正在尝试按照this post 的内容使用我的自签名证书进行 SSL 固定。

所以我使用以下代码来比较我从服务器获得的证书和应用程序中捆绑的证书。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
    SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
    NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
    NSLog(@"Remote Certificate Data Length: %d",[remoteCertificateData length]);
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"apache" ofType:@"crt"];
    NSData *localCertData = [NSData dataWithContentsOfFile:cerPath];
    NSLog(@"Local Certificate Data Length: %d",[localCertData length]);
    if ([remoteCertificateData isEqualToData:localCertData]) {
        NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
    }
    else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

我的代码与我链接的博客文章中的代码之间唯一不同的是代表我的证书的资源的名称和扩展名(.cer 到 .crt)以及我添加的两个 NSLog,它们将派上用场稍后再说明问题所在。

事实上,当这段代码被执行时,我得到了这样的输出:

2013-05-22 16:08:53.331 HTTPS Test[5379:c07] Remote Certificate Data Length: 880
2013-05-22 16:09:01.346 HTTPS Test[5379:c07] Local Certificate Data Length: 1249

很明显Local和Remote证书比较失败,因为数据的长度不同,所以pinning也失败了。

为什么会发生这种情况,我该如何解决这个问题?

【问题讨论】:

  • 您是否考虑过将返回的证书数据保存到文件中并使用它?否则,对数据进行比较,看看有什么不同。
  • 不,我没想到!好主意,我马上试试!
  • 如果您使用 Alamofire,请查看jayprakashdubey.blogspot.in/2017/07/…

标签: ios security ssl foundation


【解决方案1】:

我有同样的问题。问题可能是因为您没有将 .crt 文件转换为正确的格式。 iOS 和 OSX 正在寻找您的证书为 .der 格式。您需要使用openssl 进行转换。 Here 是一篇关于这个主题的非常有用的文章。我的公共证书来自 Apache 服务器(我假设你的也是如此)。在查看了 openssl 文档后,我能够弄清楚如何让它工作。

1) 打开终端并将目录更改为 .crt 的位置。

2) 执行此命令:

openssl x509 -in your_cert.crt -outform der -out your_output_name.der

这将创建一个名为“your_output_file.der”的输出文件。您必须将其导入您的 xCode 项目并在

中引用它
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

NSURLConnectionDelegate 实现的方法。

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2021-12-21
    • 2021-09-15
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多