forked from opa334/Choicy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tweak.x
370 lines (302 loc) · 12.9 KB
/
Tweak.x
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright (c) 2019-2021 Lars Fröder
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#import "HBLogWeak.h"
#import "Shared.h"
#import <substrate.h>
#import <dlfcn.h>
#import <mach-o/dyld.h>
BOOL g_ChoicyLoadTweaksOnce = NO;
BOOL g_tweakInjectionDisabled = NO;
BOOL g_customTweakConfigurationEnabled = NO;
NSArray *g_allowedTweaks = nil;
NSArray *g_deniedTweaks = nil;
NSArray *g_globalDeniedTweaks = nil;
BOOL g_isApplication = NO;
NSString *g_bundleIdentifier = nil;
//methods of getting executablePath and bundleIdentifier with the least side effects possible
//for more information, check out https://github.com/checkra1n/BugTracker/issues/343
NSString *safe_getExecutablePath()
{
char executablePathC[PATH_MAX];
uint32_t executablePathCSize = sizeof(executablePathC);
_NSGetExecutablePath(&executablePathC[0], &executablePathCSize);
return [NSString stringWithUTF8String:executablePathC];
}
NSString *safe_getBundleIdentifier() {
CFBundleRef mainBundle = CFBundleGetMainBundle();
if (mainBundle != NULL) {
CFStringRef bundleIdentifierCF = CFBundleGetIdentifier(mainBundle);
return (__bridge NSString *)bundleIdentifierCF;
}
return nil;
}
NSArray *env_getDeniedTweaksOverwrite() {
char *deniedTweaksC = getenv(kEnvDeniedTweaksOverride);
if (deniedTweaksC == NULL) return nil;
unsetenv(kEnvDeniedTweaksOverride);
NSString *deniedTweaksString = [NSString stringWithCString:deniedTweaksC encoding:NSUTF8StringEncoding];
return [deniedTweaksString componentsSeparatedByString:@"/"];
}
NSArray *env_getAllowedTweaksOverwrite() {
char *allowedTweaksC = getenv(kEnvAllowedTweaksOverride);
if (allowedTweaksC == NULL) return nil;
unsetenv(kEnvAllowedTweaksOverride);
NSString *allowedTweaksString = [NSString stringWithCString:allowedTweaksC encoding:NSUTF8StringEncoding];
return [allowedTweaksString componentsSeparatedByString:@"/"];
}
BOOL env_getOverwriteGlobalTweakConfigurationOverwrite(BOOL *envOverwriteExists) {
char *overwriteGlobalTweakConfigurationStr = getenv(kEnvOverwriteGlobalConfigurationOverride);
if (overwriteGlobalTweakConfigurationStr == NULL) {
if (envOverwriteExists) *envOverwriteExists = NO;
return NO;
}
unsetenv(kEnvOverwriteGlobalConfigurationOverride);
if (envOverwriteExists) *envOverwriteExists = YES;
return !strcmp(overwriteGlobalTweakConfigurationStr, "1");
}
BOOL isTweakDylib(NSString *dylibPath)
{
if ([dylibPath containsString:@"TweakInject"] || [dylibPath containsString:@"MobileSubstrate/DynamicLibraries"]) {
NSString *plistPath = [[dylibPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"plist"];
HBLogDebugWeak(@"plistPath = %@", plistPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
//Shoutouts to libFLEX for having a plist with an empty bundles entry
NSDictionary *bundlePlistDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
HBLogDebugWeak(@"bundlePlistDict = %@", bundlePlistDict);
NSDictionary *filter = [bundlePlistDict objectForKey:@"Filter"];
for (NSString *key in [filter allKeys]) {
NSObject *obj = [filter objectForKey:key];
if ([obj respondsToSelector:@selector(count)]) {
NSArray *arrObj = (NSArray *)obj;
if (arrObj.count > 0) {
return YES;
}
}
}
}
}
return NO;
}
BOOL shouldLoadDylib(NSString *dylibPath)
{
NSString *dylibName = [dylibPath.lastPathComponent stringByDeletingPathExtension];
HBLogDebugWeak(@"Checking whether %@.dylib should be loaded...", dylibName);
if(g_tweakInjectionDisabled && !g_ChoicyLoadTweaksOnce && [dylibName isEqualToString:@"OldABI"]) {
HBLogDebugWeak(@"%@.dylib ❌ (tweak injection disabled)", dylibName);
return NO;
}
if (isTweakDylib(dylibPath)) {
// dylibs crucial for Choicy itself to work
if (g_isApplication) {
NSArray *forceInjectedTweaks;
if ([g_bundleIdentifier isEqualToString:kPreferencesBundleID]) {
forceInjectedTweaks = kAlwaysInjectPreferences;
}
else if ([g_bundleIdentifier isEqualToString:kSpringboardBundleID]) {
forceInjectedTweaks = kAlwaysInjectSpringboard;
}
if ([forceInjectedTweaks containsObject:dylibName]) {
HBLogDebugWeak(@"%@.dylib ✅ (crucial)", dylibName);
return YES;
}
}
if (g_tweakInjectionDisabled) {
HBLogDebugWeak(@"%@.dylib ❌ (tweak injection disabled)", dylibName);
return NO;
}
BOOL tweakIsInWhitelist = [g_allowedTweaks containsObject:dylibName];
BOOL tweakIsInBlacklist = [g_deniedTweaks containsObject:dylibName];
BOOL tweakIsInGlobalBlacklist = [g_globalDeniedTweaks containsObject:dylibName];
if (tweakIsInGlobalBlacklist) {
HBLogDebugWeak(@"%@.dylib ❌ (disabled in global tweak configuration)", dylibName);
return NO;
}
if (g_allowedTweaks && !tweakIsInWhitelist) {
HBLogDebugWeak(@"%@.dylib ❌ (custom tweak configuration on allow and tweak not allowed)", dylibName);
return NO;
}
if (g_deniedTweaks && tweakIsInBlacklist) {
HBLogDebugWeak(@"%@.dylib ❌ (custom tweak configuration on deny and tweak denied)", dylibName);
return NO;
}
}
else {
HBLogDebugWeak(@"%@.dylib ✅ (not a tweak)", dylibName);
return YES;
}
HBLogDebugWeak(@"%@.dylib ✅ (allowed)", dylibName);
return YES;
}
void *(*dlopen_internal_orig)(const char*, int, void *);
void *$dlopen_internal(const char *path, int mode, void *lr)
{
@autoreleasepool {
if (path != NULL) {
NSString *dylibPath = @(path);
if (!shouldLoadDylib(dylibPath)) {
return NULL;
}
}
}
return dlopen_internal_orig(path, mode, lr);
}
void *(*dlopen_orig)(const char*, int);
void *$dlopen(const char *path, int mode)
{
@autoreleasepool {
if (path != NULL) {
NSString *dylibPath = @(path);
if (!shouldLoadDylib(dylibPath)) {
return NULL;
}
}
}
return dlopen_orig(path, mode);
}
#include <sys/stat.h>
bool pathFileEqual(const char* path1, const char* path2)
{
if(!path1 || !path2) return false;
struct stat st1;
if(stat(path1, &st1) != 0)
return false;
struct stat st2;
if(stat(path2, &st2) != 0)
return false;
if(st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
return false;
return true;
}
#include "fishhook.h"
%ctor {
@autoreleasepool {
HBLogDebugWeak(@"Choicy loaded");
// Determine information about this process
g_bundleIdentifier = safe_getBundleIdentifier();
NSString *executablePath = safe_getExecutablePath();
g_isApplication = [executablePath.stringByDeletingLastPathComponent.pathExtension isEqualToString:@"app"];
BOOL isAppPlugIn = [executablePath.stringByDeletingLastPathComponent.pathExtension isEqualToString:@"appex"];
// Load global preferences
NSDictionary *preferences = [NSDictionary dictionaryWithContentsOfFile:kChoicyPrefsPlistPath];
// Load preferences specific to this process
NSDictionary *processPreferences;
if (g_isApplication) {
processPreferences = processPreferencesForApplication(preferences, g_bundleIdentifier);
}
else {
processPreferences = processPreferencesForDaemon(preferences, executablePath.lastPathComponent);
}
HBLogDebugWeak(@"Loaded Choicy process preferences: %@", processPreferences);
// Check if the "Overwrite Global Tweak Configuration" toggle is enabled for this process or enabled via environment variable
BOOL overwriteGlobalTweakConfiguration = parseNumberBool(processPreferences[kChoicyProcessPrefsKeyOverwriteGlobalTweakConfiguration], NO);
BOOL overwriteGlobalTweakConfiguration_envOverwriteExists;
BOOL overwriteGlobalTweakConfiguration_envOverwrite = env_getOverwriteGlobalTweakConfigurationOverwrite(&overwriteGlobalTweakConfiguration_envOverwriteExists);
if (overwriteGlobalTweakConfiguration_envOverwriteExists) {
overwriteGlobalTweakConfiguration = overwriteGlobalTweakConfiguration_envOverwrite;
}
if (!overwriteGlobalTweakConfiguration) {
// If not, load tweaks disabled via global tweak configuration
g_globalDeniedTweaks = preferences[kChoicyPrefsKeyGlobalDeniedTweaks];
}
HBLogDebugWeak(@"g_globalDeniedTweaks = %@", g_globalDeniedTweaks);
NSInteger allowDenyMode = 0;
if (processPreferences) {
// If this process has non default preferences, load them into variables
g_tweakInjectionDisabled = parseNumberBool(processPreferences[kChoicyProcessPrefsKeyTweakInjectionDisabled], NO);
g_customTweakConfigurationEnabled = parseNumberBool(processPreferences[kChoicyProcessPrefsKeyCustomTweakConfigurationEnabled], NO);
allowDenyMode = parseNumberInteger(processPreferences[kChoicyProcessPrefsKeyAllowDenyMode], 1);
}
// Load list overwrites from environment
NSArray *env_deniedTweaks = env_getDeniedTweaksOverwrite();
NSArray *env_allowedTweaks = env_getAllowedTweaksOverwrite();
BOOL performedOverwrite = NO;
// Perform overwrites if neccessary
if (env_deniedTweaks) {
g_customTweakConfigurationEnabled = YES;
allowDenyMode = 2; // DENY
g_deniedTweaks = env_deniedTweaks;
performedOverwrite = YES;
}
else if (env_allowedTweaks) {
g_customTweakConfigurationEnabled = YES;
allowDenyMode = 1; // ALLOW
g_allowedTweaks = env_allowedTweaks;
performedOverwrite = YES;
}
if (performedOverwrite) {
g_tweakInjectionDisabled = NO;
}
const char* _CHOICY_LOAD_TWEAKS_ONCE = getenv("_CHOICY_LOAD_TWEAKS_ONCE");
if(_CHOICY_LOAD_TWEAKS_ONCE && atoi(_CHOICY_LOAD_TWEAKS_ONCE)==1) {
g_ChoicyLoadTweaksOnce = YES;
}
if (g_tweakInjectionDisabled || g_customTweakConfigurationEnabled || g_globalDeniedTweaks.count > 0) {
// If g_tweakInjectionDisabled is true for an application other than SpringBoard,
// it means that tweak injection was enabled for one launch via 3D touch and we should not do anything
if (g_isApplication && !isAppPlugIn && g_tweakInjectionDisabled && g_ChoicyLoadTweaksOnce) {
if (![g_bundleIdentifier isEqualToString:kSpringboardBundleID]) {
HBLogDebugWeak(@"Tweak injection has been enabled via 3D touch, Choicy will do nothing!");
return;
}
}
// If custom tweak configuration is enabled for this process, load the allow / deny list based on what mode is selected
if (g_customTweakConfigurationEnabled && !performedOverwrite) {
if (allowDenyMode == 2) { // DENY
g_deniedTweaks = processPreferences[kChoicyProcessPrefsKeyDeniedTweaks];
}
else if (allowDenyMode == 1) { // ALLOW
g_allowedTweaks = processPreferences[kChoicyProcessPrefsKeyAllowedTweaks];
}
}
// // Apply Choicy dlopen hooks
// MSImageRef libdyldImage = MSGetImageByName("/usr/lib/system/libdyld.dylib");
// void *libdyldHandle = dlopen("/usr/lib/system/libdyld.dylib", RTLD_NOW);
// void *dlopen_global_var_ptr = MSFindSymbol(libdyldImage, "__ZN5dyld45gDyldE"); // if this var exists, it means we're on a version new enough to hook dlopen directly again
// if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_14_1 && !dlopen_global_var_ptr) {
// void *dlopen_internal_ptr = MSFindSymbol(libdyldImage, "__ZL15dlopen_internalPKciPv");
// MSHookFunction(dlopen_internal_ptr, (void *)$dlopen_internal, (void* *)&dlopen_internal_orig);
// }
// else {
// MSHookFunction(&dlopen, (void *)$dlopen, (void* *)&dlopen_orig);
// void *dlopen_from_ptr = dlsym(libdyldHandle, "dlopen_from");
// if (dlopen_from_ptr) {
// MSHookFunction(dlopen_from_ptr, (void *)$dlopen_internal, (void* *)&dlopen_internal_orig);
// }
// }
const void* _dyld_get_shared_cache_range(size_t* length);
size_t sharedlen=0;
const void* sharedbase = _dyld_get_shared_cache_range(&sharedlen);
struct rebinding rebindings = {
.name="dlopen",
.replacement = $dlopen,
.replaced = (void**)&dlopen_orig
};
const char* tweakloader = jbroot("/usr/lib/TweakLoader.dylib");
uint32_t c = _dyld_image_count();
for (uint32_t i = 0; i < c; i++) {
uint64_t slide = _dyld_get_image_vmaddr_slide(i);
void* header = (void*)_dyld_get_image_header(i);
if( (uint64_t)header < (uint64_t)sharedbase || (uint64_t)header > ((uint64_t)sharedbase+sharedlen) ) {
if(pathFileEqual(_dyld_get_image_name(i), tweakloader)) {
rebind_symbols_image(header, slide, &rebindings, 1);
break;
}
}
}
}
}
}