FIRInstallationsIIDStore.m 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. * Copyright 2019 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 "FirebaseInstallations/Source/Library/IIDMigration/FIRInstallationsIIDStore.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. #import <CommonCrypto/CommonDigest.h>
  23. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsErrorUtil.h"
  24. static NSString *const kFIRInstallationsIIDKeyPairPublicTagPrefix =
  25. @"com.google.iid.keypair.public-";
  26. static NSString *const kFIRInstallationsIIDKeyPairPrivateTagPrefix =
  27. @"com.google.iid.keypair.private-";
  28. static NSString *const kFIRInstallationsIIDCreationTimePlistKey = @"|S|cre";
  29. @implementation FIRInstallationsIIDStore
  30. - (FBLPromise<NSString *> *)existingIID {
  31. return [FBLPromise onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  32. do:^id _Nullable {
  33. if (![self hasPlistIIDFlag]) {
  34. return nil;
  35. }
  36. NSData *IIDPublicKeyData = [self IIDPublicKeyData];
  37. return [self IIDWithPublicKeyData:IIDPublicKeyData];
  38. }]
  39. .validate(^BOOL(NSString *_Nullable IID) {
  40. return IID.length > 0;
  41. });
  42. }
  43. - (FBLPromise<NSNull *> *)deleteExistingIID {
  44. return [FBLPromise onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  45. do:^id _Nullable {
  46. NSError *error;
  47. if (![self deleteIIDFlagFromPlist:&error]) {
  48. return error;
  49. }
  50. if (![self deleteIID:&error]) {
  51. return error;
  52. }
  53. return [NSNull null];
  54. }];
  55. }
  56. #pragma mark - IID decoding
  57. - (NSString *)IIDWithPublicKeyData:(NSData *)publicKeyData {
  58. NSData *publicKeySHA1 = [self sha1WithData:publicKeyData];
  59. const uint8_t *bytes = publicKeySHA1.bytes;
  60. NSMutableData *identityData = [NSMutableData dataWithData:publicKeySHA1];
  61. uint8_t b0 = bytes[0];
  62. // Take the first byte and make the initial four 7 by initially making the initial 4 bits 0
  63. // and then adding 0x70 to it.
  64. b0 = 0x70 + (0xF & b0);
  65. // failsafe should give you back b0 itself
  66. b0 = (b0 & 0xFF);
  67. [identityData replaceBytesInRange:NSMakeRange(0, 1) withBytes:&b0];
  68. NSData *data = [identityData subdataWithRange:NSMakeRange(0, 8 * sizeof(Byte))];
  69. return [self base64URLEncodedStringWithData:data];
  70. }
  71. /** FirebaseInstallations SDK uses the SHA1 hash for backwards compatibility with the legacy
  72. * FirebaseInstanceID SDK. The SHA1 hash is used to access Instance IDs stored on the device and not
  73. * for any security-relevant process. This is a one-time step that allows migration of old client
  74. * identifiers. Cryptographic security is not needed here, so potential hash collisions are not a
  75. * problem.
  76. */
  77. - (NSData *)sha1WithData:(NSData *)data {
  78. unsigned char output[CC_SHA1_DIGEST_LENGTH];
  79. unsigned int length = (unsigned int)[data length];
  80. CC_SHA1(data.bytes, length, output);
  81. return [NSData dataWithBytes:output length:CC_SHA1_DIGEST_LENGTH];
  82. }
  83. - (NSString *)base64URLEncodedStringWithData:(NSData *)data {
  84. NSString *string = [data base64EncodedStringWithOptions:0];
  85. string = [string stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
  86. string = [string stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
  87. string = [string stringByReplacingOccurrencesOfString:@"=" withString:@""];
  88. return string;
  89. }
  90. #pragma mark - Keychain
  91. - (NSData *)IIDPublicKeyData {
  92. NSString *tag = [self keychainKeyTagWithPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix];
  93. NSDictionary *query = [self keyPairQueryWithTag:tag returnData:YES];
  94. CFTypeRef keyRef = NULL;
  95. OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&keyRef);
  96. if (status != noErr) {
  97. if (keyRef) {
  98. CFRelease(keyRef);
  99. }
  100. return nil;
  101. }
  102. return (__bridge NSData *)keyRef;
  103. }
  104. - (BOOL)deleteIID:(NSError **)outError {
  105. if (![self deleteKeychainKeyWithTagPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix
  106. error:outError]) {
  107. return NO;
  108. }
  109. if (![self deleteKeychainKeyWithTagPrefix:kFIRInstallationsIIDKeyPairPrivateTagPrefix
  110. error:outError]) {
  111. return NO;
  112. }
  113. return YES;
  114. }
  115. - (BOOL)deleteKeychainKeyWithTagPrefix:(NSString *)tagPrefix error:(NSError **)outError {
  116. NSString *keyTag = [self keychainKeyTagWithPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix];
  117. NSDictionary *keyQuery = [self keyPairQueryWithTag:keyTag returnData:NO];
  118. OSStatus status = SecItemDelete((__bridge CFDictionaryRef)keyQuery);
  119. // When item is not found, it should NOT be considered as an error. The operation should
  120. // continue.
  121. if (status != noErr && status != errSecItemNotFound) {
  122. FIRInstallationsItemSetErrorToPointer(
  123. [FIRInstallationsErrorUtil keychainErrorWithFunction:@"SecItemDelete" status:status],
  124. outError);
  125. return NO;
  126. }
  127. return YES;
  128. }
  129. - (NSDictionary *)keyPairQueryWithTag:(NSString *)tag returnData:(BOOL)shouldReturnData {
  130. NSMutableDictionary *query = [NSMutableDictionary dictionary];
  131. NSData *tagData = [tag dataUsingEncoding:NSUTF8StringEncoding];
  132. query[(__bridge id)kSecClass] = (__bridge id)kSecClassKey;
  133. query[(__bridge id)kSecAttrApplicationTag] = tagData;
  134. query[(__bridge id)kSecAttrKeyType] = (__bridge id)kSecAttrKeyTypeRSA;
  135. if (shouldReturnData) {
  136. query[(__bridge id)kSecReturnData] = @(YES);
  137. }
  138. #if TARGET_OS_OSX
  139. if (self.keychainRef) {
  140. query[(__bridge NSString *)kSecMatchSearchList] = @[ (__bridge id)(self.keychainRef) ];
  141. }
  142. #endif // TARGET_OSX
  143. return query;
  144. }
  145. - (NSString *)keychainKeyTagWithPrefix:(NSString *)prefix {
  146. NSString *mainAppBundleID = [[NSBundle mainBundle] bundleIdentifier];
  147. if (mainAppBundleID.length == 0) {
  148. return nil;
  149. }
  150. return [NSString stringWithFormat:@"%@%@", prefix, mainAppBundleID];
  151. }
  152. - (NSString *)mainbundleIdentifier {
  153. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  154. if (!bundleIdentifier.length) {
  155. return nil;
  156. }
  157. return bundleIdentifier;
  158. }
  159. #pragma mark - Plist
  160. - (BOOL)deleteIIDFlagFromPlist:(NSError **)outError {
  161. NSString *path = [self plistPath];
  162. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  163. return YES;
  164. }
  165. NSMutableDictionary *plistContent = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
  166. plistContent[kFIRInstallationsIIDCreationTimePlistKey] = nil;
  167. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  168. return [plistContent writeToURL:[NSURL fileURLWithPath:path] error:outError];
  169. }
  170. return [plistContent writeToFile:path atomically:YES];
  171. }
  172. - (BOOL)hasPlistIIDFlag {
  173. NSString *path = [self plistPath];
  174. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  175. return NO;
  176. }
  177. NSDictionary *plistContent = [[NSDictionary alloc] initWithContentsOfFile:path];
  178. return plistContent[kFIRInstallationsIIDCreationTimePlistKey] != nil;
  179. }
  180. - (NSString *)plistPath {
  181. NSString *plistNameWithExtension = @"com.google.iid-keypair.plist";
  182. NSString *_subDirectoryName = @"Google/FirebaseInstanceID";
  183. NSArray *directoryPaths =
  184. NSSearchPathForDirectoriesInDomains([self supportedDirectory], NSUserDomainMask, YES);
  185. NSArray *components = @[ directoryPaths.lastObject, _subDirectoryName, plistNameWithExtension ];
  186. return [NSString pathWithComponents:components];
  187. }
  188. - (NSSearchPathDirectory)supportedDirectory {
  189. #if TARGET_OS_TV
  190. return NSCachesDirectory;
  191. #else
  192. return NSApplicationSupportDirectory;
  193. #endif
  194. }
  195. @end