AFSecurityPolicy.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out);
  53. allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);
  54. _out:
  55. if (allowedTrust) {
  56. CFRelease(allowedTrust);
  57. }
  58. if (policy) {
  59. CFRelease(policy);
  60. }
  61. if (allowedCertificate) {
  62. CFRelease(allowedCertificate);
  63. }
  64. return allowedPublicKey;
  65. }
  66. static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
  67. BOOL isValid = NO;
  68. SecTrustResultType result;
  69. __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out);
  70. isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
  71. _out:
  72. return isValid;
  73. }
  74. static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
  75. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  76. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  77. for (CFIndex i = 0; i < certificateCount; i++) {
  78. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  79. [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
  80. }
  81. return [NSArray arrayWithArray:trustChain];
  82. }
  83. static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
  84. SecPolicyRef policy = SecPolicyCreateBasicX509();
  85. CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
  86. NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
  87. for (CFIndex i = 0; i < certificateCount; i++) {
  88. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
  89. SecCertificateRef someCertificates[] = {certificate};
  90. CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
  91. SecTrustRef trust;
  92. __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out);
  93. SecTrustResultType result;
  94. __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out);
  95. [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
  96. _out:
  97. if (trust) {
  98. CFRelease(trust);
  99. }
  100. if (certificates) {
  101. CFRelease(certificates);
  102. }
  103. continue;
  104. }
  105. CFRelease(policy);
  106. return [NSArray arrayWithArray:trustChain];
  107. }
  108. #pragma mark -
  109. @interface AFSecurityPolicy()
  110. @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode;
  111. @property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys;
  112. @end
  113. @implementation AFSecurityPolicy
  114. + (NSSet *)certificatesInBundle:(NSBundle *)bundle {
  115. NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
  116. NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]];
  117. for (NSString *path in paths) {
  118. NSData *certificateData = [NSData dataWithContentsOfFile:path];
  119. [certificates addObject:certificateData];
  120. }
  121. return [NSSet setWithSet:certificates];
  122. }
  123. + (NSSet *)defaultPinnedCertificates {
  124. static NSSet *_defaultPinnedCertificates = nil;
  125. static dispatch_once_t onceToken;
  126. dispatch_once(&onceToken, ^{
  127. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  128. _defaultPinnedCertificates = [self certificatesInBundle:bundle];
  129. });
  130. return _defaultPinnedCertificates;
  131. }
  132. + (instancetype)defaultPolicy {
  133. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  134. securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
  135. return securityPolicy;
  136. }
  137. + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode {
  138. return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]];
  139. }
  140. + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates {
  141. AFSecurityPolicy *securityPolicy = [[self alloc] init];
  142. securityPolicy.SSLPinningMode = pinningMode;
  143. [securityPolicy setPinnedCertificates:pinnedCertificates];
  144. return securityPolicy;
  145. }
  146. - (instancetype)init {
  147. self = [super init];
  148. if (!self) {
  149. return nil;
  150. }
  151. self.validatesDomainName = YES;
  152. return self;
  153. }
  154. - (void)setPinnedCertificates:(NSSet *)pinnedCertificates {
  155. _pinnedCertificates = pinnedCertificates;
  156. if (self.pinnedCertificates) {
  157. NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]];
  158. for (NSData *certificate in self.pinnedCertificates) {
  159. id publicKey = AFPublicKeyForCertificate(certificate);
  160. if (!publicKey) {
  161. continue;
  162. }
  163. [mutablePinnedPublicKeys addObject:publicKey];
  164. }
  165. self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys];
  166. } else {
  167. self.pinnedPublicKeys = nil;
  168. }
  169. }
  170. #pragma mark -
  171. - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
  172. forDomain:(NSString *)domain
  173. {
  174. if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) {
  175. // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html
  176. // According to the docs, you should only trust your provided certs for evaluation.
  177. // Pinned certificates are added to the trust. Without pinned certificates,
  178. // there is nothing to evaluate against.
  179. //
  180. // From Apple Docs:
  181. // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors).
  182. // Instead, add your own (self-signed) CA certificate to the list of trusted anchors."
  183. NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning.");
  184. return NO;
  185. }
  186. NSMutableArray *policies = [NSMutableArray array];
  187. if (self.validatesDomainName) {
  188. [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
  189. } else {
  190. [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
  191. }
  192. SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
  193. if (self.SSLPinningMode == AFSSLPinningModeNone) {
  194. return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust);
  195. } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
  196. return NO;
  197. }
  198. switch (self.SSLPinningMode) {
  199. case AFSSLPinningModeNone:
  200. default:
  201. return NO;
  202. case AFSSLPinningModeCertificate: {
  203. NSMutableArray *pinnedCertificates = [NSMutableArray array];
  204. for (NSData *certificateData in self.pinnedCertificates) {
  205. [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
  206. }
  207. SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
  208. if (!AFServerTrustIsValid(serverTrust)) {
  209. return NO;
  210. }
  211. // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA)
  212. NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust);
  213. for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) {
  214. if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
  215. return YES;
  216. }
  217. }
  218. return NO;
  219. }
  220. case AFSSLPinningModePublicKey: {
  221. NSUInteger trustedPublicKeyCount = 0;
  222. NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
  223. for (id trustChainPublicKey in publicKeys) {
  224. for (id pinnedPublicKey in self.pinnedPublicKeys) {
  225. if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
  226. trustedPublicKeyCount += 1;
  227. }
  228. }
  229. }
  230. return trustedPublicKeyCount > 0;
  231. }
  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:[NSArray 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