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