FIRAuthKeychainServices.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAuth/Sources/Storage/FIRAuthKeychainServices.h"
  17. #import <Security/Security.h>
  18. #import "FirebaseAuth/Sources/Storage/FIRAuthUserDefaults.h"
  19. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  20. /** @var kAccountPrefix
  21. @brief The prefix string for keychain item account attribute before the key.
  22. @remarks A number "1" is encoded in the prefix in case we need to upgrade the scheme in future.
  23. */
  24. static NSString *const kAccountPrefix = @"firebase_auth_1_";
  25. NS_ASSUME_NONNULL_BEGIN
  26. @implementation FIRAuthKeychainServices {
  27. /** @var _service
  28. @brief The name of the keychain service.
  29. */
  30. NSString *_service;
  31. /** @var _legacyItemDeletedForKey
  32. @brief Indicates whether or not this class knows that the legacy item for a particular key has
  33. been deleted.
  34. @remarks This dictionary is to avoid unecessary keychain operations against legacy items.
  35. */
  36. NSMutableDictionary *_legacyEntryDeletedForKey;
  37. }
  38. - (id<FIRAuthStorage>)initWithService:(NSString *)service {
  39. self = [super init];
  40. if (self) {
  41. _service = [service copy];
  42. _legacyEntryDeletedForKey = [[NSMutableDictionary alloc] init];
  43. }
  44. return self;
  45. }
  46. - (nullable NSData *)dataForKey:(NSString *)key error:(NSError **_Nullable)error {
  47. if (!key.length) {
  48. [NSException raise:NSInvalidArgumentException format:@"%@", @"The key cannot be nil or empty."];
  49. return nil;
  50. }
  51. NSData *data = [self itemWithQuery:[self genericPasswordQueryWithKey:key] error:error];
  52. if (error && *error) {
  53. return nil;
  54. }
  55. if (data) {
  56. return data;
  57. }
  58. // Check for legacy form.
  59. if (_legacyEntryDeletedForKey[key]) {
  60. return nil;
  61. }
  62. data = [self itemWithQuery:[self legacyGenericPasswordQueryWithKey:key] error:error];
  63. if (error && *error) {
  64. return nil;
  65. }
  66. if (!data) {
  67. // Mark legacy data as non-existing so we don't have to query it again.
  68. _legacyEntryDeletedForKey[key] = @YES;
  69. return nil;
  70. }
  71. // Move the data to current form.
  72. if (![self setData:data forKey:key error:error]) {
  73. return nil;
  74. }
  75. [self deleteLegacyItemWithKey:key];
  76. return data;
  77. }
  78. - (BOOL)setData:(NSData *)data forKey:(NSString *)key error:(NSError **_Nullable)error {
  79. if (!key.length) {
  80. [NSException raise:NSInvalidArgumentException format:@"%@", @"The key cannot be nil or empty."];
  81. return NO;
  82. }
  83. NSDictionary *attributes = @{
  84. (__bridge id)kSecValueData : data,
  85. (__bridge id)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
  86. };
  87. return [self setItemWithQuery:[self genericPasswordQueryWithKey:key]
  88. attributes:attributes
  89. error:error];
  90. }
  91. - (BOOL)removeDataForKey:(NSString *)key error:(NSError **_Nullable)error {
  92. if (!key.length) {
  93. [NSException raise:NSInvalidArgumentException format:@"%@", @"The key cannot be nil or empty."];
  94. return NO;
  95. }
  96. if (![self deleteItemWithQuery:[self genericPasswordQueryWithKey:key] error:error]) {
  97. return NO;
  98. }
  99. // Legacy form item, if exists, also needs to be removed, otherwise it will be exposed when
  100. // current form item is removed, leading to incorrect semantics.
  101. [self deleteLegacyItemWithKey:key];
  102. return YES;
  103. }
  104. #pragma mark - Private methods for non-sharing keychain operations
  105. - (nullable NSData *)itemWithQuery:(NSDictionary *)query error:(NSError **_Nullable)error {
  106. NSMutableDictionary *returningQuery = [query mutableCopy];
  107. returningQuery[(__bridge id)kSecReturnData] = @YES;
  108. returningQuery[(__bridge id)kSecReturnAttributes] = @YES;
  109. // Using a match limit of 2 means that we can check whether there is more than one item.
  110. // If we used a match limit of 1 we would never find out.
  111. returningQuery[(__bridge id)kSecMatchLimit] = @2;
  112. CFArrayRef result = NULL;
  113. OSStatus status =
  114. SecItemCopyMatching((__bridge CFDictionaryRef)returningQuery, (CFTypeRef *)&result);
  115. if (status == noErr && result != NULL) {
  116. NSArray *items = (__bridge_transfer NSArray *)result;
  117. if (items.count != 1) {
  118. if (error) {
  119. *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching" status:status];
  120. }
  121. return nil;
  122. }
  123. if (error) {
  124. *error = nil;
  125. }
  126. NSDictionary *item = items[0];
  127. return item[(__bridge id)kSecValueData];
  128. }
  129. if (status == errSecItemNotFound) {
  130. if (error) {
  131. *error = nil;
  132. }
  133. } else {
  134. if (error) {
  135. *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching" status:status];
  136. }
  137. }
  138. return nil;
  139. }
  140. - (BOOL)setItemWithQuery:(NSDictionary *)query
  141. attributes:(NSDictionary *)attributes
  142. error:(NSError **_Nullable)error {
  143. NSMutableDictionary *combined = [attributes mutableCopy];
  144. [combined addEntriesFromDictionary:query];
  145. BOOL hasItem = NO;
  146. OSStatus status = SecItemAdd((__bridge CFDictionaryRef)combined, NULL);
  147. if (status == errSecDuplicateItem) {
  148. hasItem = YES;
  149. status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)attributes);
  150. }
  151. if (status == noErr) {
  152. return YES;
  153. }
  154. if (error) {
  155. NSString *function = hasItem ? @"SecItemUpdate" : @"SecItemAdd";
  156. *error = [FIRAuthErrorUtils keychainErrorWithFunction:function status:status];
  157. }
  158. return NO;
  159. }
  160. - (BOOL)deleteItemWithQuery:(NSDictionary *)query error:(NSError **_Nullable)error {
  161. OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
  162. if (status == noErr || status == errSecItemNotFound) {
  163. return YES;
  164. }
  165. if (error) {
  166. *error = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemDelete" status:status];
  167. }
  168. return NO;
  169. }
  170. /** @fn deleteLegacyItemsWithKey:
  171. @brief Deletes legacy item from the keychain if it is not already known to be deleted.
  172. @param key The key for the item.
  173. */
  174. - (void)deleteLegacyItemWithKey:(NSString *)key {
  175. if (_legacyEntryDeletedForKey[key]) {
  176. return;
  177. }
  178. NSDictionary *query = [self legacyGenericPasswordQueryWithKey:key];
  179. SecItemDelete((__bridge CFDictionaryRef)query);
  180. _legacyEntryDeletedForKey[key] = @YES;
  181. }
  182. /** @fn genericPasswordQueryWithKey:
  183. @brief Returns a keychain query of generic password to be used to manipulate key'ed value.
  184. @param key The key for the value being manipulated, used as the account field in the query.
  185. */
  186. - (NSDictionary *)genericPasswordQueryWithKey:(NSString *)key {
  187. return @{
  188. (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
  189. (__bridge id)kSecAttrAccount : [kAccountPrefix stringByAppendingString:key],
  190. (__bridge id)kSecAttrService : _service,
  191. };
  192. }
  193. /** @fn legacyGenericPasswordQueryWithKey:
  194. @brief Returns a keychain query of generic password without service field, which is used by
  195. previous version of this class.
  196. @param key The key for the value being manipulated, used as the account field in the query.
  197. */
  198. - (NSDictionary *)legacyGenericPasswordQueryWithKey:(NSString *)key {
  199. return @{
  200. (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
  201. (__bridge id)kSecAttrAccount : key,
  202. };
  203. }
  204. #pragma mark - Private methods for shared keychain operations
  205. - (nullable NSData *)getItemWithQuery:(NSDictionary *)query
  206. error:(NSError *_Nullable *_Nullable)outError {
  207. NSMutableDictionary *mutableQuery = [query mutableCopy];
  208. mutableQuery[(__bridge id)kSecReturnData] = @YES;
  209. mutableQuery[(__bridge id)kSecReturnAttributes] = @YES;
  210. mutableQuery[(__bridge id)kSecMatchLimit] = @2;
  211. CFArrayRef result = NULL;
  212. OSStatus status =
  213. SecItemCopyMatching((__bridge CFDictionaryRef)mutableQuery, (CFTypeRef *)&result);
  214. if (status == noErr && result != NULL) {
  215. NSArray *items = (__bridge_transfer NSArray *)result;
  216. if (items.count != 1) {
  217. if (outError) {
  218. *outError = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching"
  219. status:status];
  220. }
  221. return nil;
  222. }
  223. if (outError) {
  224. *outError = nil;
  225. }
  226. NSDictionary *item = items[0];
  227. return item[(__bridge id)kSecValueData];
  228. }
  229. if (status == errSecItemNotFound) {
  230. if (outError) {
  231. *outError = nil;
  232. }
  233. } else {
  234. if (outError) {
  235. *outError = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemCopyMatching"
  236. status:status];
  237. }
  238. }
  239. return nil;
  240. }
  241. - (BOOL)setItem:(NSData *)item
  242. withQuery:(NSDictionary *)query
  243. error:(NSError *_Nullable *_Nullable)outError {
  244. NSData *existingItem = [self getItemWithQuery:query error:outError];
  245. if (outError && *outError) {
  246. return NO;
  247. }
  248. OSStatus status;
  249. if (!existingItem) {
  250. NSMutableDictionary *queryWithItem = [query mutableCopy];
  251. [queryWithItem setObject:item forKey:(__bridge id)kSecValueData];
  252. status = SecItemAdd((__bridge CFDictionaryRef)queryWithItem, NULL);
  253. } else {
  254. NSDictionary *attributes = @{(__bridge id)kSecValueData : item};
  255. status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)attributes);
  256. }
  257. if (status == noErr) {
  258. if (outError) {
  259. *outError = nil;
  260. }
  261. return YES;
  262. }
  263. NSString *function = existingItem ? @"SecItemUpdate" : @"SecItemAdd";
  264. if (outError) {
  265. *outError = [FIRAuthErrorUtils keychainErrorWithFunction:function status:status];
  266. }
  267. return NO;
  268. }
  269. - (BOOL)removeItemWithQuery:(NSDictionary *)query error:(NSError *_Nullable *_Nullable)outError {
  270. OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
  271. if (status == noErr || status == errSecItemNotFound) {
  272. if (outError) {
  273. *outError = nil;
  274. }
  275. return YES;
  276. }
  277. if (outError) {
  278. *outError = [FIRAuthErrorUtils keychainErrorWithFunction:@"SecItemDelete" status:status];
  279. }
  280. return NO;
  281. }
  282. @end
  283. NS_ASSUME_NONNULL_END