added iOS source code
[wl-app.git] / iOS / Pods / GoogleUtilities / GoogleUtilities / Environment / third_party / GULAppEnvironmentUtil.m
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
15 #import "GULAppEnvironmentUtil.h"
16
17 #import <Foundation/Foundation.h>
18 #import <dlfcn.h>
19 #import <mach-o/dyld.h>
20 #import <sys/utsname.h>
21
22 #if TARGET_OS_IOS
23 #import <UIKit/UIKit.h>
24 #endif
25
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 {
32   uint32_t cmd;
33   uint32_t cmdsize;
34   uint32_t cryptoff;
35   uint32_t cryptsize;
36   uint32_t cryptid;
37 };
38 #endif
39
40 @implementation GULAppEnvironmentUtil
41
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
44 /// necessary checks.
45 static NSString *const kFIRAppStoreReceiptURLCheckEnabledKey =
46     @"FirebaseAppStoreReceiptURLCheckEnabled";
47
48 /// The file name of the sandbox receipt. This is available on iOS >= 8.0
49 static NSString *const kFIRAIdentitySandboxReceiptFileName = @"sandboxReceipt";
50
51 /// The following copyright from Landon J. Fuller applies to the isAppEncrypted function.
52 ///
53 /// Copyright (c) 2017 Landon J. Fuller <landon@landonf.org>
54 /// All rights reserved.
55 ///
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:
61 ///
62 /// The above copyright notice and this permission notice shall be included in all copies or
63 /// substantial portions of the Software.
64 ///
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.
70 ///
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.
79 ///
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.
85 ///
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;
93       break;
94     }
95   }
96
97   if (!executableHeader) {
98     return NO;
99   }
100
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;
105   uint32_t i = 0;
106
107   while (i++ < executableHeader->ncmds) {
108     segmentCommand = (struct segment_command *)cursor;
109
110     if (!segmentCommand) {
111       continue;
112     }
113
114     if ((!is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO) ||
115         (is64bit && segmentCommand->cmd == LC_ENCRYPTION_INFO_64)) {
116       if (is64bit) {
117         struct encryption_info_command_64 *cryptCmd =
118             (struct encryption_info_command_64 *)segmentCommand;
119         return cryptCmd && cryptCmd->cryptid != 0;
120       } else {
121         struct encryption_info_command *cryptCmd = (struct encryption_info_command *)segmentCommand;
122         return cryptCmd && cryptCmd->cryptid != 0;
123       }
124     }
125     cursor += segmentCommand->cmdsize;
126   }
127
128   return NO;
129 }
130
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];
136 #elif TARGET_OS_OSX
137   return NO;
138 #endif
139 }
140
141 static BOOL HasEmbeddedMobileProvision() {
142 #if TARGET_OS_IOS || TARGET_OS_TV
143   return [[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"].length > 0;
144 #elif TARGET_OS_OSX
145   return NO;
146 #endif
147 }
148
149 + (BOOL)isFromAppStore {
150   static dispatch_once_t isEncryptedOnce;
151   static BOOL isEncrypted = NO;
152
153   dispatch_once(&isEncryptedOnce, ^{
154     isEncrypted = IsAppEncrypted();
155   });
156
157   if ([GULAppEnvironmentUtil isSimulator]) {
158     return NO;
159   }
160
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]) {
165     return NO;
166   }
167
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.
171     return YES;
172   }
173
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();
179 }
180
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]) {
188     return NO;
189   }
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, *)) {
193 #else
194   if ([[UIDevice currentDevice].systemVersion integerValue] >= 7) {
195 #endif
196     NSURL *appStoreReceiptURL = [NSBundle mainBundle].appStoreReceiptURL;
197     NSString *appStoreReceiptFileName = appStoreReceiptURL.lastPathComponent;
198     return [appStoreReceiptFileName isEqualToString:kFIRAIdentitySandboxReceiptFileName];
199   }
200   return NO;
201 }
202
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"];
207 #elif TARGET_OS_OSX
208   return NO;
209 #endif
210 }
211
212 + (NSString *)deviceModel {
213   static dispatch_once_t once;
214   static NSString *deviceModel;
215
216   dispatch_once(&once, ^{
217     struct utsname systemInfo;
218     if (uname(&systemInfo) == 0) {
219       deviceModel = [NSString stringWithUTF8String:systemInfo.machine];
220     }
221   });
222   return deviceModel;
223 }
224
225 + (NSString *)systemVersion {
226 #if TARGET_OS_IOS
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];
235   }
236   return versionString;
237 #endif
238 }
239
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"];
244   return appExtension;
245 #elif TARGET_OS_OSX
246   return NO;
247 #endif
248 }
249
250 @end