AFSecurityPolicy.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // AFSecurityPolicy.m
  2. // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "AFSecurityPolicy.h"
  22. #import <AssertMacros.h>
  23. #if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  24. static NSData * AFSecKeyGetData(SecKeyRef key) {
  25. CFDataRef data = NULL;
  26. __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out);
  27. return (__bridge_transfer NSData *)data;
  28. _out:
  29. if (data) {
  30. CFRelease(data);
  31. }
  32. return nil;
  33. }
  34. #endif
  35. static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
  36. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  37. return [(__bridge id)key1 isEqual:(__bridge id)key2];
  38. #else
  39. return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)];
  40. #endif
  41. }
  42. static id AFPublicKeyForCertificate(NSData *certificate) {
  43. id allowedPublicKey = nil;
  44. SecCertificateRef allowedCertificate;
  45. SecCertificateRef allowedCertificates[1];
  46. CFArrayRef tempCertificates = nil;
  47. SecPolicyRef policy = nil;
  48. SecTrustRef allowedTrust = nil;
  49. SecTrustResultType result;
  50. allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
  51. __Require_Quiet(allowedCertificate != NULL, _out);
  52. allowedCertificates[0] = allowedCertificate;
  53. tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
  54. policy = SecPolicyCreateBasicX509();
  55. __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out);
  56. __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
  57. allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
  58. _out:
  59. if (allowedTrust) {
  60. CFRelease(allowedTrust);
  61. }
  62. if (policy) {
  63. CFRelease(policy);
  64. }
  65. if (tempCertificates) {
  66. CFRelease(tempCertificates);
  67. }
  68. if (allowedCertificate) {
  69. CFRelease(allowedCertificate);
  70. }
  71. return allowedPublicKey;
  72. }
  73. static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
  74. BOOL isValid = NO;
  75. SecTrustResultType result;
  76. __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
  77. isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
  78. _out:
  79. return isValid;
  80. }
  81. static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
  82. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  83. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  84. for (CFIndex i = 0; i < certificateCount; i++) {
  85. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  86. [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
  87. }
  88. return [NSArray arrayWithArray:trustChain];
  89. }
  90. static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
  91. SecPolicyRef policy = SecPolicyCreateBasicX509();
  92. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  93. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  94. for (CFIndex i = 0; i < certificateCount; i++) {
  95. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  96. SecCertificateRef someCertificates[] = {certificate};
  97. CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
  98. SecTrustRef trust;
  99. __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
  100. SecTrustResultType result;
  101. __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
  102. [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
  103. _out:
  104. if (trust) {
  105. CFRelease(trust);
  106. }
  107. if (certificates) {
  108. CFRelease(certificates);
  109. }
  110. continue;
  111. }
  112. CFRelease(policy);
  113. return [NSArray arrayWithArray:trustChain];
  114. }
  115. #pragma mark -
  116. @interface AFSecurityPolicy()
  117. @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
  118. @property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys;
  119. @end
  120. @implementation AFSecurityPolicy
  121. + (NSArray *)defaultPinnedCertificates {
  122. static NSArray *_defaultPinnedCertificates = nil;
  123. static dispatch_once_t onceToken;
  124. dispatch_once(&onceToken, ^{
  125. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  126. NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
  127. NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
  128. for (NSString *path in paths) {
  129. NSData *certificateData = [NSData dataWithContentsOfFile:path];
  130. [certificates addObject:certificateData];
  131. }
  132. _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
  133. });
  134. return _defaultPinnedCertificates;
  135. }
  136. + (instancetype)defaultPolicy {
  137. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  138. securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
  139. return securityPolicy;
  140. }
  141. + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
  142. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  143. securityPolicy.SSLPinningMode = pinningMode;
  144. [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
  145. return securityPolicy;
  146. }
  147. - (id)init {
  148. self = [super init];
  149. if (!self) {
  150. return nil;
  151. }
  152. self.validatesCertificateChain = YES;
  153. self.validatesDomainName = YES;
  154. return self;
  155. }
  156. - (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
  157. _pinnedCertificates = pinnedCertificates;
  158. if (self.pinnedCertificates) {
  159. NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
  160. for (NSData *certificate in self.pinnedCertificates) {
  161. id publicKey = AFPublicKeyForCertificate(certificate);
  162. if (!publicKey) {
  163. continue;
  164. }
  165. [mutablePinnedPublicKeys addObject:publicKey];
  166. }
  167. self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys];
  168. } else {
  169. self.pinnedPublicKeys = nil;
  170. }
  171. }
  172. #pragma mark -
  173. - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust {
  174. return [self evaluateServerTrust:serverTrust forDomain:nil];
  175. }
  176. - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
  177. forDomain:(NSString *)domain
  178. {
  179. NSMutableArray *policies = [NSMutableArray array];
  180. if (self.validatesDomainName) {
  181. [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
  182. } else {
  183. [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
  184. }
  185. SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
  186. if (self.SSLPinningMode == AFSSLPinningModeNone) {
  187. if (self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust)){
  188. return YES;
  189. } else {
  190. return NO;
  191. }
  192. } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
  193. return NO;
  194. }
  195. NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
  196. switch (self.SSLPinningMode) {
  197. case AFSSLPinningModeNone:
  198. default:
  199. return NO;
  200. case AFSSLPinningModeCertificate: {
  201. NSMutableArray *pinnedCertificates = [NSMutableArray array];
  202. for (NSData *certificateData in self.pinnedCertificates) {
  203. [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
  204. }
  205. SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
  206. if (!AFServerTrustIsValid(serverTrust)) {
  207. return NO;
  208. }
  209. if (!self.validatesCertificateChain) {
  210. return YES;
  211. }
  212. NSUInteger trustedCertificateCount = 0;
  213. for (NSData *trustChainCertificate in serverCertificates) {
  214. if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
  215. trustedCertificateCount++;
  216. }
  217. }
  218. return trustedCertificateCount == [serverCertificates count];
  219. }
  220. case AFSSLPinningModePublicKey: {
  221. NSUInteger trustedPublicKeyCount = 0;
  222. NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
  223. if (!self.validatesCertificateChain && [publicKeys count] > 0) {
  224. publicKeys = @[[publicKeys firstObject]];
  225. }
  226. for (id trustChainPublicKey in publicKeys) {
  227. for (id pinnedPublicKey in self.pinnedPublicKeys) {
  228. if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
  229. trustedPublicKeyCount += 1;
  230. }
  231. }
  232. }
  233. return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
  234. }
  235. }
  236. return NO;
  237. }
  238. #pragma mark - NSKeyValueObserving
  239. + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
  240. return [NSSet setWithObject:@"pinnedCertificates"];
  241. }
  242. @end