FIRInstallationsIIDStore.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 "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 "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. - (NSData *)sha1WithData:(NSData *)data {
  72. unsigned char output[CC_SHA1_DIGEST_LENGTH];
  73. unsigned int length = (unsigned int)[data length];
  74. CC_SHA1(data.bytes, length, output);
  75. return [NSData dataWithBytes:output length:CC_SHA1_DIGEST_LENGTH];
  76. }
  77. - (NSString *)base64URLEncodedStringWithData:(NSData *)data {
  78. NSString *string = [data base64EncodedStringWithOptions:0];
  79. string = [string stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
  80. string = [string stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
  81. string = [string stringByReplacingOccurrencesOfString:@"=" withString:@""];
  82. return string;
  83. }
  84. #pragma mark - Keychain
  85. - (NSData *)IIDPublicKeyData {
  86. NSString *tag = [self keychainKeyTagWithPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix];
  87. NSDictionary *query = [self keyPairQueryWithTag:tag returnData:YES];
  88. CFTypeRef keyRef = NULL;
  89. OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&keyRef);
  90. if (status != noErr) {
  91. if (keyRef) {
  92. CFRelease(keyRef);
  93. }
  94. return nil;
  95. }
  96. return (__bridge NSData *)keyRef;
  97. }
  98. - (BOOL)deleteIID:(NSError **)outError {
  99. if (![self deleteKeychainKeyWithTagPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix
  100. error:outError]) {
  101. return NO;
  102. }
  103. if (![self deleteKeychainKeyWithTagPrefix:kFIRInstallationsIIDKeyPairPrivateTagPrefix
  104. error:outError]) {
  105. return NO;
  106. }
  107. return YES;
  108. }
  109. - (BOOL)deleteKeychainKeyWithTagPrefix:(NSString *)tagPrefix error:(NSError **)outError {
  110. NSString *keyTag = [self keychainKeyTagWithPrefix:kFIRInstallationsIIDKeyPairPublicTagPrefix];
  111. NSDictionary *keyQuery = [self keyPairQueryWithTag:keyTag returnData:NO];
  112. OSStatus status = SecItemDelete((__bridge CFDictionaryRef)keyQuery);
  113. // When item is not found, it should NOT be considered as an error. The operation should
  114. // continue.
  115. if (status != noErr && status != errSecItemNotFound) {
  116. FIRInstallationsItemSetErrorToPointer(
  117. [FIRInstallationsErrorUtil keychainErrorWithFunction:@"SecItemDelete" status:status],
  118. outError);
  119. return NO;
  120. }
  121. return YES;
  122. }
  123. - (NSDictionary *)keyPairQueryWithTag:(NSString *)tag returnData:(BOOL)shouldReturnData {
  124. NSMutableDictionary *query = [NSMutableDictionary dictionary];
  125. NSData *tagData = [tag dataUsingEncoding:NSUTF8StringEncoding];
  126. query[(__bridge id)kSecClass] = (__bridge id)kSecClassKey;
  127. query[(__bridge id)kSecAttrApplicationTag] = tagData;
  128. query[(__bridge id)kSecAttrKeyType] = (__bridge id)kSecAttrKeyTypeRSA;
  129. if (shouldReturnData) {
  130. query[(__bridge id)kSecReturnData] = @(YES);
  131. }
  132. #if TARGET_OS_OSX
  133. if (self.keychainRef) {
  134. query[(__bridge NSString *)kSecMatchSearchList] = @[ (__bridge id)(self.keychainRef) ];
  135. }
  136. #endif // TARGET_OSX
  137. return query;
  138. }
  139. - (NSString *)keychainKeyTagWithPrefix:(NSString *)prefix {
  140. NSString *mainAppBundleID = [[NSBundle mainBundle] bundleIdentifier];
  141. if (mainAppBundleID.length == 0) {
  142. return nil;
  143. }
  144. return [NSString stringWithFormat:@"%@%@", prefix, mainAppBundleID];
  145. }
  146. - (NSString *)mainbundleIdentifier {
  147. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  148. if (!bundleIdentifier.length) {
  149. return nil;
  150. }
  151. return bundleIdentifier;
  152. }
  153. #pragma mark - Plist
  154. - (BOOL)deleteIIDFlagFromPlist:(NSError **)outError {
  155. NSString *path = [self plistPath];
  156. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  157. return YES;
  158. }
  159. NSMutableDictionary *plistContent = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
  160. plistContent[kFIRInstallationsIIDCreationTimePlistKey] = nil;
  161. if (@available(macOS 10.13, iOS 11.0, tvOS 11.0, *)) {
  162. return [plistContent writeToURL:[NSURL fileURLWithPath:path] error:outError];
  163. }
  164. return [plistContent writeToFile:path atomically:YES];
  165. }
  166. - (BOOL)hasPlistIIDFlag {
  167. NSString *path = [self plistPath];
  168. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  169. return NO;
  170. }
  171. NSDictionary *plistContent = [[NSDictionary alloc] initWithContentsOfFile:path];
  172. return plistContent[kFIRInstallationsIIDCreationTimePlistKey] != nil;
  173. }
  174. - (NSString *)plistPath {
  175. NSString *plistNameWithExtension = @"com.google.iid-keypair.plist";
  176. NSString *_subDirectoryName = @"Google/FirebaseInstanceID";
  177. NSArray *directoryPaths =
  178. NSSearchPathForDirectoriesInDomains([self supportedDirectory], NSUserDomainMask, YES);
  179. NSArray *components = @[ directoryPaths.lastObject, _subDirectoryName, plistNameWithExtension ];
  180. return [NSString pathWithComponents:components];
  181. }
  182. - (NSSearchPathDirectory)supportedDirectory {
  183. #if TARGET_OS_TV
  184. return NSCachesDirectory;
  185. #else
  186. return NSApplicationSupportDirectory;
  187. #endif
  188. }
  189. @end