在iOS中,如何使用服务器上带有自签名证书的https连接到服务器?
我正在为iOS 5开发,并且真的不想使用非ARC代码,所以我选择自己实现这个而不是使用AFNetworking。这也许是一个很大的问题,所以我把它分成两个较小的部分。
I am developing for iOS 5 and really don't want to use un-ARCed codes so I chose to implement this myself instead of using AFNetworking. Also this might be a big question so I split it into two smaller parts.
1)在iOS 5中使用https连接到服务器。我使用从 iOS 5编程推动极限在这里。因为我正在为iOS 5开发,所以我不在项目中使用已弃用的方法。 RNSecTrustEvaluateAsX509是一种将证书重新评估为简单X.509证书而非SSL握手的方法。
1) Connecting to the server using https in iOS 5. I use the codes extracted from "iOS 5 Programming Pushing the Limits" here. Because I am developing for iOS 5 I don't use the deprecated methods in my project. "RNSecTrustEvaluateAsX509" is a method that reevaluates the certificate as a simple X.509 certificate rather than as a part of an SSL handshake.
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLProtectionSpace *protSpace = challenge.protectionSpace;
SecTrustRef trust = protSpace.serverTrust;
SecTrustResultType result = kSecTrustResultFatalTrustFailure;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == errSecSuccess && result == kSecTrustResultRecoverableTrustFailure) {
SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, 0);
CFStringRef subject = SecCertificateCopySubjectSummary(cert);
NSLog(@"Trying to access %@. Got %@.", protSpace.host,
(__bridge id)subject);
CFRange range = CFStringFind(subject, CFSTR("192.168.1.100"), kCFCompareAnchored|kCFCompareBackwards);
if (range.location != kCFNotFound) {
NSLog(@"Creating new trust certificate.Ignoring the hostname.");
status = RNSecTrustEvaluateAsX509(trust, &result);
}
CFRelease(subject);
}
if (status == errSecSuccess) {
switch (result) {
case kSecTrustResultInvalid:
case kSecTrustResultDeny:
case kSecTrustResultFatalTrustFailure:
case kSecTrustResultOtherError:
case kSecTrustResultRecoverableTrustFailure: {
NSLog(@"Failing due to result: %lu", result);
[challenge.sender cancelAuthenticationChallenge:challenge];
}
break;
case kSecTrustResultProceed:
case kSecTrustResultUnspecified: {
NSLog(@"Successing with result: %lu", result);
NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
}
break;
default:
NSAssert(NO,@"Unexpected result from trust evaluation: %d", result);
break;
}
}
else {
// Something was broken
NSLog(@"Complete failure with code: %lu", status);
[challenge.sender cancelAuthenticationChallenge:challenge];
}
}
它连接到服务器但是我总是得到一个错误,说操作无法完成(NSURLErrorDomain错误-1012)。并且控制台显示由于结果5而失败,这意味着我获得了
kSecTrustResultRecoverableTrustFailure。我怀疑这是因为我在服务器上使用自签名证书。这导致第二个问题如下。
It connects to the server but I always get an error saying "The operation couldn't be completed (NSURLErrorDomain error -1012)". And the console shows "Failing due to result 5", which means I get a kSecTrustResultRecoverableTrustFailure. I suspect this is because I am using self-signed certificate on the server. This leads to the second problem as below.
2)自签名证书导致问题。所以我添加了这些行
2) Self-signed certificate is causing problems. So I added these lines
// Self-signed certificates need to be validated manually.
NSArray *anchors = [self serverAnchors];
SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)anchors);
SecTrustSetAnchorCertificatesOnly(trust, YES);
就在
OSStatus status = SecTrustEvaluate(trust, &result);
。
我还创建了一个方法:
in the above willSendRequestForAuthenticationChallenge method. and I also created a method:
- (NSArray *)serverAnchors
{
static NSArray *anchors = nil;
if (!anchors) {
NSData *caData = [CA_CERTS dataUsingEncoding:NSUTF8StringEncoding];
SecCertificateRef caRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef) caData);
anchors = [NSArray arrayWithObjects:(__bridge id)caRef, nil];
if (caRef) {
CFRelease(caRef);
}
}
return anchors;
}
我将CA_CERTS定义为der格式证书数据,这是一个NSString我通过SecCertificateCopyData从服务器获得。但我仍然继续获得kSecTrustResultRecoverableTrustFailure。我真的不知道我是否在这里做正确的事。如何使用自己的数据从服务器手动验证自签名证书?更具体地说,如何从iOS获取数据?
I defined CA_CERTS as the "der" format certificate data, which is a NSString I got from the server via SecCertificateCopyData. But I still keep getting kSecTrustResultRecoverableTrustFailure. I don't really know if I am doing the right thing here. How can I manually validate the self-signed certificate from the server using its own data? More specifically, how to get its data from iOS?
我建议将OpenSSL合并到您的项目中以处理证书和授权挑战!
然后在你的'连接:didReceiveAuthenticationChallenge:''NSURLConnectionDelegate'协议的方法做这样的事情:
I'd suggest to incorporate OpenSSL into your project for handling certificates and authorization challenges! then in your 'connection:didReceiveAuthenticationChallenge:' method of the 'NSURLConnectionDelegate' protocol do something like this:
- (void) connection:(NSURLConnection*) connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge*) challenge {
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust]) {
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
NSMutableArray* certificates = [NSMutableArray array];
NSData* certificate2Data = // your certificate data
NSData* certificate3Data = // even more certificate data if needed
SecCertificateRef certificate2 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate2Data);
SecCertificateRef certificate3 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate3Data);
[certificates addObject: (id) certificate2];
[certificates addObject: (id) certificate3];
CFRelease(certificate2);
CFRelease(certificate3);
SecTrustSetAnchorCertificates(trust, (CFArrayRef) certificates);
SecTrustSetAnchorCertificatesOnly(trust, true);
SecTrustResultType trust_result;
SecTrustEvaluate(trust, &trust_result);
if (trust_result == kSecTrustResultUnspecified) {
if (SecTrustGetCertificateCount(trust) > 0) {
SecCertificateRef leafCertificate = SecTrustGetCertificateAtIndex(trust, 0);
NSData* leafCertificateData = (NSData*) SecCertificateCopyData(leafCertificate);
const unsigned char* certificateDataBytes = (const unsigned char *)[leafCertificateData bytes];
X509* certificateX509 = d2i_X509(NULL, &certificateDataBytes, [leafCertificateData length]);
CFRelease(leafCertificateData);
X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
X509_NAME *subjectX509Name = X509_get_subject_name(certificateX509);
/*
with issuerX509Name and subjectX509Name you could check some properties of the certificate and cancel the
authentication challenge f.e.!
if ([[self valueWithKey: @"CN" inName: subjectX509Name cert: certificateX509] isEqualToString: @"xxxx"] == NO) {
[[challenge sender] cancelAuthenticationChallenge: challenge];
return;
}
*/
NSURLCredential* credential = [NSURLCredential credentialForTrust: trust];
[[challenge sender] useCredential: credential forAuthenticationChallenge: challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge: challenge];
}
} else {
[[challenge sender] cancelAuthenticationChallenge: challenge];
}
}}