Skip to content

Commit

Permalink
Add optional SSL certificate pinning
Browse files Browse the repository at this point in the history
  • Loading branch information
dstnbrkr authored and mattt committed Dec 26, 2012
1 parent a146a3b commit 07c9f6c
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions AFNetworking/AFURLConnectionOperation.m
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,24 @@ + (NSThread *)networkRequestThread {
return _networkRequestThread;
}

+ (NSArray *)pinnedCertificates {
static NSArray *_pinnedCertificates = nil;
static dispatch_once_t oncePredicate;

dispatch_once(&oncePredicate, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableArray *certificates = [NSMutableArray array];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});

return _pinnedCertificates;
}

- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super init];
if (!self) {
Expand Down Expand Up @@ -467,6 +485,25 @@ - (void)cancelConnection {

#pragma mark - NSURLConnectionDelegate

#ifdef _AFNETWORKING_PIN_SSL_CERTIFICATES_
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));

NSArray *pinnedCertificates = [[self class] pinnedCertificates];
if ([pinnedCertificates containsObject:remoteCertificateData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
}
#endif

- (BOOL)connection:(NSURLConnection *)connection
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
Expand Down

0 comments on commit 07c9f6c

Please sign in to comment.