AFSecurityPolicy.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // AFSecurityPolicy.m
  2. // Copyright (c) 2011–2016 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 !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV
  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 TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
  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. SecPolicyRef policy = nil;
  46. SecTrustRef allowedTrust = nil;
  47. SecTrustResultType result;
  48. allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
  49. __Require_Quiet(allowedCertificate != NULL, _out);
  50. policy = SecPolicyCreateBasicX509();
  51. __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out);
  52. #pragma clang diagnostic push
  53. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  54. __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
  55. #pragma clang diagnostic pop
  56. allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
  57. _out:
  58. if (allowedTrust) {
  59. CFRelease(allowedTrust);
  60. }
  61. if (policy) {
  62. CFRelease(policy);
  63. }
  64. if (allowedCertificate) {
  65. CFRelease(allowedCertificate);
  66. }
  67. return allowedPublicKey;
  68. }
  69. static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
  70. BOOL isValid = NO;
  71. SecTrustResultType result;
  72. #pragma clang diagnostic push
  73. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  74. __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
  75. #pragma clang diagnostic pop
  76. isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
  77. _out:
  78. return isValid;
  79. }
  80. static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
  81. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  82. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  83. for (CFIndex i = 0; i < certificateCount; i++) {
  84. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  85. [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
  86. }
  87. return [NSArray arrayWithArray:trustChain];
  88. }
  89. static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
  90. SecPolicyRef policy = SecPolicyCreateBasicX509();
  91. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  92. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  93. for (CFIndex i = 0; i < certificateCount; i++) {
  94. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  95. SecCertificateRef someCertificates[] = {certificate};
  96. CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
  97. SecTrustRef trust;
  98. __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
  99. SecTrustResultType result;
  100. #pragma clang diagnostic push
  101. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  102. __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
  103. #pragma clang diagnostic pop
  104. [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
  105. _out:
  106. if (trust) {
  107. CFRelease(trust);
  108. }
  109. if (certificates) {
  110. CFRelease(certificates);
  111. }
  112. continue;
  113. }
  114. CFRelease(policy);
  115. return [NSArray arrayWithArray:trustChain];
  116. }
  117. #pragma mark -
  118. @interface AFSecurityPolicy()
  119. @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
  120. @property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
  121. @end
  122. @implementation AFSecurityPolicy
  123. + (NSSet *)certificatesInBundle:(NSBundle *)bundle {
  124. NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
  125. NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
  126. for (NSString *path in paths) {
  127. NSData *certificateData = [NSData dataWithContentsOfFile:path];
  128. [certificates addObject:certificateData];
  129. }
  130. return [NSSet setWithSet:certificates];
  131. }
  132. + (instancetype)defaultPolicy {
  133. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  134. securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
  135. return securityPolicy;
  136. }
  137. + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
  138. NSSet <NSData *> *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]];
  139. return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates];
  140. }
  141. + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
  142. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  143. securityPolicy.SSLPinningMode = pinningMode;
  144. [securityPolicy setPinnedCertificates:pinnedCertificates];
  145. return securityPolicy;
  146. }
  147. - (instancetype)init {
  148. self = [super init];
  149. if (!self) {
  150. return nil;
  151. }
  152. self.validatesDomainName = YES;
  153. return self;
  154. }
  155. - (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
  156. _pinnedCertificates = pinnedCertificates;
  157. if (self.pinnedCertificates) {
  158. NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
  159. for (NSData *certificate in self.pinnedCertificates) {
  160. id publicKey = AFPublicKeyForCertificate(certificate);
  161. if (!publicKey) {
  162. continue;
  163. }
  164. [mutablePinnedPublicKeys addObject:publicKey];
  165. }
  166. self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
  167. } else {
  168. self.pinnedPublicKeys = nil;
  169. }
  170. }
  171. #pragma mark -
  172. - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
  173. forDomain:(NSString *)domain
  174. {
  175. if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
  176. // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
  177. // According to the docs, you should only trust your provided certs for evaluation.
  178. // Pinned certificates are added to the trust. Without pinned certificates,
  179. // there is nothing to evaluate against.
  180. //
  181. // From Apple Docs:
  182. // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
  183. // Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
  184. NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
  185. return NO;
  186. }
  187. NSMutableArray *policies = [NSMutableArray array];
  188. if (self.validatesDomainName) {
  189. [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
  190. } else {
  191. [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
  192. }
  193. SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
  194. if (self.SSLPinningMode == AFSSLPinningModeNone) {
  195. return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
  196. } else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) {
  197. return NO;
  198. }
  199. switch (self.SSLPinningMode) {
  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. // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
  210. NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
  211. for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
  212. if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
  213. return YES;
  214. }
  215. }
  216. return NO;
  217. }
  218. case AFSSLPinningModePublicKey: {
  219. NSUInteger trustedPublicKeyCount = 0;
  220. NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
  221. for (id trustChainPublicKey in publicKeys) {
  222. for (id pinnedPublicKey in self.pinnedPublicKeys) {
  223. if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
  224. trustedPublicKeyCount += 1;
  225. }
  226. }
  227. }
  228. return trustedPublicKeyCount > 0;
  229. }
  230. default:
  231. return NO;
  232. }
  233. return NO;
  234. }
  235. #pragma mark - NSKeyValueObserving
  236. + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys {
  237. return [NSSet setWithObject:@"pinnedCertificates"];
  238. }
  239. #pragma mark - NSSecureCoding
  240. + (BOOL)supportsSecureCoding {
  241. return YES;
  242. }
  243. - (instancetype)initWithCoder:(NSCoder *)decoder {
  244. self = [self init];
  245. if (!self) {
  246. return nil;
  247. }
  248. self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue];
  249. self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
  250. self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))];
  251. self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))];
  252. return self;
  253. }
  254. - (void)encodeWithCoder:(NSCoder *)coder {
  255. [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))];
  256. [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))];
  257. [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))];
  258. [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))];
  259. }
  260. #pragma mark - NSCopying
  261. - (instancetype)copyWithZone:(NSZone *)zone {
  262. AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init];
  263. securityPolicy.SSLPinningMode = self.SSLPinningMode;
  264. securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates;
  265. securityPolicy.validatesDomainName = self.validatesDomainName;
  266. securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone];
  267. return securityPolicy;
  268. }
  269. @end