FIRInstallationsIIDStore.m 7.7 KB

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