From a0f1f83a2b2cfb29129cbf3680203c5141bb4dc1 Mon Sep 17 00:00:00 2001 From: Oliver Letterer Date: Wed, 27 Mar 2013 11:19:51 +0100 Subject: [PATCH 1/2] Pinning certificates will now trust all derived certificates. --- AFNetworking/AFURLConnectionOperation.m | 90 ++++++++++++++----------- 1 file changed, 52 insertions(+), 38 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 51cfd6b..ae1bea9 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -542,57 +542,71 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0); - NSData *certificateData = (__bridge_transfer NSData *)SecCertificateCopyData(certificate); - - if ([[[self class] pinnedCertificates] containsObject:certificateData]) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - switch (self.SSLPinningMode) { - case AFSSLPinningModePublicKey: { - id publicKey = (__bridge_transfer id)SecTrustCopyPublicKey(serverTrust); - + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + if (self.SSLPinningMode == AFSSLPinningModeCertificate) { + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } else if (self.SSLPinningMode == AFSSLPinningModePublicKey) { + SecTrustRef trust = NULL; + OSStatus status = SecTrustCreateWithCertificates(certificate, policy, &trust); + NSAssert(status == noErr, @"SecTrustCreateWithCertificates error: %ld", (long int)status); + + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + CFRelease(trust); + } + } + + CFRelease(policy); + + switch (self.SSLPinningMode) { + case AFSSLPinningModePublicKey: { + for (id publicKey in trustChain) { if ([[self.class pinnedPublicKeys] containsObject:publicKey]) { NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; + return; } - - break; } - case AFSSLPinningModeCertificate: { - SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0); - NSData *serverCertificateData = (__bridge_transfer NSData *)SecCertificateCopyData(serverCertificate); - - if ([[[self class] pinnedCertificates] containsObject:serverCertificateData]) { + + [[challenge sender] cancelAuthenticationChallenge:challenge]; + break; + } + case AFSSLPinningModeCertificate: { + for (id serverCertificateData in trustChain) { + if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) { NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; + return; } - - break; } - case AFSSLPinningModeNone: { + + [[challenge sender] cancelAuthenticationChallenge:challenge]; + break; + } + case AFSSLPinningModeNone: { #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; +#else + SecTrustResultType result = 0; + OSStatus status = SecTrustEvaluate(serverTrust, &result); + NSAssert(status == noErr, @"SecTrustEvaluate error: %ld", (long int)status); + + if (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed) { NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; -#else - SecTrustResultType result = 0; - OSStatus status = SecTrustEvaluate(serverTrust, &result); - NSAssert(status == noErr, @"SecTrustEvaluate error: %ld", (long int)status); - - if (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } -#endif - break; + } else { + [[challenge sender] cancelAuthenticationChallenge:challenge]; } +#endif + break; } } } From 8b2d01a503beb987fb6e11ab23c5d58bc6197cde Mon Sep 17 00:00:00 2001 From: Oliver Letterer Date: Sun, 7 Apr 2013 08:29:29 +0200 Subject: [PATCH 2/2] Fixes SecTrustCreateWithCertificates expecting an array as first argument. --- AFNetworking/AFURLConnectionOperation.m | 117 ++++++++++++------------ 1 file changed, 61 insertions(+), 56 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index ae1bea9..ac1ca7e 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -174,7 +174,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; [_networkRequestThread start]; }); - + return _networkRequestThread; } @@ -185,7 +185,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat dispatch_once(&onceToken, ^{ NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - + NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; for (NSString *path in paths) { NSData *certificateData = [NSData dataWithContentsOfFile:path]; @@ -194,7 +194,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat _pinnedCertificates = [[NSArray alloc] initWithArray:certificates]; }); - + return _pinnedCertificates; } @@ -208,7 +208,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat for (NSData *data in pinnedCertificates) { SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data); NSCParameterAssert(allowedCertificate); - + SecCertificateRef allowedCertificates[] = {allowedCertificate}; CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); @@ -219,13 +219,13 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust); [publicKeys addObject:(__bridge_transfer id)allowedPublicKey]; - + CFRelease(allowedTrust); CFRelease(policy); CFRelease(certificates); CFRelease(allowedCertificate); } - + _pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys]; }); @@ -238,20 +238,20 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat if (!self) { return nil; } - + self.lock = [[NSRecursiveLock alloc] init]; self.lock.name = kAFNetworkingLockName; - + self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - + self.request = urlRequest; - + self.shouldUseCredentialStorage = YES; - + self.outputStream = [NSOutputStream outputStreamToMemory]; - + self.state = AFOperationReadyState; - + return self; } @@ -260,7 +260,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat [_outputStream close]; _outputStream = nil; } - + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) if (_backgroundTaskIdentifier) { [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; @@ -281,7 +281,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat __weak __typeof(&*self)weakSelf = self; [super setCompletionBlock:^ { __strong __typeof(&*weakSelf)strongSelf = weakSelf; - + block(); [strongSelf setCompletionBlock:nil]; }]; @@ -305,7 +305,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat if (outputStream == _outputStream) { return; } - + [self willChangeValueForKey:@"outputStream"]; if (_outputStream) { [_outputStream close]; @@ -322,14 +322,14 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat __weak __typeof(&*self)weakSelf = self; self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ __strong __typeof(&*weakSelf)strongSelf = weakSelf; - + if (handler) { handler(); } - + if (strongSelf) { [strongSelf cancel]; - + [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; } @@ -386,7 +386,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; } [self.lock unlock]; - + return _responseString; } @@ -400,11 +400,11 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); } } - + self.responseStringEncoding = stringEncoding; } [self.lock unlock]; - + return _responseStringEncoding; } @@ -412,20 +412,20 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat if ([self isPaused] || [self isFinished] || [self isCancelled]) { return; } - + [self.lock lock]; - + if ([self isExecuting]) { [self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - + dispatch_async(dispatch_get_main_queue(), ^{ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; }); } - + self.state = AFOperationPausedState; - + [self.lock unlock]; } @@ -437,10 +437,10 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat if (![self isPaused]) { return; } - + [self.lock lock]; self.state = AFOperationReadyState; - + [self start]; [self.lock unlock]; } @@ -467,7 +467,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat [self.lock lock]; if ([self isReady]) { self.state = AFOperationExecutingState; - + [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } [self.lock unlock]; @@ -512,7 +512,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat _cancelled = YES; [super cancel]; [self didChangeValueForKey:@"isCancelled"]; - + // Cancel the connection on the thread it runs on to prevent race conditions [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } @@ -525,10 +525,10 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; } self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - + if (self.connection) { [self.connection cancel]; - + // Manually send this delegate message since `[self.connection cancel]` causes the connection to never send another message to its delegate [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.error]; } @@ -553,13 +553,18 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe if (self.SSLPinningMode == AFSSLPinningModeCertificate) { [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; } else if (self.SSLPinningMode == AFSSLPinningModePublicKey) { + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + SecTrustRef trust = NULL; - OSStatus status = SecTrustCreateWithCertificates(certificate, policy, &trust); + + OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); NSAssert(status == noErr, @"SecTrustCreateWithCertificates error: %ld", (long int)status); [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; CFRelease(trust); + CFRelease(certificates); } } @@ -622,7 +627,7 @@ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace return YES; } #endif - + if (self.authenticationAgainstProtectionSpace) { return self.authenticationAgainstProtectionSpace(connection, protectionSpace); } else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) { @@ -641,16 +646,16 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge return; } #endif - + if (self.authenticationChallenge) { self.authenticationChallenge(connection, challenge); } else { if ([challenge previousFailureCount] == 0) { NSURLCredential *credential = nil; - + NSString *user = [[self.request URL] user]; NSString *password = [[self.request URL] password]; - + if (user && password) { credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceNone]; } else if (user) { @@ -658,11 +663,11 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge } else { credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[challenge protectionSpace]]; } - + if (!credential) { credential = self.credential; } - + if (credential) { [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } else { @@ -684,7 +689,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge if ([request.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { return [request.HTTPBodyStream copy]; } - + return nil; } @@ -715,7 +720,7 @@ totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite didReceiveResponse:(NSURLResponse *)response { self.response = response; - + [self.outputStream open]; } @@ -738,11 +743,11 @@ didReceiveResponse:(NSURLResponse *)response - (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; - + [self.outputStream close]; - + [self finish]; - + self.connection = nil; } @@ -750,11 +755,11 @@ didReceiveResponse:(NSURLResponse *)response didFailWithError:(NSError *)error { self.error = error; - + [self.outputStream close]; - + [self finish]; - + self.connection = nil; } @@ -767,7 +772,7 @@ didReceiveResponse:(NSURLResponse *)response if ([self isCancelled]) { return nil; } - + return cachedResponse; } } @@ -776,27 +781,27 @@ didReceiveResponse:(NSURLResponse *)response - (id)initWithCoder:(NSCoder *)aDecoder { NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"]; - + self = [self initWithRequest:request]; if (!self) { return nil; } - + self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"]; self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"]; self.response = [aDecoder decodeObjectForKey:@"response"]; self.error = [aDecoder decodeObjectForKey:@"error"]; self.responseData = [aDecoder decodeObjectForKey:@"responseData"]; self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue]; - + return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [self pause]; - + [aCoder encodeObject:self.request forKey:@"request"]; - + switch (self.state) { case AFOperationExecutingState: case AFOperationPausedState: @@ -806,7 +811,7 @@ didReceiveResponse:(NSURLResponse *)response [aCoder encodeInteger:self.state forKey:@"state"]; break; } - + [aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"]; [aCoder encodeObject:self.response forKey:@"response"]; [aCoder encodeObject:self.error forKey:@"error"]; @@ -818,7 +823,7 @@ didReceiveResponse:(NSURLResponse *)response - (id)copyWithZone:(NSZone *)zone { AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; - + operation.uploadProgress = self.uploadProgress; operation.downloadProgress = self.downloadProgress; operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace;