GULAppEnvironmentUtil.m 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleUtilities/Environment/third_party/GULAppEnvironmentUtil.h"
  15. #import <Foundation/Foundation.h>
  16. #import <dlfcn.h>
  17. #import <mach-o/dyld.h>
  18. #import <sys/utsname.h>
  19. #if TARGET_OS_IOS
  20. #import <UIKit/UIKit.h>
  21. #endif
  22. /// The encryption info struct and constants are missing from the iPhoneSimulator SDK, but not from
  23. /// the iPhoneOS or Mac OS X SDKs. Since one doesn't ever ship a Simulator binary, we'll just
  24. /// provide the definitions here.
  25. #if TARGET_OS_SIMULATOR && !defined(LC_ENCRYPTION_INFO)
  26. #define LC_ENCRYPTION_INFO 0x21
  27. struct encryption_info_command {
  28. uint32_t cmd;
  29. uint32_t cmdsize;
  30. uint32_t cryptoff;
  31. uint32_t cryptsize;
  32. uint32_t cryptid;
  33. };
  34. #endif
  35. @implementation GULAppEnvironmentUtil
  36. /// A key for the Info.plist to enable or disable checking if the App Store is running in a sandbox.
  37. /// This will affect your data integrity when using Firebase Analytics, as it will disable some
  38. /// necessary checks.
  39. static NSString *const kFIRAppStoreReceiptURLCheckEnabledKey =
  40. @"FirebaseAppStoreReceiptURLCheckEnabled";
  41. /// The file name of the sandbox receipt. This is available on iOS >= 8.0
  42. static NSString *const kFIRAIdentitySandboxReceiptFileName = @"sandboxReceipt";
  43. /// The following copyright from Landon J. Fuller applies to the isAppEncrypted function.
  44. ///
  45. /// Copyright (c) 2017 Landon J. Fuller <landon@landonf.org>
  46. /// All rights reserved.
  47. ///
  48. /// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  49. /// and associated documentation files (the "Software"), to deal in the Software without
  50. /// restriction, including without limitation the rights to use, copy, modify, merge, publish,
  51. /// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
  52. /// Software is furnished to do so, subject to the following conditions:
  53. ///
  54. /// The above copyright notice and this permission notice shall be included in all copies or
  55. /// substantial portions of the Software.
  56. ///
  57. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
  58. /// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  59. /// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  60. /// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  61. /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  62. ///
  63. /// Comment from <a href="http://iphonedevwiki.net/index.php/Crack_prevention">iPhone Dev Wiki
  64. /// Crack Prevention</a>:
  65. /// App Store binaries are signed by both their developer and Apple. This encrypts the binary so
  66. /// that decryption keys are needed in order to make the binary readable. When iOS executes the
  67. /// binary, the decryption keys are used to decrypt the binary into a readable state where it is
  68. /// then loaded into memory and executed. iOS can tell the encryption status of a binary via the
  69. /// cryptid structure member of LC_ENCRYPTION_INFO MachO load command. If cryptid is a non-zero
  70. /// value then the binary is encrypted.
  71. ///
  72. /// 'Cracking' works by letting the kernel decrypt the binary then siphoning the decrypted data into
  73. /// a new binary file, resigning, and repackaging. This will only work on jailbroken devices as
  74. /// codesignature validation has been removed. Resigning takes place because while the codesignature
  75. /// doesn't have to be valid thanks to the jailbreak, it does have to be in place unless you have
  76. /// AppSync or similar to disable codesignature checks.
  77. ///
  78. /// More information at <a href="http://landonf.org/2009/02/index.html">Landon Fuller's blog</a>
  79. static BOOL IsAppEncrypted() {
  80. const struct mach_header *executableHeader = NULL;
  81. for (uint32_t i = 0; i < _dyld_image_count(); i++) {
  82. const struct mach_header *header = _dyld_get_image_header(i);
  83. if (header && header->filetype == MH_EXECUTE) {
  84. executableHeader = header;
  85. break;
  86. }
  87. }
  88. if (!executableHeader) {
  89. return NO;
  90. }
  91. BOOL is64bit = (executableHeader->magic == MH_MAGIC_64);
  92. uintptr_t cursor = (uintptr_t)executableHeader +
  93. (is64bit ? sizeof(struct mach_header_64) : sizeof(struct mach_header));
  94. const struct segment_command *segmentCommand = NULL;
  95. uint32_t i = 0;
  96. while (i++ < executableHeader->ncmds) {
  97. segmentCommand = (struct segment_command *)cursor;
  98. if (!segmentCommand) {
  99. continue;
  100. }
  101. if ((!is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO) ||
  102. (is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO_64)) {
  103. if (is64bit) {
  104. struct encryption_info_command_64 *cryptCmd =
  105. (struct encryption_info_command_64 *)segmentCommand;
  106. return cryptCmd && cryptCmd->cryptid != 0;
  107. } else {
  108. struct encryption_info_command *cryptCmd = (struct encryption_info_command *)segmentCommand;
  109. return cryptCmd && cryptCmd->cryptid != 0;
  110. }
  111. }
  112. cursor += segmentCommand->cmdsize;
  113. }
  114. return NO;
  115. }
  116. static BOOL HasSCInfoFolder() {
  117. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  118. NSString *bundlePath = [NSBundle mainBundle].bundlePath;
  119. NSString *scInfoPath = [bundlePath stringByAppendingPathComponent:@"SC_Info"];
  120. return [[NSFileManager defaultManager] fileExistsAtPath:scInfoPath];
  121. #elif TARGET_OS_OSX
  122. return NO;
  123. #endif
  124. }
  125. static BOOL HasEmbeddedMobileProvision() {
  126. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  127. return [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"].length > 0;
  128. #elif TARGET_OS_OSX
  129. return NO;
  130. #endif
  131. }
  132. + (BOOL)isFromAppStore {
  133. static dispatch_once_t isEncryptedOnce;
  134. static BOOL isEncrypted = NO;
  135. dispatch_once(&isEncryptedOnce, ^{
  136. isEncrypted = IsAppEncrypted();
  137. });
  138. if ([GULAppEnvironmentUtil isSimulator]) {
  139. return NO;
  140. }
  141. // If an app contain the sandboxReceipt file, it means its coming from TestFlight
  142. // This must be checked before the SCInfo Folder check below since TestFlight apps may
  143. // also have an SCInfo folder.
  144. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox]) {
  145. return NO;
  146. }
  147. if (HasSCInfoFolder()) {
  148. // When iTunes downloads a .ipa, it also gets a customized .sinf file which is added to the
  149. // main SC_Info directory.
  150. return YES;
  151. }
  152. // For iOS >= 8.0, iTunesMetadata.plist is moved outside of the sandbox. Any attempt to read
  153. // the iTunesMetadata.plist outside of the sandbox will be rejected by Apple.
  154. // If the app does not contain the embedded.mobileprovision which is stripped out by Apple when
  155. // the app is submitted to store, then it is highly likely that it is from Apple Store.
  156. return isEncrypted && !HasEmbeddedMobileProvision();
  157. }
  158. + (BOOL)isAppStoreReceiptSandbox {
  159. // Since checking the App Store's receipt URL can be memory intensive, check the option in the
  160. // Info.plist if developers opted out of this check.
  161. id enableSandboxCheck =
  162. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRAppStoreReceiptURLCheckEnabledKey];
  163. if (enableSandboxCheck && [enableSandboxCheck isKindOfClass:[NSNumber class]] &&
  164. ![enableSandboxCheck boolValue]) {
  165. return NO;
  166. }
  167. // The #else is for pre Xcode 9 where @available is not yet implemented.
  168. #if __has_builtin(__builtin_available)
  169. if (@available(iOS 7.0, *)) {
  170. #else
  171. if ([[UIDevice currentDevice].systemVersion integerValue] >= 7) {
  172. #endif
  173. NSURL *appStoreReceiptURL = [NSBundle mainBundle].appStoreReceiptURL;
  174. NSString *appStoreReceiptFileName = appStoreReceiptURL.lastPathComponent;
  175. return [appStoreReceiptFileName isEqualToString:kFIRAIdentitySandboxReceiptFileName];
  176. }
  177. return NO;
  178. }
  179. + (BOOL)isSimulator {
  180. #if TARGET_OS_SIMULATOR
  181. return YES;
  182. #elif TARGET_OS_MACCATALYST
  183. return NO;
  184. #elif TARGET_OS_IOS || TARGET_OS_TV
  185. NSString *platform = [GULAppEnvironmentUtil deviceModel];
  186. return [platform isEqual:@"x86_64"] || [platform isEqual:@"i386"];
  187. #elif TARGET_OS_OSX
  188. return NO;
  189. #endif
  190. return NO;
  191. }
  192. + (NSString *)deviceModel {
  193. static dispatch_once_t once;
  194. static NSString *deviceModel;
  195. dispatch_once(&once, ^{
  196. struct utsname systemInfo;
  197. if (uname(&systemInfo) == 0) {
  198. deviceModel = [NSString stringWithUTF8String:systemInfo.machine];
  199. }
  200. });
  201. return deviceModel;
  202. }
  203. + (NSString *)systemVersion {
  204. #if TARGET_OS_IOS
  205. return [UIDevice currentDevice].systemVersion;
  206. #elif TARGET_OS_OSX || TARGET_OS_TV || TARGET_OS_WATCH
  207. // Assemble the systemVersion, excluding the patch version if it's 0.
  208. NSOperatingSystemVersion osVersion = [NSProcessInfo processInfo].operatingSystemVersion;
  209. NSMutableString *versionString = [[NSMutableString alloc]
  210. initWithFormat:@"%ld.%ld", (long)osVersion.majorVersion, (long)osVersion.minorVersion];
  211. if (osVersion.patchVersion != 0) {
  212. [versionString appendFormat:@".%ld", (long)osVersion.patchVersion];
  213. }
  214. return versionString;
  215. #endif
  216. }
  217. + (BOOL)isAppExtension {
  218. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  219. // Documented by <a href="https://goo.gl/RRB2Up">Apple</a>
  220. BOOL appExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"];
  221. return appExtension;
  222. #elif TARGET_OS_OSX
  223. return NO;
  224. #endif
  225. }
  226. + (BOOL)isIOS7OrHigher {
  227. #if __has_builtin(__builtin_available)
  228. if (@available(iOS 7.0, *)) {
  229. #else
  230. if ([[UIDevice currentDevice].systemVersion integerValue] >= 7) {
  231. #endif
  232. return YES;
  233. }
  234. return NO;
  235. }
  236. @end